text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _OLC1_Proyecto1_201611269.ANALISIS { class analizador1 { public List<token> miListaToken = new List<token>(); public List<token> miListaError = new List<token>(); private token miToken; /*public analizador1(string aa) { token mio = new token(aa, aa); miListaToken.Add(mio); mio = new token(aa, aa); miListaToken.Add(mio); miListaError.Add(mio); mio = new token("error", aa); miListaError.Add(mio); GeneraReporteTokens(); }*/ public void analizame(string contenido) { //OJO CUIDADO limpia(); //OJO CUIDADO int fila = 0, columna = 0, EstadoPrincipal=0, EstadoComentarios=0, EstadoTemporalPrincial=0, estadoConjuntos=0, estadoPatron=0, estadoLex=0; char actual, siguiente, anterior; string cadenaTemporal1 = string.Empty, nombreCONJ="", contCONJ=""; for (int i = 0; i < contenido.Length; i++) { //Console.WriteLine("Princiapl: " + EstadoPrincipal + " Tempo: " + EstadoTemporalPrincial+" CONJ: "+estadoConjuntos+ " Y el char es: "+contenido[i]); if (contenido[i] == '\n') { fila++; columna = 0; //SI ESTAMOS EN ELE ESTAOD DE COMENTARIOS, PODREMOS RETORNAR AL ESTADO EN EL QUE ESTABAMOS if (EstadoPrincipal == 4) { EstadoPrincipal = EstadoTemporalPrincial; EstadoTemporalPrincial = 0; } } else { //AQUI VA EL PRIMER ANALISIS //MANEJAREMOS UNA MAQUINA DE ESTADOS QUE PODEMOS IR DE UNO A OTRO CREANDO TOKENS //AQUI ABAAJO DEBE DEFINIRSE EL TIPO DE TOKENS //DE PRIMERA MANO IGNORAMOS EL ENTER PARA EVITAR PROBLEMAS //SOLO LO USAREMOS PARA EL ESTADOCOMENTARIO TIPO 1 //VAMOS A EMPEZAR CON LOS ESTADOS DE COMENTARIOS Y LOS VAMOS A IGNORAR columna = i; if (i - 1 >= 0 && i + 1 < contenido.Length) { anterior = contenido[i - 1]; actual = contenido[i]; siguiente = contenido[i + 1]; } else { actual = contenido[i]; siguiente = anterior = (char)32; } switch (EstadoPrincipal) { //AQUI VAMOS A DESGLOSAR LOS QUE SON LOS TIPOS DE GRUPOS DE CARACTERES A ANALIZAR, EN NUESTRO CASO SERAN 4 //ESTADO DE CONJUNTOS //ESTADO DE PATRONES //ESTADO DE LEXEMAS //ESTADO DE COMENTARIOS UNA LINEA //ESTADO DE COMENTARIOS DOS LINEAS //CASO CONJUNTOS case 0: //AQUI ESPERAMOS 2 COSAS //LA DECLARACION DE CONJUNTOS Y/O COMENTARIOS //DEBEMOS HACER LA MANERA DE INTENTAR RECUPERARNOS DE ESOS ERRORES if (estadoComentario(actual, siguiente) == 4 || estadoComentario(anterior, actual) == 4) { //EN ESTA CONDICION VERIFICAREMOS EL ESTADO DE SI ENTRAMOS A COMENTARIOS //DE SER ASI CAMBIAREMOS EL ESTADO PRINCIPAL AL NORMAL EstadoTemporalPrincial = EstadoPrincipal; EstadoPrincipal = 4; } else if (estadoComentario(actual, siguiente) == 5 || estadoComentario(anterior, actual) == 5) { EstadoTemporalPrincial = EstadoPrincipal; EstadoPrincipal = 5; } else { cadenaTemporal1 += actual; //AQUI DEBEMOS BUSCAR CONJUNTOS switch (estadoConjuntos) { //CADENATEMPORAL1 debe ser igual al caracter case 0: //CASO UNO DONDE ESPERAMOS 2 ESTADOS DE SALIDA //1 DONDE ESTEN LOS 2 PUNTOS Y LUEGO VAMOS A CREAR UN TOKEN RESERVADA Y SEGUIMOS EN ESTADO CONJUNTOS //2 DONDE RECONOCEMOS OTRO TOKEN DONDE ES -> Y QUIERE DECIR QUE VAMOS AL ESTADO PATRON if (actual == ':') { if (cadenaTemporal1.Contains("CONJ")) { estadoConjuntos++; //TOOOKEN miListaToken.Add(new token("RESERVADA", "CONJ", fila, columna-4)); miToken = new token("PUNTOS", ":", fila, columna); miListaToken.Add(miToken); cadenaTemporal1 = ""; } else estadoConjuntos = -1; } else if (actual == '-' && siguiente == '>') { //TOOOKEN EstadoPrincipal++; miListaToken.Add(new token("ID_PATRON", quitaTodo(cadenaTemporal1), fila, columna - 1)); cadenaTemporal1 = string.Empty; //ESTADO ESPECIAL PARA IR AL NUEVO ESTADO estadoConjuntos = 10; } break; case 1: //SI ESTAMOS AQUI QUIERE DECIR QUE VAMOS A RECONOCER EL ID DE CONJ if (anterior == '-' && actual == '>') { estadoConjuntos++; //TOOOKEN miToken = new token("ID_CONJ", nombreCONJ.Replace("-", ""), fila, columna); miListaToken.Add(miToken); nombreCONJ = ""; } else nombreCONJ += actual; break; case 2: //AQUI VAMOS A RECONCER EL CONTENIDO DEL CONJ if (actual == ';') { //TOOOKEN miToken = new token("CONTENIDO_CONJ",contCONJ.Replace(" ", ""), fila, columna); miListaToken.Add(miToken); contCONJ = ""; estadoConjuntos = 0; cadenaTemporal1 = ""; //AQUI ESTAMOS EN EL ESTADO FINAL BUSCANDO } else { contCONJ += actual; } break; default: //AQUI DEBEMOS ENCONTRAR ALGUN ERROR; //DIGAMOS QUE OBTENEMOS UN -1 //HAREMOS QUE ENTREMOS A ESTE ESTADO Y LA VARIABLE CADENATEMPORAL1 SERA ALMACENADA COMO UN ERROR //Y VOLVEREMOS A EL SIGUIENTE ESTADO, TAMBI[EN GUARDAREMOS EL TOKEN COMO ERROR EstadoPrincipal++; token miError = new token("Error", cadenaTemporal1, fila, columna); miListaError.Add(miError); cadenaTemporal1 = string.Empty; estadoConjuntos=0; break; }//switch conjuntos }//else case 0 break;//BREAK CASE0 CONJUNTO //CASO PATRONES case 1: if (estadoComentario(actual, siguiente) == 4 || estadoComentario(anterior, actual) == 4) { //EN ESTA CONDICION VERIFICAREMOS EL ESTADO DE SI ENTRAMOS A COMENTARIOS //DE SER ASI CAMBIAREMOS EL ESTADO PRINCIPAL AL NORMAL EstadoTemporalPrincial = EstadoPrincipal; EstadoPrincipal = 4; } else if (estadoComentario(actual, siguiente) == 5 || estadoComentario(anterior, actual) == 5) { EstadoTemporalPrincial = EstadoPrincipal; EstadoPrincipal = 5; } else { cadenaTemporal1+=actual; switch(estadoPatron){ case 0: //DEBERIAMOS ENTRAR A ESTE ESTADO PRINCIPALEMNTE //YA QUE LO LLAMAMOS CUANDO VENIMOS DE CONJUNTOS // Y LA PALABRA RESERVADA NO ES LA CORRECTA Y LOS TOQUENS SON IGUALES if (anterior == '-' && actual == '>' && estadoConjuntos == 10) { cadenaTemporal1 = ""; estadoPatron++; //VOLVEMOS ESTADO CONJUNTOS A SU ESTADO NORMAL estadoConjuntos = 0; } else if(anterior=='-' && actual=='>' ){ //TOOOKEN miListaToken.Add(new token("ID_PATRON",quitaTodo(cadenaTemporal1), fila, columna)); cadenaTemporal1=""; estadoPatron++; }else if(actual==':'){ //TOOOKEN miListaToken.Add(new token("ID_LEXEMA",quitaTodo(cadenaTemporal1), fila, columna)); cadenaTemporal1=""; EstadoPrincipal++; estadoPatron=10; //ESTADO ESPECIAL } break; case 1: //SI LLEGAMOS A ESTE CASO QUIERE DECIR QUE DEBEMOS ALMACENAR TODO EL CONTENIDO EN ESTA INFORMACION Y LUEGO ESPERAR //UN PUNTO Y COMA if(actual==';'){ //TOOOKEN miListaToken.Add(new token("CONTENIDO_PATRON",quitatodoDos(cadenaTemporal1), fila, columna)); cadenaTemporal1=""; estadoPatron=0; } break; default: //TOOOKEN miListaToken.Add(new token("ERROR_PATRON",cadenaTemporal1, fila, columna)); cadenaTemporal1=""; EstadoPrincipal++; break; }//switch patrones //AQUI DEBEMOS BUSCAR PATRONES //if (actual == '(') EstadoPrincipal = 2; //DEBEMOS CONSIDERAR EL TOKEN ANTERIOR //PUESTO QUE EL ACTUAL DEL CASO ANTERIOR, ES UN ERROR, PARA ESE, PERO NO PARA ESTE CASO //EN FIN USAR EL CHAR ANTERIOR } break; //LEXEMAS case 2: if (estadoComentario(actual, siguiente) == 4 || estadoComentario(anterior, actual) == 4) { //EN ESTA CONDICION VERIFICAREMOS EL ESTADO DE SI ENTRAMOS A COMENTARIOS //DE SER ASI CAMBIAREMOS EL ESTADO PRINCIPAL AL NORMAL EstadoTemporalPrincial = EstadoPrincipal; EstadoPrincipal = 4; } else if (estadoComentario(actual, siguiente) == 5 || estadoComentario(anterior, actual) == 5) { EstadoTemporalPrincial = EstadoPrincipal; EstadoPrincipal = 5; } else { //AQUI DEBEMOS BUSCAR LEXEMAS cadenaTemporal1+=actual; switch(estadoLex){ case 0: if( (actual=='"' || actual==':') && estadoPatron==10){ estadoPatron=0; cadenaTemporal1=""; estadoLex++; } else if(actual=='"' || actual==':'){ //TOOOKEN miListaToken.Add(new token("ID_LEXEMA",quitaTodo(cadenaTemporal1), fila, columna)); cadenaTemporal1=""; estadoLex++; } break; case 1: if(actual==';'){ //TOOOKEN miListaToken.Add(new token("CONT_LEXEMA",quitatodoDos(cadenaTemporal1), fila, columna)); cadenaTemporal1=""; estadoLex=0; } break; default: break; }//switch lexema } break; //CASO COMENTARIOS MULTILINEA case 5: //DEBIDO A LA CONDICION INICIAL, DONDE IGNORAMOS EL ENTER, YA CUANDO ESTE SE RECONOCE //CAMBIAMOS AL ESTADO EN EL QUE ESTABA //Console.WriteLine("Toy caso 5 " + actual); if (anterior == '!' && actual == '>') { EstadoPrincipal = EstadoTemporalPrincial; EstadoTemporalPrincial = 0; } break; default: break; } } }//for contenido MessageBox.Show("analizadoo"); } private string dameCorrecto(string cadena) { string cad = cadena; if (cadena.Contains("&")) cad = cadena.Replace("&", "&amp;"); if (cadena.Contains(">")) cad = cadena.Replace(">", "&gt;"); if (cadena.Contains("\"")) cad = cadena.Replace("\"", "&quot;"); if (cadena.Contains("'")) cad = cadena.Replace("'", "&apos;"); if (cadena.Contains("<")) cad = cadena.Replace("<", "&lt;"); return cad; } private int estadoComentario(char actual, char siguiente) { //VAMOS A INTENTAR DEFINIR NUESTRO METODO //POR AHORA NECESITAMOS 3 ESTADOS /* 4 DONDE ENTRAMOS CON DOS BARRAS 5 CUANDO ESTAMOS CON AMBAS LINEAS 0 CUANDO NO SEA NINGUNO * */ if (actual == '/' && siguiente == '/') return 4; else if (actual == '<' && siguiente == '!') return 5; else return 0; } private bool EntroEnComentario(char actual, char siguiente) { if ((actual == '/' && siguiente == '/') || (actual == '<' && siguiente == '!')) return true; else return false; } private void limpia() { miListaToken.Clear(); miListaError.Clear(); } private string quitaTodo(string cadena) { string cad = cadena; /*if(cadena.Contains(" "))cad = cadena.Replace(" ", ""); if(cadena.Contains(">"))cad = cadena.Replace(">", ""); if (cadena.Contains("-")) cad = cadena.Replace("-", ""); if (cadena.Contains(":")) cad = cadena.Replace(":", ""); if (cadena.Contains("\"")) cad = cadena.Replace("\"", "");*/ return cad.Replace(" ", "").Replace(">", "").Replace("-", "").Replace(":", "") .Replace("\"", "").Replace(";", ""); } private string quitatodoDos(string cadena) { string cad = cadena; return cad.Replace(">", "").Replace("-", "").Replace(":", "") .Replace("\"", "").Replace(";", ""); } public string dameTokens() { string contenido=string.Empty; foreach (token mi in miListaToken) { contenido += mi.dameNombre() + " " + mi.dameContenido() + " " + mi.fila + " " + mi.columna + System.Environment.NewLine; } contenido += "\n\n\n"; foreach (token mi in miListaError) { contenido += mi.dameNombre() + " " + mi.dameContenido() + " " + mi.fila + " " + mi.columna + System.Environment.NewLine; } return contenido; } public void GeneraReporteTokens() { //VAMOS A CREAR UN ARCHIVO DE REPORTE DE TOKENS string contenido = string.Empty; string nombre = System.Reflection.Assembly.GetEntryAssembly().Location.ToString().Replace("[OLC1]Proyecto1_201611269.exe", "") + "TokenR.xml"; try { if (File.Exists(nombre)) { File.Delete(nombre); } using (StreamWriter sw = File.CreateText(nombre)) { sw.WriteLine("<ListaTokens>"); sw.WriteLine("<Generado>Carlos Hernandez 201611269 " + DateTime.Now.ToString() + " </Generado>"); //contenido += "<ListaTokens>\n"; foreach (token to in miListaToken) { sw.WriteLine("<Token>\n<Nombre>" + to.dameNombre() + "</Nombre>\n<Valor>" + dameCorrecto(to.dameContenido()) + "</Valor>\n<Fila>" + to.fila + "</Fila>\n<Columna>" + to.columna + "</Columna>\n</Token>"); } sw.WriteLine("<TokenError>\n"); //AQUI VA EL CICLO DE ERRORES foreach (token to in miListaError) { sw.WriteLine("<Token>\n<Nombre>" + to.dameNombre() + "</Nombre>\n<Valor>" + dameCorrecto(to.dameContenido()) + "</Valor>\n<Fila>" + to.fila + "</Fila>\n<Columna>" + to.columna + "</Columna>\n</Token>"); } sw.WriteLine("</TokenError>\n"); sw.WriteLine("</ListaTokens>\n\n\n"); } System.Diagnostics.Process.Start("TokenR.xml"); } catch (Exception ex) { MessageBox.Show(ex.Message); //throw; } } } }
using System.Collections.Generic; using System.Linq; using Grimoire.Game; using Grimoire.Game.Data; namespace Grimoire.Networking.Handlers { public class HandlerGetQuests : IJsonMessageHandler { public string[] HandledCommands { get; } = {"getQuests"}; public void Handle(JsonMessage message) { var quests = message.DataObject?["quests"]?.ToObject<Dictionary<int, Quest>>(); if (quests?.Count > 0) Player.Quests.OnQuestsLoaded(quests.Select(q => q.Value).ToList()); } } }
using CoreFrameWork.Modularity; using System; using System.Collections.Generic; using System.Text; namespace CoreFrameWork.EntityFrameWorkCore { public class CoreEfCoreModule : CoreModuleBase { public override void ConfigureServices(ServiceCollectionContext context) { context.Services.AddEntityFrameworkRepository(); } } }
using System; using System.Collections.Generic; using SubSonic.BaseClasses; using SubSonic.Extensions; using SubSonic.SqlGeneration.Schema; namespace Pes.Core { [SubSonicTableNameOverride("Gags")] public partial class Gag : EntityBase<Gag> { #region Properties public override object Id { get { return GagID; } set { GagID = (long)value; } } [SubSonicPrimaryKey] public long GagID { get; set; } public int AccountID { get; set; } public string AccountUsername { get; set; } public DateTime CreateDate { get; set; } public System.Data.Linq.Binary TimeStamp { get; set; } public string Reason { get; set; } public DateTime? GagUntilDate { get; set; } public int GaggedByAccountID { get; set; } #endregion public Gag() { } public Gag(object id) { if (id != null) { Gag entity = Single(id); if (entity != null) entity.CopyTo<Gag>(this); else this.GagID = 0; } } public bool Save() { bool rs = false; if (GagID > 0) rs = Update(this) > 0; else rs = Add(this) != null; return rs; } } }
using System; using System.Collections.Generic; using System.Text; using SoftDeleteTest.Localization; using Volo.Abp.Application.Services; namespace SoftDeleteTest { /* Inherit your application services from this class. */ public abstract class SoftDeleteTestAppService : ApplicationService { protected SoftDeleteTestAppService() { LocalizationResource = typeof(SoftDeleteTestResource); } } }
namespace Models.BuildingModels { public class GasMine : Mine { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades1 { public class Calculadora { /// <summary> /// Valida si el operador es correcto /// </summary> /// <param name="operador"> Recibe un string operador</param> /// <returns>Retorna el operador y si no es correcto devuelve "+" </returns> private static string ValidarOperador(string operador) { string retorno=""; switch (operador) { case "+": retorno = operador; break; case "-": retorno = operador; break; case "/": retorno = operador; break; case "*": retorno = operador; break; default: retorno = "+"; break; } return retorno; } /// <summary> /// Valida y realiza las operaciones entre los dos parametros /// </summary> /// <param name="num1">Recibe una clase Numero</param> /// <param name="num2">Recibe una clase Numero</param> /// <param name="operador">Recibe un string</param> /// <returns>Retorna el resultado de las operaciones</returns> public double Operar(Numero num1, Numero num2, string operador) { double resultado=0; string operadores; operadores = ValidarOperador(operador); switch(operadores) { case "+": resultado = num1 + num2; break; case "-": resultado = num1 - num2; break; case "*": resultado = num1 * num2; break; case "/": resultado = num1 / num2; break; } return resultado; } } }
// // commercio.sdk - Sdk for Commercio Network // // Riccardo Costacurta // Dec. 30, 2019 // BlockIt s.r.l. // /// Represents the transaction message that must be used when wanting to buy a membership. // using System; using System.Text; using System.Collections.Generic; using System.Diagnostics; using commercio.sacco.lib; using Newtonsoft.Json; namespace commercio.sdk { public class MsgBuyMembership : StdMsg { #region Properties [JsonProperty("buyMembership", Order = 1)] public BuyMembership buyMembership { get; private set; } // The override of the value getter is mandatory to obtain a correct codified Json public override Dictionary<String, Object> value { get { return _toJson(); } } #endregion #region Constructors /// Public constructor. public MsgBuyMembership(BuyMembership buyMembership) { Trace.Assert(buyMembership != null); // Assigns the properties this.buyMembership = buyMembership; base.setProperties("commercio/MsgBuyMembership", _toJson()); } #endregion #region Public Methods #endregion #region Helpers private Dictionary<String, Object> _toJson() { Dictionary<String, Object> wk = this.buyMembership.toJson(); return wk; } #endregion /* #region Properties [JsonProperty("membershipType", Order = 2)] public MembershipType membershipType { get; private set; } [JsonProperty("buyerDid", Order = 1)] public String buyerDid { get; private set; } // The override of the value getter is mandatory to obtain a correct codified Json public override Dictionary<String, Object> value { get { return _toJson(); } } #endregion #region Constructors /// Public constructor. public MsgBuyMembership(MembershipType membershipType, String buyerDid) { // Trace.Assert(membershipType != null); Trace.Assert(buyerDid != null); // Assigns the properties this.membershipType = membershipType; this.buyerDid = buyerDid; base.setProperties("commercio/MsgBuyMembership", _toJson()); } #endregion #region Public Methods #endregion #region Helpers private Dictionary<String, Object> _toJson() { Dictionary<String, Object> wk = new Dictionary<String, Object>(); wk.Add("membership_type", (Enum.GetName(typeof(MembershipType), this.membershipType)).ToLower()); wk.Add("buyer", this.buyerDid); return wk; } #endregion */ } }
using System; using System.Web; using System.Threading; using System.Globalization; /// <summary> /// Summary description for BasePage /// </summary> public class BasePage : Systems.Web.UI.Page { /// <summary> /// 设置页面语言 /// </summary> protected override void InitializeCulture() { HttpCookie cookieLang = new HttpCookie("lang"); if (Request.Form["lang"] != null) { String strlang = Request.Form["lang"]; cookieLang.Value = strlang; Response.Cookies.Add(cookieLang); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(strlang); Thread.CurrentThread.CurrentUICulture = new CultureInfo(strlang); } else if (Request.Cookies["lang"] != null) { cookieLang = Request.Cookies["lang"]; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cookieLang.Value); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cookieLang.Value); } else { cookieLang.Value = "zh-cn"; Response.Cookies.Add(cookieLang); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("zh-cn"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-cn"); } base.InitializeCulture(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OakIdeas.Volunteer.Models { public class Location :BaseModel { private string _street; public string Street { get { return _street; } set { _street = value; } } private string _streetNumber; public string StreetNumber { get { return _streetNumber; } set { _streetNumber = value; } } private string _postalCode; public string PostalCode { get { return _postalCode; } set { _postalCode = value; } } private string _city; public string City { get { return _city; } set { _city = value; } } private string _adminDistrict; public string AdminDistrict { get { return _adminDistrict; } set { _adminDistrict = value; } } private string _adminDistrict2; public string AdminDistrict2 { get { return _adminDistrict2; } set { _adminDistrict2 = value; } } private string _countryRegion; public string CountryRegion { get { return _countryRegion; } set { _countryRegion = value; } } private List<Organization> _organizations; public virtual List<Organization> Organizations { get { return _organizations; } set { _organizations = value; } } } }
using Alfheim.FuzzyLogic; using Alfheim.FuzzyLogic.Functions; using Alfheim.FuzzyLogic.FuzzyFunctionAttributes; using Alfheim.FuzzyLogic.Variables.Model; using Alfheim.GUI.Resources; using Alfheim.GUI.Services; using LiveCharts; using LiveCharts.Defaults; using LiveCharts.Wpf; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using MahApps.Metro; using System.ComponentModel; namespace Alfheim.GUI.Views { /// <summary> /// Логика взаимодействия для LinguisticVariablePage.xaml /// </summary> public partial class LinguisticVariablePage : Page { private Page mOwner; private LinguisticVariable mThisVariable; private PlotBindingService mPlotBindingService; private TermPropertyViewService mTermPropertyViewService; public LinguisticVariablePage(Page owner, LinguisticVariable variable) { InitializeComponent(); mOwner = owner; mThisVariable = variable; Init(); } private void PreviousPage_Click(object sender, RoutedEventArgs e) { (Window.GetWindow(this) as MainWindow).OpenPage(mOwner); } private void Init() { mTermList.ItemsSource = mThisVariable.Terms; mTitleTB.Text = mThisVariable.Name; mXAxis.MinValue = mThisVariable.MinValue; mXAxis.MaxValue = mThisVariable.MaxValue; mXAxis.Separator.Step = ((double)(mThisVariable.MinValue + mThisVariable.MaxValue) / 10.0); mXAxis.Separator.StrokeThickness = 2; mPlotBindingService = new PlotBindingService(mPlot, mThisVariable); mTermPropertyViewService = new TermPropertyViewService(mStackPanel); mTermPropertyViewService.TermChanged += OnTermChanged; App.ChartQualityChanged += ChartQualityChanged; } private void ChartQualityChanged(object sender, EventArgs e) { mPlotBindingService.Update(); } private void OutputListBoxDoubleClick(object sender, MouseButtonEventArgs e) { } private void AddTerm_Click(object sender, RoutedEventArgs e) { CreateTerm(); } private void RemoveTerm_Click(object sender, RoutedEventArgs e) { } private void CreateTerm() { AddTermWindow addVariableWindow = new AddTermWindow(mThisVariable); addVariableWindow.Owner = Window.GetWindow(this); addVariableWindow.ShowDialog(); } private void TermList_SelectionChanged(object sender, SelectionChangedEventArgs e) { var term = (mTermList.SelectedItem as Term); if (term == null) return; mTermPropertyViewService.ShowTermProperties(term); } private void OnTermChanged(object sender, PropertyChangedEventArgs e) { Term term = (sender as Term); if (term == null) return; mPlotBindingService.UpdateTerm(term, e.PropertyName); mTermList.Items.Refresh(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Xml; using InvoiceClient.Helper; using InvoiceClient.Properties; using Model.Locale; using Model.Schema.EIVO; using Model.Schema.EIVO.B2B; using Model.Schema.TXN; using Utility; using CsvHelper; namespace InvoiceClient.Agent.CsvRequestHelper { public class CsvRequestWatcher : InvoiceWatcher { public CsvRequestWatcher(String fullPath) : base(fullPath) { } protected override void prepareStorePath(string fullPath) { _failedTxnPath = fullPath + "(Failure)"; _failedTxnPath.CheckStoredPath(); if (__FailedTxnPath != null) { __FailedTxnPath.Add(_failedTxnPath); } _inProgressPath = Path.Combine(Logger.LogPath, Path.GetFileName(fullPath), $"{Process.GetCurrentProcess().Id}"); _inProgressPath.CheckStoredPath(); } protected List<String[]> DataItems { get; set; } protected List<String[]> ParseCsv(String csvFile) { List<String[]> items = new List<String[]>(); using (StreamReader sr = new StreamReader(csvFile, Encoding.GetEncoding(Settings.Default.CsvEncoding))) { sr.ReadLine(); int lineIdx = 0; using (CsvParser parser = new CsvParser(sr, new CsvHelper.Configuration.Configuration() { TrimOptions = CsvHelper.Configuration.TrimOptions.Trim }, leaveOpen: false)) { String[] column; while ((column = parser.Read()) != null) { lineIdx++; items.Add(column); } } } return items; } protected override void processFile(string invFile) { DataItems = null; if (!File.Exists(invFile)) return; String fileName = Path.GetFileName(invFile); String fullPath = Path.Combine(_inProgressPath, fileName); try { File.Move(invFile, fullPath); } catch (Exception ex) { Logger.Error(ex); return; } try { DataItems = ParseCsv(fullPath); storeFile(fullPath, Path.Combine(Logger.LogDailyPath, fileName)); } catch (Exception ex) { Logger.Error(ex); storeFile(fullPath, Path.Combine(_failedTxnPath, fileName)); } } } }
using ShCore.Extensions; using System.Linq; using ShCore.DataBase.ADOProvider.Attributes; namespace ShCore.DataBase.ADOProvider.ShSqlCommand { /// <summary> /// Câu lệnh thực hiện Insert /// </summary> class ShInsertCommand : ShCommand { public override void Build(ModelBase t, TSqlBuilder builder, params string[] fields) { var f1 = string.Empty; // Các field cần insert var f2 = string.Empty; // Tham số của các field cần insert FieldAttribute fn = null; // // Danh sách các thuộc tính của đối tượng var ps = builder.AllProperties; // Duyệt qua từng thuộc tính ps.ForEach(p => { fn = builder.FieldPKs.FirstOrDefault(f => f.FieldName == p.Name); // Kiểm tra xem có phải là tự tăng không if (fn == null || !fn.IsIdentity) // Nếu không phải là tự tăng mới build câu lệnh { f1 += "[" + p.Name + "],"; f2 += "@" + p.Name + ","; this.Parameter[p.Name] = t.Eval(p.Name); } }); // Xem có trường tự tăng thì lấy ra số tự tăng fn = builder.FieldPKs.FirstOrDefault(f => f != null && f.IsIdentity); // Tạo identity theo key tự tăng var @identity = fn != null ? "SELECT @@IDENTITY {0}".Frmat(fn.FieldName) : "SELECT 0"; f1 = f1.TrimEnd(','); f2 = f2.TrimEnd(','); // Build câu lệnh this.Command = "BEGIN INSERT INTO {0} ({1}) VALUES ({2}) {3} END".Frmat(builder.TableInfo.TableName, f1, f2, @identity); } } }
using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Kit.Forms.Controls.LogsViewer { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LogViewer : ContentView { public LogViewer() { InitializeComponent(); } protected override void OnParentSet() { base.OnParentSet(); if (Parent is null) { Model?.Dispose(); } } } }
using PayPal.PayPalAPIInterfaceService; using PayPal.PayPalAPIInterfaceService.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Paypal_API.API_Call { public class ManageTransaction { public void VoidTransaction(string transactionId) { // Create request object DoVoidRequestType request = new DoVoidRequestType(); request.AuthorizationID =transactionId; // Invoke the API DoVoidReq wrapper = new DoVoidReq(); wrapper.DoVoidRequest = request; Dictionary<string, string> configurationMap = confiugraion.GetAcctAndConfig(); // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); // # API call // Invoke the DoVoid method in service wrapper object DoVoidResponseType doVoidResponse = service.DoVoid(wrapper); // Check for API return status setKeyResponseObjects(service, doVoidResponse); } private void setKeyResponseObjects(PayPalAPIInterfaceServiceService service, DoVoidResponseType doVoidResponse) { Dictionary<string, string> responseParams = new Dictionary<string, string>(); HttpContext CurrContext = HttpContext.Current; CurrContext.Items.Add("Response_keyResponseObject", responseParams); CurrContext.Items.Add("Response_apiName", "DoVoid"); CurrContext.Items.Add("Response_redirectURL", null); CurrContext.Items.Add("Response_requestPayload", service.getLastRequest()); CurrContext.Items.Add("Response_responsePayload", service.getLastResponse()); if (doVoidResponse.Ack.Equals(AckCodeType.FAILURE) || (doVoidResponse.Errors != null && doVoidResponse.Errors.Count > 0)) { CurrContext.Items.Add("Response_error", doVoidResponse.Errors); } else { CurrContext.Items.Add("Response_error", null); responseParams.Add("Authorization Id", doVoidResponse.AuthorizationID); //Selenium Test Case responseParams.Add("Acknowledgement", doVoidResponse.Ack.ToString()); } } public string Refund(string transactionId,string amount,string currencyCode) { // Create request object RefundTransactionRequestType request = new RefundTransactionRequestType(); request.TransactionID = transactionId; request.RefundType = (RefundType) Enum.Parse(typeof(RefundType), "FULL"); // (Optional) Refund amount. The amount is required if RefundType is Partial. // Note: If RefundType is Full, do not set the amount. if (request.RefundType.Equals(RefundType.PARTIAL) && amount != string.Empty) { CurrencyCodeType currency = (CurrencyCodeType) Enum.Parse(typeof(CurrencyCodeType), currencyCode); request.Amount = new BasicAmountType(currency, amount); } // Invoke the API RefundTransactionReq wrapper = new RefundTransactionReq(); wrapper.RefundTransactionRequest = request; Dictionary<string, string> configurationMap = confiugraion.GetAcctAndConfig(); // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); // # API call // Invoke the RefundTransaction method in service wrapper object RefundTransactionResponseType refundTransactionResponse = service.RefundTransaction(wrapper); // Check for API return status string response= processResponse(service, refundTransactionResponse); return response; } private string processResponse(PayPalAPIInterfaceServiceService service, RefundTransactionResponseType response) { HttpContext CurrContext = HttpContext.Current; CurrContext.Items.Add("Response_apiName", "RefundTransaction"); CurrContext.Items.Add("Response_redirectURL", null); CurrContext.Items.Add("Response_requestPayload", service.getLastRequest()); CurrContext.Items.Add("Response_responsePayload", service.getLastResponse()); Dictionary<string, string> keyParameters = new Dictionary<string, string>(); keyParameters.Add("Correlation Id", response.CorrelationID); keyParameters.Add("API Result", response.Ack.ToString()); if (response.Ack.Equals(AckCodeType.FAILURE) || (response.Errors != null && response.Errors.Count > 0)) { CurrContext.Items.Add("Response_error", response.Errors); } else { CurrContext.Items.Add("Response_error", null); keyParameters.Add("Refund transaction Id", response.RefundTransactionID); keyParameters.Add("Total refunded amount", response.TotalRefundedAmount.value + response.TotalRefundedAmount.currencyID); } CurrContext.Items.Add("Response_keyResponseObject", keyParameters); string message = response.Ack.ToString(); return message; } } }
using UnityEngine; [AddComponentMenu("Hitman GO/Rock")] public class Rock : MonoBehaviour { Waypoint currentWaypoint; void Start() { //get the waypoint where is the rock GetCurrentWaypoint(); //add to objects on waypoint currentWaypoint.AddObjectToWaypoint(this.gameObject); } void GetCurrentWaypoint() { //find current waypoint with a raycast to the down RaycastHit hit; Physics.Raycast(this.transform.position + Vector3.up, Vector3.down, out hit); currentWaypoint = hit.transform.gameObject.GetComponent<Waypoint>(); } }
using Bomberman.Api; using Bomberman.Logic.Extensions; using Bomberman.Logic.Handlers.Facade; using System; using System.Collections.Generic; using System.Linq; namespace Bomberman.Logic.Handlers { internal class BlastHandler : AbstractHandler<BlastHandler> { private int[,] _timeToBoom; private bool[,] _isMyBoom; internal int WillNotExploded => int.MaxValue; private BlastHandler() { } internal override void HandleCondition(Board condition) { base.HandleCondition(condition); HandleAllBombs(condition); } internal int GetTimeToBoom(Point point) => _timeToBoom[point.X, point.Y]; internal bool IsMyBoom(Point point) => _isMyBoom[point.X, point.Y]; private void HandleAllBombs(Board condition) { ICollection<Point> bombs = condition.GetBombs(); Dictionary<Point, bool> used = bombs.ToDictionary(x => x, x => false); foreach (var bomb in bombs) { if (used[bomb]) continue; int timeToBoom = WillNotExploded; HashSet<Point> affectedPoints = new HashSet<Point>(); bool isMyBoom = false; timeToBoom = HandleBomb(condition, bomb, affectedPoints, used, timeToBoom, ref isMyBoom); foreach (var p in affectedPoints) { if (timeToBoom < _timeToBoom[p.X, p.Y]) { _timeToBoom[p.X, p.Y] = timeToBoom; _isMyBoom[p.X, p.Y] = isMyBoom; } else if (timeToBoom == _timeToBoom[p.X, p.Y]) { _isMyBoom[p.X, p.Y] = isMyBoom || _isMyBoom[p.X, p.Y]; // mb synchronous boom with another player } } } } private int HandleBomb(Board condition, Point bomb, HashSet<Point> affectedPoints, Dictionary<Point, bool> used, int timeToBoom, ref bool isMyBoom) { used[bomb] = true; affectedPoints.Add(bomb); int ttb = GetTimeToBoom(condition, bomb); if (ttb < timeToBoom) { timeToBoom = ttb; isMyBoom = HandlersFacade.MyBombs.Contains(bomb); } else if (ttb == timeToBoom) { isMyBoom = isMyBoom || HandlersFacade.MyBombs.Contains(bomb); // mb synchronous boom with another player } foreach (Move direction in new Move[] { Move.Left, Move.Right, Move.Up, Move.Down }) checkDirection(direction, ref isMyBoom); void checkDirection(Move direction, ref bool isMB) { Point p = bomb; for (int i = 0; i < Parameters.BlastRadius; i++) { p = p.Shift(direction); affectedPoints.Add(p); if (Utils.IsActiveBomb(condition.GetAt(p))) if (!used[p]) timeToBoom = Math.Min(timeToBoom, HandleBomb(condition, p, affectedPoints, used, timeToBoom, ref isMB)); if (condition.GetAt(p) == Element.WALL || condition.GetAt(p) == Element.DESTROYABLE_WALL) break; } } return timeToBoom; } private int GetTimeToBoom(Board board, Point bombPoint) { switch (board.GetAt(bombPoint)) { case Element.BOMB_TIMER_1: return 1; case Element.BOMB_TIMER_2: return 2; case Element.BOMB_TIMER_3: return 3; case Element.BOMB_TIMER_4: return 4; case Element.BOMB_TIMER_5: return 5; case Element.BOMB_BOMBERMAN: return 4; // TODO: calc that case Element.OTHER_BOMB_BOMBERMAN: return 4; // TODO: calc that default: throw new ArgumentException("Invalid bomb type"); } } protected override void Reset() { for (int i = 0; i < MapSize; i++) for (int j = 0; j < MapSize; j++) { _timeToBoom[i, j] = WillNotExploded; _isMyBoom[i, j] = false; } } internal override void Init(int size) { base.Init(size); _timeToBoom = new int[size, size]; _isMyBoom = new bool[size, size]; } } }
using Godot; using System; public class PlayerController : Spatial { private Vector3 torque; private float mouseSensitivity = 0.2f; private RayCast aimingRay; private Spatial aimingSight; private PhysicalEntity target; // Called when the node enters the scene tree for the first time. public override void _Ready() { aimingRay = GetNode<RayCast>("AimingRay"); aimingSight = GetNode<Spatial>("AimingSight"); } public PhysicalEntity get_object_under_mouse() { var mouse_pos = GetViewport().GetMousePosition(); var camera = GetViewport().GetCamera(); var ray_from = camera.ProjectRayOrigin(mouse_pos); var ray_to = ray_from + camera.ProjectRayNormal(mouse_pos) * 10000.0f; var space_state = GetWorld().DirectSpaceState; var selection = space_state.IntersectRay(ray_from, ray_to); try { return (selection["collider"] as PhysicalEntity); } catch {} return null; } public override void _Input(InputEvent ev) { if (Input.GetMouseMode() == Input.MouseMode.Captured) { if (ev is InputEventMouseMotion) { var mouseEvent = (InputEventMouseMotion)ev; torque = torque + new Vector3( mouseEvent.Relative.y * -mouseSensitivity, mouseEvent.Relative.x * -mouseSensitivity, 0 ); } } } public override void _PhysicsProcess(float delta) { Node parent = GetParent(); if (aimingRay.IsColliding()) { Vector3 cpoint = ToLocal(aimingRay.GetCollisionPoint()); aimingSight.Translation = cpoint; aimingSight.Visible = true; } else { aimingSight.Visible = false; } if (parent != null) { PhysicalEntity entity = (PhysicalEntity)parent; Vector3 force = new Vector3(0,0,0); if (Input.IsActionJustPressed("fire")) { var ent = get_object_under_mouse(); if (IsInstanceValid(ent)) { if (IsInstanceValid(target)) { target.Deselect(); } target = ent; target.Select(); (GetParent() as PhysicalEntity).LockOn(ent); } else { (GetParent() as PhysicalEntity).LockOn(null); if (IsInstanceValid(target)) { target.Deselect(); } target = null; } } if (target != null) { entity.Engage(); } if (Input.IsActionPressed("fire")) { entity.Engage(); } if (Input.IsActionPressed("move_forward")) { force.z += 1; } if (Input.IsActionPressed("move_backward")) { force.z += -1; } if (Input.IsActionPressed("move_left")) { force.x += 1; } if (Input.IsActionPressed("move_right")) { force.x += -1; } entity.boost(force); if (Input.IsActionPressed("rotate_left")) { torque.z += -1; } if (Input.IsActionPressed("rotate_right")) { torque.z += 1; } Vector3 ret = torque; torque = new Vector3(); entity.turn(ret); } } private void _on_AimingThing_area_entered(object area) { Area a = area as Area; if (a != null) { a.Visible = true; var tar = a.GetParent() as AI_Controller; if (tar != null) (GetParent() as PhysicalEntity).LockOn(tar.GetEntity()); } } private void _on_AimingThing_area_exited(object area) { Area a = area as Area; if (a != null) { a.Visible = false; } } }
 using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace FIT5032_wefit.Models { public enum ReservationStatus { PENDING, ACCEPTED, DECLINED, CANCELLED } public class Reservation { [Key] public int Id { get; set; } public ReservationStatus Status { get; set; } public DateTime Date { get; set; } public virtual ApplicationUser User { get; set; } public virtual Event Event { get; set; } } }
using EscuelasDeportivas.Models; using FreshMvvm; using PropertyChanged; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; namespace EscuelasDeportivas.ViewModels { [ImplementPropertyChanged] public class DetalleDeporteViewModel : FreshBasePageModel { public Deporte Deporte { get; set; } public DetalleDeporteViewModel() { } public override void Init(object initData) { base.Init(initData); Deporte = initData as Deporte; } public ICommand EditCommand { get { return new Command(async () => { await CoreMethods.PushPageModel<EditarDeporteViewModel>(Deporte); }); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Platformer.Mechanics; public class CameraSet : MonoBehaviour { GameObject donut; public GameObject mainCamera; public GameObject bossCamera; void Start() { donut = GameObject.Find("Donut"); if(donut != null) mainCamera = donut.GetComponent<CharacterSwapping>().mainCamera.gameObject; } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.tag == "Player") { mainCamera.SetActive(false); bossCamera.SetActive(true); } } void OnTriggerExit2D(Collider2D other) { if (other.gameObject.tag == "Player") { mainCamera.SetActive(true); bossCamera.SetActive(false); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NewsMooseConsole.Models { public class OutputModel { public int YPosStart { get; set; } public int XPosStart { get; set; } public int Length { get; set; } public string Text { get; set; } } }
using System.Collections.Generic; namespace TrackingServiceAlejo { public interface IDataRepository<TEntity> { IEnumerable<TEntity> GetAll(); TEntity Get(long id); void Add(TEntity entity); void AddRange(IEnumerable<TEntity> entities); } }
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. // VisualNovelToolkit /_/_/_/_/_/_/_/_/_/. // Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/. //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. using UnityEditor; using UnityEngine; using System.IO; namespace ViNoToolkit{ public class ADVCreateWizard : EditorWindow { public string projectFolderName = "New ADV Project"; public string firstScenarioName = "1"; public Texture2D titleBGTexture; private string scenePath = ""; [MenuItem ("ViNo/Create ADV")] static void CreateWizard () { GetWindow( typeof(ADVCreateWizard) ); } void OnGUI (){ EditorGUILayout.BeginHorizontal(); { titleBGTexture = EditorGUILayout.ObjectField( titleBGTexture , typeof(Texture2D) , false , GUILayout.Width( 128f ) , GUILayout.Height( 128f ) ) as Texture2D ; EditorGUILayout.BeginVertical(); { EditorGUILayout.LabelField( "Title BG"); projectFolderName = EditorGUILayout.TextField( "Project Folder Name" , projectFolderName ); firstScenarioName = EditorGUILayout.TextField( "First Scenario Name" , firstScenarioName ); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.HelpBox( "Project folder is created under Assets folder." , MessageType.Info ); EditorGUILayout.BeginHorizontal(); { GUILayout.Space( 30f ); if( GUILayout.Button( "Create" ) ){ OnWizardCreate(); } } EditorGUILayout.EndHorizontal(); } void OnWizardCreate () { bool succeeded =EditorApplication.SaveScene (scenePath, true); if ( ! succeeded) { EditorUtility.DisplayDialog ("Note", "Please save scene at first", "OK"); return; } // -------------------------------------------. // Create ADV scene from Templates. // -------------------------------------------. DrawTemplatesTab.CreateAdvScene( "ADV Scene" , projectFolderName ); // -------------------------------------------. // Create folders. // -------------------------------------------. CreateFolders(); // -------------------------------------------. // Create Scenario Script. // -------------------------------------------. CreateScenario(); // -------------------------------------------. // Change Title BG. // -------------------------------------------. ChangeTitleBGMaterial(); // Close this window. Close (); } void CreateFolders(){ // Create Resources folder. if( ! System.IO.Directory.Exists( "Assets/" + projectFolderName + "/Resources" ) ) { AssetDatabase.CreateFolder( "Assets/" + projectFolderName , "/Resources" ); } // Create ScenarioScripts folder. if( ! System.IO.Directory.Exists( "Assets/" + projectFolderName + "/ScenarioScripts" ) ) { AssetDatabase.CreateFolder( "Assets/" + projectFolderName , "ScenarioScripts" ); } // Create Materials folder. if( ! System.IO.Directory.Exists( "Assets/" + projectFolderName + "/Materials" ) ) { AssetDatabase.CreateFolder( "Assets/" + projectFolderName , "Materials" ); } // Create GameInfo folder. if( ! System.IO.Directory.Exists( "Assets/" + projectFolderName + "/GameInfo" ) ) { AssetDatabase.CreateFolder( "Assets/" + projectFolderName , "GameInfo" ); } } void CreateScenario(){ // Create Scenario Object. string filePath = Application.dataPath + "/" + projectFolderName + "/ScenarioScripts/" + firstScenarioName + ".txt"; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append( "*start" ); sb.Append( System.Environment.NewLine ); sb.Append( "[current layer=TextBox]" ); sb.Append( System.Environment.NewLine ); sb.Append( "[enterscene name=Scene1 fade=true]" ); sb.Append( System.Environment.NewLine ); sb.Append( "[enteractor name=Sachi position=left fade=true]" ); sb.Append( System.Environment.NewLine ); sb.Append( "[enteractor name=Yoshino position=right fade=true]" ); sb.Append( System.Environment.NewLine ); sb.Append( "Hello , World ![p]" ); File.WriteAllText( filePath , sb.ToString() ); AssetDatabase.Refresh(); TextAsset script = AssetDatabase.LoadAssetAtPath( "Assets/" + projectFolderName + "/ScenarioScripts/" + firstScenarioName + ".txt" , typeof(TextAsset) ) as TextAsset; GameObject scenarioObj = ViNoToolUtil.CreateANewScenario( firstScenarioName , true , script ); // -------------------------------------------. // Create New Game Info , Flag and SaveInfo. // -------------------------------------------. // Create New Game Info in Project view. string newGameInfoPath = "Assets/" + projectFolderName + "/GameInfo/NewGameInfo.asset"; ViNoSaveInfo newGameInfo = ScriptableObjectUtility.CreateScriptableObject( "ViNoSaveInfo" , newGameInfoPath ) as ViNoSaveInfo; string[] paths = EditorApplication.currentScene.Split(char.Parse("/")); string levelName = paths[paths.Length-1].Split( "."[0] )[0]; newGameInfo.m_LoadedLevelName = levelName; newGameInfo.m_LoadedLevelIndex = 0; newGameInfo.m_CurrentScenarioName = firstScenarioName; // Create Flag and SaveInfo. string scenarioFlagDataPath = "Assets/" + projectFolderName + "/GameInfo/FlagTable.asset"; string scenarioSaveDataPath = "Assets/" + projectFolderName + "/GameInfo/SaveData.asset"; // Create Game Info. ViNoSaveInfo saveInfo = ScriptableObjectUtility.CreateScriptableObject( "ViNoSaveInfo" , scenarioSaveDataPath ) as ViNoSaveInfo; FlagTable flagTable = ScriptableObjectUtility.CreateScriptableObject( "FlagTable" , scenarioFlagDataPath ) as FlagTable; ScenarioNode scenarioNode = scenarioObj.GetComponent<ScenarioNode>(); scenarioNode.m_PlayAtStart = true; scenarioNode.flagTable = flagTable; ViNoEditorUtil.CreatePrefab( scenarioObj , "Assets/" + projectFolderName + "/Resources/" + firstScenarioName + ".prefab" ); ScenarioCtrl scenarioCtrl = GameObject.FindObjectOfType( typeof(ScenarioCtrl) ) as ScenarioCtrl; scenarioCtrl.newGameInfo = newGameInfo; scenarioCtrl.quickSaveSlot = saveInfo; scenarioCtrl.saveInfo = saveInfo; GameObject.DestroyImmediate( scenarioObj ); } void ChangeTitleBGMaterial(){ Material material = new Material (Shader.Find( "Unlit/UnlitAlphaWithFade" )); material.mainTexture = titleBGTexture; AssetDatabase.CreateAsset(material , "Assets/" + projectFolderName + "/Materials/Title.mat"); GameObject titleBG = GameObject.Find( "Panel_Title/Background"); MeshRenderer ren = titleBG.GetComponent<MeshRenderer>(); ren.sharedMaterial = material; } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("AndroidDeviceSettings")] public class AndroidDeviceSettings : MonoClass { public AndroidDeviceSettings(IntPtr address) : this(address, "AndroidDeviceSettings") { } public AndroidDeviceSettings(IntPtr address, string className) : base(address, className) { } public static AndroidDeviceSettings Get() { return MonoClass.smethod_15<AndroidDeviceSettings>(TritonHs.MainAssemblyPath, "", "AndroidDeviceSettings", "Get", Array.Empty<object>()); } public static bool IsCurrentTextureFormatSupported() { return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "AndroidDeviceSettings", "IsCurrentTextureFormatSupported", Array.Empty<object>()); } public bool IsMusicPlaying() { return base.method_11<bool>("IsMusicPlaying", Array.Empty<object>()); } public string applicationStorageFolder { get { return base.method_4("applicationStorageFolder"); } } public float aspectRatio { get { return base.method_2<float>("aspectRatio"); } } public int densityDpi { get { return base.method_2<int>("densityDpi"); } } public float diagonalInches { get { return base.method_2<float>("diagonalInches"); } } public float heightInches { get { return base.method_2<float>("heightInches"); } } public float heightPixels { get { return base.method_2<float>("heightPixels"); } } public bool isExtraLarge { get { return base.method_2<bool>("isExtraLarge"); } } public bool isOnPhoneWhitelist { get { return base.method_2<bool>("isOnPhoneWhitelist"); } } public bool isOnTabletWhitelist { get { return base.method_2<bool>("isOnTabletWhitelist"); } } public int screenLayout { get { return base.method_2<int>("screenLayout"); } } public static int SCREENLAYOUT_SIZE_XLARGE { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AndroidDeviceSettings", "SCREENLAYOUT_SIZE_XLARGE"); } } public float widthInches { get { return base.method_2<float>("widthInches"); } } public float widthPixels { get { return base.method_2<float>("widthPixels"); } } public float xdpi { get { return base.method_2<float>("xdpi"); } } public float ydpi { get { return base.method_2<float>("ydpi"); } } } }
using RubikCube.Draws; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RubikCube { class Animation { private List<Cube> animationCubes; public bool AnimationEnded; private RubikCubeMoviment moviment; int leftDegree; public Animation(List<Cube> animationCubes, int degree, RubikCubeMoviment moviment){ this.animationCubes = animationCubes; this.leftDegree = degree; this.moviment = moviment; this.AnimationEnded = false; } public void Animate(){ int rotateFactor = 10; if (moviment.Axis == Axis.X){ if(moviment.Spin == Spin.Clockwise){ rotateFactor = -rotateFactor; } foreach (var item in animationCubes){ item.Rotate(rotateFactor, 0, 0); } } if (moviment.Axis == Axis.Y){ if (moviment.Spin == Spin.Clockwise){ rotateFactor = -rotateFactor; } foreach (var item in animationCubes){ item.Rotate(0, rotateFactor, 0); } } if (moviment.Axis == Axis.Z){ if (moviment.Spin == Spin.Clockwise){ rotateFactor = -rotateFactor; } foreach (var item in animationCubes){ item.Rotate(0, 0, rotateFactor); } } leftDegree -= Math.Abs(rotateFactor); if (leftDegree <= 0){ this.AnimationEnded = true; this.Place(); } } public void Place(){ foreach (var item in animationCubes){ item.Place(moviment); } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; namespace CreateGist.Helpers { public static class HttpHelper { public static Dictionary<string, object> Get(string uri, string authorizationHeader = null) { var request = WebRequest.Create(uri); if (authorizationHeader != null) { request.Headers[HttpRequestHeader.Authorization] = authorizationHeader; } using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var body = reader.ReadToEnd(); return JsonConvert.DeserializeObject<Dictionary<string, object>>(body); } } public static string Post(string uri, object data, string authorizationHeader = null) { var request = WebRequest.Create(uri); request.Method = "POST"; var postData = JsonConvert.SerializeObject(data); request.ContentLength = postData.Length; request.ContentType = "application/json"; if (authorizationHeader != null) { request.Headers[HttpRequestHeader.Authorization] = authorizationHeader; } using (var requestStream = request.GetRequestStream()) using (var requestWriter = new StreamWriter(requestStream)) { requestWriter.Write(postData); } using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var body = reader.ReadToEnd(); var responseData = JsonConvert.DeserializeObject<Dictionary<string, object>>(body); return (string)responseData["html_url"]; } } } }
using Data; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace _5._15._19 { public class TaskHub : Hub { private string _conn; private TasksRepository _repo; public TaskHub(IConfiguration configuration) { _conn = configuration.GetConnectionString("ConStr"); _repo = new TasksRepository(_conn); } public void NewAssignment(Assignment assignment) { Assignment a = _repo.AddTask(assignment); Clients.All.SendAsync("NewTask", a); } public void AcceptAssignment(Assignment assignment) { Assignment a = _repo.AssignTaskToUser(assignment); Clients.Others.SendAsync("AssignmentGotAccepted", a); Clients.Caller.SendAsync("IAcceptedAssignment", a); } public void FinishedAssignment(Assignment assignment) { _repo.FinishedAssignment(assignment); Clients.All.SendAsync("RemoveFromList", assignment); } } }
using System.Data.Entity; using System.Data.Entity.Infrastructure; using BugsReporter.Data.Migrations; using BugsReporter.Models; namespace BugsReporter.Data { public class BugsDbContext : DbContext, IBugsDbContext { public BugsDbContext() : base("BugsReporter") { Database.SetInitializer(new MigrateDatabaseToLatestVersion<BugsDbContext, Configuration>()); } public virtual IDbSet<Bug> Bugs { get; set; } public IDbSet<T> Set<T>() where T : class { return base.Set<T>(); } public DbEntityEntry<T> Entry<T>(T entity) where T : class { return base.Entry<T>(entity); } public int SaveChanges() { return base.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Navigation.DAL; using Navigation.Helper; using Navigation.Models; namespace Navigation.Areas.Control.Controllers { [AuthAdmin] public class BlogsController : Controller { private NaviContext db = new NaviContext(); // GET: Control/Blogs public ActionResult Index() { return View(db.Blogs.ToList()); } // GET: Control/Blogs/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Blog blog = db.Blogs.Find(id); if (blog == null) { return HttpNotFound(); } return View(blog); } // GET: Control/Blogs/Create public ActionResult Create() { return View(); } // POST: Control/Blogs/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,Orderby,BigPhoto,SmallPhoto,Title,CreateAt,BlogType,Info")] Blog blog,HttpPostedFileBase BigPhoto,HttpPostedFileBase SmallPhoto) { if (BigPhoto == null || SmallPhoto == null) { Session["PhotoError"] = "Şəkil Yükləməmisiniz"; return RedirectToAction("Create", blog); } if (SmallPhoto != null) { string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + SmallPhoto.FileName; string path = Path.Combine(Server.MapPath("~/Public/img/blog"), filename); SmallPhoto.SaveAs(path); blog.SmallPhoto = filename; } if (BigPhoto != null) { string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + BigPhoto.FileName; string path = Path.Combine(Server.MapPath("~/Public/img/blog"), filename); BigPhoto.SaveAs(path); blog.BigPhoto = filename; } if (ModelState.IsValid) { blog.CreateAt=DateTime.Now; db.Blogs.Add(blog); db.SaveChanges(); return RedirectToAction("Index"); } return View(blog); } // GET: Control/Blogs/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Blog blog = db.Blogs.Find(id); if (blog == null) { return HttpNotFound(); } return View(blog); } // POST: Control/Blogs/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Orderby,BigPhoto,SmallPhoto,Title,CreateAt,BlogType,Info")] Blog blog, HttpPostedFileBase BigPhoto, HttpPostedFileBase SmallPhoto) { if (ModelState.IsValid) { db.Entry(blog).State = EntityState.Modified; if (SmallPhoto != null) { string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + SmallPhoto.FileName; string path = Path.Combine(Server.MapPath("~/Public/img/blog"), filename); SmallPhoto.SaveAs(path); blog.SmallPhoto = filename; } else { db.Entry(blog).Property(x => x.SmallPhoto).IsModified = false; } if (BigPhoto != null) { string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + BigPhoto.FileName; string path = Path.Combine(Server.MapPath("~/Public/img/blog"), filename); BigPhoto.SaveAs(path); blog.BigPhoto = filename; } else { db.Entry(blog).Property(x => x.BigPhoto).IsModified = false; } db.SaveChanges(); return RedirectToAction("Index"); } return View(blog); } // GET: Control/Blogs/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Blog blog = db.Blogs.Find(id); if (blog == null) { return HttpNotFound(); } return View(blog); } // POST: Control/Blogs/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Blog blog = db.Blogs.Find(id); db.Blogs.Remove(blog); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using PhotoFrame.Domain.Model; using PhotoFrameApp; using System; using System.Collections.Generic; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; namespace PhotoFrameApp.Tests { [TestClass()] public class SlideShowFormTests { private PhotoFrameForm photoframeform; private SlideShowForm slideshowform; private PrivateObject privateobject; private SoundPlayer player = null; private List<Photo> dummyPhotoList; [TestInitialize] public void SetUp() { dummyPhotoList = new List<Photo>(); slideshowform = new SlideShowForm(dummyPhotoList); privateobject = new PrivateObject(slideshowform); } [TestMethod()] public void 音楽を再生する() { //slideshowform.PlayMusic(); var playmusic = privateobject.Invoke("PlayMusic"); // Assert.AreSame(@"C:\\ミニシステム開発演習.ver2\\PhotoFrameTeamC\\PhotoFrameAppTests\\bin\\Debug\\music.wav", slideshowform.musicFile); } [TestMethod()] public void 音楽を停止する() { var playmusic = privateobject.Invoke("PlayMusic"); System.Threading.Thread.Sleep(2000); var stopmusic = privateobject.Invoke("StopMusic"); } } }
using DataAccess.Mappings; using Entity; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace DataAccess { public class Context : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer( @"Server=database-1.cslmyk6dvzby.us-east-1.rds.amazonaws.com;Initial Catalog=DataUsers;Persist Security Info=False;User ID=admin;Password=12345678;"); } protected override void OnModelCreating(ModelBuilder builder) { builder.ApplyConfiguration(new UserMappings()); } public DbSet<User> Users { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SRP { public class Email : IEmail { public void setSender(String sender) {} public void setReceiver(String receiver) { } public void setContent(String content) {} } }
using UnityEngine; public class BlockerModel : MonoBehaviour { public int blockerTier; public int XpForDestroy { get; set; } }
namespace DocumentationABS.Documentation { public class DocumentFile { public string Name { get; set; } public string Content { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shield : MonoBehaviour { // Start is called before the first frame update public static int idCount = 0; // each shield has a unique ID public GameObject globalOBJ; // global game object public int id; public int remainingHits; void Start() { globalOBJ = GameObject.FindWithTag("Global"); id = idCount; remainingHits = 5; idCount++; } // Update is called once per frame void Update() { } void Break() { globalOBJ.GetComponent<Global>().RemoveShield(this.id); // remove the shield with given id Destroy(gameObject); // Break the shield } public void HitUpdate() { remainingHits--; // Each hit makes the shield shrink if (GetComponent<Renderer>().enabled) { Vector3 scaleChange = new Vector3(-0.4f, 0, 0); gameObject.transform.localScale += scaleChange; } if (remainingHits == 0) { Break(); } } }
using Jieshai.Cache.CacheManagers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Jieshai.Cache { public class CacheContainer { public CacheContainer() { this.CacheManagers = new List<ICacheManager>(); } public List<ICacheManager> CacheManagers { set; get; } public T CreateManager<T>(params object[] args) where T : ICacheManager { T manager = (T)Activator.CreateInstance(typeof(T), args); this.CacheManagers.Add(manager); return manager; } public ICacheManager CreateManagerByCacheType<CacheType>(params object[] args) where CacheType : class { ICacheManager manager = null; Type cacheManagerType = ReflectionHelper.GetSingleSubclass<CacheManager<CacheType>>(this.GetTypes()); if (cacheManagerType != null) { manager = Activator.CreateInstance(cacheManagerType, args) as ICacheManager; this.CacheManagers.Add(manager); } return manager; } protected virtual Type[] GetTypes() { return this.GetType().Assembly.GetExportedTypes(); } public virtual object Get(object key, Type type) { ICacheManager manager = this.GetManager(type); if (manager != null) { return manager.Get(key); } return null; } public bool Contains(Type type) { return this.CacheManagers.Any(l => l.IsCache(type)); } public ICacheManager GetManager(Type type) { return this.CacheManagers.Find(l => l.IsCache(type)); } public CacheManager<T> GetManager<T>() where T : class { return this.GetManager(typeof(T)) as CacheManager<T>; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CSBasic.Tests { [TestClass()] public class EnumDemoTests { [TestMethod()] public void GetOptionsYesValueTest() { //Arrange var handleObj = new EnumDemo(); var expectedValue = 0; //Act var actualValue = (int)EnumDemo.Options.yes; //Assert Assert.AreEqual(expectedValue, actualValue); } [TestMethod()] public void GetOptionsNoValueTest() { //Arrange var handleObj = new EnumDemo(); var expectedValue = 1; //Act var actualValue = (int)EnumDemo.Options.no; //Assert Assert.AreEqual(expectedValue, actualValue); } [TestMethod()] public void GetSuperHeroBatmanValueTest() { //Arrange var handleObj = new EnumDemo(); var expectedValue = 1; //Act var actualValue = (int)EnumDemo.SuperHero.BatMan; //Assert Assert.AreEqual(expectedValue, actualValue); } [TestMethod()] public void GetSuperHeroSupermanValueTest() { //Arrange var handleObj = new EnumDemo(); var expectedValue = 3; //Act var actualValue = (int)EnumDemo.SuperHero.SuperMan; //Assert Assert.AreEqual(expectedValue, actualValue); } } }
/// <summary> /// Scribble.rs Pad namespace /// </summary> namespace ScribblersPad { /// <summary> /// Used to signal when lobby list menu has been shown /// </summary> public delegate void LobbyListMenuShownDelegate(); }
// Copyright (c) .NET Foundation. 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.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Storage; namespace Microsoft.EntityFrameworkCore.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public class ManyToManyLoader<TEntity, TSourceEntity> : ICollectionLoader<TEntity> where TEntity : class where TSourceEntity : class { private readonly ISkipNavigation _skipNavigation; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public ManyToManyLoader(ISkipNavigation skipNavigation) { _skipNavigation = skipNavigation; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void Load(InternalEntityEntry entry) { var keyValues = PrepareForLoad(entry); // Short-circuit for any null key values for perf and because of #6129 if (keyValues != null) { Query(entry.StateManager.Context, keyValues).Load(); } entry.SetIsLoaded(_skipNavigation); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual async Task LoadAsync(InternalEntityEntry entry, CancellationToken cancellationToken = default) { var keyValues = PrepareForLoad(entry); // Short-circuit for any null key values for perf and because of #6129 if (keyValues != null) { await Query(entry.StateManager.Context, keyValues).LoadAsync(cancellationToken).ConfigureAwait(false); } entry.SetIsLoaded(_skipNavigation); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IQueryable<TEntity> Query(InternalEntityEntry entry) { var keyValues = PrepareForLoad(entry); var context = entry.StateManager.Context; // Short-circuit for any null key values for perf and because of #6129 if (keyValues == null) { // Creates an empty Queryable that works with Async. Has to be an EF query because it could be used in a composition. var queryRoot = _skipNavigation.TargetEntityType.HasSharedClrType ? context.Set<TEntity>(_skipNavigation.TargetEntityType.Name) : context.Set<TEntity>(); return queryRoot.Where(e => false); } return Query(context, keyValues); } private object[]? PrepareForLoad(InternalEntityEntry entry) { if (entry.EntityState == EntityState.Detached) { throw new InvalidOperationException(CoreStrings.CannotLoadDetached(_skipNavigation.Name, entry.EntityType.DisplayName())); } var properties = _skipNavigation.ForeignKey.PrincipalKey.Properties; var values = new object[properties.Count]; for (var i = 0; i < values.Length; i++) { var value = entry[properties[i]]; if (value == null) { return null; } values[i] = value; } return values; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IQueryable ICollectionLoader.Query(InternalEntityEntry entry) => Query(entry); private IQueryable<TEntity> Query( DbContext context, object[] keyValues) { var loadProperties = _skipNavigation.ForeignKey.PrincipalKey.Properties; // Example of query being built: // // IQueryable<EntityTwo> loaded // = context.Set<EntityOne>() // .AsTracking() // .Where(e => e.Id == left.Id) // .SelectMany(e => e.TwoSkip) // .NotQuiteInclude(e => e.OneSkip.Where(e => e.Id == left.Id)); var queryRoot = _skipNavigation.DeclaringEntityType.HasSharedClrType ? context.Set<TSourceEntity>(_skipNavigation.DeclaringEntityType.Name) : context.Set<TSourceEntity>(); return queryRoot .AsTracking() .Where(BuildWhereLambda(loadProperties, new ValueBuffer(keyValues))) .SelectMany(BuildSelectManyLambda(_skipNavigation)) .NotQuiteInclude(BuildIncludeLambda(_skipNavigation.Inverse, loadProperties, new ValueBuffer(keyValues))) .AsQueryable(); } private static Expression<Func<TEntity, IEnumerable<TSourceEntity>>> BuildIncludeLambda( ISkipNavigation skipNavigation, IReadOnlyList<IProperty> keyProperties, ValueBuffer keyValues) { var whereParameter = Expression.Parameter(typeof(TSourceEntity), "e"); var entityParameter = Expression.Parameter(typeof(TEntity), "e"); return Expression.Lambda<Func<TEntity, IEnumerable<TSourceEntity>>>( Expression.Call( EnumerableMethods.Where.MakeGenericMethod(typeof(TSourceEntity)), Expression.MakeMemberAccess( entityParameter, skipNavigation.GetIdentifyingMemberInfo()!), Expression.Lambda<Func<TSourceEntity, bool>>( ExpressionExtensions.BuildPredicate(keyProperties, keyValues, whereParameter), whereParameter)), entityParameter); } private static Expression<Func<TSourceEntity, bool>> BuildWhereLambda( IReadOnlyList<IProperty> keyProperties, ValueBuffer keyValues) { var entityParameter = Expression.Parameter(typeof(TSourceEntity), "e"); return Expression.Lambda<Func<TSourceEntity, bool>>( ExpressionExtensions.BuildPredicate(keyProperties, keyValues, entityParameter), entityParameter); } private static Expression<Func<TSourceEntity, IEnumerable<TEntity>>> BuildSelectManyLambda(INavigationBase navigation) { var entityParameter = Expression.Parameter(typeof(TSourceEntity), "e"); return Expression.Lambda<Func<TSourceEntity, IEnumerable<TEntity>>>( Expression.MakeMemberAccess( entityParameter, navigation.GetIdentifyingMemberInfo()!), entityParameter); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Extension_Methods_Delegates_Lambda_LINQ { public class TimerEventArgs : EventArgs { public TimerEventArgs(int s) { interval = s; } private int interval; public int Interval { get { return interval; } set { interval = value; } } } /// <summary> /// Problem 8.* /// Read in MSDN about the keyword event in C# and how to publish events. /// Re-implement the above using .NET events and following the best practices. /// </summary> class TimerEvents { private int interval; private System.Timers.Timer timer; public event EventHandler<TimerEventArgs> RaiseTimerEvent; public TimerEvents(int seconds) { timer = new System.Timers.Timer(seconds * 1000); interval = seconds; } public void Start() { timer.Start(); timer.Elapsed += timer_Elapsed; } void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { OnRaiseTimerEvent(new TimerEventArgs(interval)); } public void Stop() { timer.Stop(); } protected virtual void OnRaiseTimerEvent(TimerEventArgs e) { EventHandler<TimerEventArgs> handler = RaiseTimerEvent; if (handler != null) { e.Interval = interval; handler(this, e); } } } }
using HandCloud.Backend.Models; using HandCloud.Backend.Repositories; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace HandCloud.Backend.Services { public class CarService : ICarService { private readonly ICarRepository _carRepository; public CarService(ICarRepository carRepository) { _carRepository = carRepository; } public async Task<List<Car>> GetAllAsync() { return await _carRepository.GetAllAsync(); } public async Task<Car> GetAsync(int id) { return await _carRepository.GetAsync(id); } public async Task<Car> AddAsync(Car car) { return await _carRepository.AddAsync(car); } public async Task<Car> UpdateAsync(Car entity) { return await _carRepository.UpdateAsync(entity); } public async Task<Car> DeleteAsync(int id) { return await _carRepository.DeleteAsync(id); } } }
using LuaInterface; using SLua; using System; using System.Collections.Generic; using System.Runtime.Serialization; public class Lua_System_Collections_Generic_Dictionary_2_int_string : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 1) { Dictionary<int, string> o = new Dictionary<int, string>(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (LuaObject.matchType(l, num, 2, typeof(IEqualityComparer<int>))) { IEqualityComparer<int> equalityComparer; LuaObject.checkType<IEqualityComparer<int>>(l, 2, out equalityComparer); Dictionary<int, string> o = new Dictionary<int, string>(equalityComparer); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (LuaObject.matchType(l, num, 2, typeof(IDictionary<int, string>))) { IDictionary<int, string> dictionary; LuaObject.checkType<IDictionary<int, string>>(l, 2, out dictionary); Dictionary<int, string> o = new Dictionary<int, string>(dictionary); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (LuaObject.matchType(l, num, 2, typeof(int))) { int num2; LuaObject.checkType(l, 2, out num2); Dictionary<int, string> o = new Dictionary<int, string>(num2); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (LuaObject.matchType(l, num, 2, typeof(IDictionary<int, string>), typeof(IEqualityComparer<int>))) { IDictionary<int, string> dictionary2; LuaObject.checkType<IDictionary<int, string>>(l, 2, out dictionary2); IEqualityComparer<int> equalityComparer2; LuaObject.checkType<IEqualityComparer<int>>(l, 3, out equalityComparer2); Dictionary<int, string> o = new Dictionary<int, string>(dictionary2, equalityComparer2); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (LuaObject.matchType(l, num, 2, typeof(int), typeof(IEqualityComparer<int>))) { int num3; LuaObject.checkType(l, 2, out num3); IEqualityComparer<int> equalityComparer3; LuaObject.checkType<IEqualityComparer<int>>(l, 3, out equalityComparer3); Dictionary<int, string> o = new Dictionary<int, string>(num3, equalityComparer3); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else { result = LuaObject.error(l, "New object failed."); } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Add(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); int num; LuaObject.checkType(l, 2, out num); string text; LuaObject.checkType(l, 3, out text); dictionary.Add(num, text); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Clear(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); dictionary.Clear(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ContainsKey(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); int num; LuaObject.checkType(l, 2, out num); bool b = dictionary.ContainsKey(num); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ContainsValue(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); bool b = dictionary.ContainsValue(text); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetObjectData(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); SerializationInfo serializationInfo; LuaObject.checkType<SerializationInfo>(l, 2, out serializationInfo); StreamingContext streamingContext; LuaObject.checkValueType<StreamingContext>(l, 3, out streamingContext); dictionary.GetObjectData(serializationInfo, streamingContext); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int OnDeserialization(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); object obj; LuaObject.checkType<object>(l, 2, out obj); dictionary.OnDeserialization(obj); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Remove(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); int num; LuaObject.checkType(l, 2, out num); bool b = dictionary.Remove(num); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int TryGetValue(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); int num; LuaObject.checkType(l, 2, out num); string s; bool b = dictionary.TryGetValue(num, ref s); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); LuaObject.pushValue(l, s); result = 3; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_Count(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, dictionary.get_Count()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_Comparer(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, dictionary.get_Comparer()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_Keys(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, dictionary.get_Keys()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_Values(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, dictionary.get_Values()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int getItem(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); int num; LuaObject.checkType(l, 2, out num); string s = dictionary.get_Item(num); LuaObject.pushValue(l, true); LuaObject.pushValue(l, s); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int setItem(IntPtr l) { int result; try { Dictionary<int, string> dictionary = (Dictionary<int, string>)LuaObject.checkSelf(l); int num; LuaObject.checkType(l, 2, out num); string text; LuaObject.checkType(l, 3, out text); dictionary.set_Item(num, text); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "DictIntStr"); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.Add)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.Clear)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.ContainsKey)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.ContainsValue)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.GetObjectData)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.OnDeserialization)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.Remove)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.TryGetValue)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.getItem)); LuaObject.addMember(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.setItem)); LuaObject.addMember(l, "Count", new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.get_Count), null, true); LuaObject.addMember(l, "Comparer", new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.get_Comparer), null, true); LuaObject.addMember(l, "Keys", new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.get_Keys), null, true); LuaObject.addMember(l, "Values", new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.get_Values), null, true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_System_Collections_Generic_Dictionary_2_int_string.constructor), typeof(Dictionary<int, string>)); } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; public class Tinter { private const float FadeSpeed = 1f; public Color Initial; private Color _delta = Color.black; public Tinter(Color initial) { Initial = initial; } public void Update(float dt) { _delta.r = Math.Max(0, _delta.r - dt * FadeSpeed); _delta.g = Math.Max(0, _delta.g - dt * FadeSpeed); _delta.b = Math.Max(0, _delta.b - dt * FadeSpeed); } public Color GetCurrent() { var c = Initial; c.r += _delta.r; c.g += _delta.g; c.b += _delta.b; return c; } public void Blink(Color color) { _delta.r += color.r; _delta.r = Math.Min(_delta.r, 2f); _delta.g += color.g; _delta.g = Math.Min(_delta.g, 2f); _delta.b += color.b; _delta.b = Math.Min(_delta.b, 2f); } }
// Copyright (C) 2020 Kazuhiro Fujieda <fujieda@users.osdn.me> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using KancolleSniffer.Model; namespace KancolleSniffer.View.MainWindow { public class MissionPanel : PanelWithToolTip, IUpdateTimers { private const int TopMargin = 3; private const int LeftMargin = 2; private const int LabelHeight = 12; private const int LineHeight = 15; private const int Lines = 3; private readonly MissionLabels[] _labels = new MissionLabels[Lines]; private Label _caption; private class MissionLabels { public Label Number { get; set; } public Label Name { get; set; } public Label Params { get; set; } public Label Timer { get; set; } } public UpdateContext Context { private get; set; } public MissionPanel() { BorderStyle = BorderStyle.FixedSingle; for (var i = 0; i < Lines; i++) { var y = TopMargin + i * LineHeight; _labels[i] = new MissionLabels { Number = new Label { Location = new Point(LeftMargin, y), AutoSize = true, Text = "第" + new[] {"二", "三", "四"}[i] }, Params = new Label { Location = new Point(LeftMargin + 54, y), Size = new Size(161, LabelHeight) }, Name = new Label { Location = new Point(LeftMargin + 30, y), Size = new Size(135, LabelHeight) }, Timer = new GrowLeftLabel() { Location = new Point(LeftMargin + 216, y - 2), GrowLeft = true, MinimumSize = new Size(0, LineHeight), TextAlign = ContentAlignment.MiddleLeft } }; } Controls.AddRange(_labels.SelectMany(l => new Control[] {l.Number, l.Params, l.Timer, l.Name}).ToArray()); var timers = _labels.Select(l => l.Timer).ToArray(); SetCursor(timers); SetClickHandler(timers); } public void SetClickHandler(Label caption) { caption.Click += ClickHandler; _caption = caption; } private void SetCursor(IEnumerable<Control> controls) { foreach (var control in controls) control.Cursor = Cursors.Hand; } private void SetClickHandler(IEnumerable<Control> controls) { foreach (var control in controls) control.Click += ClickHandler; } private void ClickHandler(Object sender, EventArgs e) { Context.Config.ShowEndTime ^= TimerKind.Mission; SetCaption(); UpdateTimers(); } public new void Update() { var names = Context.Sniffer.Missions.Select(mission => mission.Name).ToArray(); for (var i = 0; i < Lines; i++) { var fleetParams = Context.Sniffer.Fleets[i + 1].MissionParameter; var inPort = string.IsNullOrEmpty(names[i]); var labels = _labels[i]; labels.Params.Visible = inPort; if (inPort) { labels.Params.BringToFront(); } else { labels.Params.SendToBack(); } labels.Params.Text = fleetParams; labels.Name.Text = names[i]; ToolTip.SetToolTip(labels.Name, inPort ? "" : fleetParams); } SetCaption(); } private void SetCaption() { _caption.Text = (Context.Config.ShowEndTime & TimerKind.Mission) != 0 ? "遠征終了" : "遠征"; } public void UpdateTimers() { var now = Context.GetStep().Now; var showEndTime = (Context.Config.ShowEndTime & TimerKind.Mission) != 0; for (var i = 0; i < Lines; i++) { var entry = Context.Sniffer.Missions[i]; SetTimerColor(_labels[i].Timer, entry.Timer, now); _labels[i].Timer.Text = entry.Timer.ToString(now, showEndTime); } } private void SetTimerColor(Label label, AlarmTimer timer, DateTime now) { label.ForeColor = timer.IsFinished(now) ? CUDColors.Red : Color.Black; } } }
using Microsoft.Xaml.Behaviors; using MultiCommentCollector.Extensions; using System.Collections.Specialized; using System.Windows.Controls; namespace MultiCommentCollector.Behavior { public class ListViewBehavior : Behavior<ListView> { private ScrollViewer scrollViewer; public int AutoResizeToItemColmunNumber { get; set; } = -1; protected override void OnAttached() { base.OnAttached(); (AssociatedObject.Items as INotifyCollectionChanged).CollectionChanged += CollectionChanged; } protected override void OnDetaching() { base.OnDetaching(); (AssociatedObject.Items as INotifyCollectionChanged).CollectionChanged -= CollectionChanged; } private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (scrollViewer is null) { scrollViewer = AssociatedObject.FindElement<ScrollViewer>(); if (scrollViewer is not null) { scrollViewer.ScrollChanged += ScrollViewer_ScrollChanged; } } if (e.Action == NotifyCollectionChangedAction.Add) { if (scrollToEnd) { scrollViewer.ScrollToEnd(); if (AutoResizeToItemColmunNumber > -1) { var view = AssociatedObject.View as GridView; view.Columns[AutoResizeToItemColmunNumber].Width = 0; view.Columns[AutoResizeToItemColmunNumber].Width = double.NaN; } } } } private bool scrollToEnd = false; private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e) { if (scrollViewer.ScrollableHeight == scrollViewer.VerticalOffset) { scrollToEnd = true; } else { scrollToEnd = false; } } } }
using MaterialDesignThemes.Wpf; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace PlayFairCiphering { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { [DllImport("C:\\Users\\hp\\source\\repos\\PlayFairCiphering\\Project.dll")] public static extern void Encryption([In]char[] x, int count, [In, Out]char[] y); [DllImport("C:\\Users\\hp\\source\\repos\\PlayFairCiphering\\Project.dll")] public static extern void Decryption([In]char[] x, int count, [In, Out]char[] y); [DllImport("C:\\Users\\hp\\source\\repos\\PlayFairCiphering\\Project.dll")] public static extern void EncryptBouns([In]char[] x, int count, [In, Out]char[] y); [DllImport("C:\\Users\\hp\\source\\repos\\PlayFairCiphering\\Project.dll")] public static extern void DecryptBouns([In]char[] x, int count, [In, Out]char[] y); private static bool encrypt_pfair; private static bool decrypt_pfair; private static bool encrypt_vig; private static bool decrypt_vig; public MainWindow() { InitializeComponent(); } private void MenuButtonMainLeft_Click(object sender, RoutedEventArgs e) { } private void Close_icon(object sender, RoutedEventArgs e) { Close(); } private void MinMax(object sender, RoutedEventArgs e) { Thickness marginThickness = Menu.Margin; if (WindowState != WindowState.Maximized) { this.WindowState = WindowState.Maximized; maxOrMin.Kind = PackIconKind.SquareInc; if (marginThickness.Left == 0) { MenuGrid.Width = 50; DisplayArea.Width = 1330; plntContent.Width = 1373; } else { Menu.Margin = new Thickness(195, 0, 0, 0); MenuGrid.Width = 250; DisplayArea.Width = 1130; plntContent.Width = 1073; } } else { this.WindowState = WindowState.Normal; maxOrMin.Kind = PackIconKind.SquareOutline; if (marginThickness.Left == 0) { Menu.Margin = new Thickness(0, 0, 0, 0); MenuGrid.Width = 50; DisplayArea.Width = 1060; plntContent.Width = 1003; } else { Menu.Margin = new Thickness(145, 0, 0, 0); MenuGrid.Width = 200; DisplayArea.Width = 910; plntContent.Width = 853; } } } private void MiniMiz(object sender, RoutedEventArgs e) { this.WindowState = WindowState.Minimized; } private void ListViewItem_MouseEnter(object sender, MouseEventArgs e) { } private void ListViewItem_Selected(object sender, RoutedEventArgs e) { this.path_file.Visibility = Visibility.Visible; this.Home_page.Visibility = Visibility.Collapsed; this.Theme_page.Visibility = Visibility.Collapsed; this.About_page.Visibility = Visibility.Collapsed; this.help.Visibility = Visibility.Collapsed; encrypt_pfair = true; } private void ListViewItem_Selected_1(object sender, RoutedEventArgs e) { this.path_file.Visibility = Visibility.Visible; this.Home_page.Visibility = Visibility.Collapsed; this.Theme_page.Visibility = Visibility.Collapsed; this.About_page.Visibility = Visibility.Collapsed; this.help.Visibility = Visibility.Collapsed; decrypt_pfair = true; } private void ListViewItem_Selected_2(object sender, RoutedEventArgs e) { this.path_file.Visibility = Visibility.Visible; this.Home_page.Visibility = Visibility.Collapsed; this.Theme_page.Visibility = Visibility.Collapsed; this.About_page.Visibility = Visibility.Collapsed; this.help.Visibility = Visibility.Collapsed; encrypt_vig = true; } private void ListViewItem_Selected_3(object sender, RoutedEventArgs e) { this.path_file.Visibility = Visibility.Visible; this.Home_page.Visibility = Visibility.Collapsed; this.Theme_page.Visibility = Visibility.Collapsed; this.About_page.Visibility = Visibility.Collapsed; this.help.Visibility = Visibility.Collapsed; decrypt_vig = true; } private void home_fun(object sender, RoutedEventArgs e) { this.Home_page.Visibility = Visibility.Visible; this.Theme_page.Visibility = Visibility.Collapsed; this.path_file.Visibility = Visibility.Collapsed; this.About_page.Visibility = Visibility.Collapsed; this.help.Visibility = Visibility.Collapsed; } private void theme_fun(object sender, RoutedEventArgs e) { this.Theme_page.Visibility = Visibility.Visible; this.Home_page.Visibility = Visibility.Collapsed; this.path_file.Visibility = Visibility.Collapsed; this.About_page.Visibility = Visibility.Collapsed; this.help.Visibility = Visibility.Collapsed; } private void help_fun(object sender, RoutedEventArgs e) { this.Theme_page.Visibility = Visibility.Collapsed; this.Home_page.Visibility = Visibility.Collapsed; this.About_page.Visibility = Visibility.Collapsed; this.help.Visibility = Visibility.Visible; this.path_file.Visibility = Visibility.Collapsed; } private static string pat_f; private void ListViewItem_Selected_4(object sender, RoutedEventArgs e) { MessageBox.Show("op"); FileDialog fileDialog = new OpenFileDialog(); fileDialog.DefaultExt = ".txt"; fileDialog.ShowDialog(); if (fileDialog.FileName != null) { this.path.Text = fileDialog.FileName; pat_f= fileDialog.FileName; } else { MessageBox.Show("no file select"); } } private void ListViewItem_Selected_5(object sender, RoutedEventArgs e) { string outfilename="no file"; try { if (encrypt_pfair && pat_f != null ) { char[] c = pat_f.ToCharArray(); char[] out_f = new char[100]; Encryption(c, c.Length, out_f); outfilename = new string(out_f); MessageBox.Show("path of Message is :"+outfilename); } else if (decrypt_pfair && pat_f != null) { char[] c = pat_f.ToCharArray(); char[] out_f = new char[100]; Decryption(c, c.Length, out_f); outfilename = new string(out_f); MessageBox.Show("path of Message is : " + outfilename); } else if (encrypt_vig && pat_f!=null) { char[] c = pat_f.ToCharArray(); char[] out_f = new char[100]; EncryptBouns(c, c.Length, out_f); outfilename = new string(out_f); MessageBox.Show("path of Message is : " + outfilename); } else if (decrypt_vig && pat_f!=null) { char[] c = pat_f.ToCharArray(); char[] out_f = new char[100]; DecryptBouns(c, c.Length, out_f); outfilename = new string(out_f); MessageBox.Show("path of Message is : " + outfilename); } } catch (DivideByZeroException e1) { MessageBox.Show(outfilename); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void ListViewItem_Selected_6(object sender, RoutedEventArgs e) { this.Left_side.Background = new SolidColorBrush(Colors.Black); } private void ListViewItem_Selected_7(object sender, RoutedEventArgs e) { this.Left_side.Background = new SolidColorBrush(Colors.CadetBlue); } private void ListViewItem_Selected_8(object sender, RoutedEventArgs e) { this.Left_side.Background = new SolidColorBrush(Colors.DarkCyan); } private void ListViewItem_Selected_9(object sender, RoutedEventArgs e) { this.Left_side.Background = new SolidColorBrush(Colors.DarkTurquoise); } private void ListViewItem_Selected_10(object sender, RoutedEventArgs e) { this.Left_side.Background = new SolidColorBrush(Colors.DarkSlateGray); } private void ListViewItem_Selected_11(object sender, RoutedEventArgs e) { this.Left_side.Background = new SolidColorBrush(Colors.BurlyWood); } private void ListViewItem_Selected_12(object sender, RoutedEventArgs e) { this.Left_side.Background = new SolidColorBrush(Colors.Lavender); } private void ListViewItem_Selected_13(object sender, RoutedEventArgs e) { this.Left_side.Background = new SolidColorBrush(Colors.Khaki); } private void about_fun(object sender, RoutedEventArgs e) { this.Theme_page.Visibility = Visibility.Collapsed; this.Home_page.Visibility = Visibility.Collapsed; this.About_page.Visibility = Visibility.Visible; this.help.Visibility = Visibility.Collapsed; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using DinoDiner.Menu; namespace PointOfSale { /// <summary> /// Interaction logic for EntreeSelection.xaml /// </summary> public partial class EntreeSelection : Page { //backing property public Entree Entree { get; set; } public EntreeSelection() { InitializeComponent(); } public EntreeSelection(Entree entree) { InitializeComponent(); this.Entree = entree; } private void SelectEntree(Entree e) { if (DataContext is Order order) { order.Add(e); this.Entree = e; } } private void BrontowurstClicked(object sender, RoutedEventArgs e) { Brontowurst bronto = new Brontowurst(); SelectEntree(bronto); NavigationService.Navigate(new BrontowurstCustomizer(bronto)); } private void DinoNugsClicked(object sender, RoutedEventArgs e) { DinoNuggets nugs = new DinoNuggets(); SelectEntree(nugs); NavigationService.Navigate(new DinoNuggetsCustomizer(nugs)); } private void PBJClicked(object sender, RoutedEventArgs e) { PrehistoricPBJ pbj = new PrehistoricPBJ(); SelectEntree(pbj); NavigationService.Navigate(new PrehistoricPBJCustomizer(pbj)); } private void WingsClicked(object sender, RoutedEventArgs e) { SelectEntree(new PterodactylWings()); NavigationService.Navigate(new MenuCategorySelection()); } private void SteakosaurusClicked(object sender, RoutedEventArgs e) { SteakosaurusBurger steak = new SteakosaurusBurger(); SelectEntree(steak); NavigationService.Navigate(new SteakosaurusCustomizer(steak)); } private void TRexClicked(object sender, RoutedEventArgs e) { TRexKingBurger rex = new TRexKingBurger(); SelectEntree(rex); NavigationService.Navigate(new TRexCustomizer(rex)); } private void VelociwrapClicked(object sender, RoutedEventArgs e) { VelociWrap wrap = new VelociWrap(); SelectEntree(wrap); NavigationService.Navigate(new VelociwrapCustomizer(wrap)); } private void DoneClicked(object sender, RoutedEventArgs args) { NavigationService.Navigate(new MenuCategorySelection()); } } }
using System; using System.Threading; using System.Threading.Tasks; using Dapper; using FluentValidation; using MediatR; using Npgsql; namespace DDDSouthWest.Domain.Features.Account.Admin.ManageEvents.CreateNewEvent { public class CreateNewEvent { public class Command : IRequest<Response> { public string EventName { get; set; } public string EventFilename { get; set; } public DateTime EventDate { get; set; } } public class Handler : IRequestHandler<Command, Response> { private readonly CreateNewEventValidator _validator; private readonly ClientConfigurationOptions _options; public Handler(CreateNewEventValidator validator, ClientConfigurationOptions options) { _validator = validator; _options = options; } public async Task<Response> Handle(Command message, CancellationToken cancellationToken) { _validator.ValidateAndThrow(message); int eventId; using (var connection = new NpgsqlConnection(_options.Database.ConnectionString)) { const string createEventSql = "INSERT INTO events (EventName, EventFilename) Values (@EventName, @EventFilename) RETURNING Id"; eventId = await connection.QuerySingleAsync<int>(createEventSql, message); } return new Response { Id = eventId }; } } public class Response { public int Id { get; set; } } } }
using System.IO; using System.Text; namespace ZiZhuJY.Common.Services { public class BackupService { public const string BackupFolderName = "Backup"; public static string GetBackupDirectory() { return Path.Combine(Directory.GetCurrentDirectory(), BackupFolderName); } public static string GetBackupFullName(string fileName) { return Path.Combine(GetBackupDirectory(), fileName); } public static void SaveTextBackup(string fileName, string fileContent, Encoding encoding) { var fileFullName = GetBackupFullName(fileName); var directory = Path.GetDirectoryName(fileFullName); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(fileFullName, fileContent, encoding); } public static void SaveTextBackup(string fileName, string fileContent) { SaveTextBackup(fileName, fileContent, Encoding.UTF8); } public static string ReadTextBackup(string fileName, Encoding encoding) { var fileFullName = GetBackupFullName(fileName); return File.ReadAllText(fileFullName, encoding); } public static string ReadTextBackup(string fileName) { return ReadTextBackup(fileName, Encoding.UTF8); } public static void SaveBinaryBackup(string fileName, byte[] contents) { var fileFullName = GetBackupFullName(fileName); var directory = Path.GetDirectoryName(fileFullName); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllBytes(fileFullName, contents); } public static byte[] ReadBinaryBackup(string fileName) { var fileFullName = GetBackupFullName(fileName); return File.ReadAllBytes(fileFullName); } } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class TransporterReport : System.Web.UI.Page { DataSet ds = new DataSet(); BizConnectTransporter obj_class = new BizConnectTransporter(); string obj_Authenticated; PlaceHolder maPlaceHolder; UserControl obj_Tabs; UserControl obj_LoginCtrl; UserControl obj_WelcomCtrl; UserControl obj_Navi; UserControl obj_Navihome; protected void Page_Load(object sender, EventArgs e) { if (Session["UserID"] != string.Empty && Convert.ToInt32(Session["UserID"].ToString()) > 0) { if (!IsPostBack) { ChkAuthentication(); GetTruckType(); GetUnits(); gridbind(0, 0, 0, 0); } } else { Response.Redirect("Index.html"); } } public void GetTruckType() { ds = new DataSet(); ds = obj_class.Get_TruckType(); DDLTruckType.DataTextField = "TruckType"; DDLTruckType.DataValueField = "TruckTypeID"; DDLTruckType.DataSource = ds; DDLTruckType.DataBind(); DDLTruckType.Items.Insert(0, "-All Trucks-"); } public void GetUnits() { ds = new DataSet(); ds = obj_class.Get_Units(); DDLCapacity.DataTextField = "Capacity"; DDLCapacity.DataValueField = "TruckCapacity"; DDLCapacity.DataSource = ds; DDLCapacity.DataBind(); DDLCapacity.Items.Insert(0, "-All Units-"); } public void gridbind(int Type, int EnclType, int TruckType, int Capacity) { try { string FromLoc = ""; string ToLoc = ""; string Distance = ""; DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add("transporter"); dt.Columns.Add("trucktype"); dt.Columns.Add("encltype"); dt.Columns.Add("capacity"); dt.Columns.Add("quotedprice"); dt.Columns.Add("decideprice"); dt.Columns.Add("savings"); dt.Columns.Add("client"); dt.Columns.Add("Tcode"); dt.Columns.Add("Fromloc"); dt.Columns.Add("Toloc"); dt.Columns.Add("Distance"); ds = obj_class.get_RoutePriceReport(Type, EnclType, TruckType, Capacity); for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { if (FromLoc != ds.Tables[0].Rows[i].ItemArray[0].ToString() || ToLoc != ds.Tables[0].Rows[i].ItemArray[1].ToString()) { FromLoc = ds.Tables[0].Rows[i].ItemArray[0].ToString(); ToLoc = ds.Tables[0].Rows[i].ItemArray[1].ToString(); Distance = ds.Tables[0].Rows[i].ItemArray[11].ToString(); dr = dt.NewRow(); dr[0] = ds.Tables[0].Rows[i].ItemArray[0].ToString() + " - " + ds.Tables[0].Rows[i].ItemArray[1].ToString() + "-" + ds.Tables[0].Rows[i].ItemArray[11].ToString() + " Km"; dt.Rows.Add(dr); //goto x; } dr = dt.NewRow(); dr[0] = ds.Tables[0].Rows[i].ItemArray[2].ToString(); dr[1] = ds.Tables[0].Rows[i].ItemArray[3].ToString(); dr[2] = ds.Tables[0].Rows[i].ItemArray[4].ToString(); dr[3] = ds.Tables[0].Rows[i].ItemArray[5].ToString(); dr[4] = ds.Tables[0].Rows[i].ItemArray[6].ToString(); dr[5] = ds.Tables[0].Rows[i].ItemArray[7].ToString(); dr[6] = ds.Tables[0].Rows[i].ItemArray[8].ToString(); dr[7] = ds.Tables[0].Rows[i].ItemArray[9].ToString(); dr[8] = ds.Tables[0].Rows[i].ItemArray[10].ToString(); dr[9] = ds.Tables[0].Rows[i].ItemArray[0].ToString(); dr[10] = ds.Tables[0].Rows[i].ItemArray[1].ToString(); dr[11] = ds.Tables[0].Rows[i].ItemArray[11].ToString(); dt.Rows.Add(dr); } GridRouteprice.DataSource = dt; GridRouteprice.Columns[9].Visible = false; GridRouteprice.Columns[10].Visible = false; GridRouteprice.Columns[11].Visible = false; GridRouteprice.DataBind(); } catch (Exception ex) { } } protected void GridRouteprice_RowDataBound(Object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { { if (e.Row.Cells[2].Text == "&nbsp;") { e.Row.Cells[1].ForeColor = System.Drawing.Color.Red; e.Row.Cells[1].Font.Bold = true; } } } } public void ChkAuthentication() { obj_LoginCtrl = null; obj_WelcomCtrl = null; obj_Navi = null; obj_Navihome = null; if (Session["Authenticated"] == null) { Session["Authenticated"] = "0"; } else { obj_Authenticated = Session["Authenticated"].ToString(); } maPlaceHolder = (PlaceHolder)Master.FindControl("P1"); if (maPlaceHolder != null) { obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1"); if (obj_Tabs != null) { obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1"); obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1"); // obj_Navi = (UserControl)obj_Tabs.FindControl("Navii"); //obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1"); if (obj_LoginCtrl != null & obj_WelcomCtrl != null) { if (obj_Authenticated == "1") { SetVisualON(); } else { SetVisualOFF(); } } } else { } } else { } } public void SetVisualON() { obj_LoginCtrl.Visible = false; obj_WelcomCtrl.Visible = true; //obj_Navi.Visible = true; //obj_Navihome.Visible = true; } public void SetVisualOFF() { obj_LoginCtrl.Visible = true; obj_WelcomCtrl.Visible = false; // obj_Navi.Visible = true; //obj_Navihome.Visible = false; } protected void ButSearch_Click(object sender, EventArgs e) { if ((DDLEnclType.SelectedIndex == 0) && (DDLTruckType.SelectedIndex == 0) && (DDLCapacity.SelectedIndex == 0)) { gridbind(0, 0, 0, 0); } else if ((DDLEnclType.SelectedIndex > 0) && (DDLTruckType.SelectedIndex == 0) && (DDLCapacity.SelectedIndex == 0)) { gridbind(1, Convert.ToInt32(DDLEnclType.SelectedValue), 0, 0); } else if ((DDLEnclType.SelectedIndex == 0) && (DDLTruckType.SelectedIndex > 0) && (DDLCapacity.SelectedIndex == 0)) { gridbind(2, 0, Convert.ToInt32(DDLTruckType.SelectedValue), 0); } else if ((DDLEnclType.SelectedIndex == 0) && (DDLTruckType.SelectedIndex == 0) && (DDLCapacity.SelectedIndex > 0)) { gridbind(3, 0, 0, Convert.ToInt32(DDLCapacity.SelectedValue)); } else if ((DDLEnclType.SelectedIndex > 0) && (DDLTruckType.SelectedIndex > 0) && (DDLCapacity.SelectedIndex == 0)) { gridbind(4, Convert.ToInt32(DDLEnclType.SelectedValue), Convert.ToInt32(DDLTruckType.SelectedValue), 0); } else if ((DDLEnclType.SelectedIndex == 0) && (DDLTruckType.SelectedIndex > 0) && (DDLCapacity.SelectedIndex > 0)) { gridbind(5, 0, Convert.ToInt32(DDLTruckType.SelectedValue), Convert.ToInt32(DDLCapacity.SelectedValue)); } else if ((DDLEnclType.SelectedIndex > 0) && (DDLTruckType.SelectedIndex > 0) && (DDLCapacity.SelectedIndex > 0)) { gridbind(6, Convert.ToInt32(DDLEnclType.SelectedValue), Convert.ToInt32(DDLTruckType.SelectedValue), Convert.ToInt32(DDLCapacity.SelectedValue)); } } protected void ButDownload_Click(object sender, EventArgs e) { GridRouteprice.Columns[9].Visible = true; GridRouteprice.Columns[10].Visible = true; GridRouteprice.Columns[11].Visible = true; ExportGrid(GridRouteprice, "Report.xls"); } public static void ExportGrid(GridView oGrid, string exportFile) { //Clear the response, and set the content type and mark as attachment HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + exportFile + "\""); //Clear the character set HttpContext.Current.Response.Charset = ""; //Create a string and Html writer needed for output System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); //Clear the controls from the pased grid //Show grid lines oGrid.GridLines = GridLines.Both; //Color header oGrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray; //Render the grid to the writer oGrid.RenderControl(oHtmlTextWriter); //Write out the response (file), then end the response HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } }
namespace Contoso.Forms.Configuration.DataForm { public abstract class FormItemSettingsDescriptor { abstract public AbstractControlEnumDescriptor AbstractControlType { get; } } }
namespace Web.ViewModels { public class EmailAddressList { public string EmailAddress { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AttackDragon.Engines { public class CalculationEngine { public void Calculate() { } } }
// // 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 DotNetNuke.ComponentModel; using DotNetNuke.Entities.Icons; namespace DotNetNuke.Services.FileSystem { internal class IconControllerWrapper : ComponentBase<IIconController, IconControllerWrapper>, IIconController { #region Implementation of IIconController public string IconURL(string key) { return IconController.IconURL(key); } public string IconURL(string key, string size) { return IconController.IconURL(key, size); } #endregion } }
namespace Enrollment.Data.Entities { public class User : BaseDataClass { public int UserId { get; set; } public string UserName { get; set; } public Personal Personal { get; set; } public Academic Academic { get; set; } public Admissions Admissions { get; set; } public Certification Certification { get; set; } public ContactInfo ContactInfo { get; set; } public MoreInfo MoreInfo { get; set; } public Residency Residency { get; set; } } }
public abstract class OneDimensional : Shape {}
using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace HT.Framework { [CustomEditor(typeof(ProcedureManager))] [GiteeURL("https://gitee.com/SaiTingHu/HTFramework")] [GithubURL("https://github.com/SaiTingHu/HTFramework")] [CSDNBlogURL("https://wanderer.blog.csdn.net/article/details/86998412")] internal sealed class ProcedureManagerInspector : InternalModuleInspector<ProcedureManager> { private IProcedureHelper _procedureHelper; protected override string Intro { get { return "Procedure Manager, this is the beginning and the end of everything!"; } } protected override Type HelperInterface { get { return typeof(IProcedureHelper); } } protected override void OnRuntimeEnable() { base.OnRuntimeEnable(); _procedureHelper = _helper as IProcedureHelper; } protected override void OnInspectorDefaultGUI() { base.OnInspectorDefaultGUI(); GUILayout.BeginHorizontal(); GUI.enabled = !EditorApplication.isPlaying && Target.DefaultProcedure != ""; GUILayout.Label("Default: " + Target.DefaultProcedure); GUI.enabled = !EditorApplication.isPlaying; GUILayout.FlexibleSpace(); GUI.enabled = !EditorApplication.isPlaying && Target.ActivatedProcedures.Count > 0; if (GUILayout.Button("Set Default", EditorGlobalTools.Styles.MiniPopup)) { GenericMenu gm = new GenericMenu(); for (int i = 0; i < Target.ActivatedProcedures.Count; i++) { int j = i; gm.AddItem(new GUIContent(Target.ActivatedProcedures[j]), Target.DefaultProcedure == Target.ActivatedProcedures[j], () => { Undo.RecordObject(target, "Set Default Procedure"); Target.DefaultProcedure = Target.ActivatedProcedures[j]; HasChanged(); }); } gm.ShowAsContext(); } GUI.enabled = !EditorApplication.isPlaying; GUILayout.EndHorizontal(); GUILayout.BeginVertical(EditorGlobalTools.Styles.Box); GUILayout.BeginHorizontal(); GUILayout.Label("Enabled Procedures:"); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); for (int i = 0; i < Target.ActivatedProcedures.Count; i++) { GUILayout.BeginHorizontal(); GUILayout.Label((i + 1) + "." + Target.ActivatedProcedures[i]); GUILayout.FlexibleSpace(); if (GUILayout.Button("▲", EditorStyles.miniButtonLeft)) { if (i > 0) { Undo.RecordObject(target, "Set Procedure Order"); string procedure = Target.ActivatedProcedures[i]; Target.ActivatedProcedures.RemoveAt(i); Target.ActivatedProcedures.Insert(i - 1, procedure); HasChanged(); continue; } } if (GUILayout.Button("▼", EditorStyles.miniButtonMid)) { if (i < Target.ActivatedProcedures.Count - 1) { Undo.RecordObject(target, "Set Procedure Order"); string procedure = Target.ActivatedProcedures[i]; Target.ActivatedProcedures.RemoveAt(i); Target.ActivatedProcedures.Insert(i + 1, procedure); HasChanged(); continue; } } if (GUILayout.Button("Edit", EditorStyles.miniButtonMid)) { MonoScriptToolkit.OpenMonoScript(Target.ActivatedProcedures[i]); } if (GUILayout.Button("Delete", EditorStyles.miniButtonRight)) { Undo.RecordObject(target, "Delete Procedure"); if (Target.DefaultProcedure == Target.ActivatedProcedures[i]) { Target.DefaultProcedure = ""; } Target.ActivatedProcedures.RemoveAt(i); if (Target.DefaultProcedure == "" && Target.ActivatedProcedures.Count > 0) { Target.DefaultProcedure = Target.ActivatedProcedures[0]; } HasChanged(); } GUILayout.EndHorizontal(); } GUILayout.BeginHorizontal(); if (GUILayout.Button("Add Procedure", EditorGlobalTools.Styles.MiniPopup)) { GenericMenu gm = new GenericMenu(); List<Type> types = ReflectionToolkit.GetTypesInRunTimeAssemblies(type => { return type.IsSubclassOf(typeof(ProcedureBase)) && !type.IsAbstract; }); for (int i = 0; i < types.Count; i++) { int j = i; if (Target.ActivatedProcedures.Contains(types[j].FullName)) { gm.AddDisabledItem(new GUIContent(types[j].FullName)); } else { gm.AddItem(new GUIContent(types[j].FullName), false, () => { Undo.RecordObject(target, "Add Procedure"); Target.ActivatedProcedures.Add(types[j].FullName); if (Target.DefaultProcedure == "") { Target.DefaultProcedure = Target.ActivatedProcedures[0]; } HasChanged(); }); } } gm.ShowAsContext(); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUI.enabled = true; } protected override void OnInspectorRuntimeGUI() { base.OnInspectorRuntimeGUI(); GUILayout.BeginHorizontal(); GUILayout.Label("Current Procedure: " + Target.CurrentProcedure); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Procedures: " + _procedureHelper.Procedures.Count); GUILayout.EndHorizontal(); foreach (var procedure in _procedureHelper.Procedures) { GUILayout.BeginHorizontal(); GUILayout.Space(20); GUILayout.Label(procedure.Key.Name); GUILayout.FlexibleSpace(); GUI.enabled = Target.CurrentProcedure != procedure.Value; if (GUILayout.Button("Switch", EditorStyles.miniButton)) { Target.SwitchProcedure(procedure.Key); } GUI.enabled = true; GUILayout.EndHorizontal(); } } } }
using System; using System.Collections.Generic; namespace Logs.Models { public class TrainingLog { public TrainingLog() { this.Users = new HashSet<User>(); this.LogEntries = new HashSet<LogEntry>(); this.Votes = new HashSet<Vote>(); } public TrainingLog(string name, string description, DateTime dateCreated, User user) : this() { this.Name = name; this.Description = description; this.DateCreated = dateCreated; this.User = user; this.User.TrainingLog = this; this.Owner = user.UserName; this.LastEntryDate = this.DateCreated; this.LastActivityUser = this.User.UserName; } public int LogId { get; set; } public string Description { get; set; } public string Name { get; set; } public string LastActivityUser { get; set; } public DateTime DateCreated { get; set; } public DateTime LastEntryDate { get; set; } public int? LastEntryId { get; set; } public string UserId { get; set; } public string Owner { get; set; } public virtual ICollection<User> Users { get; set; } public virtual User User { get; set; } public virtual ICollection<LogEntry> LogEntries { get; set; } public virtual LogEntry LastLogEntry { get; set; } public virtual ICollection<Vote> Votes { get; set; } public virtual ICollection<Subscription> Subscriptions { get; set; } } }
using Windows.System; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; namespace FourSeafile.UserControls { public sealed partial class PasswordInputDialog { public string Password => PasswordBox.Password; public PasswordInputDialog() { InitializeComponent(); } private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { PasswordBox.Password = string.Empty; } private void Page_KeyDown(object sender, KeyRoutedEventArgs e) { if (e.Key == VirtualKey.Enter) Hide(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab1 { class Program { static string task = "Задача: Даны 5 векторов длины 4 над Z_2. Какой из этих векторов надо удалить, чтобы оставшиеся вектора образовывали векторное пространство?"; static void Main(string[] args) { int n = 0; Console.WriteLine("Программа разработанна для генерирования типовых задач"); Console.WriteLine(task); Console.WriteLine("Какое количество заданий сгенерировать?"); n = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < n; ++i) { algo(); } Console.WriteLine("Генерация заданий завершена!"); Console.ReadLine(); } static void algo() { Random rand = new Random(); string[] vectors = new string[5]; vectors[0] = "0000"; // Без этого, векторное подпространство никогда не сможет быть образовано vectors[1] = checkVector(vectors); vectors[2] = checkVector(vectors); vectors[3] = checkVector(vectors); if (vectors.Contains<String>(sumOfVectors(vectors[1], vectors[2]))) { if (vectors.Contains<String>(sumOfVectors(vectors[2], vectors[3]))) { vectors[4] = checkVector(vectors); } else { vectors[4] = sumOfVectors(vectors[2], vectors[3]); } } else { vectors[4] = sumOfVectors(vectors[1], vectors[2]); } foreach (var item in vectors) { rightAnswer(vectors, item); } foreach (var item in vectors) { Console.WriteLine(item.ToString()); } } static string sumOfVectors(string v1, string v2) { string res = ""; for (int i = 0; i < v1.Length; ++i) { res += sumOfEls(int.Parse(v1[i].ToString()), int.Parse(v2[i].ToString())); } return res; } static int sumOfEls(int e1, int e2) { int res = 0; if (e1 + e2 == 0 || e1 + e2 == 2) res = 0; if (e1 + e2 == 1) res = 1; return res; } static string generateVector(Random rand) { string v = ""; for (int i = 0; i < 4; ++i) { if (rand.Next(0, 2) == 0) v += '0'; else v += '1'; } return v; } static string checkVector(string[] vectors) { Random rand = new Random(); string vector; do { vector = generateVector(rand); } while (vectors.Contains<String>(vector)); return vector; } static void rightAnswer(string[] vectors, string vector) { Console.WriteLine("-----------------"); Console.WriteLine(vector); Console.WriteLine("-----------------"); bool[] results = new bool[5]; int k = 0; for (int i = 0; i < 5; ++i) { results[i] = vectors.Contains<String>(sumOfVectors(vector, vectors[i])); if (!results[i]) k++; Console.WriteLine((i).ToString() + ") " + results[i]); } // Если найден вектор, который можно удалить if (k >= 3) { string fileName = "out.txt"; FileStream aFile = new FileStream(fileName, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(aFile); aFile.Seek(0, SeekOrigin.End); sw.WriteLine(task); // sw.WriteLine(String.Join(", ", vectors)); string[] copy = new string[5]; vectors.CopyTo(copy, 0); //copy[0] = "Никакой"; Random rnd = new Random(); string[] MyRandomArray = copy.OrderBy(x => rnd.Next()).ToArray(); sw.WriteLine(String.Join(", ", MyRandomArray)); for (int i = 0; i < MyRandomArray.Length; ++i) { if (MyRandomArray[i] != vector) sw.WriteLine((i + 1).ToString() + ") " + MyRandomArray[i]); else sw.WriteLine((i + 1).ToString() + ") " + MyRandomArray[i] + " *"); } sw.WriteLine(); sw.Close(); } } } }
using Jieshai.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using log4net; using System.Threading; namespace Jieshai.Cache { public class CacheProviderManager { public CacheProviderManager() { this._lock = new object(); this.CacheProviders = new List<CacheProvider>(); } object _lock; public List<CacheProvider> CacheProviders { private set; get; } protected virtual T CreateCacheProvider<T>() { T cacheProvder = (T)Activator.CreateInstance(typeof(T)); this.CacheProviders.Add(cacheProvder as CacheProvider); return cacheProvder; } private bool IsLoading { set; get; } public void LoadFromNewThread() { Thread realodThread = new Thread(this.Load); realodThread.Start(); } public event TEventHandler<CacheProviderManager> Loading; public event TEventHandler<CacheProviderManager> Loaded; public void Load() { if (this.IsLoading) { return; } try { this.IsLoading = true; if (this.Loading != null) { this.Loading(this); } lock (this._lock) { ConsoleHelper.WriteLine("开始加载数据...."); foreach (CacheProvider dataProvider in this.CacheProviders) { dataProvider.Load(); } } ConsoleHelper.WriteLine("加载完成"); if (this.Loaded != null) { this.Loaded(this); } GC.Collect(); } finally { this.IsLoading = false; } } public CacheProvider GetCacheProvider<CacheType, ModelType>() where ModelType : class where CacheType : class, ICacheRefreshable<CacheType> { return this.CacheProviders.Find(provider => { return provider is CacheProvider; }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief 入力。タッチ。フェイズ。 */ /** NInput */ namespace NInput { /** Touch_Phase */ public class Touch_Phase { /** PhaseType */ public enum PhaseType { /** */ None, /** */ Began, /** */ Moved, /** */ Stationary, }; /** value_x */ public int value_x; /** value_y */ public int value_y; /** 更新。 */ public bool update; /** fadeoutframe */ public int fadeoutframe; /** phasetype */ public PhaseType phasetype; /** raw_id */ public int raw_id; /** pressure */ /* public float pressure; */ /** radius */ /* public float radius; */ /** angle_altitude */ /* public float angle_altitude; */ /** angle_azimuth */ /* public float angle_azimuth; */ /** リセット。 */ public void Reset() { //update this.update = false; //value_x this.value_x = 0; //value_y this.value_y = 0; //fadeoutframe this.fadeoutframe = 0; //phasetype this.phasetype = PhaseType.None; //raw_id this.raw_id = 0; //pressure /* this.pressure = 0.0f; */ //radius /* this.radius = 0.0f; */ //angle_altitude /* this.angle_altitude = 0.0f; */ //angle_azimuth /* this.angle_azimuth = 0.0f; */ } /** 設定。 */ public void Set(int a_value_x,int a_value_y,PhaseType a_phasetype) { //value_x this.value_x = a_value_x; //value_y this.value_y = a_value_y; //phasetype this.phasetype = a_phasetype; } /** RawID。 */ public void SetRawID(int a_raw_id) { this.raw_id = a_raw_id; } /** 圧力。 */ /* public void SetPressure(float a_pressure) { //pressure this.pressure = a_pressure; } */ /** 半径。 */ /* public void SetRadius(float a_radius) { //radius this.radius = a_radius; } */ /** 角度。 */ /* public void SetAngle(float a_angle_altitude,float a_angle_azimuth) { //angle_altitude this.angle_altitude = a_angle_altitude; //angle_azimuth this.angle_azimuth = a_angle_azimuth; } */ /** 更新。 */ public void Main() { } } }
namespace SSW.DataOnion.Interfaces { public interface ISoftDeletableEntity { bool IsDeleted { get; set; } } }
using FacultyV3.Core.Interfaces; using FacultyV3.Core.Interfaces.IServices; using FacultyV3.Core.Models.Entities; using PagedList; using System; using System.Collections.Generic; using System.Linq; using System.Data.Entity; namespace FacultyV3.Core.Services { public class LecturerService : ILecturerService { private IDataContext context; public LecturerService(IDataContext context) { this.context = context; } public IEnumerable<Lecturer> PageList(string name, int page, int pageSize) { if (!string.IsNullOrEmpty(name)) { return context.Lecturers.Where(x => x.FullName.Contains(name)).OrderByDescending(x => new { x.Serial, x.Update_At }).ToPagedList(page, pageSize); } return context.Lecturers.OrderByDescending(x => new { x.Serial, x.Update_At }).ToPagedList(page, pageSize); } public Lecturer GetLecturerByID(string id) { try { Guid ID = new Guid(id); return context.Lecturers.Where(x => x.Id == ID).Include(x => x.Training_Processes).SingleOrDefault(); } catch (Exception) { } return null; } public Lecturer GetLecturerByCode(string code) { try { return context.Lecturers.Where(x => x.Code == code).Include(x => x.Training_Processes).SingleOrDefault(); } catch (Exception) { } return null; } public List<Lecturer> GetStudentOrderBySerial(int amount) { try { return context.Lecturers.OrderBy(x => x.Serial).Take(amount).Select(x => x).ToList(); } catch (Exception) { } return null; } } }
using System; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Linq.Expressions; namespace JimBobBennett.JimLib.Extensions { public static class PropertyChangedEventArgsExtension { /// <summary> /// Gets if a property change matches the given property name. /// This will also match any property to string.Empty as this is the standard way /// to indicate all properties have changed /// </summary> /// <typeparam name="TValue"></typeparam> /// <param name="args"></param> /// <param name="propertyExpression"></param> /// <returns></returns> [Pure] public static bool PropertyNameMatches<TValue>(this PropertyChangedEventArgs args, Expression<Func<TValue>> propertyExpression) { return args.PropertyName == string.Empty || args.PropertyName == args.ExtractPropertyName(propertyExpression); } } }
namespace BookService.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.Authors", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Books", c => new { Id = c.Int(nullable: false, identity: true), Title = c.String(nullable: false), Year = c.Int(nullable: false), Price = c.Decimal(nullable: false, precision: 18, scale: 2), Genre = c.String(), AuthorId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Authors", t => t.AuthorId, cascadeDelete: true) .Index(t => t.AuthorId); CreateTable( "dbo.GlowHubs", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), CommandRelationId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Users", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.CommandRelations", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.Int(nullable: false), GlowHubId = c.Int(nullable: false), Command = c.String(nullable: false), NextUserId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.GlowHubs", t => t.GlowHubId, cascadeDelete: true) .ForeignKey("dbo.Users", t => t.NextUserId, cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.Books", "AuthorId", "dbo.Authors"); DropIndex("dbo.Books", new[] { "AuthorId" }); DropTable("dbo.Books"); DropTable("dbo.Authors"); DropTable("dbo.Users"); DropTable("dbo.GlowHubs"); DropForeignKey("dbo.CommandRelations", "UserId", "dbo.Users"); DropForeignKey("dbo.CommandRelations", "GlowHubId", "dbo.GlowHubs"); DropTable("dbo.CommandRelations"); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IntegrationTest.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.Entities; using FluentAssertions; using FluentNHibernate.Testing; using NUnit.Framework; namespace CGI.Reflex.Core.Tests.Entities { public class IntegrationTest : BaseDbTest { [Test] public void It_should_persist() { new PersistenceSpecification<Integration>(NHSession, new PersistenceEqualityComparer()) .CheckProperty(x => x.Name, Rand.String(15)) .CheckProperty(x => x.Description, Rand.LoremIpsum()) .CheckProperty(x => x.DataDescription, Rand.LoremIpsum()) .CheckProperty(x => x.Frequency, Rand.String(40)) .CheckProperty(x => x.Comments, Rand.LoremIpsum()) .CheckReference(x => x.AppSource, Factories.Application.Save()) .CheckReference(x => x.AppDest, Factories.Application.Save()) .CheckReference(x => x.Nature, Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.IntegrationNature)) .VerifyTheMappings(); } [Test] public void It_should_add_techno_links() { var integration = Factories.Integration.Save(); var techno1 = Factories.Technology.Save(); var techno2 = Factories.Technology.Save(); integration.AddTechnologyLinks(new[] { techno1, techno2 }); NHSession.Flush(); NHSession.Clear(); var inttest = NHSession.Get<Integration>(integration.Id); inttest.TechnologyLinks.Should().HaveCount(2); inttest.TechnologyLinks.Should().OnlyContain(tl => (tl.Technology.Id == techno1.Id) || (tl.Technology.Id == techno2.Id)); } [Test] public void It_should_remove_techno_links() { var integration = Factories.Integration.Save(); var techno1 = Factories.Technology.Save(); var techno2 = Factories.Technology.Save(); integration.AddTechnologyLinks(new[] { techno1, techno2 }); NHSession.Flush(); integration.RemoveTechnologyLink(techno1); NHSession.Flush(); NHSession.Clear(); var inttest = NHSession.Get<Integration>(integration.Id); inttest.TechnologyLinks.Should().HaveCount(1); inttest.TechnologyLinks.Should().OnlyContain(tl => tl.Technology.Id == techno2.Id); NHSession.QueryOver<IntegrationTechnoLink>().RowCount().Should().Be(1); } } }
using System.Web.Mvc; using AttributeRouting.Helpers; using AttributeRouting.Web.Mvc; namespace AttributeRouting.Tests.Subjects.Mvc { [RoutePrefix("Defaults")] public class DefaultsController : Controller { [GET("Inline/{p=param}?{q=query}")] public string Inline(string p, string q) { return "Defaults.Inline({0}, {1})".FormatWith(p, q); } [GET("Optional/{p?}?{q?}")] public string Optional(string p, string q) { return "Defaults.Optional({0}, {1})".FormatWith(p, q); } [GET("{controller}/ControllerName", IsAbsoluteUrl = true)] public string ControllerName() { return "Defaults.ControllerName"; } [GET("{action}")] public string ActionName() { return "Defaults.ActionName"; } } }
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace NtApiDotNet.Win32 { /// <summary> /// Source of an event trace provider. /// </summary> public enum EventTraceProviderSource { /// <summary> /// Unknown source. /// </summary> Unknown = 0, /// <summary> /// From WMI. /// </summary> WMI, /// <summary> /// From NtTraceControl. /// </summary> TraceControl, /// <summary> /// From the security key. /// </summary> Security } /// <summary> /// Class to represent an Event Trace Provider. /// </summary> public sealed class EventTraceProvider { private readonly Lazy<SecurityDescriptor> _security_descriptor; /// <summary> /// The ID of the provider. /// </summary> public Guid Id { get; } /// <summary> /// The name of the provider. /// </summary> public string Name { get; } /// <summary> /// Whether the provider is defined as an XML file or a MOF. /// </summary> public bool FromXml { get; } /// <summary> /// The provider security descriptor (only available as admin). /// </summary> public SecurityDescriptor SecurityDescriptor => _security_descriptor.Value; /// <summary> /// Indicates the source of the provider. /// </summary> public EventTraceProviderSource Source { get; } internal EventTraceProvider(Guid id) : this(id, id.ToString(), false) { Source = EventTraceProviderSource.TraceControl; } internal EventTraceProvider(Guid id, SecurityDescriptor security_descriptor) : this(id, id.ToString(), false) { Source = EventTraceProviderSource.Security; _security_descriptor = new Lazy<SecurityDescriptor>(() => security_descriptor); } internal EventTraceProvider(Guid id, string name, bool from_xml) { Id = id; Name = name; FromXml = from_xml; _security_descriptor = new Lazy<SecurityDescriptor>(() => EventTracing.QueryTraceSecurity(Id, false).GetResultOrDefault()); Source = EventTraceProviderSource.WMI; } } }
using System; using System.Drawing; using MonoTouch.ObjCRuntime; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace AlexTouch.Greystripe { [BaseType (typeof (NSObject))] [Model] interface GSAd { [Wrap ("WeakDelegate")] GSAdDelegate Delegate { get; set; } [Export ("delegate", ArgumentSemantic.Assign)][NullAllowed] NSObject WeakDelegate { get; set; } [Export ("isAdReady")] bool IsAdReady (); [Export ("fetch")] void Fetch (); } [BaseType (typeof (NSObject))] [Model] interface GSAdDelegate { [Export ("greystripeBannerDisplayViewController")] UIViewController BannerDisplayViewController (); [Export ("greystripeGUID")] string GreystripeGUID (); [Export ("greystripeBannerAutoload")] bool BannerAutoload (); [Export ("greystripeAdFetchSucceeded:")] void AdFetchSucceeded (GSAd ad); [Export ("greystripeAdFetchFailed:withError:")] void AdFetchFailed (GSAd ad, GSAdError error); [Export ("greystripeAdClickedThrough:")] void AdClickedThrough (GSAd ad); [Export ("greystripeWillPresentModalViewController")] void WillPresentModalViewController (); [Export ("greystripeWillDismissModalViewController")] void WillDismissModalViewController (); [Export ("greystripeDidDismissModalViewController")] void DidDismissModalViewController (); } [BaseType (typeof (UIView))] interface GSAdView { } [BaseType (typeof (GSAdView))] interface GSBannerAdView : GSAd { [Export ("initWithDelegate:")] IntPtr Constructor (GSAdDelegate aDelegate); [Export ("initWithDelegate:GUID:")] IntPtr Constructor (GSAdDelegate aDelegate, string guid); [Export ("initWithDelegate:GUID:autoload:")] IntPtr Constructor (GSAdDelegate aDelegate, string guid, bool autoload); } [BaseType (typeof (NSObject))] interface GSConstants { [Field ("kGSSDKVersion", "__Internal")] NSString GSSDKVersion { get; } [Export ("hashedDeviceId")] [Static] string HashedDeviceId { get; } [Export ("setGUID:")] [Static] void SetGUID (string guid); } [BaseType (typeof (NSObject))] interface GSAdModel : GSAd { } [BaseType (typeof (GSAdModel))] interface GSFullscreenAd { [Export ("initWithDelegate:")] IntPtr Constructor (GSAdDelegate aDelegate); [Export ("initWithDelegate:GUID:")] IntPtr Constructor (GSAdDelegate aDelegate, string guid); [Export ("displayFromViewController:")] bool DisplayFromViewController (UIViewController viewController); } [BaseType (typeof (GSBannerAdView))] interface GSLeaderboardAdView { [Field ("kGSLeaderboardParameter", "__Internal")] NSString LeaderboardParameter { get; } } [BaseType (typeof (GSBannerAdView))] interface GSMediumRectangleAdView { [Field ("kGSMediumRectangleParameter", "__Internal")] NSString MediumRectangleParameter { get; } } [BaseType (typeof (GSBannerAdView))] interface GSMobileBannerAdView { [Field ("kGSMobileBannerParameter", "__Internal")] NSString MobileBannerParameter { get; } } }
using System.Collections.Generic; using System.Threading.Tasks; using API.DTOs; namespace API.Interfaces { public interface ICategoryRepository { Task<IEnumerable<CategoryDto>> GetCategories(); Task<IEnumerable<SubcategoryDto>> GetSubategories(int categoryId); Task<IEnumerable<string>> GetAllSubategories(); } }
using ECode.Data; namespace Sample1.Models { [Table("Score")] public class ScoreModel { [Column(IsRequired = true)] public string SchoolId { get; set; } [Column(IsRequired = true)] public string StudentId { get; set; } [PrimaryKey(IsIdentity = true)] public int ID { get; set; } [Column(IsRequired = true)] public string Course { get; set; } [Column] public double Score { get; set; } } }
using FindSelf.Application.Configuration.Queries; using System; using System.Collections.Generic; using System.Text; namespace FindSelf.Application.Users.GetUser { public class GetUserQuery : IQuery<UserDTO> { public Guid Uid { get; set; } public GetUserQuery(Guid uid) { Uid = uid; } } }
namespace ns17 { using System; internal interface Interface12 : Interface10 { void imethod_1(Interface10 interface10_0); string imethod_2(string string_0); } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using SprintFour.Background; using SprintFour.Blocks; using SprintFour.Collisions; using SprintFour.ComponentMachines; using SprintFour.Controllers; using SprintFour.HUD; using SprintFour.Levels; using SprintFour.Player; using SprintFour.Player.MarioStates; using SprintFour.Triggers; using SprintFour.Utilities; using System.Collections.Generic; namespace SprintFour { public class SprintFourGame : Game { BackgroundImageCollection background; Overlay overlay; public enum GameState { LevelSelect, Playing, Loading, Winning, HighScore, Lost }; readonly GraphicsDeviceManager graphics; public SpriteBatch SpriteBatch; private static SprintFourGame instance; public Mario Mario; private IList<IController> controllerList; public ILevel level; private int delay; public GameState CurrentGameState; private int winTimer = Utility.DELAY; IUpdateable pausedException; public bool Paused { get; set; } public bool LevelIsInfinite { get; set; } private bool initialLoadup = true; public Cursor cursor; private LevelSelectController levelSelect; private LevelSelectGamePadController levelSelectGP; public SprintFourGame() { instance = this; graphics = new GraphicsDeviceManager(this); Content.RootDirectory = Utility.CONTENT; } protected override void Initialize() { controllerList = new List<IController> { new KeyboardController() }; SpriteBatch = new SpriteBatch(GraphicsDevice); graphics.PreferredBackBufferHeight = (int)(Utility.SCREEN_WIDTH * Utility.CAMERA_SCALE); graphics.PreferredBackBufferWidth = (int)(Utility.SCREEN_HEIGHT * Utility.CAMERA_SCALE); graphics.ApplyChanges(); IsMouseVisible = true; Mario = new Mario(Vector2.Zero); Mario.CurrentState = new JumpingMarioState(true, Utility.SMALL, Mario); Components.Add(Mario); background = new BackgroundImageCollection(); Components.Add(background); delay = Utility.GAME_LOAD_DELAY; overlay = new Overlay(); Components.Add(overlay); CollisionDetectionManager.Initialize(); BoggusLoader.LoadQuotes("quotes.txt"); //level = new Level("Level1.csv"); //level = new InfiniteLevel(); Camera.Initialize(); SoundManager.Initialize(this); HighScore.Initialize(); BulletBillMachine.Initialize(this); if (initialLoadup) { CurrentGameState = GameState.LevelSelect; cursor = new Cursor(); levelSelect = new LevelSelectController(); levelSelectGP = new LevelSelectGamePadController(); } else { if (CurrentGameState != GameState.Lost) { CurrentGameState = GameState.Loading; } if (LevelIsInfinite) level = new InfiniteLevel(); else { level = new Level("Level1.csv"); Components.Add(new Collectibles.Rifle(Vector2.One * 200)); } } Paused = true; base.Initialize(); } protected override void LoadContent() { TempMessage.Font = Content.Load<SpriteFont>(Utility.MESSAGE_FONT); Overlay.Font = Content.Load<SpriteFont>(Utility.OVERLAY_FONT); Boggus.Font = Content.Load<SpriteFont>(Utility.OVERLAY_FONT); base.LoadContent(); } private void UpdateWinningAnimation(GameTime gameTime) { if (!Mario.OnGround) return; // SoundManager.PlayVictorySound(); winTimer -= gameTime.ElapsedGameTime.Seconds; Mario.CurrentState.RightPressed(); Mario.Position += Vector2.UnitX; if(--winTimer >= Utility.ZERO) return; Camera.Reset(); if (HighScore.IsNewHighScore(Overlay.Score)) { HighScore.CalculateNewScoreIndex(Overlay.Score); CurrentGameState = GameState.HighScore; } else { Reset(); overlay.Reset(); CurrentGameState = GameState.Loading; } } public void ChangeToWinning(Block flagpole) { SoundManager.Pause(); CurrentGameState = GameState.Winning; Mario.Velocity = Vector2.Zero; Mario.Position = new Vector2(flagpole.Bounds.X - Mario.Bounds.Width/Utility.TWO, Mario.Position.Y); Mario.CurrentState = new SlidingMarioState(true, Mario.CurrentState.Row,Mario); SoundManager.PlayAweSound(); winTimer = 100; } protected override void Update(GameTime gameTime) { if (CurrentGameState == GameState.LevelSelect) { levelSelect.Update(); levelSelectGP.Update(); cursor.Update(); return; } level.Update(); if (--delay > Utility.ZERO) return; if (Paused) { if (pausedException != null) pausedException.Update(gameTime); } else { base.Update(gameTime); CollisionDetectionManager.Update(gameTime); LevelTriggers.Update(); BulletBillMachine.Update(Mario); } if (CurrentGameState == GameState.Winning) { UpdateWinningAnimation(gameTime); } else { foreach (IController controller in controllerList) { controller.Update(); } } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, Camera.WorldTransform); switch (CurrentGameState) { case GameState.Loading: overlay.Draw(gameTime); SpriteBatch.End(); if (--delay >= Utility.ZERO) return; CurrentGameState = GameState.Playing; Paused = false; SoundManager.Resume(); SoundManager.PlayACWarningSound(); break; case GameState.Lost: SoundManager.Pause(); SoundManager.PlayDefeatSound(); overlay.Draw(gameTime); SpriteBatch.End(); break; case GameState.HighScore: SoundManager.Pause(); overlay.Draw(gameTime); SpriteBatch.End(); break; case GameState.LevelSelect: cursor.Draw(); overlay.Draw(gameTime); SpriteBatch.End(); if (cursor.ChoiceSelected) { initialLoadup = false; LevelIsInfinite = cursor.Choice == Utility.LEVEL_SELECT_INFINITE_CHOICE; Initialize(); Reset(); } break; default: base.Draw(gameTime); SpriteBatch.End(); break; } } public static SprintFourGame GetInstance() { return instance; } public void Pause(IUpdateable exception = null) { pausedException = exception; delay = Utility.DELAY; Paused = true; foreach (IController c in controllerList) { c.Pause(); } } public void Unpause() { pausedException = null; delay = Utility.DELAY; Paused = false; foreach (IController c in controllerList) { c.Unpause(); } } public void Reset() { if (--Overlay.Lives < Utility.ZERO) { CurrentGameState = GameState.Lost; } if (CurrentGameState == GameState.Winning) ++Overlay.Lives; CollisionDetectionManager.Reset(); LevelTriggers.Reset(); Components.Clear(); ResetElapsedTime(); Initialize(); LoadContent(); Camera.Reset(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HackerRank_HomeCode { public class MigratoryBirds { public void FindMigBirdTypes() { List<int> arr = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(arrTemp => Convert.ToInt32(arrTemp)).ToList(); var birdtypeCounts = new int[5]; for(int i = 0;i< arr.Count;i++) { birdtypeCounts[arr[i] - 1]++; } var maxBirdcount = birdtypeCounts[0]; var maxBirdtype = 1; for(int i = 1;i<5;i++) { if (maxBirdcount < birdtypeCounts[i]) { maxBirdcount = birdtypeCounts[i]; maxBirdtype = i + 1; } //if (maxBirdcount == birdtypeCounts[i] && i + 1 < maxBirdtype) //{ // maxBirdtype = i + 1; //} } Console.WriteLine(maxBirdtype); } } }
using System.Text.Json; namespace FeedsProcessing.Common.Models { public class FacebookNotification : Notification { public JsonElement Posts { get; set; } } }
using GAP.Procesos.Model.Context; using GAP.Seguros.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GAP.Procesos.Model.Dao { internal class ClientesDao { internal List<Cliente> ObtenerClientes() { using (SegurosContext con = new SegurosContext()) { return con.Cliente.ToList(); } } internal Cliente ObtenerClientePorId(int clienteId) { using (SegurosContext con = new SegurosContext()) { return con.Cliente.FirstOrDefault(p => p.Id == clienteId); } } } }
using System.Collections.Generic; using System.Threading.Tasks; namespace Torshify.Radio.Framework { public interface IBackdropService { Task<IEnumerable<string>> Query(string artistName); bool TryGet(string artistName, out string fileName); bool TryGet(string artistName, out string[] fileNames); bool TryGetAny(out string[] fileNames); } }
using System; using System.Collections.Generic; namespace Learn_Colemak { class main { static void Main(string[] args) { int numCorrect = 0; int numIncorrect = 0; char currentChar = ' '; List<char> charList = new List<char> {}; char currentCorrectChar = args[new Random().Next(args.Length)][0]; ConsoleKeyInfo currentKey = new ConsoleKeyInfo(); for (int i = 0; i < 10; i++) { charList.Add(args[new Random().Next(args.Length)][0]); } Console.WriteLine("Ready: "); while (currentKey.Key != ConsoleKey.Escape) { currentChar = ' '; charList.RemoveAt(0); charList.Add(args[new Random().Next(args.Length)][0]); currentCorrectChar = charList[0]; while (currentKey.Key != ConsoleKey.Escape && currentChar != currentCorrectChar) { Console.Clear(); Console.WriteLine($"Correct: {numCorrect} Incorrect: {numIncorrect}"); foreach (char futureCorrectChar in charList){ Console.Write(futureCorrectChar + " "); } currentKey = Console.ReadKey(); currentChar = currentKey.KeyChar; if (currentChar == currentCorrectChar) { numCorrect++; } else { numIncorrect++; } } } } } }
using System; using System.Threading.Tasks; namespace XamChat { public interface IWebServices { Task<User> Login(string username,string password); Task<User> Register (User user); Task<User[]> GetFriend(int userid); Task<User> addFriend(int userid,string username); Task<Conversation[]> getConversation(int userid); Task<MessageM[]> getMessage(int conversationID); Task<MessageM> sendMessage(MessageM message); } }
using System.Windows; using System.Windows.Controls; namespace Modscleo4.WPFUI.Controls { public class TitlebarButton : Button { static TitlebarButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(TitlebarButton), new FrameworkPropertyMetadata(typeof(TitlebarButton))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataObject.Abstract; namespace DataObject { public class ViPham:Vat { private string tenViPham; private decimal soTienPhat; public decimal SoTienPhat { get { return soTienPhat; } set { soTienPhat = value; } } public string TenViPham { get { return tenViPham; } set { tenViPham = value; } } } }
using System; using System.Collections.Generic; using System.Text; namespace FastSQL.Sync.Core.Enums { [Flags] public enum ItemState { None = 0, Removed = 1, Changed = 2, Processed = 4, Invalid = 8, RelatedItemNotFound = 16, RelatedItemNotSynced = 32 } }
using Logs.Data.Contracts; using Logs.Data.Tests.EfGenericRepositoryTests.Fakes; using Moq; using NUnit.Framework; namespace Logs.Data.Tests.EfGenericRepositoryTests { [TestFixture] public class UpdateTests { [Test] public void TestUpdate_ShouldCallDbContextSetUpdated() { // Arrange var mockedDbContext = new Mock<ILogsDbContext>(); var repository = new EntityFrameworkRepository<FakeGenericRepositoryType>(mockedDbContext.Object); var entity = new Mock<FakeGenericRepositoryType>(); // Act repository.Update(entity.Object); // Assert mockedDbContext.Verify(c => c.SetUpdated(entity.Object), Times.Once); } } }
using AGERunner; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AGE.GPU { public class BGP { public byte DataForDot11; public byte DataForDot10; public byte DataForDot01; public byte DataForDot00; public byte ToByte() { byte returnByte = 0b0000_0000; returnByte |= DataForDot00; returnByte |= (byte)(DataForDot01 << 2); returnByte |= (byte)(DataForDot10 << 4); returnByte |= (byte)(DataForDot11 << 6); return returnByte; } public static BGP ToBGP(byte b) { BGP returnBGP = new BGP(); returnBGP.DataForDot00 = (byte)(b & 3); returnBGP.DataForDot01 = (byte)((b & 12) >> 2); returnBGP.DataForDot10 = (byte)((b & 48) >> 4); returnBGP.DataForDot11 = (byte)((b & 192) >> 6); return returnBGP; } } public class LCDC { public bool OperationEnabled; public bool TileMapSelect; public bool Display; public bool BGWindowTileDataSelect; public bool BGTileMapDisplaySelect; public bool OBJSpriteSize; public bool OBJSpriteDisplay; public bool BGAndWindowDisplay; public byte ToByte() { byte returnByte = 0b0000_0000; returnByte |= (byte)(Convert.ToByte(BGAndWindowDisplay)); returnByte |= (byte)(Convert.ToByte(OBJSpriteDisplay) << 1); returnByte |= (byte)(Convert.ToByte(OBJSpriteSize) << 2); returnByte |= (byte)(Convert.ToByte(BGTileMapDisplaySelect) << 3); returnByte |= (byte)(Convert.ToByte(BGWindowTileDataSelect) << 4); returnByte |= (byte)(Convert.ToByte(Display) << 5); returnByte |= (byte)(Convert.ToByte(TileMapSelect) << 6); returnByte |= (byte)(Convert.ToByte(OperationEnabled) << 7); return returnByte; } public static LCDC ToLCDC(byte b) { LCDC returnLCDC = new LCDC(); returnLCDC.BGAndWindowDisplay = (b & 1) != 0; returnLCDC.OBJSpriteDisplay = (b & 2) != 0; returnLCDC.OBJSpriteSize = (b & 4) != 0; returnLCDC.BGTileMapDisplaySelect = (b & 8) != 0; returnLCDC.BGWindowTileDataSelect = (b & 16) != 0; returnLCDC.Display = (b & 32) != 0; returnLCDC.TileMapSelect = (b & 64) != 0; returnLCDC.OperationEnabled = (b & 128) != 0; return returnLCDC; } } public enum ModeFlag { HBlank, VBlank, Searching, Transfering } public class GameBoyGPU { /// <summary> /// A complete cycle through these states /// </summary> public const int HorizontalLine = 456; /// <summary> /// /// </summary> public const int VerticalLine = 70224 / 456; /// <summary> /// The sprite attribute memory. 0xFE00 - 0xFE9F. /// </summary> public byte[] SpriteAttribMemory = null; /// <summary> /// The video RAM. 0x8000 - 0x9FFF. /// </summary> public byte[] VRAM = null; /// <summary> /// LCD Control object /// </summary> public LCDC LCDControl = null; /// <summary> /// The size of the screen in pixels. /// </summary> public Size ScreenSize = new Size(160, 144); public bool InterruptVBlank = false; public int ScrollY = 0; public BGP BGP = null; public int HorizontalTick = 0; public int Line = 0; public ModeFlag Mode = ModeFlag.Searching; public GameBoyGPU() { SpriteAttribMemory = new byte[160]; VRAM = new byte[Map.GameBoyMap.VRAM.Item2 - Map.GameBoyMap.VRAM.Item1 + 1]; // This is for shit and giggles, the ram on startup is filled with random values so we do it too. Random r = new Random(); for (int i = 0; i < VRAM.Length; i++) { VRAM[i] = (byte)r.Next(0, 256); } BGP = new BGP(); } /// <summary> /// Renders and draws the pixel at the coords specified. /// </summary> /// <param name="point"></param> public void RenderPixel(Point point) { } public Color[] ReadTilePattern() { // A tile is 8*8 pixels in size. 3 Bytes for each color; Color[] ReturnArray = new Color[64]; } public short GetTileIndex(ushort address) { } public void Tick() { // We ticked, so we increase the horizontal tick amount and mod it to the total amount of hor ticks. HorizontalTick = (HorizontalTick + 1) % HorizontalLine; // Console.WriteLine(HorizontalTick); switch(Mode) { case ModeFlag.VBlank: // We are in a VBlank, we need to increase the VBlank tick amount if we are in the beginning of a new line. if(HorizontalTick == 0) { Line = (Line + 1) % VerticalLine; Mode = (Line == 0) ? ModeFlag.Searching : Mode; } break; default: switch (HorizontalTick) { case 0: // We finished drawing a line xd Line++; // We reached the end of the screen. We need to trigger the VBlank interrupt. if(Line >= ScreenSize.Height) { InterruptVBlank = true; Mode = ModeFlag.VBlank; } else { // Else, we need to ready for the next line. Mode = ModeFlag.Searching; } break; case 252: // We reached the end of the line. We need to set the HBlank. Mode = ModeFlag.HBlank; break; case 80: // Page 53 (77 - 83), I averaged to 80, this corresponds to Mode 10 (2) Mode = ModeFlag.Transfering; // The CPU cannot access the OAM during this period break; } break; } if (Mode != ModeFlag.VBlank) { // Render a line. for (int x = 0; x <= ScreenSize.Width; x++) { RenderPixel(new Point(x, Line)); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace MapEditor { class TreeObject { private Rectangle pRect; //khung cua doi tuong //(neu doi tuong dung yen thi lay bang sprite con di chuyen thi lay bang khung di chuyen) private int ID; private GameObject m_listObject; public TreeObject() { this.ID = 0; this.pRect = new Rectangle(0, 0, 0, 0); } public TreeObject(int id, Rectangle rect) { this.ID = id; this.pRect = rect; } public void setRect(Rectangle rect) { this.pRect = rect; } public void setID(int id) { this.ID = id; } public Rectangle getRect() { return pRect; } public int getID() { return this.ID; } } }
using System; using System.Collections.Generic; namespace SheMediaConverterClean.Infra.Data.Models { public partial class VwAktionstyp { public VwAktionstyp() { VwAktivitaet = new HashSet<VwAktivitaet>(); } public int AktionstypId { get; set; } public string Bezeichnung { get; set; } public virtual ICollection<VwAktivitaet> VwAktivitaet { get; set; } } }
using System; using System.Reflection; using Akka.Persistence.Journal; using Akkatecture.Aggregates; namespace Akkatecture.Events { public static class DomainEventMapper { internal static object FromComittedEvent(object evt) { var type = typeof(ICommittedEvent<,,>); if (type.GetTypeInfo().IsAssignableFrom(evt.GetType())) { //dynamic dispach here to get AggregateEvent var comittedEvent = evt as dynamic; var genericType = typeof(DomainEvent<,,>) .MakeGenericType(type.GetGenericArguments()[0], type.GetGenericArguments()[1],type.GetGenericArguments()[2]); var domainEvent = Activator.CreateInstance( genericType, comittedEvent.AggregateIdentity, comittedEvent.AggregateEvent, comittedEvent.Metadata, comittedEvent.Timestamp, comittedEvent.AggregateSequenceNumber); return domainEvent; } else { return evt; } } } public class DomainEventReadAdapter : IReadEventAdapter { public IEventSequence FromJournal(object evt, string manifest) { var newEvent = DomainEventMapper.FromComittedEvent(evt); return new SingleEventSequence(newEvent); } } }
using System.ComponentModel; using BPiaoBao.AppServices.DataContracts.DomesticTicket; using BPiaoBao.Client.DomesticTicket.Model; using BPiaoBao.Common.Enums; using GalaSoft.MvvmLight; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.Client.DomesticTicket.ViewModel { public class FlightInformationItemViewModel : ViewModelBase { private FlightInfoModel _fi; public FlightInfoModel FlightInfoModel { get { return _fi; } } #region CarrayShortName protected const string c_CarrayShortPropertyNameName = "CarrayShortName"; protected string _CarrayShortName = null; /// <summary> /// CarrayShortName /// </summary> [DisplayName("航空公司")] public string CarrayShortName { get { return _CarrayShortName; } set { if (_CarrayShortName != value) { RaisePropertyChanging(c_CarrayShortPropertyNameName); _CarrayShortName = value; RaisePropertyChanged(c_CarrayShortPropertyNameName); } } } #endregion #region CarrayCode protected const string c_CarrayCodePropertyName = "CarrayCode"; protected string _CarrayCode; /// <summary> /// CarrayCode /// </summary> [DisplayName("CarrayCode")] public string CarrayCode { get { return _CarrayCode; } set { if (_CarrayCode != value) { RaisePropertyChanging(c_CarrayCodePropertyName); _CarrayCode = value; RaisePropertyChanged(c_CarrayCodePropertyName); } } } #endregion #region FlightNumber protected const string c_FlightNumberPropertyName = "FlightNumber"; protected string _FlightNumber = null; /// <summary> /// FlightNumber /// </summary> [DisplayName("航空类型")] public string FlightNumber { get { return _FlightNumber; } set { if (_FlightNumber != value) { RaisePropertyChanging(c_FlightNumberPropertyName); _FlightNumber = value; RaisePropertyChanged(c_FlightNumberPropertyName); } } } #endregion #region Model protected const string c_ModelPropertyName = "Model"; protected string _Model = null; /// <summary> /// Model /// </summary> public string Model { get { return _Model; } set { if (_Model != value) { RaisePropertyChanging(c_ModelPropertyName); _Model = value; RaisePropertyChanged(c_ModelPropertyName); } } } #endregion #region People protected const string c_PeoplePropertyName = "People"; protected string _People = null; /// <summary> /// People /// </summary> public string People { get { return _People; } set { if (_People != value) { RaisePropertyChanging(c_PeoplePropertyName); _People = value; RaisePropertyChanged(c_PeoplePropertyName); } } } #endregion #region TaxFee protected const string c_TaxFeePropertyName = "TaxFee"; protected decimal _TaxFee; /// <summary> /// TaxFee /// </summary> public decimal TaxFee { get { return _TaxFee; } set { if (_TaxFee != value) { RaisePropertyChanging(c_TaxFeePropertyName); _TaxFee = value; RaisePropertyChanged(c_TaxFeePropertyName); } } } #endregion #region RQFee protected const string c_RQFeePropertyName = "RQFee"; protected decimal _RQFee; /// <summary> /// RQFee /// </summary> public decimal RQFee { get { return _RQFee; } set { if (_RQFee != value) { RaisePropertyChanging(c_RQFeePropertyName); _RQFee = value; RaisePropertyChanged(c_RQFeePropertyName); } } } #endregion #region SeatCode protected const string c_SeatCodePropertyName = "SeatCode"; protected string _SeatCode; /// <summary> /// SeatCode /// </summary> public string SeatCode { get { return _SeatCode; } set { if (_SeatCode != value) { RaisePropertyChanging(c_SeatCodePropertyName); _SeatCode = value; RaisePropertyChanged(c_SeatCodePropertyName); } } } #endregion #region Discount protected const string c_DiscountPropertyName = "Discount"; protected decimal _Discount; /// <summary> /// Discount /// </summary> public decimal Discount { get { return _Discount; } set { if (_Discount != value) { RaisePropertyChanging(c_DiscountPropertyName); _Discount = value; RaisePropertyChanged(c_DiscountPropertyName); } } } #endregion #region SeatCount protected const string c_SeatCountPropertyName = "SeatCount"; protected string _SeatCount; /// <summary> /// SeatCount /// </summary> public string SeatCount { get { return _SeatCount; } set { if (_SeatCount != value) { RaisePropertyChanging(c_SeatCountPropertyName); _SeatCount = value; RaisePropertyChanged(c_SeatCountPropertyName); } } } #endregion #region SeatPrice protected const string c_SeatPricePropertyName = "SeatPrice"; protected decimal _SeatPrice; /// <summary> /// SeatPrice /// </summary> public decimal SeatPrice { get { return _SeatPrice; } set { if (_SeatPrice != value) { RaisePropertyChanging(c_SeatPricePropertyName); _SeatPrice = value; RaisePropertyChanged(c_SeatPricePropertyName); } } } #endregion #region TotalPrice protected const string c_TotalPricePropertyName = "TotalPrice"; /// <summary> /// TotalPrice /// </summary> public decimal TotalPrice { get { return TaxFee + RQFee + SeatPrice; } } #endregion #region FromTerminal protected const string c_FromTerminalPropertyName = "FromTerminal"; protected string _FromTerminal; /// <summary> /// FromTerminal /// </summary> [DisplayName("FromTerminal")] public string FromTerminal { get { return _FromTerminal; } set { if (_FromTerminal != value) { RaisePropertyChanging(c_FromTerminalPropertyName); _FromTerminal = value; RaisePropertyChanged(c_FromTerminalPropertyName); } } } #endregion #region StartDateTime protected const string c_StartDateTimePropertyName = "StartDateTime"; protected DateTime _StartDateTime; /// <summary> /// StartDateTime /// </summary> [DisplayName("StartDateTime")] public DateTime StartDateTime { get { return _StartDateTime; } set { if (_StartDateTime != value) { RaisePropertyChanging(c_StartDateTimePropertyName); _StartDateTime = value; RaisePropertyChanged(c_StartDateTimePropertyName); } } } #endregion #region FromAirPortrName protected const string c_FromAirPortrNamePropertyName = "FromAirPortrName"; protected string _FromAirPortrName; /// <summary> /// FromAirPortrName /// </summary> [DisplayName("FromAirPortrName")] public string FromAirPortrName { get { return _FromAirPortrName; } set { if (_FromAirPortrName != value) { RaisePropertyChanging(c_FromAirPortrNamePropertyName); _FromAirPortrName = value; RaisePropertyChanged(c_FromAirPortrNamePropertyName); } } } #endregion #region ToTerminal protected const string c_ToTerminalPropertyName = "ToTerminal"; protected string _ToTerminal; /// <summary> /// ToTerminal /// </summary> [DisplayName("ToTerminal")] public string ToTerminal { get { return _ToTerminal; } set { if (_ToTerminal != value) { RaisePropertyChanging(c_ToTerminalPropertyName); _ToTerminal = value; RaisePropertyChanged(c_ToTerminalPropertyName); } } } #endregion #region ToDateTime protected const string c_ToDateTimePropertyName = "ToDateTime"; protected DateTime _ToDateTime; /// <summary> /// ToDateTime /// </summary> [DisplayName("ToDateTime")] public DateTime ToDateTime { get { return _ToDateTime; } set { if (_ToDateTime != value) { RaisePropertyChanging(c_ToDateTimePropertyName); _ToDateTime = value; RaisePropertyChanged(c_ToDateTimePropertyName); } } } #endregion #region ToAirPortrName protected const string c_ToAirPortrNamePropertyName = "ToAirPortrName"; protected string _ToAirPortrName; /// <summary> /// ToAirPortrName /// </summary> [DisplayName("ToAirPortrName")] public string ToAirPortrName { get { return _ToAirPortrName; } set { if (_ToAirPortrName != value) { RaisePropertyChanging(c_ToAirPortrNamePropertyName); _ToAirPortrName = value; RaisePropertyChanged(c_ToAirPortrNamePropertyName); } } } #endregion #region 政策点数 protected decimal _PolicyPoint; /// <summary> /// 政策点数 /// </summary> [DisplayName("政策点数")] public decimal PolicyPoint { get { return _PolicyPoint; } set { if (_PolicyPoint != value) { const string c_PolicyPointPropertyName = "PolicyPoint"; RaisePropertyChanging(c_PolicyPointPropertyName); _PolicyPoint = value; RaisePropertyChanged(c_PolicyPointPropertyName); } } } #endregion #region 特殊政策类型 private const string PolicySpecialTypePortrNamePropertyName = "PolicySpecialType"; private EnumPolicySpecialType _policySpecialType; /// <summary> /// 政策特殊类型 /// </summary> public EnumPolicySpecialType PolicySpecialType { get { return _policySpecialType; } set { if (_policySpecialType == value) return; RaisePropertyChanging(PolicySpecialTypePortrNamePropertyName); _policySpecialType = value; RaisePropertyChanged(PolicySpecialTypePortrNamePropertyName); } } #endregion #region YPrice protected const string c_YPricePropertyName = "YPrice"; protected decimal _YPrice; /// <summary> /// SeatPrice /// </summary> public decimal YPrice { get { return _YPrice; } set { if (_YPrice != value) { RaisePropertyChanging(c_YPricePropertyName); _YPrice = value; RaisePropertyChanged(c_YPricePropertyName); } } } #endregion /// <summary> /// Ibe机建费 /// </summary> public decimal IbeTaxFee { get; set; } /// <summary> /// Ibe燃油费 /// </summary> public decimal IbeRQFee { get; set; } /// <summary> /// Ibe舱位价 /// </summary> public decimal IbeSeatPrice { get; set; } public FlightInformationItemViewModel(FlightInfoModel fi) { this._fi = fi; CarrayShortName = fi.CarrayShortName; CarrayCode = fi.CarrayCode; FlightNumber = fi.FlightNumber; Model = fi.Model; FromTerminal = fi.FromTerminal; StartDateTime = fi.StartDateTime; FromAirPortrName = fi.FromAirPortrName; ToTerminal = fi.ToTerminal; ToDateTime = fi.ToDateTime; ToAirPortrName = fi.ToAirPortrName; People = fi.CarrayShortName; TaxFee = fi.TaxFee; RQFee = fi.RQFee; YPrice = fi.DefaultSite.SpecialYPrice; SeatCode = fi.DefaultSite.SeatCode; SeatCount = fi.DefaultSite.SeatCount; Discount = fi.DefaultSite.Discount; SeatPrice = fi.DefaultSite.SeatPrice; PolicyPoint = fi.DefaultSite.PolicyPoint; PolicySpecialType = fi.DefaultSite.PolicySpecialType; IbeRQFee = fi.IbeRQFee; IbeTaxFee = fi.IbeTaxFee; IbeSeatPrice = fi.DefaultSite.IbeSeatResponse.IbeSeatPrice; OnTotalPriceChanged(); } public FlightInformationItemViewModel() { } public void OnTotalPriceChanged() { RaisePropertyChanged(c_TotalPricePropertyName); } public string ToolTip { get { return ToString(); } } public override string ToString() { var str = string.Format( @"航空公司编码:{0} 航空公司简称:{1} 折扣:{2} 航班号:{3} 出发城市机场:{4} 出发航站楼:{5} 机型:{6} 航空公司:{7} 政策点数:{8} 燃油费:{9} 舱位:{10} 剩余座位数:{11} 舱位价:{12} 起飞时间:{13:yyyy-MM-dd HH:mm:ss} 机建费:{14} 到达城市机场名称:{15} 到达时间:{16:yyyy-MM-dd HH:mm:ss} 到达航站楼:{17}" , _CarrayCode , _CarrayShortName , _Discount , _FlightNumber , _FromAirPortrName , _FromTerminal , _Model , _People , _PolicyPoint , _RQFee , _SeatCode , _SeatCount , _SeatPrice , _StartDateTime , _TaxFee , _ToAirPortrName , _ToDateTime , _ToTerminal) ; return str; } } }
namespace PluginStudy.EntityFramework.Migrations { using System; using System.Data.Entity.Migrations; public partial class ModifyDept : DbMigration { public override void Up() { DropPrimaryKey("dbo.Departments"); AddColumn("dbo.Departments", "DeptParentGuid", c => c.String()); AlterColumn("dbo.Departments", "Guid", c => c.String(nullable: false, maxLength: 128)); AddPrimaryKey("dbo.Departments", "Guid"); DropColumn("dbo.Departments", "DeptParentId"); } public override void Down() { AddColumn("dbo.Departments", "DeptParentId", c => c.Guid(nullable: false)); DropPrimaryKey("dbo.Departments"); AlterColumn("dbo.Departments", "Guid", c => c.Guid(nullable: false)); DropColumn("dbo.Departments", "DeptParentGuid"); AddPrimaryKey("dbo.Departments", "Guid"); } } }
using Microsoft.EntityFrameworkCore; namespace dbcodefirst { public class AppDbContext : DbContext { public DbSet<Produto> Produtos { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source=DESKTOP-1KRMKFK;" + "Initial Catalog= EFCoreDB; Integrated Security=True"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AfterFrogger : MonoBehaviour { private AudioSource _as; public AudioClip GotScarf; public AudioClip DontGotScarf; public float delay = 2f; private float _delay = 0f; private bool playing = false; // Start is called before the first frame update void Start() { _as = GetComponent<AudioSource>(); } void Update() { _delay += Time.deltaTime; if (_delay >= delay && !playing) Play(); } void Play() { playing = true; if (GameProperties.HaveShoes == 1 && GotScarf) { _as.clip = GotScarf; _as.Play(); } if (GameProperties.HaveShoes == 0 && DontGotScarf) { _as.clip = DontGotScarf; _as.Play(); } } }
using System; using System.Collections.Generic; namespace App3 { public interface IBaseUrl { string Get(); List<string> GetMusic(); } }
using System; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Data; using System.Windows.Markup; namespace Grisaia.SpriteViewer.Converters { /// <summary> /// A value converter for manipulating a thickness to preserve or modify certain parts of the value through use of /// the converter parameter.<para/> /// This converter does not support <see cref="IValueConverter.ConvertBack"/>. /// </summary> /// /// <remarks> /// Converter Parameter Usage:<para/> /// The parameter must be defined with either 1, 2, or 4 comma-separated parts like any thickness. /// <code> /// * : Use existing value /// +* : Use existing value /// 13+* : Use existing value + 13 /// -6+* : Use existing value - 6 /// -* : Use negative existing value /// 9.9-* : Use 9.9 - existing value /// </code> /// </remarks> public sealed class PreserveThickness : MarkupExtension, IValueConverter { #region Constants /// <summary> /// Gets the single instance used by the <see cref="MarkupExtension"/>. /// </summary> public static readonly PreserveThickness Instance = new PreserveThickness(); /// <summary> /// The regular expression used to parse "+*" or "-*" expressions. /// </summary> private static readonly Regex AddSubRegex = new Regex(@"\s*(?'type'\+|-)\s*\*$"); #endregion #region MarkupExtension Overrides /// <summary> /// When implemented in a derived class, returns an object that is provided as the value of the target /// property for this markup extension. /// </summary> /// <param name="serviceProvider"> /// A service provider helper that can provide services for the markup extension. /// </param> /// <returns>The object value to set on the property where the extension is applied.</returns> public override object ProvideValue(IServiceProvider serviceProvider) => Instance; #endregion #region IValueConverter Implementation public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(parameter is string parameterStr)) throw new ArgumentException("Must supply a converter parameter!"); if (!(value is Thickness preserveThickness)) throw new ArgumentException("Value to convert must be a thickness!"); string[] parts = parameterStr.Split(','); if (parts.Length == 1) { return new Thickness( ParsePart(parts[0], preserveThickness.Left), ParsePart(parts[0], preserveThickness.Top), ParsePart(parts[0], preserveThickness.Right), ParsePart(parts[0], preserveThickness.Bottom)); } else if (parts.Length == 2) { return new Thickness( ParsePart(parts[0], preserveThickness.Left), ParsePart(parts[1], preserveThickness.Top), ParsePart(parts[0], preserveThickness.Right), ParsePart(parts[1], preserveThickness.Bottom)); } else if (parts.Length == 4) { return new Thickness( ParsePart(parts[0], preserveThickness.Left), ParsePart(parts[1], preserveThickness.Top), ParsePart(parts[2], preserveThickness.Right), ParsePart(parts[3], preserveThickness.Bottom)); } throw new ArgumentException($"Invalid preserve thickness parameter! " + $"Expected 1, 2, or 4 parts, got {parts.Length}!"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } #endregion #region Private Methods private static double ParsePart(string part, double preservedThickness) { part = part.Trim(); double preservePart = 0d; Match match; if (part.Length == 0) throw new ArgumentException($"Preserve thickness parameter part cannot be empty!"); if (part == "*") { return preservedThickness; } else if ((match = AddSubRegex.Match(part)).Success) { preservePart = preservedThickness; if (match.Groups["type"].Value == "-") preservePart = -preservePart; part = part.Substring(0, part.Length - match.Length); } if (part.Length != 0) { if (double.TryParse(part, out double parameterPart)) return parameterPart + preservePart; throw new ArgumentException($"Preserve thickness parameter part expected double, " + $"got \"{part}\"!"); } return preservePart; } #endregion } }
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.IO; using KaVE.Commons.Model.ObjectUsage; using KaVE.RS.Commons.CodeCompletion; using Smile; namespace KaVE.RS.Commons.Tests_Unit.CodeCompletion { internal static class SmilePBNRecommenderFixture { public static CoReTypeName SomeType() { return new CoReTypeName("LType"); } public static Network CreateNetwork() { var network = new Network(); var patternHandle = network.AddNode(Network.NodeType.Cpt, SmilePBNRecommenderConstants.PatternTitle); network.SetNodeName(patternHandle, SmilePBNRecommenderConstants.PatternTitle); network.SetNodeProperties(patternHandle, new[] {"p1", "p2", "p3"}, new[] {0.3, 0.5, 0.2}); AddNode( network, patternHandle, SmilePBNRecommenderConstants.ClassContextTitle, SmilePBNRecommenderConstants.ClassContextTitle, new[] {"LType", "LType2", "LType3"}, new[] {0.6, 0.2, 0.2, 0.3, 0.4, 0.3, 0.2, 0.3, 0.5}); AddNode( network, patternHandle, SmilePBNRecommenderConstants.MethodContextTitle, SmilePBNRecommenderConstants.MethodContextTitle, new[] {"LType.M()LVoid;", "LType.Ret()LRet;", "LType.Param(LArg;)LVoid;", "LType.Id(LArg;)LRet;"}, new[] {0.6, 0.2, 0.1, 0.1, 0.3, 0.4, 0.2, 0.1, 0.2, 0.3, 0.4, 0.1}); AddNode( network, patternHandle, SmilePBNRecommenderConstants.DefinitionTitle, SmilePBNRecommenderConstants.DefinitionTitle, new[] {"RETURN:LType.Create()LType;", "THIS", "CONSTANT", "FIELD:LType.object;LType"}, new[] {0.6, 0.2, 0.1, 0.1, 0.1, 0.3, 0.3, 0.3, 0.1, 0.4, 0.1, 0.4}); AddMethod(network, patternHandle, "LType.Init()LVoid;", new[] {0.95, 0.15, 0.05}); AddMethod(network, patternHandle, "LType.Execute()LVoid;", new[] {0.6, 0.99, 0.7}); AddMethod(network, patternHandle, "LType.Finish()LVoid;", new[] {0.05, 0.5, 0.9}); return network; } public static string CreateNetworkAsString() { var net = CreateNetwork(); var tmpFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".xdsl"); net.WriteFile(tmpFile); var str = File.ReadAllText(tmpFile); File.Delete(tmpFile); return str; } private static void AddMethod(Network net, int patternNodeHandle, string methodName, double[] probabilities) { var nodeId = "C_" + SmilePBNRecommender.ConvertToLegalSmileName(methodName); AddNode( net, patternNodeHandle, nodeId, methodName, new[] {SmilePBNRecommenderConstants.StateTrue, SmilePBNRecommenderConstants.StateFalse}, Expand(probabilities)); } private static double[] Expand(double[] trues) { var probs = new double[trues.Length * 2]; for (var i = 0; i < trues.Length; i++) { probs[2 * i] = trues[i]; probs[2 * i + 1] = 1 - trues[i]; } return probs; } private static void AddNode( Network net, int patternNodeHandle, string nodeId, string nodeName, IEnumerable<string> states, double[] probs) { var handle = net.AddNode(Network.NodeType.Cpt, nodeId); net.SetNodeName(handle, nodeName); net.AddArc(patternNodeHandle, handle); net.SetNodeProperties(handle, states, probs); } private static void SetNodeProperties(this Network net, int nodeHandle, IEnumerable<string> states, double[] probs) { foreach (var state in states) { var convertedName = SmilePBNRecommender.ConvertToLegalSmileName(state); net.AddOutcome(nodeHandle, convertedName); } //Remove default states net.DeleteOutcome(nodeHandle, "State0"); net.DeleteOutcome(nodeHandle, "State1"); net.SetNodeDefinition(nodeHandle, probs); } public static Query CreateDefaultQuery() { var query = new Query { type = new CoReTypeName("LTypeUnknown"), classCtx = new CoReTypeName("LTypeUnknown"), methodCtx = new CoReMethodName("LTypeUnknown.M()LVoid;"), definition = new DefinitionSite {kind = DefinitionSiteKind.UNKNOWN} }; return query; } } }
//////////////////////////////////////////////////////////////////////////// // Copyright 2016 : Vladimir Novick https://www.linkedin.com/in/vladimirnovick/ // // NO WARRANTIES ARE EXTENDED. USE AT YOUR OWN RISK. // // To contact the author with suggestions or comments, use :vlad.novick@gmail.com // //////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Com.SGcombo.DataSynchronization.Utils { public class MultiKeyCollection<T> where T : ReflectionObject { protected string[] _Properties = new string[]{}; protected string _Delimiter = "#"; protected Dictionary<string, T> _Keys = new Dictionary<string, T>(); public MultiKeyCollection(string[] properties) { _Properties = properties; } #region Properties public IList<string> Keys { get { return _Keys.Keys.ToList<string>(); } } public IList<T> Objects { get { return _Keys.Values.ToList<T>(); } } #endregion public string GetKey(T obj) { string key = string.Empty; foreach (string property in _Properties) { string propValue = obj.GetProperty(property).ToString(); if (propValue.IndexOf(_Delimiter) >= 0) throw new Exception(string.Format("Cannot create key from this object, property value of this object '{0}' contains '#'.", propValue)); key += propValue + _Delimiter; } if (key.EndsWith(_Delimiter) && key.Length != 1) key = key.Substring(0, key.Length - 1); return key; } public T GetAddObject(T obj) { string key = GetKey(obj); if (_Keys.ContainsKey(key)) return _Keys[key]; _Keys.Add(key, obj); return obj; } public T GetObjectByKey(string key) { if (_Keys.ContainsKey(key)) return _Keys[key]; return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Cogent.IoC; namespace Cogent.IoCTests.Models { [ConstructorFor(typeof(ITransientClass))] [ConstructorFor(typeof(ISingletonClass))] [ConstructorFor(typeof(StringDelegate))] [ConstructorFor(typeof(MultiConstructorClass))] [ConstructorFor(typeof(IExampleFactory))] public partial class TestContainer : Container, Register.Transient<ITransientClass, TransientClass>, Register.Singleton<ISingletonClass, SingletonClass>, Register.Transient<DependencyClass>, Register.Delegate<StringDelegate>, Register.Transient<GenericClass<int>>, Register.Transient<MultiConstructorClass>, Register.Factory<IExampleFactory> { private readonly string _stringDelegateContents; public TestContainer(string stringDelegateContents) { _stringDelegateContents = stringDelegateContents; } public TestContainer() { _stringDelegateContents = "Hello World! "; } public StringDelegate Create() => () => _stringDelegateContents; } }
using PlatformRacing3.Common.PrivateMessage; using PlatformRacing3.Server.Game.Client; using PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json; namespace PlatformRacing3.Server.Game.Communication.Messages.Incoming; internal class ReportPmIncomingMessage : MessageIncomingJson<JsonReportPmIncomingMessage> { internal override void Handle(ClientSession session, JsonReportPmIncomingMessage message) { if (session.IsGuest) { return; } PrivateMessageManager.ReportPrivateMessageAsync(session.UserData.Id, message.MessageId); } }