text
stringlengths
13
6.01M
namespace Phonebook.ConsoleCommands.Parsers { using Phonebook.ConsoleCommands.Info; public interface ICommandParser { CommandInfo Parse(string commandText); } }
using UnityEngine; namespace YuME.Util { public class SingletonMonoCls<T> : MonoBehaviour where T : SingletonMonoCls<T> { protected static T _instance; public static T Instance { get { if (_instance == null) { GameObject go = new GameObject(); go.name = typeof(T).ToString(); _instance = go.AddComponent<T>(); } return _instance; } } protected virtual void Awake() { T thisT = this as T; if (_instance != null && _instance != thisT) { if (_instance.gameObject == thisT.gameObject) { Destroy(thisT); } else { Destroy(thisT.gameObject); } return; } _instance = thisT; DontDestroyOnLoad(thisT.gameObject); } } public class SingletonCls<T> where T : SingletonCls<T>, new() { protected static T _instance; public static T Instance { get { if (_instance == null) { _instance = new T(); } return _instance; } } protected SingletonCls() { } } }
using Bentley.DgnPlatformNET; using Bentley.DgnPlatformNET.Elements; using DgnOrganizer.XmlData; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace DgnOrganizer { class Organizer { public static void Run(Options options) { try { Logger.setLogFolder(options.LogDir); Logger.Log.StartErrorsCounting(); Config.setPath(options.ConfigPath); if (options.FillConf) { Logger.Log.Info("=== START WORK: заполнение конфиг-файла"); fillConfig_(options); } else { Logger.Log.Info("=== START WORK: Компоновка dgn-файлов"); run_(options); } } catch (Exception ex) { ex.LogError(); } finally { Logger.Log.Info("=== END WORK"); Logger.Log.Info($"Ошибок: {Logger.Log.GetErrorsCount()}"); } if (!options.CloseOnStop) { Console.ReadKey(); } else { Environment.Exit(0); //Application.Exit(); } } private static void fillConfig_(Options options) { if (string.IsNullOrWhiteSpace(options.Path)) { Logger.Log.ErrorEx("В качестве 1-го аргумента должен выступать путь к обрабатываемому каталогу моделей dgn"); return; } string workFolder = Path.GetFullPath(options.Path); if (!Directory.Exists(workFolder)) { Logger.Log.ErrorEx($"Не найден рабочий каталог '{workFolder}'"); return; } string[] dgnPaths = Directory.GetFiles(workFolder, "*.dgn", SearchOption.AllDirectories); bool dirty = false; int i = 0; foreach (string dgnPath in dgnPaths) { try { processFileToFillConfig(dgnPath, ref dirty); } catch (Exception ex) { ex.LogError($"Файл '{dgnPath}':"); } finally { if (i % 50 == 0) { System.Console.ForegroundColor = ConsoleColor.Green; System.Console.WriteLine($"Обработано {(int)(double)i * 100 / dgnPaths.Count()} %"); System.Console.ResetColor(); } ++i; } } if (Config.Instance.HasChanges()) { Config.Instance.SaveChanges(); Logger.Log.Info("Конфиг-файл обновлён"); } else { Logger.Log.Info("Изменений не было найдено"); } } private static void processFileToFillConfig(string dgnUri, ref bool dirty) { string prefix; string unitCode; string specTag; string itemCode; SimFile simFile; if (!getData(dgnUri, out prefix, out unitCode, out specTag, out itemCode, out simFile)) { return; } SortedDictionary<string, CatalogTypeData> configCatalogTypes = Config.Instance.CatalogTypesData; Dictionary<string, string> tags2spec = Config.Instance.TagToSpecialization; string specFullName = tags2spec.ContainsKey(specTag) ? tags2spec[specTag] : null; foreach (string catalogType in simFile.CatalogToElement.Keys) { if (!configCatalogTypes.ContainsKey(catalogType)) { configCatalogTypes.Add(catalogType, new CatalogTypeData() {Specialization = specFullName}); dirty = true; } else if (!string.IsNullOrWhiteSpace(specFullName)) { CatalogTypeData typeData = configCatalogTypes[catalogType]; if (string.IsNullOrWhiteSpace(typeData.Specialization)) { typeData.Specialization = specFullName; dirty = true; } } } } private static void run_(Options options) { if (string.IsNullOrWhiteSpace(options.Path)) { Logger.Log.ErrorEx("В качестве 1-го аргумента должен выступать путь к обрабатываемому каталогу моделей dgn"); return; } string outputDir = options.OutputDir; if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } if (!HasWriteAccessToFolder(outputDir)) { Logger.Log.ErrorEx($"Нет прав на запись в выходной каталог '{outputDir}'"); return; } clearFolder(outputDir); string workFolder = Path.GetFullPath(options.Path); if (!Directory.Exists(workFolder)) { Logger.Log.ErrorEx($"Не найден рабочий каталог '{workFolder}'"); return; } Logger.Log.Info($"Обработка каталога '{workFolder}'"); string[] dgnPaths = Directory.GetFiles(workFolder, "*.dgn", SearchOption.AllDirectories); if (dgnPaths.Count() == 0) { Logger.Log.Warn($"Найдено dgn-моделей: {dgnPaths.Count()} шт."); return; } Logger.Log.Info($"Найдено dgn-моделей: {dgnPaths.Count()} шт."); { // ! Важно var host = new Host(); DgnPlatformLib.Initialize(host, false); } System.Console.Write("Обработка... "); int i = 0; foreach (string dgnPath in dgnPaths) { if (dgnPath.EndsWith("FH1_10UBA00_M_ET-Route_+0.100.dgn")) { ; } try { processFile(dgnPath, outputDir); } catch (Exception ex) { ex.LogError($"Файл '{dgnPath}':"); } finally { ++i; if (i > 1 && (i % 50 == 0 || i == dgnPaths.Count())) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Обработано {(int)(double)i * 100 / dgnPaths.Count()} %"); Console.ResetColor(); } } } Logger.Log.Info($"Результирующий каталог обработанных файлов: \"{outputDir}\""); } static string ensureFolderStructure(string rootFolder, string[] structure) { return Directory.CreateDirectory( Path.Combine(rootFolder, Path.Combine(structure)) ).FullName; } static bool getData(string dgnUri, out string prefix, out string unitCode, out string specTag, out string itemCode, out SimFile simFile) { prefix = null; unitCode = null; specTag = null; itemCode = null; simFile = null; Regex regex = new Regex(@"^([A-Z0-9]{3,4})_(([0-9]{2}[A-Z]{3})[0-9&]{0,2})(_[A-Z]_)?"); string sourceFileName = Path.GetFileName(dgnUri); Match match = regex.Match(sourceFileName); if (!match.Success) { Logger.Log.ErrorEx($"'{sourceFileName}' - не удалось распарсить имя файла"); return false; } prefix = match.Groups[1].Value; itemCode = match.Groups[2].Value; unitCode = match.Groups[3].Value; specTag = match.Groups[4].Value.Trim('_'); string xmlDataPath = Path.ChangeExtension(dgnUri, ".xml"); try { simFile = new SimFile(xmlDataPath); } catch (Exception ex) { ex.LogError($"Ошибка в чтении файла '{xmlDataPath}': "); return false; } return true; } static bool processFile(string dgnUri, string outputFolder) { string prefix; string unitCode; string specTag; string itemCode; SimFile simFile; if (!getData(dgnUri, out prefix, out unitCode, out specTag, out itemCode, out simFile)) { // файл не обработан: string copyFileName = Path.Combine( ensureFolderStructure(outputFolder, new string[] {MISSED}), Path.GetFileName(dgnUri)); File.Copy(dgnUri, copyFileName); return false; } string sourceFileName = Path.GetFileName(dgnUri); string specialization = null; bool IsUnrecognizedSpec = false; if (Config.Instance.TagToSpecialization.ContainsKey(specTag)) { specialization = Config.Instance.TagToSpecialization[specTag]; } else { IsUnrecognizedSpec = true; Logger.Log.Warn($"'{sourceFileName}': не распозана литера специальности '{specTag}', файл будет обработан в соответствии с конфигом"); specialization = UNRECOGNIZED; } if (simFile.CatalogToElement.Keys.Count() == 0) { Logger.Log.Warn($"'{sourceFileName}': не найдены элементы для обработки"); return false; } // Открываем Исходную модель: DgnFile sourceFile; DgnModel sourceModel; DgnDocument sourceDgnDoc; DgnFileOwner sourceDgnFileOwner; LoadOrCreate_FileAndDefaultModel(out sourceFile, out sourceModel, out sourceDgnDoc, out sourceDgnFileOwner, dgnUri, null); foreach (var pair in simFile.CatalogToElement) { string catalogType = pair.Key; IList<SimElement> simElements = pair.Value; if (IsUnrecognizedSpec) { CatalogTypeData typeData = null; if (Config.Instance.CatalogTypesData.ContainsKey(catalogType)) { typeData = Config.Instance.CatalogTypesData[catalogType]; catalogType = string.IsNullOrWhiteSpace(typeData.OverrideName) ? catalogType : typeData.OverrideName; } string configSpec = typeData?.Specialization; if (!string.IsNullOrWhiteSpace(configSpec)) { specialization = configSpec; } } // итоговая структура каталогов: var structure = new string[] { unitCode, specialization, itemCode }; string destFolder = ensureFolderStructure(outputFolder, structure); string destUri = Path.Combine(destFolder, $"{prefix}_{itemCode}_{catalogType}.dgn"); // Открываем Целевую модель: DgnFile destFile; DgnModel destModel; DgnDocument destDgnDoc; DgnFileOwner destDgnFileOwner; LoadOrCreate_FileAndDefaultModel( out destFile, out destModel, out destDgnDoc, out destDgnFileOwner, destUri, sourceFile); using (ElementCopyContext copyContext = new ElementCopyContext(destModel)) { copyContext.CopyingReferences = true; copyContext.WriteElements = true; foreach (SimElement simEl in simElements) { Element sourceElement = sourceModel.FindElementById(simEl.ElementId); if (sourceElement == null) { Logger.Log.ErrorEx( $"Не найден элемент '{simEl.ElementId}' в файле '{dgnUri}'"); continue; } copyContext.DoCopy(sourceElement); } destFile.ProcessChanges(DgnSaveReason.None); } destDgnFileOwner.Dispose(); destDgnDoc.Dispose(); } sourceDgnDoc.Dispose(); sourceDgnFileOwner.Dispose(); return true; } private static bool LoadOrCreate_FileAndDefaultModel( out DgnFile file, out DgnModel defaultModel, out DgnDocument dgnDoc, out DgnFileOwner dgnFileOwner, string uri, DgnFile seedFile) { StatusInt statusInt; DgnFileStatus status; if (File.Exists(uri)) { dgnDoc = DgnDocument.CreateForLocalFile(uri); dgnFileOwner = DgnFile.Create(dgnDoc, DgnFileOpenMode.ReadWrite); file = dgnFileOwner.DgnFile; } else { string fileName = Path.GetFileName(uri); dgnDoc = DgnDocument.CreateForNewFile(out status, fileName, uri, 0, fileName, DgnDocument.OverwriteMode.Prompt, DgnDocument.CreateOptions.Default); SeedData seedData = new SeedData(seedFile, 0, SeedCopyFlags.AllData, true); dgnFileOwner = DgnFile.CreateNew(out status, dgnDoc, DgnFileOpenMode.ReadWrite, seedData, DgnFileFormatType.V8, true); file = dgnFileOwner.DgnFile; } status = file.LoadDgnFile(out statusInt); defaultModel = file.LoadRootModelById(out statusInt, file.GetModelIndexCollection().First().Id); return status == DgnFileStatus.Success; } public static void clearFolder(string FolderName) { DirectoryInfo dir = new DirectoryInfo(FolderName); foreach(FileInfo fi in dir.GetFiles()) { fi.Delete(); } foreach (DirectoryInfo di in dir.GetDirectories()) { clearFolder(di.FullName); di.Delete(); } } public static bool HasWriteAccessToFolder(string folderPath) { try { bool canWrite = false; string tmpName = Path.GetFileName(Path.GetTempFileName()); string tmpPath = Path.Combine(folderPath, tmpName); using(var fileStream = File.Create(tmpPath)) { canWrite = fileStream.CanWrite; fileStream.Close(); } File.Delete(tmpPath); return canWrite; } catch (UnauthorizedAccessException) { return false; } } private const string UNRECOGNIZED = "[UNRECOGNIZED]"; private const string MISSED = "[MISSED]"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Panda.Attributes { public class AUTO_INCREMENT : SQLInject { public override string Value { get; set; } = "IDENTITY(1,1) PRIMARY KEY"; } }
using System.Collections.Generic; using System.Threading.Tasks; using FluentValidation; using ProductTest.Models; namespace ProductTest.Data { public class PatternValidator : AbstractValidator<PatternTest> { public PatternValidator() { RuleFor(x => x.BrandTitle).NotEmpty().Length(1, 20); RuleFor(x => x.Title).NotEmpty().Length(1, 20); RuleFor(x => x.Overview); RuleFor(x => x.SalesHookLine); RuleFor(x => x.Features); RuleFor(x => x.Images); RuleFor(x => x.Active).Must(x => x == false || x == true); RuleFor(x => x.Synonyms).Must(x => x == false || x == true); RuleFor(x => x.Performance).Must(x => x == false || x == true); RuleFor(x => x.LowerNoise).Must(x => x == false || x == true); RuleFor(x => x.HigherMileage).Must(x => x == false || x == true); RuleFor(x => x.UltraHighPerformance).Must(x => x == false || x == true); RuleFor(x => x.Eco).Must(x => x == false || x == true); RuleFor(x => x.SemiSlick).Must(x => x == false || x == true); RuleFor(x => x.Touring).Must(x => x == false || x == true); RuleFor(x => x.AllSeason).Must(x => x == false || x == true); RuleFor(x => x.AllTerrain).Must(x => x == false || x == true); RuleFor(x => x.HeavyAllTerrain).Must(x => x == false || x == true); RuleFor(x => x.MudTerrain).Must(x => x == false || x == true); RuleFor(x => x.TreadType).Must(x => x == false || x == true); RuleFor(x => x.QualityCategory).Must(x => x == false || x == true); RuleFor(x => x.ColourSmoke).Must(x => x == false || x == true); RuleFor(x => x.Segment).Must(x => x == false || x == true); RuleFor(x => x.Key); } } }
using CloudFile; using LuaInterface; using SLua; using System; public class Lua_CloudFile_CloudFileCallback : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { CloudFileCallback o = new CloudFileCallback(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int FireProgress(IntPtr l) { int result; try { CloudFileCallback cloudFileCallback = (CloudFileCallback)LuaObject.checkSelf(l); float progress; LuaObject.checkType(l, 2, out progress); cloudFileCallback.FireProgress(progress); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int FireSuccess(IntPtr l) { int result; try { CloudFileCallback cloudFileCallback = (CloudFileCallback)LuaObject.checkSelf(l); cloudFileCallback.FireSuccess(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int FireError(IntPtr l) { int result; try { CloudFileCallback cloudFileCallback = (CloudFileCallback)LuaObject.checkSelf(l); string error_message; LuaObject.checkType(l, 2, out error_message); cloudFileCallback.FireError(error_message); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set__ProgressCallback(IntPtr l) { int result; try { CloudFileCallback cloudFileCallback = (CloudFileCallback)LuaObject.checkSelf(l); CloudFileCallback.ProgressCallback progressCallback; int num = LuaDelegation.checkDelegate(l, 2, out progressCallback); if (num == 0) { cloudFileCallback._ProgressCallback = progressCallback; } else if (num == 1) { CloudFileCallback expr_30 = cloudFileCallback; expr_30._ProgressCallback = (CloudFileCallback.ProgressCallback)Delegate.Combine(expr_30._ProgressCallback, progressCallback); } else if (num == 2) { CloudFileCallback expr_53 = cloudFileCallback; expr_53._ProgressCallback = (CloudFileCallback.ProgressCallback)Delegate.Remove(expr_53._ProgressCallback, progressCallback); } LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set__SuccessCallback(IntPtr l) { int result; try { CloudFileCallback cloudFileCallback = (CloudFileCallback)LuaObject.checkSelf(l); CloudFileCallback.SuccessCallback successCallback; int num = LuaDelegation.checkDelegate(l, 2, out successCallback); if (num == 0) { cloudFileCallback._SuccessCallback = successCallback; } else if (num == 1) { CloudFileCallback expr_30 = cloudFileCallback; expr_30._SuccessCallback = (CloudFileCallback.SuccessCallback)Delegate.Combine(expr_30._SuccessCallback, successCallback); } else if (num == 2) { CloudFileCallback expr_53 = cloudFileCallback; expr_53._SuccessCallback = (CloudFileCallback.SuccessCallback)Delegate.Remove(expr_53._SuccessCallback, successCallback); } LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set__ErrorCallback(IntPtr l) { int result; try { CloudFileCallback cloudFileCallback = (CloudFileCallback)LuaObject.checkSelf(l); CloudFileCallback.ErrorCallback errorCallback; int num = LuaDelegation.checkDelegate(l, 2, out errorCallback); if (num == 0) { cloudFileCallback._ErrorCallback = errorCallback; } else if (num == 1) { CloudFileCallback expr_30 = cloudFileCallback; expr_30._ErrorCallback = (CloudFileCallback.ErrorCallback)Delegate.Combine(expr_30._ErrorCallback, errorCallback); } else if (num == 2) { CloudFileCallback expr_53 = cloudFileCallback; expr_53._ErrorCallback = (CloudFileCallback.ErrorCallback)Delegate.Remove(expr_53._ErrorCallback, errorCallback); } 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, "CloudFile.CloudFileCallback"); LuaObject.addMember(l, new LuaCSFunction(Lua_CloudFile_CloudFileCallback.FireProgress)); LuaObject.addMember(l, new LuaCSFunction(Lua_CloudFile_CloudFileCallback.FireSuccess)); LuaObject.addMember(l, new LuaCSFunction(Lua_CloudFile_CloudFileCallback.FireError)); LuaObject.addMember(l, "_ProgressCallback", null, new LuaCSFunction(Lua_CloudFile_CloudFileCallback.set__ProgressCallback), true); LuaObject.addMember(l, "_SuccessCallback", null, new LuaCSFunction(Lua_CloudFile_CloudFileCallback.set__SuccessCallback), true); LuaObject.addMember(l, "_ErrorCallback", null, new LuaCSFunction(Lua_CloudFile_CloudFileCallback.set__ErrorCallback), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_CloudFile_CloudFileCallback.constructor), typeof(CloudFileCallback)); } }
namespace R4ffi.CSharp9.BeerDomain { internal enum BeerType { Lager, IndiaPaleAle, WheatBeer } }
using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace StudyEspanol.iOS { partial class WordListScreen.cs : UIView { public WordListScreen.cs (IntPtr handle) : base (handle) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace Fish.Service.Models { public class ArticleDTO { [DataMember(Name="id")] public int Id { get; set; } [DataMember(Name="title")] public string Title { get; set; } [DataMember(Name = "description")] public string Description { get; set; } [DataMember(Name = "imageURL")] public string ImageURL { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using AddressBook.Models; namespace AddressBook.ViewModels { public class PersonViewModel { public List<Person> ListOfPeople { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Spine.Unity; public class spinePasaALoop : MonoBehaviour { public string Loop; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(GetComponent<SkeletonGraphic>().AnimationState.GetCurrent(0).Animation.Name != Loop) //.GetComponent<SkeletonGraphic>().AnimationState.GetCurrent(0).Animation.Name != "loops") { StartCoroutine(EspAnim()); } } IEnumerator EspAnim() { yield return new WaitForSpineAnimationComplete(GetComponent<SkeletonGraphic>().AnimationState.GetCurrent(0)); GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, Loop, true); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LogicaLetra : MonoBehaviour { TextMesh text; void Awake() { text = GetComponent<TextMesh>(); if (text == null) Debug.Log("La letra no tiene asociado el Text Mesh"); char A; //variable char //Creamos un int que selecciona 1 entre 3 posibilidades de generacion int bloque = Random.Range(0, 3);//Va del 0 al 3 por que no coge el ultimo valor if (bloque == 0) A = (char)Random.Range(48, 58); //Numeros else if(bloque==1) A = (char)Random.Range(65, 91);//Mayúsculas else A = (char)Random.Range(97, 123); //Minúsculas text.text = A.ToString(); //Transformamos el char a cadena de texto y la asignamos a la variable global letra } void Update() { //DECTA PULSACION TECLADO Y COMPRUEBA if (Input.inputString == text.text) Destroy(this.gameObject); } }
using System; using System.Net.Http; using System.Net.Http.Headers; using MusicCatalogue.Model.ServiceModels; namespace MusicCatalogue.ConsoleClient { public class ConsoleClient { private const string BaseUrl = "http://localhost:36926/api"; public static void Main() { var webClient = new HttpClient() { BaseAddress = new Uri(BaseUrl) }; webClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var artistService = new ArtistService(webClient, BaseUrl, "Artists"); var artists = artistService.GetAll(); var artist = artistService.GetByID(1); var songs = artistService.GetSongs(1); var albums = artistService.GetAlbums(1); var newSong = new SongModel() { Title = "I stand alone", Year = 2001, Genre = "Rock" }; var songsService = new SongService(webClient, BaseUrl, "Songs"); var songsArray = songsService.GetAll(); var currentSong = songsService.GetByID(3); var artitsFromSong = songsService.GetArtists(currentSong.SongID); var album = songsService.GetAlbum(currentSong.SongID); songsService.Add(newSong); var albumsService = new AlbumService(webClient, BaseUrl, "Albums"); var allAlbums = albumsService.GetAll(); var currentAlbum = albumsService.GetByID(1); var artistsFromAlbum = albumsService.GetArtists(currentAlbum.AlbumID); var songsFromAlbum = albumsService.GetSongs(currentAlbum.AlbumID); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace Constructor.Selectors { public partial class ColorSelect : UserControl { public ColorSelect() { InitializeComponent(); } public string color { get { if (this.textBox1.Text != "#") return this.textBox1.Text; else return string.Empty; } set { this.textBox1.Text = value; this.colorDialog1.Color = System.Drawing.ColorTranslator.FromHtml(value); } } private void button1_Click(object sender, EventArgs e) { this.color = color; if (this.colorDialog1.ShowDialog() == DialogResult.OK) { this.textBox1.Text = System.Drawing.ColorTranslator.ToHtml(colorDialog1.Color); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Clases { [Serializable] public class BallBearing : CarPart { public float Diameter { get; set; } public BallBearing(float diameter, int stock) : base(stock, "BB-D" + diameter.ToString()) { this.Diameter = diameter; } public override CarPart GetCopy() { return new BallBearing(this.Diameter, 0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.IO; public partial class Farmerpage : System.Web.UI.Page { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { int count; con.Open(); SqlCommand cmd = new SqlCommand("select count(*) from farmerproduct", con); count = Convert.ToInt16(cmd.ExecuteScalar()) + 1; TextBox1.Text = "P0R0I0D0" + count; con.Close(); } protected void Button2_Click(object sender, EventArgs e) { con.Open(); SqlCommand cmd = new SqlCommand("insert into farmerproduct values('" + Label6.Text.Trim() + "','" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','" + TextBox3.Text.Trim() + "')", con); cmd.ExecuteNonQuery(); con.Close(); ClientScript.RegisterStartupScript(Page.GetType(), "Validation", "<script language='javascript'>alert('Product Uploaded Successfully..');window.location='Home.aspx';</script>"); } protected void LinkButton1_Click(object sender, EventArgs e) { string folderPath = Server.MapPath("~/productimage/"); //Check whether Directory (Folder) exists. if (!Directory.Exists(folderPath)) { //If Directory (Folder) does not exists Create it. Directory.CreateDirectory(folderPath); } //Save the File to the Directory (Folder). FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName)); //Display the Picture in Image control. Image1.ImageUrl = "~/productimage/" + Path.GetFileName(FileUpload1.FileName); string s = FileUpload1.FileName; Label6.Text = s; } }
using System; using System.Collections.Generic; using ValueMail.Receive.Model; using ValueMail.Receive.IMAP.Infrastructure; namespace ValueMail.Receive.Infrastructure { public interface IMailBase : IDisposable { /// <summary> /// 连接服务器 /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <returns></returns> void Connect(String server, Int32 port); /// <summary> /// 连接服务器重载 /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <param name="ssl"></param> /// <returns></returns> void Connect(String server, Int32 port, Boolean ssl); /// <summary> /// 登陆账号 /// </summary> /// <param name="account"></param> /// <param name="password"></param> Boolean Loging(String account, String password); /// <summary> /// 获得邮件头 /// </summary> /// <returns></returns> List<MailHeadModel> GetMailHeaders(); List<MailHeadModel> GetMailHeaders(SearchType searchType); List<MailHeadModel> GetMailHeaders(String expression); /// <summary> /// 获得完整邮件 /// </summary> /// <returns></returns> MailModel GetMail(Int32 index); /// <summary> /// 删除邮件 /// </summary> /// <param name="index"></param> void DeleMail(Int32 index); /// <summary> /// 获得完整邮件列表 /// </summary> /// <returns></returns> List<MailModel> GetMails(); /// <summary> /// 重置状态 /// </summary> void ResetStatus(); /// <summary> /// 断开与服务器的连接 /// </summary> void Disconnect(); /// <summary> /// 释放资源 /// </summary> /// <param name="disposing"></param> void Dispose(Boolean disposing); } }
using System; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace ExperimentFive.Controllers { public class AboutController : Controller { [Route("About")] public IActionResult Index() => View(); [HttpGet("GetString")] public string GetData() => "42"; [HttpGet("AddAndReturn")] public int AddAndReturn( [FromQuery] int number1, int number2 ) => number1 + number2; [HttpGet("GetBoolean")] public bool GetBoolean() => true; [HttpGet("GetJsonObject")] public string GetJsonObject() { var cat = new cat(); cat.color = "black"; cat.gender = "male"; cat.name = "skitter"; return JsonConvert.SerializeObject(cat); } [HttpGet("GetJsonObjectVariables")] public string GetJsonObjectVariables( [FromQuery] string color, string gender, string name ) { Console.WriteLine(color, gender, name); var cat = new cat(); cat.color = color; cat.gender = gender; cat.name = name; return JsonConvert.SerializeObject(cat); } } public class cat : ICat { public string color { get; set; } public string gender { get; set; } public string name { get; set; } } } public interface ICat { string color {get; set;} string gender {get; set;} string name {get; set;} }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using HseClass.Core.EF; using HseClass.Data.Entities; using HseClass.Data.IRepositories; using Microsoft.EntityFrameworkCore; namespace HseClass.Core.Repositories { public class TaskLabRepository : ITaskLabRepository { private readonly HseClassContext _context; public TaskLabRepository(HseClassContext context) { _context = context; } public async Task<TaskLab> Create(TaskLab taskLab) { var result = await _context.TaskLabs.AddAsync(taskLab); await _context.SaveChangesAsync(); return result.Entity; } public async Task Delete(int taskLabId) { var taskLab = await _context.TaskLabs.FirstOrDefaultAsync(c => c.Id == taskLabId); _context.TaskLabs.Remove(taskLab); await _context.SaveChangesAsync(); } public async Task<List<TaskLab>> GetAll() { return await _context.TaskLabs.ToListAsync(); } public async Task<TaskLab> Update(TaskLab taskLab) { var result = _context.TaskLabs.Update(taskLab); await _context.SaveChangesAsync(); return result.Entity; } public async Task<TaskLab> GetById(int labId) { return await _context.TaskLabs.FirstOrDefaultAsync(l => l.Id == labId); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New UserUseableObject Object", menuName = "Inventory System/Items/UserUseableObject")] public class UserUseableObject : ItemObject { //public int pickableTimes; //public int useableTimes; public void Awake(){ itemType = ItemType.UserUseable; } }
namespace OCP.AppFramework { /** * Class App * @package OCP\AppFramework * * Any application must inherit this call - all controller instances to be used are * to be registered using IContainer::registerService * @since 6.0.0 */ class App { /** @var IAppContainer */ private IAppContainer container; /** * Turns an app id into a namespace by convetion. The id is split at the * underscores, all parts are camelcased and reassembled. e.g.: * some_app_id . OCA\SomeAppId * @param string appId the app id * @param string topNamespace the namespace which should be prepended to * the transformed app id, defaults to OCA\ * @return string the starting namespace for the app * @since 8.0.0 */ public static string buildAppNamespace(string appId, string topNamespace="OCA\\") { return buildAppNamespace(appId, topNamespace); } /** * @param string appName * @param array urlParams an array with variables extracted from the routes * @since 6.0.0 */ public App(string appName, array urlParams = []) { try { this.container = \OC::server.getRegisteredAppContainer(appName); } catch (QueryException e) { this.container = new \OC\AppFramework\DependencyInjection\DIContainer(appName, urlParams); } } /** * @return IAppContainer * @since 6.0.0 */ public IAppContainer getContainer() { return this.container; } /** * This function is to be called to create single routes and restful routes based on the given routes array. * * Example code in routes.php of tasks app (it will register two restful resources): * routes = array( * 'resources' => array( * 'lists' => array('url' => '/tasklists'), * 'tasks' => array('url' => '/tasklists/{listId}/tasks') * ) * ); * * a = new TasksApp(); * a.registerRoutes(this, routes); * * @param \OCP\Route\IRouter router * @param array routes * @since 6.0.0 * @suppress PhanAccessMethodInternal */ public void registerRoutes(IRouter router, array routes) { routeConfig = new RouteConfig(this.container, router, routes); routeConfig.register(); } /** * This function is called by the routing component to fire up the frameworks dispatch mechanism. * * Example code in routes.php of the task app: * this.create('tasks_index', '/').get().action( * function(params){ * app = new TaskApp(params); * app.dispatch('PageController', 'index'); * } * ); * * * Example for for TaskApp implementation: * class TaskApp extends \OCP\AppFramework\App { * * public function __construct(params){ * parent::__construct('tasks', params); * * this.getContainer().registerService('PageController', function(IAppContainer c){ * a = c.query('API'); * r = c.query('Request'); * return new PageController(a, r); * }); * } * } * * @param string controllerName the name of the controller under which it is * stored in the DI container * @param string methodName the method that you want to call * @since 6.0.0 */ public function dispatch(string controllerName, string methodName) { \OC\AppFramework\App::main(controllerName, methodName, this.container); } } }
using System; namespace Arch.Data.Orm.FastInvoker { public interface IDynamicPropertyInfo { Object GetValue(Object obj, Object[] index); void SetValue(Object obj, Object value, Object[] index); } }
namespace MyApp.Web.Models { using System.ComponentModel.DataAnnotations; public class MovieViewModel { public int Id { get; set; } [Required] [StringLength( 100, ErrorMessage = "Title must be between 2 and 100 characters long", MinimumLength = 2 )] public string Title { get; set; } [Range( 1900, 2020, ErrorMessage = "The year must be between 1900 and 2020" )] public int? Year { get; set; } public string DirectorName { get; set; } public int? DirectorId { get; set; } public string MaleActorName { get; set; } public int? MaleActorId { get; set; } public string FemaleActorName { get; set; } public int? FemaleActorId { get; set; } public string StudioName { get; set; } public int? StudioId { get; set; } [UIHint( "MovieMaleActor" )] public MaleActorViewModel MaleActor { get; set; } [UIHint( "MovieFemaleActor" )] public FemaleActorViewModel FemaleActor { get; set; } [UIHint( "MovieStudio" )] public StudioViewModel Studio { get; set; } [UIHint( "Director" )] public DirectorViewModel Director { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using WPFCore.Models; namespace bonnekesprinter.Models { public class Servicecall { public string _id { get; set; } public Boolean status { get; set; } public string description { get; set; } public string tablenumber { get; set; } public string tableid { get; set; } public string name { get; set; } public Restaurant restaurantid { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MMSdb.dbo.Tables { [Table("tbl_Reports")] public class tbl_Reports { [Key] public long rpt_ID { get; set; } public String? rpt_Name { get; set; } public String? rpt_Description { get; set; } public String? rpt_Path { get; set; } public Boolean? rpt_Enabled { get; set; } public Boolean? rpt_CanAccess { get; set; } public Boolean? deleted { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using EatDrinkApplication.Data; using EatDrinkApplication.Models; using Microsoft.AspNetCore.Authorization; using EatDrinkApplication.Contracts; using System.Security.Claims; using EatDrinkApplication.ViewModel; namespace EatDrinkApplication.Controllers { [Authorize(Roles = "HomeCook")] public class HomeCooksController : Controller { private readonly ApplicationDbContext _context; public HomeCooksController(ApplicationDbContext context) { _context = context; } // GET: HomeCooks public async Task<IActionResult> Index() { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var homeCook = _context.HomeCook.Where(c => c.IdentityUserId == userId).SingleOrDefault(); if(homeCook == null) { return RedirectToAction("Create"); } return View(homeCook); } // GET: HomeCooks/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var homeCook = await _context.HomeCook .Include(h => h.IdentityUser) .FirstOrDefaultAsync(m => m.HomeCookId == id); if (homeCook == null) { return NotFound(); } return View(homeCook); } // GET: HomeCooks/Create public IActionResult Create() { ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id"); return View(); } // POST: HomeCooks/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("HomeCookId,FirstName,LastName,IdentityUserId")] HomeCook homeCook) { if (ModelState.IsValid) { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); homeCook.IdentityUserId = userId; _context.Add(homeCook); _context.Add(homeCook); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", homeCook.IdentityUserId); return View(homeCook); } public async Task<IActionResult> ViewSavedRecipes() { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var homeCook = _context.HomeCook.Where(c => c.IdentityUserId == userId).SingleOrDefault(); var savedDrinks = _context.SavedDrinks.Where(a => a.HomeCookId == homeCook.HomeCookId).ToList(); var savedFoods = _context.SavedFoods.Where(a => a.HomeCookId == homeCook.HomeCookId).ToList(); SavedRecipesViewModel recipesViewModel = new SavedRecipesViewModel() { SavedDrinks = savedDrinks, SavedFoods = savedFoods }; return View(recipesViewModel); } public async Task<IActionResult> ViewCart() { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var homeCook = _context.HomeCook.Where(c => c.IdentityUserId == userId).SingleOrDefault(); var cart = _context.ShoppingCart.Where(a => a.HomeCookId == homeCook.HomeCookId).FirstOrDefault(); return View(cart); } public async Task<IActionResult> DeleteCart(int id) { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var homeCook = _context.HomeCook.Where(c => c.IdentityUserId == userId).SingleOrDefault(); var cartToRemove = _context.ShoppingCart.Where(a => a.ShoppingCartId == id).FirstOrDefault(); _context.ShoppingCart.Remove(cartToRemove); _context.SaveChanges(); return View("Index", homeCook); } public async Task<IActionResult> DeleteFood(int id) { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var homeCook = _context.HomeCook.Where(c => c.IdentityUserId == userId).SingleOrDefault(); var foodToRemove = _context.SavedFoods.Where(a => a.SavedFoodsId == id).FirstOrDefault(); _context.SavedFoods.Remove(foodToRemove); _context.SaveChanges(); var savedFoods = _context.SavedFoods.Where(a => a.HomeCookId == homeCook.HomeCookId).ToList(); var savedDrinks = _context.SavedDrinks.Where(a => a.HomeCookId == homeCook.HomeCookId).ToList(); SavedRecipesViewModel recipesViewModel = new SavedRecipesViewModel() { SavedFoods = savedFoods, SavedDrinks = savedDrinks }; return View("ViewSavedRecipes", recipesViewModel); } public async Task<IActionResult> DeleteDrink(int id) { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var homeCook = _context.HomeCook.Where(c => c.IdentityUserId == userId).SingleOrDefault(); var drinkToRemove = _context.SavedDrinks.Where(a => a.SavedDrinksId == id).FirstOrDefault(); _context.SavedDrinks.Remove(drinkToRemove); _context.SaveChanges(); var savedFoods = _context.SavedFoods.Where(a => a.HomeCookId == homeCook.HomeCookId).ToList(); var savedDrinks = _context.SavedDrinks.Where(a => a.HomeCookId == homeCook.HomeCookId).ToList(); SavedRecipesViewModel recipesViewModel = new SavedRecipesViewModel() { SavedFoods = savedFoods, SavedDrinks = savedDrinks }; return View("ViewSavedRecipes", recipesViewModel); } // GET: HomeCooks/Edit/5 public async Task<IActionResult> Edit(int? id) { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var homeCook = _context.HomeCook.Where(c => c.IdentityUserId == userId).SingleOrDefault(); if (homeCook == null) { return NotFound(); } ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", homeCook.IdentityUserId); return View(homeCook); } // POST: HomeCooks/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("HomeCookId,FirstName,LastName,IdentityUserId")] HomeCook homeCook) { if (id != homeCook.HomeCookId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(homeCook); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!HomeCookExists(homeCook.HomeCookId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", homeCook.IdentityUserId); return View(homeCook); } // GET: HomeCooks/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var homeCook = await _context.HomeCook .Include(h => h.IdentityUser) .FirstOrDefaultAsync(m => m.HomeCookId == id); if (homeCook == null) { return NotFound(); } return View(homeCook); } // POST: HomeCooks/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var homeCook = await _context.HomeCook.FindAsync(id); _context.HomeCook.Remove(homeCook); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool HomeCookExists(int id) { return _context.HomeCook.Any(e => e.HomeCookId == id); } } }
using Microsoft.SharePoint; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Reflection; using System.Text; using System.Web; using System.Web.UI; namespace Waffles { public partial class testPage : Page { public static WDataOutput Output; public StringBuilder OutputHTML = new StringBuilder(); protected void Page_Load() { Output = new WDataOutput(); try { SPWebCollection webs = SPContext.Current.Site.AllWebs; List<string[]> pages_with_icons = new List<string[]>(); List<string[]> pages_with_url_get_contents = new List<string[]>(); foreach (SPWeb web in webs) { SPListItemCollection pages = web.Lists["Pages"].Items; foreach (SPListItem page in pages) { if ((page["Content"] ?? "").ToString().Contains("icon-")) pages_with_icons.Add(new string[] { page.Title, web.Url.TrimEnd('/') + "/" + page.Url }); if ((page["Content"] ?? "").ToString().Contains("url_get_contents")) pages_with_url_get_contents.Add(new string[] { page.Title, web.Url.TrimEnd('/') + "/" + page.Url }); } } Output.Add("pages_with_icons", pages_with_icons); Output.Add("pages_with_url_get_contents", pages_with_url_get_contents); } catch (Exception e) { Output.Add("Error: ", "" + e); } finally { if (OutputHTML.Length > 0) { Response.ContentType = "text/plain"; Response.Write(OutputHTML.ToString()); } else { Response.ContentType = "application/json"; Response.Write(WContext.Serialize(Output)); } Response.End(); } } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; using Triton.Game; using Triton.Game.Mono; [Attribute38("ParticleEffects")] public class ParticleEffects : MonoBehaviour { public ParticleEffects(IntPtr address) : this(address, "ParticleEffects") { } public ParticleEffects(IntPtr address, string className) : base(address, className) { } public void OnDrawGizmos() { base.method_8("OnDrawGizmos", Array.Empty<object>()); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public static float VectorAngle(Vector3 forwardVector, Vector3 targetVector, Vector3 upVector) { object[] objArray1 = new object[] { forwardVector, targetVector, upVector }; return MonoClass.smethod_14<float>(TritonHs.MainAssemblyPath, "", "ParticleEffects", "VectorAngle", objArray1); } public List<ParticleEffectsAttractor> m_ParticleAttractors { get { Class267<ParticleEffectsAttractor> class2 = base.method_3<Class267<ParticleEffectsAttractor>>("m_ParticleAttractors"); if (class2 != null) { return class2.method_25(); } return null; } } public ParticleEffectsOrientation m_ParticleOrientation { get { return base.method_3<ParticleEffectsOrientation>("m_ParticleOrientation"); } } public List<ParticleEffectsRepulser> m_ParticleRepulsers { get { Class267<ParticleEffectsRepulser> class2 = base.method_3<Class267<ParticleEffectsRepulser>>("m_ParticleRepulsers"); if (class2 != null) { return class2.method_25(); } return null; } } public bool m_WorldSpace { get { return base.method_2<bool>("m_WorldSpace"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Conditions { internal class Motor { public Motor() { ReadInt(); } private void ReadString() { Console.WriteLine("Escreve uma palavra:"); string word1 = Console.ReadLine(); Console.WriteLine("Escreve outra palavra"); string word2 = Console.ReadLine(); Console.WriteLine(ConcatString(word1, word2)); } private void ReadInt() { Console.WriteLine("Escreve um número :"); string word1 = Console.ReadLine(); Console.WriteLine("Escreve outro número"); string word2 = Console.ReadLine(); Sum(word1, word2); } private string ConcatString(string word1, string word2) { if (String.IsNullOrEmpty(word1) || String.IsNullOrEmpty(word2)) { throw new Exception("Valores vazios"); } return word1 + " " + word2; } private int Sum(string one, string two) { if(String.IsNullOrEmpty(one) || String.IsNullOrEmpty(two)) { throw new Exception("Valores vazios"); } int oneInt = Int32.Parse(one); int oneTwo = Int32.Parse(two); return oneInt + oneTwo; } private void WriteList(List<string> list) { string final = ""; if (list.Count == 0 || list == null) { throw new Exception("Valores vazios"); } for (int i = 0; i != list.Count; i++) { final += list[i]; } } } }
using System; using System.Collections.Generic; namespace QLTHPT.Models { public partial class Khoi { public Khoi() { Hocsinh = new HashSet<Hocsinh>(); } public string KhoiMa { get; set; } public string KhoiTen { get; set; } public virtual ICollection<Hocsinh> Hocsinh { get; set; } } }
// ----------------------------------------------------------------------- // <copyright file="JsonDictionaryConverter.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root // for license information. // </copyright> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; namespace Mlos.Model.Services.Spaces.JsonConverters { /// <summary> /// Converts a key value dictionary object to or from JSON. /// </summary> /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam> /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam> public class JsonDictionaryConverter<TKey, TValue> : JsonConverterWithExpectations<Dictionary<TKey, TValue>> { /// <inheritdoc/> public override Dictionary<TKey, TValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Expect(ref reader, expectedTokenType: JsonTokenType.StartObject); var value = new Dictionary<TKey, TValue>(); while (PeekNextTokenType(reader) == JsonTokenType.PropertyName) { Expect(ref reader, JsonTokenType.PropertyName); JsonConverter<TKey> keyConverter = (JsonConverter<TKey>)options.GetConverter(typeof(TKey)); TKey key = keyConverter.Read(ref reader, typeof(TKey), options); Expect(ref reader, JsonTokenType.StartObject); Expect(ref reader, JsonTokenType.PropertyName, "ObjectType"); Expect(ref reader, JsonTokenType.String, "set"); Expect(ref reader, JsonTokenType.PropertyName, "Values"); JsonConverter<TValue> valueConverter = (JsonConverter<TValue>)options.GetConverter(typeof(TValue)); TValue element = valueConverter.Read(ref reader, typeof(TValue), options); value.Add(key, element); Expect(ref reader, JsonTokenType.EndObject); } Expect(ref reader, JsonTokenType.EndObject); return value; } /// <inheritdoc/> public override void Write(Utf8JsonWriter writer, Dictionary<TKey, TValue> value, JsonSerializerOptions options) { writer.WriteStartObject(); foreach (var entry in value) { writer.WritePropertyName(entry.Key.ToString()); writer.WriteStartObject(); JsonSerializer.Serialize(writer, entry.Value, options); writer.WriteEndObject(); } writer.WriteEndObject(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Accord.Neuro; using Accord.Neuro.Networks; using Accord.Neuro.Learning; using Accord.Neuro.ActivationFunctions; using Accord.Math; using Accord.Statistics; using DeepLearning.Const; using System.Windows.Media.Imaging; using DeepLearning.VewModel; using System.Collections.ObjectModel; namespace DeepLearning.MachineLearning { public class DeepBeliefNetworks { private double[][] _inputs; private double[][] _outputs; private double[] _testInput; public void Init(double[][] inputs, double[][] outputs, double[] testInput) { _inputs = inputs; _outputs = outputs; _testInput = testInput; } public string Training(BitmapSource bitmapSource, MainWindowViewModel vm) { var result = string.Empty; // DBNの生成 // 〇 〇 〇 〇 〇 〇  // 〇 〇 〇 〇 // 〇 〇 var network = new DeepBeliefNetwork( inputsCount: _inputs[0].Length, // 入力層の次元 hiddenNeurons: new int[] { 50, DeepLearningConst.OutputDimention }); // 隠れ層と出力層の次元 // ネットワークの重みをガウス分布で初期化する new GaussianWeights(network).Randomize(); network.UpdateVisibleWeights(); // DBNの学習アルゴリズムの生成 5000回繰り返し入力 var teacher = new BackPropagationLearning(network); for (int i = 0; i < 5000; i++) { var error = teacher.RunEpoch(_inputs, _outputs); vm.LearningProgressItems.Add(string.Format("Epoch:{0} Error:{1} \r\n", i, error)); // 画像の切り替え if (i % 3 == 0) vm.TrainingBitmapSource = vm.ImageSourceList[i % 10].BitmapSource; } // 重みの更新 network.UpdateVisibleWeights(); // 学習されたネットワークでテストデータが各クラスに属する確率を計算 var output = network.Compute(_testInput); // 一番確率の高いクラスのインデックスを得る int imax; output.Max(out imax); result += string.Format("{0} \r\n", imax); // 結果出力 int index = 0; output.ToList().ForEach(x => { result += string.Format("{0}: {1} \r\n", index++, x); }); return result; } //public string Training() //{ // var result = string.Empty; // // トレーニングデータ // double[][] inputs = { // new double[] { 1, 1, 1, 0, 0, 0 }, // new double[] { 1, 0, 1, 0, 0, 0 }, // new double[] { 1, 1, 1, 0, 0, 0 }, // new double[] { 0, 0, 1, 1, 1, 0 }, // new double[] { 0, 0, 1, 1, 0, 0 }, // new double[] { 0, 0, 1, 1, 1, 0 }, // }; // double[][] outputs = { // new double[] { 1, 0 }, // new double[] { 1, 0 }, // new double[] { 1, 0 }, // new double[] { 1, 0 }, // new double[] { 0, 1 }, // new double[] { 0, 1 }, // new double[] { 0, 1 }, // }; // // DBNの生成 // var network = new DeepBeliefNetwork( // inputsCount: inputs.Length, // 入力層の次元 // hiddenNeurons: new int[] { 4, 2 }); // 隠れ層と出力層の次元 // // ネットワークの重みをガウス分布で初期化する // new GaussianWeights(network).Randomize(); // network.UpdateVisibleWeights(); // // DBNの学習アルゴリズムの生成 5000回繰り返し入力 // var teacher = new BackPropagationLearning(network); // for (int i = 0; i < 5000; i++) // { // var error = teacher.RunEpoch(inputs, outputs); // //result += string.Format("Error:{0} \r\n", error); // } // // 重みの更新 // network.UpdateVisibleWeights(); // // 学習されたネットワークでテストデータが各クラスに属する確率を計算 // double[] input = { 1, 1, 1, 1, 0, 0 }; // var output = network.Compute(input); // // 一番確率の高いクラスのインデックスを得る // int imax; output.Max(out imax); // result += string.Format("{0} \r\n", imax); // // 結果出力 // foreach (var o in output) // { // result += string.Format("{0} \r\n", o); // } // return result; //} } }
using AzureFunctions.Extensions.Swashbuckle.Attribute; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using SkillsGardenApi.Models; using SkillsGardenApi.Repositories; using SkillsGardenApi.Services; using SkillsGardenApi.Utils; using SkillsGardenDTO; using SkillsGardenDTO.Error; using System; using System.Collections.Generic; using System.Security.Claims; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace SkillsGardenApi.Controllers { class BeaconController { private BeaconService beaconService; private LocationService locationService; public BeaconController(BeaconService beaconService, LocationService locationService) { this.beaconService = beaconService; this.locationService = locationService; } [FunctionName("BeaconGetAll")] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status200OK)] public async Task<IActionResult> LocationGetAll( [HttpTrigger(AuthorizationLevel.User, "get", Route = "beacons")] HttpRequest req, [SwaggerIgnore] ClaimsPrincipal userClaim) { // only admin can update beacon if (!userClaim.IsInRole(UserType.Admin.ToString())) return ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)); // get the locations List<Beacon> beacons = await beaconService.GetAllBeacons(); return new OkObjectResult(beacons); } [FunctionName("BeaconGet")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task<IActionResult> BeaconGet( [HttpTrigger(AuthorizationLevel.User, "get", Route = "beacons/{beaconId}")] HttpRequest req, int beaconId, [SwaggerIgnore] ClaimsPrincipal userClaim) { // only admin can update beacon if (!userClaim.IsInRole(UserType.Admin.ToString())) return new UnauthorizedObjectResult(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)); // get the user Beacon beacon = await beaconService.GetBeaconById(beaconId); // if the user was not found if (beacon == null) return new NotFoundObjectResult(new ErrorResponse(ErrorCode.BEACON_NOT_FOUND)); //beacon not found return new OkObjectResult(beacon); } [FunctionName("BeaconCreate")] [ProducesResponseType(typeof(BeaconBody), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task<IActionResult> BeaconCreate( [HttpTrigger(AuthorizationLevel.User, "post", Route = "beacons")] [RequestBodyType(typeof(BeaconBody), "The beacon to create")] HttpRequest req, [SwaggerIgnore] ClaimsPrincipal userClaim) { // only admin can update beacon if (!userClaim.IsInRole(UserType.Admin.ToString())) return ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)); // deserialize request BeaconBody beaconBody; try { beaconBody = await SerializationUtil.Deserialize<BeaconBody>(req.Body); } catch (JsonException e) { return new BadRequestObjectResult(new ErrorResponse(400, e.Message)); } // check for required fields if (beaconBody.Name == null) return new BadRequestObjectResult(new ErrorResponse(400, "Name is required")); if (beaconBody.LocationId == null) return new BadRequestObjectResult(new ErrorResponse(400, "LocationId is required")); if (beaconBody.Lat == null) return new BadRequestObjectResult(new ErrorResponse(400, "Latitude is required")); if (beaconBody.Lng == null) return new BadRequestObjectResult(new ErrorResponse(400, "Longitude is required")); if (!await locationService.Exists((int)beaconBody.LocationId)) return new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)); // create user Beacon createdBeacon = await this.beaconService.CreateBeacon(beaconBody); return new OkObjectResult(createdBeacon); } [FunctionName("BeaconUpdate")] [ProducesResponseType(typeof(UserBody), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task<IActionResult> BeaconUpdate( [HttpTrigger(AuthorizationLevel.User, "put", Route = "beacons/{beaconId}")] [RequestBodyType(typeof(BeaconBody), "The beacon to update")] HttpRequest req, int beaconId, [SwaggerIgnore] ClaimsPrincipal userClaim) { // only admin can update beacon if (!userClaim.IsInRole(UserType.Admin.ToString())) return ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)); // deserialize request BeaconBody beaconBody; try { beaconBody = await SerializationUtil.Deserialize<BeaconBody>(req.Body); } catch (JsonException e) { return new BadRequestObjectResult(new ErrorResponse(400, e.Message)); } if (beaconBody.LocationId != null && !await locationService.Exists((int)beaconBody.LocationId)) return new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)); // update beacon Beacon updatedBeacon = await this.beaconService.UpdateBeacon(beaconId, beaconBody); // when beacon was not found if (updatedBeacon == null) return new NotFoundObjectResult(new ErrorResponse(ErrorCode.BEACON_NOT_FOUND)); return new OkObjectResult(updatedBeacon); } [FunctionName("BeaconDelete")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status401Unauthorized)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task<IActionResult> BeaconDelete( [HttpTrigger(AuthorizationLevel.User, "delete", Route = "beacons/{beaconId}")] HttpRequest req, int beaconId, [SwaggerIgnore] ClaimsPrincipal userClaim) { // only admin can delete user if (!userClaim.IsInRole(UserType.Admin.ToString())) return ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_TO_DELETE_USER)); // delete beacon bool isDeleted = await beaconService.DeleteBeacon(beaconId); // if beacon was not found if (!isDeleted) return new NotFoundObjectResult(new ErrorResponse(ErrorCode.BEACON_NOT_FOUND)); return new OkResult(); } } }
using System; using System.Collections.Generic; using System.Text; namespace SudokuApp { class ViewController { public void WriteandAdd(Sudokulist sl, int value, int i, int f, bool possible) { if (value > 0 && possible) { sl.Sudokus.Find(x => x.number == value).AddValues(value, i, f); } if (f != 9 - 1) { if (value == 0) { Console.Write(" "); } else Console.Write(value); Console.Write('|'); } else { if (value == 0) { Console.Write(" "); } else Console.Write(value); Console.WriteLine(); } } } }
using DryIoc.Microsoft.DependencyInjection.Extension; using LDMApp.Views; using Prism.DryIoc; using Prism.Ioc; using Refit; using System.Windows; using LDMApp.Services.Interfaces; using LDMApp.Core; using LDMApp.Services; using Microsoft.Extensions.DependencyInjection; using System; using Prism.Modularity; using LDMApp.Modules.MenuBar; using LDMApp.Modules.Samples; using LDMApp.Module.Images; using LDMApp.Dialogs; using LDMApp.Modules.DatasetImport.Views; using LDMApp.Modules.DatasetImport; using LDMApp.Modules.DatasetImport.ViewModels; namespace LDMApp { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.GetContainer().RegisterServices(services => { services.AddRefitClient<IDatasetApi>() .ConfigureHttpClient(c => c.BaseAddress = new Uri(ApiSettings.DatasetApiURL)); services.AddRefitClient<ISamplesApi>() .ConfigureHttpClient(c => c.BaseAddress = new Uri(ApiSettings.SamplesApiURL)); services.AddRefitClient<IImagesApi>() .ConfigureHttpClient(c => c.BaseAddress = new Uri(ApiSettings.ImagesApiURL)); }); containerRegistry.RegisterDialog<DatasetSelectDialog, DatasetSelectDialogViewModel>(); containerRegistry.RegisterDialog<DatasetImportDialog, DatasetImportDialogViewModel>(); } protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) { moduleCatalog.AddModule<MenuBarModule>(); moduleCatalog.AddModule<SamplesModule>(); moduleCatalog.AddModule<ImagesModule>(); moduleCatalog.AddModule<DatasetImportModule>(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EventQuery.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using CGI.Reflex.Core.Entities; using NHibernate; using NHibernate.Criterion; namespace CGI.Reflex.Core.Queries { public class EventQuery : BaseQueryOver<Event> { public int? ApplicationId { get; set; } public string SourceLike { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } public int? TypeId { get; set; } public string DescriptionLike { get; set; } protected override IQueryOver<Event, Event> OverImpl(ISession session) { var query = session.QueryOver<Event>(); if (ApplicationId.HasValue) query.Where(e => e.Application.Id == ApplicationId.Value); if (!string.IsNullOrEmpty(SourceLike)) query.Where(Restrictions.InsensitiveLike(Projections.Property<Event>(e => e.Source), SourceLike, MatchMode.Anywhere)); if (DateFrom.HasValue) query.Where(e => e.Date >= DateFrom.Value); if (DateTo.HasValue) query.Where(e => e.Date <= DateTo.Value); if (TypeId.HasValue) query.Where(e => e.Type.Id == TypeId.Value); if (!string.IsNullOrEmpty(DescriptionLike)) query.Where(Restrictions.InsensitiveLike(Projections.Property<Event>(e => e.Description), DescriptionLike, MatchMode.Anywhere)); return query; } protected override bool OrderByCallback(IQueryOver<Event, Event> queryOver, string propertyName, OrderType orderType) { switch (propertyName) { case "EventType.Name": queryOver.JoinQueryOver(a => a.Type).OrderByDomainValue(orderType); queryOver.OrderBy(a => a.Date, OrderType.Desc); return true; case "Source": queryOver.OrderBy(a => a.Source, orderType).OrderBy(a => a.Date, OrderType.Desc); return true; default: return false; } } } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { public class StockItemBatchAudit { public Int32 BatchId; public Int32 BatchInventoryId; public Int32 QuantityDelta; public Decimal StockValueDelta; public String ChangeNote; public String Username; public DateTime ChangeDate; public String BinRack; public String BatchNumber; public String Location; } }
using System; using System.Collections.Generic; using System.Text; namespace PDTech.OA.Model { [Serializable] public class Pro_TASKHandle { /// <summary> /// 当前任务ID /// </summary> public decimal? P_TASK_ID { get; set; } /// <summary> /// 下一步骤ID /// </summary> public decimal? P_NEXT_STEP_ID { get; set; } /// <summary> /// 跳过下一步原因 如果有 /// </summary> public string P_SKIPP_REMARK { get; set; } /// <summary> /// 下一个任务的用户ID /// </summary> public string P_NEXT_USER_LIST { get; set; } /// <summary> /// 当前任务备注和说明 /// </summary> public string P_TASK_REMARK { get; set; } /// <summary> /// 任务时限 /// </summary> public DateTime? P_LIMIT_TIME { get; set; } /// <summary> /// 是否立即发送短信 1:发送 0:不发送 /// </summary> public decimal? P_IS_SEND_SMS_NOW { get; set; } /// <summary> /// 工作到期之前是否发送短信 1:发送 0:不发送 /// </summary> public decimal? P_IS_SEND_SMS_LIMIT { get; set; } /// <summary> /// 工作到期之前发送短信时间 /// </summary> public DateTime? P_SMS_LIMIT_TIME { get; set; } /// <summary> /// 短信接收人类型1:下一步操作人员、2:当前和下一步操作人员 /// </summary> public decimal? P_SMS_TO_USER_TYPE { get; set; } /// <summary> /// 0表示失败,其它表示成功 /// </summary> public decimal? RESULTCODE { get; set; } /// <summary> /// 盖章时需要保护的数据 /// </summary> public string P_PROTECT_DATA { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using Marchen.DAL; using Marchen.Model; using Message = Sisters.WudiLib.SendingMessage; using Sisters.WudiLib.Responses; using Marchen.Helper; namespace Marchen.BLL { class CaseRemind : GroupMsgBLL { /// <summary> /// At未出满三刀的成员 /// </summary> /// <param name="strGrpID">消息发起人所属群号</param> /// <param name="strUserID">消息发起人QQ号</param> /// <param name="memberInfo">消息发起人的成员资料</param> public static void NoticeRemainStrikers(string strGrpID, string strUserID, GroupMemberInfo memberInfo) { if (!(memberInfo.Authority == GroupMemberInfo.GroupMemberAuthority.Leader || memberInfo.Authority == GroupMemberInfo.GroupMemberAuthority.Manager)) { MsgMessage += new Message("拒绝:仅有管理员或群主可执行出刀提醒指令。\r\n"); ApiProperties.HttpApi.SendGroupMessageAsync(long.Parse(strGrpID), MsgMessage).Wait(); return; } DataTable dtResult; try { RecordDAL.QueryStrikeStatus(strGrpID, out dtResult); } catch (Exception ex) { MsgMessage += Message.At(long.Parse(strUserID)); MsgMessage += new Message(ex.Message.ToString()); ApiProperties.HttpApi.SendGroupMessageAsync(long.Parse(strGrpID), MsgMessage).Wait(); return; } MsgMessage += new Message("请以下成员尽早出刀:"); for (int i = 0; i < dtResult.Rows.Count; i++) { string strUID = dtResult.Rows[i]["MBRID"].ToString(); int intCountMain = int.Parse(dtResult.Rows[i]["cmain"].ToString()); int intCountLastAtk = int.Parse(dtResult.Rows[i]["cla"].ToString()); int intCountExTime = int.Parse(dtResult.Rows[i]["cex"].ToString()); if ((intCountMain + intCountLastAtk) < 3) { if (intCountLastAtk > intCountExTime) { MsgMessage += new Message("\r\nID:" + strUID + ",剩余" + (3 - (intCountMain + intCountLastAtk)).ToString() + "刀与补时刀 ") + Message.At(long.Parse(strUID)); } else { MsgMessage += new Message("\r\nID:" + strUID + ",剩余" + (3 - (intCountMain + intCountLastAtk)).ToString() + "刀 ") + Message.At(long.Parse(strUID)); } } } ApiProperties.HttpApi.SendGroupMessageAsync(long.Parse(strGrpID), MsgMessage).Wait(); } /// <summary> /// 查询成员出刀情况 /// </summary> /// <param name="strGrpID">消息发起人所属群号</param> /// <param name="strUserID">消息发起人QQ号</param> /// <param name="memberInfo">消息发起人的成员资料</param> /// <param name="intType">命令种类:1=只显示不提醒;2=提醒全部没满三刀的;3=只提醒三刀都没出的</param> //public static void RemainStrikes(string strGrpID, string strUserID,GroupMemberInfo memberInfo,int intType) //{ // if (!ClanInfoDAL.GetClanTimeOffset(strGrpID, out int intHourSet)) // { // MsgMessage += new Message("与数据库失去连接,查询区域时间设定失败。\r\n"); // MsgMessage += Message.At(long.Parse(strUserID)); // ApiProperties.HttpApi.SendGroupMessageAsync(long.Parse(strGrpID), MsgMessage).Wait(); // return; // } // if (intHourSet < 0) // { // MsgMessage += new Message("每日更新小时设定小于0,尚未验证这种形式的时间格式是否正常,已退回本功能。\r\n"); // MsgMessage += Message.At(long.Parse(strUserID)); // ApiProperties.HttpApi.SendGroupMessageAsync(long.Parse(strGrpID), MsgMessage).Wait(); // return; // } // if (RecordDAL.QueryTimeNowOnDatabase(out DataTable dtResultTime)) // { // DateTime dtNow = (DateTime)dtResultTime.Rows[0]["sysdate"]; // DateTime dtStart = CmdHelper.GetZeroTime(dtNow).AddHours(intHourSet);//每天凌晨4点开始 // DateTime dtEnd = CmdHelper.GetZeroTime(dtNow.AddDays(1)).AddHours(intHourSet);//第二天凌晨4点结束 // if (dtNow.Hour >= 0 && dtNow.Hour < intHourSet) // { // dtStart = dtStart.AddDays(-1);//每天凌晨4点开始 // dtEnd = dtEnd.AddDays(-1);//第二天凌晨4点结束 // } // if (RecordDAL.QueryStrikeStatus(strGrpID, dtStart, dtEnd, out DataTable dtInsuff)) // { // //MsgMessage += new Message("截至目前尚有余刀的成员:"); // //int intCount = 0; // //string strLeft1 = ""; // //string strLeft2 = ""; // //string strLeft3 = ""; // //for (int i = 0; i < dtInsuff.Rows.Count; i++) // //{ // // string strUID = dtInsuff.Rows[i]["userid"].ToString(); // // int intCountMain = int.Parse(dtInsuff.Rows[i]["cmain"].ToString()); // // if (intCountMain == 2) // // { // // intCount += 1; // // strLeft1 += "\r\nID:" + strUID + ",剩余1刀"; // // } // // if (intCountMain == 1) // // { // // intCount += 2; // // strLeft2 += "\r\nID:" + strUID + ",剩余2刀"; // // } // // if (intCountMain == 0) // // { // // intCount += 3; // // strLeft3 += "\r\nID:" + strUID + ",剩余3刀"; // // } // //} // //MsgMessage += new Message(strLeft1 + "\r\n--------------------" + strLeft2 + "\r\n--------------------" + strLeft3); // //MsgMessage += new Message("\r\n合计剩余" + intCount.ToString() + "刀"); // } // else // { // //MsgMessage += new Message("与数据库失去连接,查询失败。\r\n"); // //MsgMessage += Message.At(long.Parse(strUserID)); // } // } // else // { // //MsgMessage += new Message("与数据库失去连接,查询失败。\r\n"); // //MsgMessage += Message.At(long.Parse(strUserID)); // } // //ApiProperties.HttpApi.SendGroupMessageAsync(long.Parse(strGrpID), MsgMessage).Wait(); //} /// <summary> /// 查询未出满三刀的成员 /// </summary> /// <param name="strGrpID">消息发起人所属群号</param> /// <param name="strUserID">消息发起人QQ号</param> public static void ShowRemainStrikes(string strGrpID, string strUserID,string strCmdContext) { if (!CmdHelper.CmdSpliter(strCmdContext)) { //MsgMessage += Message.At(long.Parse(strUserID)); ApiProperties.HttpApi.SendGroupMessageAsync(long.Parse(strGrpID), MsgMessage).Wait(); return; } DataTable dtResult; try { RecordDAL.QueryStrikeStatus(strGrpID, out dtResult); } catch (Exception ex) { MsgMessage += Message.At(long.Parse(strUserID)); MsgMessage += new Message(ex.Message.ToString()); ApiProperties.HttpApi.SendGroupMessageAsync(long.Parse(strGrpID), MsgMessage).Wait(); return; } MsgMessage += new Message("截至目前尚有余刀的成员:"); int intCountLeft = 0; int intCountUsed = 0; int intCountExLeft = 0; string strLeft1 = ""; string strLeft2 = ""; string strLeft3 = ""; string strLeft0_EX = ""; string strLeft1_EX = ""; string strLeft2_EX = ""; string strErr = ""; for (int i = 0; i < dtResult.Rows.Count; i++) { string strUID = dtResult.Rows[i]["MBRID"].ToString(); string strUName = dtResult.Rows[i]["MBRNAME"].ToString(); int intCountMain = int.Parse(dtResult.Rows[i]["cmain"].ToString()); int intCountLastAtk = int.Parse(dtResult.Rows[i]["cla"].ToString()); int intCountExTime = int.Parse(dtResult.Rows[i]["cex"].ToString()); if ((intCountMain + intCountLastAtk) > 3) { //一种异常,主+尾刀超出了3,记为3刀 intCountUsed += 3; strErr += "\r\n异常:" + strUName + "(" + strUID + "),非补时刀数超过3,请检查"; } if (intCountLastAtk < intCountExTime) { //一种异常,补时刀大于尾刀,记为主+补时刀 intCountUsed += (intCountMain + intCountLastAtk); intCountLeft += 3 - (intCountMain + intCountLastAtk); strErr += "\r\n异常:" + strUName + "(" + strUID + "),补时刀数(" + intCountExTime + ")与尾刀数(" + intCountLastAtk + ")不匹配,请检查(推测剩余" + (3 - (intCountMain + intCountLastAtk)).ToString() + "刀)"; } if ((intCountMain + intCountLastAtk) == 3) { if (intCountLastAtk > intCountExTime) { intCountUsed += 3; intCountExLeft += 1; strLeft0_EX += "\r\n仅剩补时刀:" + strUName + "(" + strUID + ")"; } else { intCountUsed += 3; } } if ((intCountMain + intCountLastAtk) == 2) { if (intCountLastAtk > intCountExTime) { intCountExLeft += 1; intCountUsed += 2; intCountLeft += 1; strLeft1_EX += "\r\n剩余1刀+补时刀:" + strUName + "(" + strUID + ")"; } else { intCountUsed += 2; intCountLeft += 1; strLeft1 += "\r\n剩余1刀:" + strUName + "(" + strUID + ")"; } } if ((intCountMain + intCountLastAtk) == 1) { if (intCountLastAtk > intCountExTime) { intCountExLeft += 1; intCountUsed += 1; intCountLeft += 2; strLeft2_EX += "\r\n剩余2刀+补时刀:" + strUName + "(" + strUID + ")"; } else { intCountUsed += 1; intCountLeft += 2; strLeft2 += "\r\n剩余2刀:" + strUName + "(" + strUID + ")"; } } if ((intCountMain + intCountLastAtk) == 0) { intCountLeft += 3; strLeft3 += "\r\n剩余3刀:" + strUName + "(" + strUID + ")"; } } MsgMessage += new Message("\r\n--------------------"); if (strLeft0_EX != null && strLeft0_EX != "") { MsgMessage += new Message(strLeft0_EX + "\r\n--------------------"); } if (strLeft1_EX != null && strLeft1_EX != "") { MsgMessage += new Message(strLeft1_EX + "\r\n--------------------"); } if (strLeft2_EX != null && strLeft2_EX != "") { MsgMessage += new Message(strLeft2_EX + "\r\n--------------------"); } if (strLeft1 != null && strLeft1 != "") { MsgMessage += new Message(strLeft1 + "\r\n--------------------"); } if (strLeft2 != null && strLeft2 != "") { MsgMessage += new Message(strLeft2 + "\r\n--------------------"); } if (strLeft3 != null && strLeft3 != "") { MsgMessage += new Message(strLeft3 + "\r\n--------------------"); } MsgMessage += new Message("\r\n合计已出" + intCountUsed.ToString() + "刀\r\n合计剩余" + intCountLeft.ToString() + "刀," + intCountExLeft.ToString() + "补时刀"); if (strErr != null && strErr != "") { MsgMessage += new Message("\r\n--------------------" + strErr); } MsgSendHelper.UniversalMsgSender(MsgSendType.Auto, MsgTargetType.Group, strGrpID, MsgMessage); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace GameUtilities { /// <summary> /// Button class that contains a texture and a position /// </summary> public class GameButton { private Texture2D image; private Vector2 position; /// <summary> /// Constructs a new Button using a Texture for that Button and the position it should be on screen /// </summary> /// <param name="i">Texture that represents this button</param> /// <param name="p">Position on the screen where the button is located</param> public GameButton(Texture2D i, Vector2 p) { image = i; position = p; } /// <summary> /// Access the texture /// </summary> /// <returns></returns> public Texture2D Texture { get { return image; } } public Vector2 Position { get { return position; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TurnIndicator : MonoBehaviour { //Flag Variables [Header("Flag Variables")] [SerializeField] bool singleUse; [SerializeField] bool switcher; [SerializeField] bool switching; //Direction Variables [Header("Direction Variables")] [SerializeField] int directionIndex; [SerializeField] string directionTag; [SerializeField] List<string> directionMap = new List<string>(); //Main Methods // Start is called before the first frame update void Start() { switching = true; if(switcher) { directionIndex = 0; } } // Update is called once per frame void Update() { if (switcher) { directionTag = directionMap[directionIndex]; } } //Custom Methods //If the TurnIndicator is a switcher, it sends the command to switch to the next direction on the list public void OnTriggerExit(Collider collision) { if(switching) { UnityEngine.Debug.Log("I know that a car has exited my collider"); switching = false; StartCoroutine(SwitchLabel()); StartCoroutine(waitToSwitch()); } } //switches the label on the turn indicator if it is a switcher, activated in the OnTriggerExit Method private IEnumerator SwitchLabel() { UnityEngine.Debug.Log("The Coroutine is starting"); yield return new WaitForSeconds(1f); if (switcher) { directionIndex += 1; if (directionIndex >= directionMap.Count) { directionIndex = 0; } directionTag = directionMap[directionIndex]; } //switching = true; } //tells the turnIndicator to wait to switch it's label to make sure that it doesn't collide with the car multiple times public IEnumerator waitToSwitch() { yield return new WaitForSeconds(.5f); switching = true; } //Accessors and Mutators //Accesses the directionTag variable public string GetDirection() { return directionTag; } //Mutates the directionTag variable public void SetDirection(string direction) { directionTag = direction; } //Returns true if the indicator is a switcher public bool IsSwitcher() { return switcher; } //Mutates the value of switcher to become true public void MakeSwitcher() { switcher = true; } //Returns true if the turn indicator is single use public bool GetFrequency() { return singleUse; } //Adds another string value to the direction map public void AddToDirectionMap(string direction) { directionMap.Add(direction); } }
using System; using System.ComponentModel; using System.Diagnostics; using ww898.AELauncher.Impl.Interop; namespace ww898.AELauncher.Impl { internal static class ElevationUtil { public static unsafe bool IsUacEnabled() { if (Environment.OSVersion.Version < new Version(6, 0)) return false; uint elevationFlags; var error = NtDllDll.RtlQueryElevationFlags(&elevationFlags); if (error != (int) WinError.ERROR_SUCCESS) throw new Win32Exception(error, "Can't get elevation flags"); return ((ELEVATION_FLAGS) elevationFlags & ELEVATION_FLAGS.ELEVATION_UAC_ENABLED) != 0; } public static unsafe TOKEN_ELEVATION_TYPE GetElevationType(Process process) { if (process == null) throw new ArgumentNullException(nameof(process)); if (Environment.OSVersion.Version < new Version(6, 0)) return TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault; void* handle; if (Advapi32Dll.OpenProcessToken(process.Handle.ToPointer(), (uint) TokenAccessRights.TOKEN_QUERY, &handle) == 0) throw new Win32Exception("Can't open process token"); try { TOKEN_ELEVATION_TYPE tet; var size = (uint) sizeof(TOKEN_ELEVATION_TYPE); if (Advapi32Dll.GetTokenInformation(handle, (int) TOKEN_INFORMATION_CLASS.TokenElevationType, &tet, size, &size) == 0) throw new Win32Exception("Can't get elevation type"); return tet; } finally { Kernel32Dll.CloseHandle(handle); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Stage3Talk : StageBase { public GameObject makiObject; GameObject maki; GameObject makiChara; Maki makiScript; //GraphDiffer akariEyeBrows, akariEye, akariMouse, akariOption; //GraphDiffer makiBody, makiEyeBrows, makiEye, makiMouse, makiOption; GraphDiffer makiBody; protected CharaPicture makiPicture; int firstObentouBulletCount; int firstMaxHp; // Start is called before the first frame update void Start() { StaticValues.havingShooter = 1; ResetSceneParameters(); step = StaticValues.stage3Step; firstObentouBulletCount = StaticValues.obentouBulletMax; firstMaxHp = StaticValues.maxHp; makiChara = GameObject.Find("Maki"); if (makiChara != null) makiScript = makiChara.GetComponent<Maki>(); if (StaticValues.isEXMode) { step = 9999; GameObject.Find("door").SetActive(false); } AkariInstantiate(); MakiInstantiate(); AudioManager.Instance.ChangeDSPSnapshot("AddReverb"); LoadACB("Stage3", "Stage3.acb"); PlayBGM("stage"); StaticValues.Save(); } // Update is called once per frame void Update() { bool forceNext = false; time += Time.deltaTime; // ボス撃破後に連打でページ送りしてしまうのを防止するため1秒入力を受け付けない if (StaticValues.isTalkPause) { if (time >= 1.0f) { StaticValues.isTalkPause = false; } else { return; } } if (step == 0 && time >= 2.0f) forceNext = true; if (step <= 2) StaticValues.isPause = true; if (firstObentouBulletCount != StaticValues.obentouBulletMax) { firstObentouBulletCount = StaticValues.obentouBulletMax; tmpStep = step; step = 101; forceNext = true; } if (firstMaxHp != StaticValues.maxHp) { firstMaxHp = StaticValues.maxHp; tmpStep = step; step = 201; forceNext = true; } if (bossStageEntrance != null && bossStageEntrance.GetTrigger() && !isBossEnter) { if (StaticValues.isEXMode) { isBossEnter = true; enemyGaugeScript.PlayGaugeAppear(); PlayBGM("boss"); } else { StaticValues.isPause = true; if (!cameraScript.IsFixPosMoving()) { isBossEnter = true; tmpStep = step; step = 501; forceNext = true; } } } if (makiScript != null && makiScript.IsDead() && !isBossDead) { if (StaticValues.isEXMode) { ChangeScene("Stage4-5"); } else { isBossDead = true; tmpStep = step; step = 601; forceNext = true; } } if (makiChara != null && !isBossDead) { } if (Input.GetButtonDown("Shot") || Input.GetButtonDown("Jump") || forceNext) { UpdateStep(); } StaticValues.stage3Step = step; } void UpdateStep() { switch (step) { case 0: akari.GetComponent<Animator>().SetBool("isOut", false); akariPicture.SetSprite("sad", "normal", "omega"); AddTextWindow(speechWindowLeft, "洞窟はもっと暗いなぁ!"); PlayVoice("Stage3Akari-0"); break; case 1: akariPicture.eye.SetSprite("close"); AddTextWindow(speechWindowLeft, "気をつけて進もう"); PlayVoice("Stage3Akari-1"); break; case 2: step++; break; case 3: akari.GetComponent<Animator>().SetBool("isOut", true); step++; StaticValues.isPause = false; break; case 4: break; case 5: break; case 6: step++; break; case 7: break; case 101: StaticValues.isPause = true; akariPicture.SetSprite("normal", "shiitake", "laugh"); akari.GetComponent<Animator>().SetBool("isOut", false); AddTextWindow(speechWindowLeft, "携帯食だ!"); PlayVoice("Stage3Akari-2"); break; case 102: akariPicture.SetSprite("", "smile", "omega"); akari.GetComponent<Animator>().SetBool("isOut", false); AddTextWindow(speechWindowLeft, "お弁当の量が\n増えました!"); PlayVoice("Stage3Akari-3"); break; case 103: step++; break; case 104: StaticValues.isPause = false; akari.GetComponent<Animator>().SetBool("isOut", true); step = tmpStep; break; case 105: break; case 201: StaticValues.isPause = true; akariPicture.SetSprite("anger", "star", "laugh"); akari.GetComponent<Animator>().SetBool("isOut", false); AddTextWindow(speechWindowLeft, "パワーアップアイテムだ!"); PlayVoice("Stage3Akari-4"); break; case 202: StaticValues.isPause = true; akariPicture.SetSprite("normal", "smile"); AddTextWindow(speechWindowLeft, "体力が少し増えました!"); PlayVoice("Stage3Akari-5"); break; case 203: step++; break; case 204: StaticValues.isPause = false; akari.GetComponent<Animator>().SetBool("isOut", true); step = tmpStep; break; case 205: break; case 501: maki.GetComponent<Animator>().SetBool("isOut", false); makiBody.SetSprite("maki"); makiPicture.SetSprite("sad", "normal", "o"); AddTextWindow(speechWindowRight, "う〜ん...\nどうしようかな"); PlayVoice("Stage3Maki-0"); break; case 502: akari.GetComponent<Animator>().SetBool("isOut", false); akariPicture.SetSprite("anger", "shiitake", "laugh", "star"); AddTextWindow(speechWindowLeft, "マキさんだ!"); PlayVoice("Stage3Akari-6"); break; case 503: makiScript.SetIsRight(false); makiPicture.SetSprite("normal", "", "laugh"); AddTextWindow(speechWindowRight, "おっ、あかりちゃん"); PlayVoice("Stage3Maki-1"); break; case 504: akariPicture.SetSprite("normal", "white", "omega", "nothing"); AddTextWindow(speechWindowLeft, "難しい顔して、\nどうかしたんですか?"); PlayVoice("Stage3Akari-7"); break; case 505: makiPicture.SetSprite("sad"); AddTextWindow(speechWindowRight, "それがねぇ、先に進む道に\n変なギミックが追加されててさ"); PlayVoice("Stage3Maki-2"); break; case 506: AddTextWindow(speechWindowRight, "誰かが仕掛けを\n作動させている間だけ\n通れるみたいなんだ"); PlayVoice("Stage3Maki-3"); break; case 507: akariPicture.SetSprite("sad", "normal", "omega"); AddTextWindow(speechWindowLeft, "一人では先に進めない\nっていうことですね"); PlayVoice("Stage3Akari-8"); break; case 508: makiPicture.SetSprite("", "half_open", "omega"); AddTextWindow(speechWindowRight, "きっとそんな感じかなあ"); PlayVoice("Stage3Maki-4"); break; case 509: makiPicture.SetSprite("anger", "normal", "laugh"); AddTextWindow(speechWindowRight, "そうだ!"); PlayVoice("Stage3Maki-5"); break; case 510: makiPicture.SetSprite("", "smile"); AddTextWindow(speechWindowRight, "私たちでバトルして、\n勝った方が先に進む\nっていうのはどうかな!"); PlayVoice("Stage3Maki-6"); break; case 511: akariPicture.SetSprite("anger", "half_open", "mu"); AddTextWindow(speechWindowLeft, "なるほど、負けた方が\n仕掛け係をするんですね"); PlayVoice("Stage3Akari-9"); break; case 512: akariPicture.SetSprite("anger", "shiitake", "mu"); AddTextWindow(speechWindowLeft, "わかりました!"); PlayVoice("Stage3Akari-10"); break; case 513: makiPicture.SetSprite("", "close", "omega"); AddTextWindow(speechWindowRight, "よーし、どっちが勝っても\n恨みっこなしだよ"); PlayVoice("Stage3Maki-7"); break; case 514: makiPicture.SetSprite("", "normal", "laugh"); AddTextWindow(speechWindowRight, "いざ勝負!"); PlayVoice("Stage3Maki-8"); break; case 515: step++; break; case 516: PlayBGM("boss"); akari.GetComponent<Animator>().SetBool("isOut", true); maki.GetComponent<Animator>().SetBool("isOut", true); enemyGaugeScript.PlayGaugeAppear(); step++; break; case 517: break; case 601: StaticValues.isPause = true; StaticValues.isTalkPause = true; time = 0; AudioManager.Instance.FadeInBGM("stage"); akari.GetComponent<Animator>().SetBool("isOut", false); maki.GetComponent<Animator>().SetBool("isOut", false); makiPicture.SetSprite("sad", "white_tears", "omega"); AddTextWindow(speechWindowRight, "やられたー!"); PlayVoice("Stage3Maki-9"); break; case 602: akariPicture.SetSprite("anger", "smile", "laugh"); AddTextWindow(speechWindowLeft, "やったー!"); PlayVoice("Stage3Akari-11"); break; case 603: makiPicture.SetSprite("", "normal", "laugh"); AddTextWindow(speechWindowRight, "強いねー、完敗だよ"); PlayVoice("Stage3Maki-10"); break; case 604: makiPicture.SetSprite("", "smile", "laugh"); AddTextWindow(speechWindowRight, "約束通り先に進ませてあげるね"); PlayVoice("Stage3Maki-11"); break; case 605: akariPicture.SetSprite("normal", "normal", "laugh"); AddTextWindow(speechWindowLeft, "ありがとうございます!"); PlayVoice("Stage3Akari-12"); break; case 606: makiPicture.SetSprite("anger", "normal", "laugh"); AddTextWindow(speechWindowRight, "それともう一つ、\nこれもあげちゃう"); PlayVoice("Stage3Maki-12"); break; case 607: StaticValues.havingShooter = 2; akariPicture.SetSprite("normal", "white", "o"); AddTextWindow(speechWindowLeft, "これは...?"); PlayVoice("Stage3Akari-13"); break; case 608: makiPicture.SetSprite("", "half_open", "omega"); AddTextWindow(speechWindowRight, "その装備は、名付けて\nエレキバリヤー!!"); PlayVoice("Stage3Maki-13"); break; case 609: akariPicture.SetSprite("normal", "white", "omega"); AddTextWindow(speechWindowLeft, "エレキバリヤー?"); PlayVoice("Stage3Akari-14"); break; case 610: makiPicture.SetSprite("", "close", "laugh"); AddTextWindow(speechWindowRight, "周囲に電気のバリアを纏って\n攻撃を受け付けないのさ!"); PlayVoice("Stage3Maki-14"); break; case 611: akariPicture.SetSprite("anger", "star", "laugh"); AddTextWindow(speechWindowLeft, "すごい!\nそれなら飛びかかってくる\n敵にも安心ですね!"); PlayVoice("Stage3Akari-15"); break; case 612: makiPicture.SetSprite("normal", "smile"); AddTextWindow(speechWindowRight, "サブウェポン切り替え(SPACE)\nをして使ってね"); PlayVoice("Stage3Maki-15"); break; case 613: akariPicture.SetSprite("normal", "smile", "laugh"); AddTextWindow(speechWindowLeft, "了解です!"); PlayVoice("Stage3Akari-16"); break; case 614: makiPicture.SetSprite("", "normal"); AddTextWindow(speechWindowRight, "よーし、\nそれじゃあ道を開けるよ\n頑張ってきてね!"); PlayVoice("Stage3Maki-16"); break; case 615: akariPicture.SetSprite("anger", "normal", "laugh"); maki.GetComponent<Animator>().SetBool("isOut", true); AddTextWindow(speechWindowLeft, "はい、行ってきます!"); PlayVoice("Stage3Akari-17"); break; case 616: akari.GetComponent<Animator>().SetBool("isOut", true); step++; break; case 617: ChangeScene("Stage4-1"); step++; break; case 618: break; } } void PlayVoice(string seName) { AudioManager.Instance.PlayExVoice(seName); } void MakiInstantiate() { maki = Instantiate(makiObject); maki.transform.parent = transform.parent; maki.transform.localScale = new Vector2(1, 1); makiBody = maki.GetComponent<GraphDiffer>(); makiPicture = new CharaPicture(maki); DontDestroyOnLoad(maki); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Recording.Models.ResponseModels.RecordingInfo { public class RecordingInfoListResponse { } }
using quanlysinhvien.Models.EF; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace quanlysinhvien.Models.DAO { public class SinhVienDAO : baseDAO { public List<SinhVien> getAll() { return db_.SinhVien.ToList(); } public string addStudent(string [] data,Image avt) { try { string malop = data[8]; var getMaLop = db_.Lop.Where(lop => lop.MaLop.CompareTo(malop) == 0).ToList(); string maSv = data[0]; var getMaSv = db_.SinhVien.Where(sv => sv.MaSV.CompareTo(maSv) == 0).ToList(); if (getMaLop.Any()) { if (getMaSv.Count() == 0) { bool gender; if (data[4] == "nam") { gender = true; } else { gender = false; } SinhVien sv = new SinhVien { MaSV = data[0], HoTen = data[1], QueQuan = data[2], NgaySinh = DateTime.Parse("2020-09-02"), GioiTinh = gender, DiaChi = data[5], EMail = data[6], SDT = data[7], MaLop = data[8], Pic = ConvertImage(avt) }; db_.SinhVien.Add(sv); db_.SaveChanges(); return "Them Thanh Cong"; } else { return "Ma Sinh Vien Da Ton Tai"; } } else { return "Ma lop khong ton tai!"; } }catch(Exception ex) { return ex.Message; } } public Image ByteArrayToImage(byte[] byteArr) { if (byteArr != null) { using (MemoryStream ms = new MemoryStream(byteArr)) { Image img = Image.FromStream(ms); return img; } } else { return null; } } byte[] ConvertImage(Image img) { if (img != null) { using (MemoryStream ms = new MemoryStream()) { img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); } } return null; } public List<Lop> GetMaLop() { return db_.Lop.ToList(); } public List<SinhVien> searchByKey(string key) { return db_.SinhVien.Where(sv => sv.HoTen.Contains(key) || sv.MaSV.Contains(key)|| sv.MaLop.Contains(key)).ToList(); } public List<SinhVien> getInfor(string maSv) { return db_.SinhVien.Where(sv => sv.MaSV.CompareTo(maSv) == 0).ToList(); } public string updated(string[] data,Image avt) { try { string malop = data[8]; var getMaLop = db_.Lop.Where(lop => lop.MaLop.CompareTo(malop) == 0).ToList(); string maSv = data[0]; var getMaSv = db_.SinhVien.Where(sv => sv.MaSV.CompareTo(maSv) == 0).ToList(); if (getMaLop.Any()) { if (getMaSv.Count() == 1) { bool gender; if (data[4] == "nam") { gender = true; } else { gender = false; } foreach(var item in getMaSv) { item.HoTen = data[1]; item.QueQuan = data[2]; item.NgaySinh = DateTime.Parse("2020-09-02"); item.GioiTinh = gender; item.DiaChi = data[5]; item.EMail = data[6]; item.SDT = data[7]; item.MaLop = data[8]; if (avt != null) { if (ConvertImage(avt) != item.Pic) { item.Pic = ConvertImage(avt); } } else { item.Pic = null; } } db_.SaveChanges(); return "Sua Thanh Cong"; } else { return "Ma Sinh Vien Da Ton Tai"; } } else { return "Ma lop khong ton tai!"; } } catch (Exception ex) { return ex.Message; } } public bool remove(string masv) { try { var infor =db_.SinhVien.Where(sv=>sv.MaSV.CompareTo(masv)==0).FirstOrDefault(); if (infor!=null) { db_.SinhVien.Remove(infor); db_.SaveChanges(); return true; } return false; }catch(Exception ex) { return false; } } } }
using System.Web.Mvc; namespace HQF.Daily.Web.Controllers { public class AboutController : DailyControllerBase { public ActionResult Index() { return View(); } } }
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(MVC_Library.Startup))] namespace MVC_Library { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EarthDefender { class Player : Sprite { public Input mInput; public List<Bullet> mBullets; private Texture2D mBulletSprite; private float mTimer; public Player(Texture2D texture, Vector2 position, Texture2D bulletSprite) : base(texture, position) { mBullets = new List<Bullet>(); mBulletSprite = bulletSprite; mScale = 0.5f; } public override void update(GameTime gameTime) { mPreviousKey = mCurrentKey; mCurrentKey = Keyboard.GetState(); if (mInput == null) return; mTimer += (float)gameTime.ElapsedGameTime.TotalSeconds; move(); checkAndFire(); for (int i = 0; i < mBullets.Count; i++) { Bullet bullet = mBullets[i]; if (bullet.mIsRemoved) { mBullets.RemoveAt(i); i--; } mBullets.ElementAt(i).update(gameTime); } base.update(gameTime); } public void move() { KeyboardState kbState = Keyboard.GetState(); if (kbState.IsKeyDown(mInput.Left)) { mPosition.X -= mSpeed; } if (kbState.IsKeyDown(mInput.Right)) { mPosition.X += mSpeed; } } public void checkAndFire() { KeyboardState kbState = Keyboard.GetState(); if (kbState.IsKeyDown(mInput.Fire) && mPreviousKey.IsKeyUp(mInput.Fire)) { if (mTimer > 0.5f) { mTimer = 0f; fireBullet(); } } } public void fireBullet() { Bullet bullet = new Bullet(mBulletSprite, new Vector2(mPosition.X + 0.5f * mTexture.Width / 2, mPosition.Y)); mBullets.Add(bullet); } public override void draw(SpriteBatch spriteBatch) { //base.draw(spriteBatch); spriteBatch.Draw(mTexture, mPosition, null, Color.White, 0, Vector2.Zero, mScale, SpriteEffects.None, 0f); for (int i = 0; i < mBullets.Count; i++) { mBullets.ElementAt(i).draw(spriteBatch); } } /** * asteroidRectangle - checks if any bullet hits the specific asteroid * RETURN - Vector2 of the bullet which hit the asteroid * IF no bullet hit - returns a zero vector */ public Vector2 hasBulletHitAsteroid(Rectangle asteroidRectangle) { //asteroidRectangle = new Rectangle(0, 0, 1500, 1500); for (int i=0; i < mBullets.Count; i++) { Bullet currentBullet = mBullets[i]; Rectangle bulletRect = currentBullet.mSpriteRectangle; if (bulletRect.Intersects(asteroidRectangle)) { mBullets.RemoveAt(i); return new Vector2(currentBullet.mPosition.X, currentBullet.mPosition.Y); } } return Vector2.Zero; } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.Generic; using Tff.Panzer.Models.Geography; using System.Xml.Serialization; namespace Tff.Panzer.Models.Army.Unit { public abstract class BaseUnit : IUnit { public BaseUnit() { MoveableTiles = new List<Tile>(); VisibleTiles = new List<Tile>(); } //Static In Each Scenario public int UnitId { get; set; } public string UnitName { get; set; } public Boolean CoreIndicator { get; set; } public Nation Nation { get; set; } public NationEnum NationEnum { get { return Nation.NationEnum; } } public SideEnum SideEnum { get { return Nation.SideEnum; } } //Changes Occasionally public Equipment Equipment { get; set; } [XmlIgnoreAttribute] public EquipmentSubClassEnum EquipmentSubClassEnum { get { return Equipment.EquipmentSubClassEnum; } } [XmlIgnoreAttribute] public EquipmentClassEnum EquipmentClassEnum { get { return Equipment.EquipmentClassEnum; } } [XmlIgnoreAttribute] public EquipmentGroupEnum EquipmentGroupEnum { get { return Equipment.EquipmentGroupEnum; } } [XmlIgnoreAttribute] public Boolean CanCaptureHexes { get { return Equipment.CanCaptureHexes; } } [XmlIgnoreAttribute] public TargetTypeEnum TargetTypeEnum { get { return Equipment.TargetTypeEnum; } } [XmlIgnoreAttribute] public EquipmentLossCalculationGroupEnum EquipmentLossCalculationGroupEnum { get { return Equipment.EquipmentLossCalculationGroupEnum; } } //Changes Often public int CurrentStrength { get; set; } public int CurrentExperience { get; set; } [XmlIgnoreAttribute] public int CurrentNumberOfStars { get { return (Int32)(CurrentExperience * .1); } } [XmlIgnoreAttribute] public int CurrentAttackPoints { get; set; } [XmlIgnoreAttribute] public List<Tile> MoveableTiles { get; set; } [XmlIgnoreAttribute] public List<Tile> VisibleTiles { get; set; } public Boolean CanMove { get; set; } public Boolean CanUpdate { get; set; } public Int32 CurrentTileId { get; set; } public override string ToString() { return UnitName; } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } BaseUnit targetUnit = (BaseUnit)obj; if (targetUnit.UnitId == this.UnitId) return true; else return false; } public override int GetHashCode() { return this.UnitId; } } }
namespace Plus.Communication.Packets.Outgoing.Rooms.Notifications { internal class RoomNotificationComposer : MessageComposer { public string Type { get; } public string Key { get; } public string Value { get; } public string Title { get; } public string Message { get; } public string Image { get; } public string HotelName { get; } public string HotelUrl { get; } public RoomNotificationComposer(string type, string key, string value) : base(ServerPacketHeader.RoomNotificationMessageComposer) { Type = type; Key = key; Value = value; } public RoomNotificationComposer(string type) : base(ServerPacketHeader.RoomNotificationMessageComposer) { Type = type; } public RoomNotificationComposer(string title, string message, string image, string hotelName = "", string hotelUrl = "") : base(ServerPacketHeader.RoomNotificationMessageComposer) { Title = title; Message = message; Image = image; HotelName = hotelName; HotelUrl = hotelUrl; } public override void Compose(ServerPacket packet) { if (!string.IsNullOrEmpty(Message)) { packet.WriteString(Image); packet.WriteInteger(string.IsNullOrEmpty(HotelName) ? 2 : 4); packet.WriteString("title"); packet.WriteString(Title); packet.WriteString("message"); packet.WriteString(Message); if (!string.IsNullOrEmpty(HotelName)) { packet.WriteString("linkUrl"); packet.WriteString(HotelUrl); packet.WriteString("linkTitle"); packet.WriteString(HotelName); } } else if (!string.IsNullOrEmpty(Key)) { packet.WriteString(Type); packet.WriteInteger(1); //Count { packet.WriteString(Key); //Type of message packet.WriteString(Value); } } else { packet.WriteString(Type); packet.WriteInteger(0); //Count } } } }
using Roaring.DataStores; using System.Diagnostics; using System; namespace Roaring { public class MutableRoaringBitmap : RoaringBitmap { private MutableRoaringBitmap(ushort[][] arrayValues, ulong[][] bitmapValues, KeyedList<RoaringContainer> containers) : base(new MutableArrayStore(arrayValues), new MutableBitmapStore(bitmapValues), containers, true) { } internal MutableRoaringBitmap(MutableArrayStore arrayStore, MutableBitmapStore bitmapStore, KeyedList<RoaringContainer> containers) : base(arrayStore, bitmapStore, containers, true) { } internal static MutableRoaringBitmap Create() { return new MutableRoaringBitmap(Array.Empty<ushort[]>(), Array.Empty<ulong[]>(), new KeyedList<RoaringContainer>(0)); } internal new static MutableRoaringBitmap Create(int capacity) { Debug.Assert(capacity >= 0); return Create((uint)capacity); } internal new static MutableRoaringBitmap Create(uint capacity) { int containerCapacity = (int)((capacity + Container.MaxCardinality - 1U) / Container.MaxCardinality); return new MutableRoaringBitmap(new MutableArrayStore(containerCapacity), new MutableBitmapStore(containerCapacity), new KeyedList<RoaringContainer>(containerCapacity)); } internal static MutableRoaringBitmap FromRange(uint min, uint max, uint step = 1) { uint count = (max - min) / step + 1; var bitmap = Create(count); for (uint i = min; i <= max; i += step) { bitmap.IAdd(i); Debug.Assert(bitmap.Cardinality == i - min + 1); } Debug.Assert(bitmap.Cardinality == count); bitmap.CheckState(); return bitmap; } internal static MutableRoaringBitmap FromValues(uint[] values) { var bitmap = Create(values.Length); for (uint i = 0; i < values.Length; i++) bitmap.IAdd(values[i]); Debug.Assert(bitmap.Cardinality == (ulong)values.Length); bitmap.CheckState(); return bitmap; } /*public static IRoaringBitmap FromRange(uint min, uint max, uint step = 1) { uint count = (max - min) / step; var bitmap = new ArrayRoaringBitmap(count); for (uint i = min; i <= max; i += step) bitmap.Add(i); return bitmap; } public static IRoaringBitmap FromValues(uint[] values) { var bitmap = new ArrayRoaringBitmap(values.Length); for (uint i = 0; i < values.Length; i++) bitmap.Add(i); return bitmap; }*/ public new MutableRoaringBitmap Clone() { var newKeys = new ushort[_containers.Keys.Length]; Array.Copy(_containers.Keys, 0, newKeys, 0, newKeys.Length); var newContainers = new RoaringContainer[_containers.Values.Length]; Array.Copy(_containers.Values, 0, newContainers, 0, newContainers.Length); return new MutableRoaringBitmap(((MutableArrayStore)_arrayStore).Clone(), ((MutableBitmapStore)_bitmapStore).Clone(), new KeyedList<RoaringContainer>(newKeys, newContainers, _containers.Count)); } protected override RoaringBitmap CloneInternal() => Clone(); } }
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 UI。スクロール。縦スクロール。 */ /** NUi */ namespace NUi { /** Scroll_Vertical_Base */ public abstract class Scroll_Vertical_Base<ITEM> : Scroll_List_Base<ITEM> where ITEM : ScrollItem_Base { /** constructor */ public Scroll_Vertical_Base(NDeleter.Deleter a_deleter,long a_drawpriority,int a_item_length) : base(a_deleter,a_drawpriority,a_item_length) { } /** [Scroll_List_Base]アイテムの位置更新。スクロール方向の座標。 */ protected override void UpdateItemPos(ITEM a_item,int a_index) { int t_y = this.rect.y + a_index * this.item_length - this.view_position; a_item.SetY(t_y); } /** [Scroll_List_Base]アイテムの位置更新。スクロール方向ではない座標。 */ protected override void UpdateItemOtherPos(ITEM a_item,int a_index) { a_item.SetX(this.rect.x); } /** [Scroll_List_Base]表示幅更新。 */ protected override void UpdateViewLength() { this.view_length = this.rect.h; } } }
#region License /*** * Copyright © 2018-2025, 张强 (943620963@qq.com). * * 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. */ #endregion using System; using System.Collections.Generic; using System.Linq.Expressions; /**************************** * [Author] 张强 * [Date] 2019-03-27 * [Describe] 泛型映射工具类 * **************************/ namespace ZqUtils.Helpers { /// <summary> /// 泛型映射工具类 /// </summary> /// <typeparam name="T">源类型</typeparam> /// <typeparam name="F">目标类型</typeparam> public static class MapperHelper<T, F> { /// <summary> /// 私有静态字段 /// </summary> private static readonly Func<T, F> map = MapProvider(); /// <summary> /// 私有方法 /// </summary> /// <returns></returns> private static Func<T, F> MapProvider() { var memberBindingList = new List<MemberBinding>(); var parameterExpression = Expression.Parameter(typeof(T), "x"); foreach (var item in typeof(F).GetProperties()) { if (!item.CanWrite) continue; var propertyInfo = typeof(T).GetProperty(item.Name); if (propertyInfo == null) continue; var property = Expression.Property(parameterExpression, propertyInfo); var memberBinding = Expression.Bind(item, property); memberBindingList.Add(memberBinding); } var memberInitExpression = Expression.MemberInit( Expression.New(typeof(F)), memberBindingList.ToArray()); var lambda = Expression.Lambda<Func<T, F>>( memberInitExpression, new ParameterExpression[] { parameterExpression }); return lambda.Compile(); } /// <summary> /// 映射方法 /// </summary> /// <param name="entity">待映射的对象</param> /// <returns>目标类型对象</returns> public static F MapTo(T entity) { return map(entity); } } }
namespace Meziantou.Analyzer; internal static class RuleCategories { public const string Design = "Design"; public const string Naming = "Naming"; public const string Style = "Style"; public const string Usage = "Usage"; public const string Performance = "Performance"; public const string Security = "Security"; }
using Caliburn.Micro; using System; using System.Threading.Tasks; namespace Notifications.Wpf.Core.Caliburn.Micro.Sample.ViewModels { public class NotificationViewModel : PropertyChangedBase, INotificationViewModel { private readonly INotificationManager _manager; private Guid? _notificationIdentifier; public string? Title { get; set; } public string? Message { get; set; } public NotificationViewModel(INotificationManager manager) { _manager = manager; } public void SetNotificationIdentifier(Guid identifier) { _notificationIdentifier = identifier; } public async Task Ok() { await Task.Delay(500); await _manager.ShowAsync(new NotificationContent { Title = "Success!", Message = $"Ok button was clicked.\nNotification identifier: {_notificationIdentifier}", Type = NotificationType.Success }); } public async Task Cancel() { await Task.Delay(500); await _manager.ShowAsync(new NotificationContent { Title = "Error!", Message = $"Cancel button was clicked!\nNotification identifier: {_notificationIdentifier}", Type = NotificationType.Error }); } } }
using System; using System.Collections.Generic; using SiscomSoft.Models; using System.Data.Entity; using System.Linq; namespace SiscomSoft.Controller { public class ManejoCategoria { /// <summary> /// Funcion encargada de guardar un nuevo registro en la base de datos /// </summary> /// <param name="nCategoria">variable de tipo modelo categoria</param> public static void RegistrarNuevaCategoria(Categoria nCategoria) { try { using (var ctx = new DataModel()) { ctx.Categorias.Add(nCategoria); ctx.SaveChanges(); } } catch (Exception) { throw; } } /// <summary> /// Funcion encargada de obtener un registro mediante una id /// </summary> /// <param name="idCategoria">variable de tipo entera</param> /// <returns></returns> public static Categoria getById(int idCategoria) { try { using (var ctx = new DataModel()) { return ctx.Categorias.Where(r => r.bStatus == true && r.idCategoria == idCategoria).FirstOrDefault(); } } catch (Exception) { throw; } } /// <summary> /// Funcion encargada de eliminar un registro de la base de datos mediante una id /// </summary> /// <param name="idCategoria"></param> public static void Eliminar(int idCategoria) { try { using (var ctx = new DataModel()) { Categoria nCategoria = ManejoCategoria.getById(idCategoria); nCategoria.bStatus = false; ctx.Entry(nCategoria).State = EntityState.Modified; ctx.SaveChanges(); } } catch (Exception) { throw; } } /// <summary> /// Funcion encargada de obtener todo los registros dandole un nombre y un statis(activo) y retonar una lista con los mismos. /// </summary> /// </summary> /// <param name="valor">variable de tipo string</param> /// <param name="Status">variable de tipo boolean</param> /// <returns></returns> public static List<Categoria> Buscar(string nombre, Boolean Status) { try { using (var ctx = new DataModel()) { return ctx.Categorias.Where(r => r.bStatus == Status && r.sNomCat.Contains(nombre)).ToList(); } } catch (Exception) { throw; } } /// <summary> /// Funcion encargada de modificar un registro de la base de datos /// </summary> /// <param name="nCategoria">variable de tipo modelo categoria</param> public static void Modificar(Categoria nCategoria) { try { using (var ctx = new DataModel()) { ctx.Categorias.Attach(nCategoria); ctx.Entry(nCategoria).State = EntityState.Modified; ctx.SaveChanges(); } } catch (Exception) { throw; } } /// <summary> /// Funcion encargada de obtener todos los registros activos de la base de datos y retornar una lista de los mismos. /// </summary> /// <param name="status">variable de tipo boolean</param> /// <returns></returns> public static List<Categoria> getAll(Boolean status) { try { using (var ctx = new DataModel()) { return ctx.Categorias.Where(r => r.bStatus == status).ToList(); } } catch (Exception) { throw; } } } }
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models; using Ocularis.Capabilities.Remote.LUIS.IntentHandlers; using Ocularis.IO.Input; using Ocularis.IO.Output; using Ocularis.LUIS; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Media.Playback; using Windows.Storage; namespace Ocularis.IO { public class Buddy { private ApplicationDataContainer _localSettings = ApplicationData.Current.LocalSettings; private MediaPlayer _voicePlayer; private Dictionary<string, Type> _intentHandlersDict; public Buddy(MediaPlayer voicePlayer) { _voicePlayer = voicePlayer; Init(); } private void Init() { var intentHandlers = from a in AppDomain.CurrentDomain.GetAssemblies().AsParallel() from t in a.GetTypes() let attributes = t.GetCustomAttributes(typeof(LuisIntentAttribute), true) where attributes != null && attributes.Length > 0 select new { Type = t, Attributes = attributes.Cast<LuisIntentAttribute>() }; _intentHandlersDict = intentHandlers.ToDictionary(q => q.Attributes.First().Name, q => q.Type); } public async Task Help() { var orderText = await SpeechRecognizer.GetText(); var connector = new LuisConnector(AppConfiguration.LuisApiSubscriptionKey, AppConfiguration.LuisApiEndPoint, AppConfiguration.LuisApiApplicationId); var luisResult = await connector.PredictAsync(orderText); var intentHandler = GetIntentHandler(luisResult); var resultText = await intentHandler.Handle(luisResult); await SpeechSynthesizer.Read(resultText, _voicePlayer); } private IIntentHandler GetIntentHandler(LuisResult luisResult) { var type = _intentHandlersDict[luisResult.TopScoringIntent.Intent]; return (IIntentHandler)Activator.CreateInstance(type); } } }
using System; using DataDynamics.ActiveReports; using DataDynamics.ActiveReports.Document; using System.Data; using System.Data.SqlClient; using lianda.Component; namespace lianda.REP { public class LDRPG3RP_2 : ActiveReport { private string GUID = null; private DateTime ZYRQ_Date = DateTime.Now; public LDRPG3RP_2(string GUID, DateTime ZYRQ_Date) { InitializeReport(); this.GUID = GUID; this.ZYRQ_Date = ZYRQ_Date; this.SubReport1.Report = new LDRPG3RP_2_1(GUID); paint(); } private void paint() { this.TextBox_ZYRQ.Value = ZYRQ_Date; this.TextBox_JBRQ.Value = ZYRQ_Date; string sqlStr = @" SELECT WTRQ, SUM(SYZYZL+ZYZL+DRWPZL+CDZL) AS DRZL, SUM(SYWPZL) AS SYWPYL, SUM(DRWPZL) AS DRWPZL, SUM(WYZL) AS WYZL, SUM(CDZL)*-1 AS CDZL, SUM(SYWYZL) AS SYWYZL, SUM(SYZYZL+ZYZL) AS DRZYZL, SUM(ZYZL) AS WCZYZL, SUM(SYZYZL) AS SYZYZL, SUM(DBZL) AS DRDBZL FROM RP_DRYS_QY WHERE GUID = @GUID GROUP BY WTRQ ORDER BY WTRQ "; SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@GUID", GUID), new SqlParameter("@CDSJ_1", this.ZYRQ_Date.AddHours(8)), new SqlParameter("@CDSJ_2", this.ZYRQ_Date.AddHours(8+24)) }; DataSet ds = SqlHelper.selectDataSet(SqlHelper.CONN_STRING,CommandType.Text,sqlStr,paras); int row_count = ds.Tables["Table"].Rows.Count; for(;row_count<15;row_count++) { ds.Tables["Table"].Rows.Add(new object[]{null,null,null,null,null,null,null,null,null}); } this.DataSource = ds; this.DataMember = "Table"; // 获取天气预报数据 sqlStr = @" SELECT WD,TQ FROM J_TQYB WHERE YBRQ = @YBRQ "; paras = new SqlParameter[] { new SqlParameter("@YBRQ", this.ZYRQ_Date) }; SqlDataReader sd = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,sqlStr,paras); if(sd.Read()) { this.TextBox_WD.Text = sd["WD"]+""; this.TextBox_TQ.Text = sd["TQ"]+""; } } private void GroupHeader1_AfterPrint(object sender, System.EventArgs eArgs) { } private void GroupHeader1_Format(object sender, System.EventArgs eArgs) { } private void Detail_Format(object sender, System.EventArgs eArgs) { } #region ActiveReports Designer generated code private PageHeader PageHeader = null; private Label Label14 = null; private Label Label16 = null; private Line Line3 = null; private Label Label17 = null; private Label Label19 = null; private Line Line4 = null; private Label Label20 = null; private Line Line5 = null; private TextBox TextBox_ZYRQ = null; private TextBox TextBox_WD = null; private TextBox TextBox_TQ = null; private Label Label36 = null; private GroupHeader GroupHeader1 = null; private Line Line1 = null; private Label Label3 = null; private Line Line2 = null; private Label Label4 = null; private Label Label5 = null; private Label Label9 = null; private Line Line9 = null; private Line Line10 = null; private Line Line11 = null; private Line Line12 = null; private Label Label24 = null; private Label Label25 = null; private Label Label26 = null; private Line Line13 = null; private Line Line14 = null; private Line Line15 = null; private Line Line16 = null; private Line Line17 = null; private Line Line18 = null; private Line Line19 = null; private Label Label27 = null; private Label Label28 = null; private Label Label29 = null; private Line Line44 = null; private Label Label34 = null; private Line Line47 = null; private Label Label35 = null; private Detail Detail = null; private TextBox TextBox1 = null; private TextBox TextBox2 = null; private TextBox TextBox3 = null; private TextBox TextBox4 = null; private TextBox TextBox5 = null; private TextBox TextBox6 = null; private TextBox TextBox7 = null; private TextBox TextBox8 = null; private TextBox TextBox9 = null; private Line Line20 = null; private Line Line21 = null; private Line Line22 = null; private Line Line23 = null; private Line Line24 = null; private Line Line25 = null; private Line Line26 = null; private Line Line27 = null; private Line Line28 = null; private Line Line29 = null; private Line Line30 = null; private Line Line45 = null; private TextBox TextBox18 = null; private Line Line48 = null; private TextBox TextBox20 = null; private GroupFooter GroupFooter1 = null; private TextBox TextBox10 = null; private TextBox TextBox11 = null; private TextBox TextBox12 = null; private TextBox TextBox13 = null; private TextBox TextBox14 = null; private TextBox TextBox15 = null; private TextBox TextBox16 = null; private TextBox TextBox17 = null; private Label Label15 = null; private Line Line31 = null; private Line Line32 = null; private Line Line33 = null; private Line Line34 = null; private Line Line35 = null; private Line Line36 = null; private Line Line37 = null; private Line Line38 = null; private Line Line39 = null; private Line Line40 = null; private SubReport SubReport1 = null; private Line Line46 = null; private TextBox TextBox19 = null; private Line Line49 = null; private TextBox TextBox21 = null; private PageFooter PageFooter = null; private TextBox TextBox_JBRQ = null; private Label Label30 = null; private Label Label31 = null; private Line Line41 = null; private Label Label32 = null; private Label Label33 = null; private Line Line42 = null; private Line Line43 = null; public void InitializeReport() { this.LoadLayout(this.GetType(), "lianda.REP.LDRPG3RP_2.rpx"); this.PageHeader = ((DataDynamics.ActiveReports.PageHeader)(this.Sections["PageHeader"])); this.GroupHeader1 = ((DataDynamics.ActiveReports.GroupHeader)(this.Sections["GroupHeader1"])); this.Detail = ((DataDynamics.ActiveReports.Detail)(this.Sections["Detail"])); this.GroupFooter1 = ((DataDynamics.ActiveReports.GroupFooter)(this.Sections["GroupFooter1"])); this.PageFooter = ((DataDynamics.ActiveReports.PageFooter)(this.Sections["PageFooter"])); this.Label14 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[0])); this.Label16 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[1])); this.Line3 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[2])); this.Label17 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[3])); this.Label19 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[4])); this.Line4 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[5])); this.Label20 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[6])); this.Line5 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[7])); this.TextBox_ZYRQ = ((DataDynamics.ActiveReports.TextBox)(this.PageHeader.Controls[8])); this.TextBox_WD = ((DataDynamics.ActiveReports.TextBox)(this.PageHeader.Controls[9])); this.TextBox_TQ = ((DataDynamics.ActiveReports.TextBox)(this.PageHeader.Controls[10])); this.Label36 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[11])); this.Line1 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[0])); this.Label3 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[1])); this.Line2 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[2])); this.Label4 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[3])); this.Label5 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[4])); this.Label9 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[5])); this.Line9 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[6])); this.Line10 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[7])); this.Line11 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[8])); this.Line12 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[9])); this.Label24 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[10])); this.Label25 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[11])); this.Label26 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[12])); this.Line13 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[13])); this.Line14 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[14])); this.Line15 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[15])); this.Line16 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[16])); this.Line17 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[17])); this.Line18 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[18])); this.Line19 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[19])); this.Label27 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[20])); this.Label28 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[21])); this.Label29 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[22])); this.Line44 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[23])); this.Label34 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[24])); this.Line47 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[25])); this.Label35 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[26])); this.TextBox1 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[0])); this.TextBox2 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[1])); this.TextBox3 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[2])); this.TextBox4 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[3])); this.TextBox5 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[4])); this.TextBox6 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[5])); this.TextBox7 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[6])); this.TextBox8 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[7])); this.TextBox9 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[8])); this.Line20 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[9])); this.Line21 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[10])); this.Line22 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[11])); this.Line23 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[12])); this.Line24 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[13])); this.Line25 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[14])); this.Line26 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[15])); this.Line27 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[16])); this.Line28 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[17])); this.Line29 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[18])); this.Line30 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[19])); this.Line45 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[20])); this.TextBox18 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[21])); this.Line48 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[22])); this.TextBox20 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[23])); this.TextBox10 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[0])); this.TextBox11 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[1])); this.TextBox12 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[2])); this.TextBox13 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[3])); this.TextBox14 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[4])); this.TextBox15 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[5])); this.TextBox16 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[6])); this.TextBox17 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[7])); this.Label15 = ((DataDynamics.ActiveReports.Label)(this.GroupFooter1.Controls[8])); this.Line31 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[9])); this.Line32 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[10])); this.Line33 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[11])); this.Line34 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[12])); this.Line35 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[13])); this.Line36 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[14])); this.Line37 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[15])); this.Line38 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[16])); this.Line39 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[17])); this.Line40 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[18])); this.SubReport1 = ((DataDynamics.ActiveReports.SubReport)(this.GroupFooter1.Controls[19])); this.Line46 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[20])); this.TextBox19 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[21])); this.Line49 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[22])); this.TextBox21 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[23])); this.TextBox_JBRQ = ((DataDynamics.ActiveReports.TextBox)(this.PageFooter.Controls[0])); this.Label30 = ((DataDynamics.ActiveReports.Label)(this.PageFooter.Controls[1])); this.Label31 = ((DataDynamics.ActiveReports.Label)(this.PageFooter.Controls[2])); this.Line41 = ((DataDynamics.ActiveReports.Line)(this.PageFooter.Controls[3])); this.Label32 = ((DataDynamics.ActiveReports.Label)(this.PageFooter.Controls[4])); this.Label33 = ((DataDynamics.ActiveReports.Label)(this.PageFooter.Controls[5])); this.Line42 = ((DataDynamics.ActiveReports.Line)(this.PageFooter.Controls[6])); this.Line43 = ((DataDynamics.ActiveReports.Line)(this.PageFooter.Controls[7])); // Attach Report Events this.GroupHeader1.AfterPrint += new System.EventHandler(this.GroupHeader1_AfterPrint); this.GroupHeader1.Format += new System.EventHandler(this.GroupHeader1_Format); this.Detail.Format += new System.EventHandler(this.Detail_Format); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; // using Android.Content; // using Foundation; // using UIKit; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; //using Android.App; //using Android.Net; namespace InfiniteMeals.Information { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class InformationPage : ContentPage { public InformationPage() { InitializeComponent(); //_ = DisplayGuidAsync(); } private async void DisplayGuidAsync(object sender, EventArgs args) { var guid = Preferences.Get("guid", "null"); await DisplayAlert("guid", guid, "OK"); Console.WriteLine("information guid:" + guid); } async void NavigateToAppSetting(System.Object sender, System.EventArgs e) { await DisplayAlert("Thank you!", "Make sure you restart the app after you've enabled", "Ok"); DependencyService.Get<ISettingsHelper>().OpenAppSettings(); //switch (Device.RuntimePlatform) //{ // case Device.iOS: // var url = new NSUrl($"app-settings:notifications"); // UIApplication.SharedApplication.OpenUrl(url); // break; // case Device.Android: // //Android.App.Application.Context.StartActivity(new Intent( // // Android.Provider.Settings.ActionApplicationDetailsSettings, // // Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName))); // Intent intent = new Intent( // Android.Provider.Settings.ActionApplicationDetailsSettings, // Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName)); // intent.AddFlags(ActivityFlags.NewTask); // Android.App.Application.Context.StartActivity(intent); // break; //} } } }
using System; namespace Task_1._5._ComplexNumber { public class ComplexNumber { private int real; private int imaginary; public ComplexNumber(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public override bool Equals(object obj) { var other = obj as ComplexNumber; if (other == null) return false; return (this.real == other.real) && (this.imaginary == other.imaginary); } #region public static bool operator ==(ComplexNumber me, ComplexNumber other) => Equals(me, other); public static bool operator !=(ComplexNumber me, ComplexNumber other) => !Equals(me, other); #endregion #region public static ComplexNumber operator *(ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber(c1.real * c2.real - c1.imaginary * c2.imaginary, c1.real * c2.imaginary + c1.imaginary * c2.real); } public static ComplexNumber operator /(ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber((c1.real * c2.real + c1.imaginary * c2.imaginary) / (c2.real * c2.real + c2.imaginary * c2.imaginary), ( - c1.real * c2.imaginary + c1.imaginary * c2.real) / (c2.real * c2.real + c2.imaginary * c2.imaginary)); } } #endregion public class EntryPoint { static void Main(string[] args) { var a = new ComplexNumber(-4, 7); var b = new ComplexNumber(1, 2); var c = new ComplexNumber(2, 3); if (a == b * c) Console.WriteLine("(-4, 7) == " + "(1, 2) * (2, 3)"); if (b != a * c) Console.WriteLine("(1, 2) !== " + "(-4, 7) * (2, 3)"); var d = new ComplexNumber(2, -1); var e = new ComplexNumber(1, 2); var f = new ComplexNumber(0, 1); if (d == e / f) Console.WriteLine("(2, -1) == " + @"(1, 2) / (0, 1)"); if (e != d / f) Console.WriteLine("(1, 2) !== " + @"(2, -1) / (0, 1)"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using VKDesktop.Core.Users; using System.Net; using System.Windows.Controls; using VKDesktop.Helpers; using System.ComponentModel; using System.Windows; namespace VKDesktop.Core.Messages { public class Dialog : INotifyPropertyChanged { ObservableCollection<Message> messages; User user; public User User { get { return user; } } public Message Last { get { return messages.Last(); } } public ObservableCollection<Message> Messages { get { return messages; } } public bool HasUnread { get { return (messages.Any(x=> x.Unread && !x.Mine)); } } public bool IsMarkingAsRead { get; set; } public Dialog(int user_id) { user = Memory.GetUser(user_id); user.Dialog = this; messages = new ObservableCollection<Message>(Memory.GetMesages(user_id)); } private bool isLoading; public bool IsLoading { get { return isLoading; } set { isLoading = value; OnPropertyChanged("IsLoading"); } } public async Task LoadMore() { IsLoading = true; Task<List<Message>> getMoreMessagesTask = Api.Request.GetMessages(user.id,messages.Count,""); //but.Content = "Взяли таск"; List<Message> messagesFromResponse = await getMoreMessagesTask; Core.Memory.messages.AddRange(messagesFromResponse); foreach (Message message in messagesFromResponse) { this.messages.Insert(0,message); } System.Threading.Thread.Sleep(200); IsLoading = false; } public async Task MarkAsRead() { IsMarkingAsRead = true; Task<int> getMarkAsReadTask = Api.Request.MarkAsRead(user.id); bool isMarked = (await getMarkAsReadTask == 1 ? true : false); IsMarkingAsRead = false; } public void ShowTypping() { if (IsOpened) Window.ShowTypping(); else { Notificator.ShowTyppingPopup(user); } } public void StopTypping() { if (IsOpened) Window.HideTypping(); } public void SendTypping() { // по таймеру // отправлять писалку // https://vk.com/dev/messages.setActivity } public void NewMessage(Message message) { StopTypping(); messages.Add(message); OnPropertyChanged("Last"); ScrollDown(); } public async void SendMessage(string messageText) { Message m = new Message() { Mine = true, Body = messageText, Sending = true, read_state = 0, user_id = user.id, Date = Time.EpochNow }; Memory.messages.Add(m); messages.Add(m); ScrollDown(); OnPropertyChanged("Last"); Task<int> sendMessageTask = Api.Request.SendMessage(user.id, messageText); int mid = await sendMessageTask; if (mid != 0) { m.id = mid; m.Sending = false; } } public void ScrollDown() { if (IsOpened) { Window.DialogsList.ScrollIntoView(Last); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string arg) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(arg)); } } public bool IsFocused { get { if (IsOpened) return Window.IsActive; return false; } } public bool IsOpened { get { return (Window == null ? false : true); } } public DialogWindow Window { get; set; } public void Open() { Show.DialogWindow(this); } } }
using System.Xml.Linq; using Caliburn.Micro; using Frontend.Core.Factories.TagReaders; namespace Frontend.Core.Factories { public class RequiredFileFactory : FactoryBase { private readonly FileTagReader fileTagReader; /// <summary> /// Initializes a new instance of the RequiredFileFactory /// </summary> /// <param name="eventAggregator">The event aggregator</param> public RequiredFileFactory(IEventAggregator eventAggregator) : base(eventAggregator, "requiredFile") { fileTagReader = new FileTagReader(eventAggregator); } protected override T OnBuildElement<T>(XElement element) { return (T) fileTagReader.ReadFile(element); } } }
using Alarmy.Common; using System; using System.Collections.Generic; using System.Linq; namespace Alarmy.Core { internal abstract class AlarmReminderManager : IAlarmReminderManager { protected readonly IAlarmService alarmService; protected readonly ITimer timer; public event EventHandler<AlarmReminderEventArgs> OnRequestNotification; public AlarmReminderManager(IAlarmService alarmService, ITimer reminderTimer) { if (alarmService == null) throw new ArgumentNullException("alarmService"); if (reminderTimer == null) throw new ArgumentNullException("reminderTimer"); this.alarmService = alarmService; this.timer = reminderTimer; reminderTimer.Elapsed += timer_Elapsed; } public void Start() { this.timer.Start(); } public void Stop() { this.timer.Stop(); } protected abstract string PrepareMessage(); private void timer_Elapsed(object source, EventArgs args) { var message = this.PrepareMessage(); if (!string.IsNullOrEmpty(message)) this.OnRequestNotification.Invoke(e: new AlarmReminderEventArgs("Alarm Reminder", message)); } protected static string PrepareMessage(string task, IEnumerable<IAlarm> alarms) { return "\r\n" + string.Join("\r\n", alarms.Select(x => string.Format("{0}: {1} - {2}", task, x.Time, x.Title))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using IoTWebApi.Models; namespace IoTWebApi.Controllers { public class personPageController : Controller { // GET: personPage public ActionResult personAdd() { return View(); } [HttpPost] public ActionResult post(string name, string phone, string email) { IoTDatabaseDataContext db = new IoTDatabaseDataContext(); Person p = new Person(); if (name != "" && email != "") { p.name = name; p.phoneNumber = phone; p.email = email; db.Persons.InsertOnSubmit(p); db.SubmitChanges(); ViewBag.result = name + " added!"; ViewBag.colour = "green"; } else { ViewBag.result = "Please insert a person"; ViewBag.colour = "red"; } return View("personAdd"); } public ActionResult index() { IoTDatabaseDataContext db = new IoTDatabaseDataContext(); return View(db.Persons.ToList()); } [HttpPost] public ActionResult del(string id) { int idCast = -1; int.TryParse(id, out idCast); IoTDatabaseDataContext db = new IoTDatabaseDataContext(); string name = ""; try { name = (from person in db.Persons where person.personID == idCast select person).Single().name; } catch (Exception e) { } ViewBag.delete = "Nothing selected"; if (idCast != -1) { var sel = from person in db.Persons where person.personID == idCast select person; foreach (var item in sel) { db.Persons.DeleteOnSubmit(item); ViewBag.delete = name + " deleted!"; } db.SubmitChanges(); } return RedirectToAction("result", "Home", new { area = "", result = ViewBag.delete }); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.Collections.Generic; using System.Data; using System.Runtime.Serialization; using DotNetNuke.ComponentModel.DataAnnotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; #endregion namespace Dnn.PersonaBar.TaskScheduler.Services.Dto { public class ScheduleDto { public int ScheduleID { get; set; } public string TypeFullName { get; set; } public string FriendlyName { get; set; } public int TimeLapse { get; set; } public string TimeLapseMeasurement { get; set; } public int RetryTimeLapse { get; set; } public string RetryTimeLapseMeasurement { get; set; } public int RetainHistoryNum { get; set; } public string AttachToEvent { get; set; } public bool CatchUpEnabled { get; set; } public bool Enabled { get; set; } public string ObjectDependencies { get; set; } public string ScheduleStartDate { get; set; } public string Servers { get; set; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Text; using System.Threading.Tasks; using PROJECT.SERV.Model.Tab; using SFP.Persistencia.Dao; using SFP.Persistencia.Model; namespace SERV.Dao.Tab { public class TCP_Tab_AreaIndDao : BaseDao { public TCP_Tab_AreaIndDao(DbConnection cn, DbTransaction transaction, String dataAdapter) : base(cn, transaction, dataAdapter) { } /* public Object dmlAgregar(TCP_Tab_AreaInd oDatos) { String sSQL = " INSERT INTO TCP_Tab_AreaInd( indclave, andorden, andmin, andsat, andsob, andpond, andavanceproject, andterminado, andresponsable, andcorreo, andcomentarios, andvalini, araclave, tmpclave) VALUES ( @P0, @P1, @P2, @P3, @P4, @P5, @P6, @P7, @P8, @P9, @P10, @P11, @P12, @P13) "; return EjecutaDML ( sSQL, oDatos.indclave, oDatos.andorden, oDatos.andmin, oDatos.andsat, oDatos.andsob, oDatos.andpond, oDatos.andavanceproject, oDatos.andterminado, oDatos.andresponsable, oDatos.andcorreo, oDatos.andcomentarios, oDatos.andvalini, oDatos.araclave, oDatos.tmpclave ); } public int dmlImportar( List<TCP_Tab_AreaInd> lstDatos) { int iTotReg = 0; String sSQL = " INSERT INTO TCP_Tab_AreaInd( indclave, andorden, andmin, andsat, andsob, andpond, andavanceproject, andterminado, andresponsable, andcorreo, andcomentarios, andvalini, araclave, tmpclave) VALUES ( @P0, @P1, @P2, @P3, @P4, @P5, @P6, @P7, @P8, @P9, @P10, @P11, @P12, @P13) "; foreach (TCP_Tab_AreaInd oDatos in lstDatos) { EjecutaDML ( sSQL, oDatos.indclave, oDatos.andorden, oDatos.andmin, oDatos.andsat, oDatos.andsob, oDatos.andpond, oDatos.andavanceproject, oDatos.andterminado, oDatos.andresponsable, oDatos.andcorreo, oDatos.andcomentarios, oDatos.andvalini, oDatos.araclave, oDatos.tmpclave ); iTotReg++; } return iTotReg; } */ public int dmlEditar(TCP_Tab_AreaInd oDatos) { throw new NotImplementedException(); } public int dmlBorrar(TCP_Tab_AreaInd oDatos) { throw new NotImplementedException(); } public List<TCP_Tab_AreaInd> dmlSelectTabla( ) { String sSQL = " SELECT * FROM TCP_Tab_AreaInd "; return CrearListaMDL<TCP_Tab_AreaInd>(ConsultaDML(sSQL) as DataTable); } public List<ComboMdl> dmlSelectCombo( ) { throw new NotImplementedException(); } public Dictionary<int, string> dmlSelectDiccionario( ) { throw new NotImplementedException(); } public TCP_Tab_AreaInd dmlSelectID(TCP_Tab_AreaInd oDatos ) { throw new NotImplementedException(); } public object dmlCRUD( Dictionary<string, object> dicParam ) { int iOper = (int)dicParam[CMD_OPERACION]; /* if (iOper == OPE_INSERTAR) return dmlAgregar(dicParam[CMD_ENTIDAD] as TCP_Tab_AreaInd ); */ if (iOper == OPE_EDITAR) return dmlEditar(dicParam[CMD_ENTIDAD] as TCP_Tab_AreaInd ); else if (iOper == OPE_BORRAR) return dmlBorrar(dicParam[CMD_ENTIDAD] as TCP_Tab_AreaInd ); else return 0; } /*INICIO*/ public List<TCP_Tab_AreaInd> dmlSelectIndicesById(Dictionary<string, object> dicParametros) { String sqlQuery = ""; sqlQuery = "SELECT Ind_ID, Ind_tipo ,Ind_nombre, Ind_descripcion, " + "Ind_Avance, Ind_Comentarios, " + " Ind_Calificacion, Ind_TipoObjetivo, " + " Uni_id,ind_reporta,ind_consecutivo, " + " ind_Min, ind_Sat, ind_Sob, Ind_Resultado," + " Ind_Semaforo, ind_Tipo_Avance, ind_AvanceProject," + " ind_ponderacion, ind_periodicidad, " + " ind_valor, ind_reglamentoint, ind_formula, ind_correo," + " ind_proveedor, ind_responsable, ind_unidad " + " FROM Tablero_Indicador WHERE " + "Uni_ID = '"+ dicParametros.First().Value + "' AND Ind_aņo = 2018 AND Ind_tipo = 'PRC'" + "ORDER BY Ind_nombre"; Dictionary<string, object> dicParam = new Dictionary<string, object>(); DataTable dt = ConsultaDML(sqlQuery, dicParam); List<TCP_Tab_AreaInd> lstAdmUsuMdl = CrearListaMDL<TCP_Tab_AreaInd>(dt); return lstAdmUsuMdl; } /*FIN*/ } }
using System.Collections.Generic; using MvcMonitor.Models; namespace MvcMonitor.Data.Providers { public interface ISummaryProvider { IEnumerable<string> GetErrorLocationsForApplication(string applications); ErrorModel GetLatestError(); ErrorModel GetLatestErrorForApplication(string application); int GetTotalErrorCount(); int GetTotalErrorCountForApplication(string application); } }
namespace nuru.Palette { public interface IGlyphLookup { char LookupGlyph(char index); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace downloader { public class WebCrawlerService { private string _path = ".."; private string _filename=""; private AbsWebCrawler tc = new TableCrawler(); public WebCrawlerService() { } public string path { set { _path = value; } get { return _path; } } public void Search(string url, string name) { string res = tc.Search(url); SaveFile(res, name); } private bool SaveFile(string data, string name) { if (data.Length <= 0) return false; _filename = path + "\\" + name+".txt"; try { if (File.Exists(_filename)) File.Delete(_filename); FileStream fs = new FileStream(_filename, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs); sw.Write(data); sw.Close(); fs.Close(); } catch(Exception e) { Console.Write(e.Message); return false; } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Model; using System.Reflection; using log4net; namespace Dao.Solicitud { public class CondicionPagoDao : ICondicionPagoDao { /// <summary> /// Propiedad para administrar el mecanismo de logeo /// de informacion y fallas /// </summary> public static readonly ILog log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Metodo que permite obtener las condiciones de pago o plazos para la venta al credito /// </summary> /// <returns>Lista de condicones de pago o plazos</returns> public List<InvCondicionPago> GetCondicionesPago(long idEmpresa) { List<InvCondicionPago> lista = new List<InvCondicionPago>(); SQLBDEntities _SQLBDEntities = new SQLBDEntities(); _SQLBDEntities.Configuration.ProxyCreationEnabled = false; try { lista = _SQLBDEntities.InvCondicionPago.AsNoTracking() .Where(x => x.Agregar > 0 && x.IdInvTipoMov == 1 && x.IdEmpresa == idEmpresa) .ToList(); } catch (Exception e) { log.Error(e); } return lista; } } }
using System; using System.Collections.Generic; using System.Net; using Microsoft.AspNet.Mvc; using Socialease.Models; using Socialease.ViewModels; using AutoMapper; using Microsoft.Extensions.Logging; namespace Socialease.Controllers.Api { [Route("api/pingtypes")] public class PingTypeController : Controller { private readonly ISocialRepository _repository; private readonly ILogger<PingTypeController> _logger; public PingTypeController(ISocialRepository repository, ILogger<PingTypeController> logger) { _repository = repository; _logger = logger; } [HttpGet("")] public JsonResult Get() { var results = Mapper.Map<IEnumerable<PingTypeViewModel>>(_repository.GetAllPingTypes()); return Json(results); } [HttpPost("")] public JsonResult Post([FromBody]PingTypeViewModel vm) { try { if (ModelState.IsValid) { var pingType = Mapper.Map<PingType>(vm); _logger.LogInformation("Attempting to save a new Ping Type."); _repository.AddPingType(pingType); if (_repository.SaveAll()) { Response.StatusCode = (int) HttpStatusCode.Created; return Json(Mapper.Map<PingTypeViewModel>(pingType)); } } } catch (Exception ex) { _logger.LogError("Failed to save a new Ping Type.", ex); Response.StatusCode = (int) HttpStatusCode.BadRequest; return Json(new { Message = ex.Message }); } Response.StatusCode = (int) HttpStatusCode.BadRequest; return Json(new { Message = "Failed", ModelState = ModelState}); } } }
namespace Core { using System; using Microsoft.Azure.KeyVault; using Microsoft.Azure.Services.AppAuthentication; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.AzureKeyVault; public static class ConfigurationBuilderExtensions { public static IConfigurationBuilder AddAzureKeyVault(this IConfigurationBuilder? configBuilder) { if (configBuilder == default) { throw new ArgumentNullException(nameof(configBuilder)); } var configRoot = configBuilder.Build(); var keyVaultName = configRoot.GetValue<string>("KeyVaultName"); if (string.IsNullOrEmpty(keyVaultName)) { return configBuilder; } var azureServiceTokenProvider = new AzureServiceTokenProvider(); using (var keyVaultClient = new KeyVaultClient( authenticationCallback: new KeyVaultClient.AuthenticationCallback( azureServiceTokenProvider.KeyVaultTokenCallback))) { configBuilder.AddAzureKeyVault( vault: $"https://{keyVaultName}.vault.azure.net/", client: keyVaultClient, manager: new DefaultKeyVaultSecretManager()); } return configBuilder; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace indoor_navigation_backend.Entities { public class LocationInfo { public Nullable<double> latitude { get; set; } public Nullable<double> longitude { get; set; } } }
using BIPBISHOP.ReadFileHelper; using BIPBISHOP.ViewModels; using Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Web; namespace BIPBISHOP.Controllers { public class ProductController : BaseController { // GET: Product [AuthorizeEntryPermission("Administrator")] public ActionResult Index() { return View(); } [HttpPost] [AuthorizeEntryPermission("Administrator")] public JsonResult GetListProduct(string barcode, string name) { var grid = new GridParameters(Request); var listProduct = db.SanPhams.ToList(); if (!string.IsNullOrEmpty(barcode)) { listProduct = listProduct.Where(x => x.barcode.ToLower().Equals(barcode.ToLower())).ToList(); } if (!string.IsNullOrEmpty(name)) { listProduct = listProduct.Where(x => x.name.ToLower().Contains(name)).ToList(); } grid.Total = listProduct.Count; grid.Rows = listProduct.Select(x => new SanPhamViewModel { Id = x.Id, name = x.name, cost = x.cost, barcode = x.barcode, sku = x.sku, note = x.note, soluong = x.soluong, soluongban = x.soluongban }).ToList(); return Json(grid, JsonRequestBehavior.AllowGet); } [HttpPost] [AuthorizeEntryPermission("Administrator")] [ValidateAntiForgeryToken] public ActionResult ProductAsync() { if (Request.Files != null && Request.Files.Count > 0) { var excelData = ExcelReader.ReadExcel(Request.Files[0]); int numberOfAddNew = 0; int numberOfUpdate = 0; foreach (var dataRow in excelData.DataRows) { string alias = dataRow.Count > 0 ? dataRow[0].ToString() : ""; string ten = dataRow.Count > 1 ? dataRow[1].ToString() : ""; string content = dataRow.Count > 2 ? dataRow[2].ToString() : ""; string masku = dataRow.Count > 3 ? dataRow[3].ToString() : ""; string kho = dataRow.Count > 4 ? dataRow[4].ToString() : ""; string gia = dataRow.Count > 5 ? dataRow[5].ToString() : ""; string barcode = dataRow.Count > 6 ? dataRow[6].ToString().Trim() : ""; string note = dataRow.Count > 7 ? dataRow[7].ToString() : ""; SanPham sanpham = new SanPham(); sanpham.alias = alias; sanpham.name = ten; sanpham.content = content; sanpham.sku = masku; int soluong = 0; int.TryParse(kho, out soluong); sanpham.soluong = soluong; sanpham.cost = float.Parse(string.IsNullOrEmpty(gia) ? "0" : gia.Replace(".", "")); sanpham.barcode = barcode; sanpham.note = note; if (!string.IsNullOrEmpty(barcode.Trim())) { SanPham spExisted = db.SanPhams.FirstOrDefault(x => x.barcode.Equals(barcode)); if (spExisted != null) { spExisted.cost = sanpham.cost; spExisted.name = sanpham.name; spExisted.note = sanpham.note; spExisted.soluong += sanpham.soluong; numberOfUpdate++; } else { db.SanPhams.Add(sanpham); numberOfAddNew++; } } } db.SaveChanges(); ViewBag.Message = string.Format("Số sản phẩm được thêm mới: {0} - Số sản phẩm được cập nhật lại: {1}", numberOfAddNew, numberOfUpdate); } return RedirectToAction("Index"); } [HttpPost] [AuthorizeEntryPermission("Administrator")] [ValidateAntiForgeryToken] public ActionResult Update(ProductViewModel viewModel) { if (viewModel.Product != null) { if (viewModel.Product.Id != 0) { var product = db.SanPhams.FirstOrDefault(x => x.Id == viewModel.Product.Id) ?? new SanPham(); if (viewModel.Product.Id != 0) { product.cost = viewModel.Product.cost; product.soluong = viewModel.Product.soluong; db.SaveChanges(); } } } return RedirectToAction("Index"); } } }
using GTANetworkAPI; using System.Collections.Generic; namespace NeptuneEvo.Voice { class Room { public string Name; public List<Player> Players; public Dictionary<string, object> MetaData { get { return new Dictionary<string, object> { { "name", Name } }; } } public Room(string Name) { this.Name = Name; this.Players = new List<Player>(); } public void OnJoin(Player player) { if (Players.Contains(player)) { var argsMe = new List<object> { MetaData }; Players.ForEach(_player => argsMe.Add(_player)); Trigger.ClientEvent(player, "voice.radioConnect", argsMe.ToArray()); Trigger.ClientEventToPlayers(Players.ToArray(), "voice.radioConnect", MetaData, player); var tempPlayer = player.GetData<VoiceMetaData>("Voip"); tempPlayer.RadioRoom = Name; player.SetData<VoiceMetaData>("Voip", tempPlayer); Players.Add(player); } } public void OnQuit(Player player) { if (Players.Contains(player)) { var argsMe = new List<object> { MetaData }; Players.ForEach(_player => argsMe.Add(_player)); Trigger.ClientEvent(player, "voice.radioDisconnect", argsMe.ToArray()); Trigger.ClientEventToPlayers(Players.ToArray(), "voice.radioDisconnect", MetaData, player); player.ResetData("Voip"); Players.Remove(player); } } public void OnRemove() { Trigger.ClientEventToPlayers(Players.ToArray(), "voice.radioDisconnect", MetaData); Players.Clear(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected void save_Click(object sender, EventArgs e) { StringBuilder shtml = new StringBuilder(); shtml.Append("<ul>"); if (Request.Form.AllKeys.Length != 0) { string[] formArray = Request.Form.AllKeys; foreach (string key in formArray) { if (key.Contains("tag[")) { shtml.Append( "<li>key:"+key+";value:"+Request.Form[key]+"</li>"); } } } shtml.Append("</ul>"); Literal1.Text = shtml.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class EventManager : Singleton<EventManager> { private void OnEnable() { StartCoroutine(SubscribeEvents()); } IEnumerator SubscribeEvents() { yield return new WaitForEndOfFrame(); TimeManager.Instance.SubscribeToEvents(); } #region Gameplay States public delegate void StartGamePlay(); public event StartGamePlay onStartGameplay; public void StartGameplay() { if (onStartGameplay != null) { onStartGameplay.Invoke(); } } public event Action<Transform> onFinalHit; public void FinalHit(Transform finalTarget) { if(onFinalHit != null) { onFinalHit(finalTarget); } } public event Action onEndGamePlay; public void EndGamePlay() { if(onEndGamePlay != null) { onEndGamePlay(); } } #endregion public event Action<TargetController> onTargetStung; public void TargetStung(TargetController target) { if(onTargetStung != null) { onTargetStung(target); } } public event Action onCollectibleHit; public void CollectibleHit() { if(onCollectibleHit != null) { onCollectibleHit(); } } }
using Dapper; using Everest.Entities; using Everest.Repository.Interfaces; using System; using System.Data; using System.Linq; using System.Threading.Tasks; namespace Everest.Repository.Implementations { public class UbicacionRepository : BaseConnection, IUbicacionRepository { public UbicacionRepository(IDbConnection dbConnection) : base(dbConnection) { } public async Task<UbicacionEntity> ConsultarPorAnuncioAsync(int id) { if (_dbConnection.State == ConnectionState.Closed) _dbConnection.Open(); var result = await _dbConnection.QueryAsync<UbicacionEntity>("ConsultarUbicacionPorAnuncio", new { Id = id }, commandType: CommandType.StoredProcedure); _dbConnection.Close(); return result.FirstOrDefault(); } public async Task<int> CrearUbicacionAsync(UbicacionEntity entity) { if (_dbConnection.State == ConnectionState.Closed) _dbConnection.Open(); var spEntity = new { entity.IdAnuncio, entity.Direccion, Latitud = Math.Round(entity.Latitud, 6), Longitud = Math.Round(entity.Longitud, 6) }; var result = await _dbConnection.QueryAsync<int>("CrearUbicacion", spEntity, commandType: CommandType.StoredProcedure); _dbConnection.Close(); return result.FirstOrDefault(); } public async Task<bool> EditarUbicacionAsync(UbicacionEntity entity) { if (_dbConnection.State == ConnectionState.Closed) _dbConnection.Open(); var spEntity = new { entity.IdUbicacion, entity.IdAnuncio, entity.Direccion, entity.Latitud, entity.Longitud }; var result = await _dbConnection.QueryAsync<bool>("EditarUbicacion", spEntity, commandType: CommandType.StoredProcedure); _dbConnection.Close(); return result.FirstOrDefault(); } public async Task<bool> EliminarUbicacionAsync(int id) { if (_dbConnection.State == ConnectionState.Closed) _dbConnection.Open(); var result = await _dbConnection.QueryAsync<bool>("EliminarUbicacion", new { Id = id }, commandType: CommandType.StoredProcedure); _dbConnection.Close(); return result.FirstOrDefault(); } } }
using UnityEngine; using System.Collections.Generic; public static class SimplePool { //You can avoid resizing of the Stack's internal data by setting this to a number equal to or greater to what you expect most of your pool sizes to be. //Note, you can also use Preload() to set the initial size of a pool. This can be handy if only some of your pools are going to be exceptionally large (for example, your bullets.). const int DEFAULT_POOL_SIZE = 3; class Pool { int nextId = 1; //The structure containing our inactive objects. Why a Stack and not a List? Because we'll never need to pluck an object from the start or middle of the array. //We'll always just grab the last one, which eliminates any need to shuffle the objects around in memory. Stack<GameObject> inactive; GameObject prefab; public Pool(GameObject prefab, int initialQty) { this.prefab = prefab; //If Stack uses a linked list internally, then this whole initialQty thing is a placebo that we could strip out for more minimal code. But it can't hurt. inactive = new Stack<GameObject>(initialQty); } //Spawn an object from our pool. public GameObject Spawn(Vector3 pos, Quaternion rot) { GameObject obj; if(inactive.Count == 0) { //We don't have an object in our pool, so we instantiate a whole new object. obj = (GameObject)GameObject.Instantiate(prefab, pos, rot); obj.name = prefab.name + " (" + (nextId++) + ")"; //Add a PoolMember component so we know what pool we belong to. obj.AddComponent<PoolMember>().myPool = this; } else { //Grab the last object in the inactive array. obj = inactive.Pop(); if(obj == null) { //The inactive object we expected to find no longer exists. The most likely causes are: // - Someone calling Destroy() on our object. // - A scene change (which will destroy all our objects). NOTE: This could be prevented with a DontDestroyOnLoad if you really don't want this. //No worries, we'll just try the next one in our sequence. return Spawn(pos, rot); } } obj.transform.position = pos; obj.transform.rotation = rot; obj.SetActive(true); return obj; } //Return an object to the inactive pool. public void Despawn(GameObject obj) { obj.SetActive(false); //Since Stack doesn't have a Capacity member, we can't control the growth factor if it does have to expand an internal array. //On the other hand, it might simply be using a linked list internally. But then, why does it allow us to specify a size the constructor? Maybe it's a placebo? Stack is weird. inactive.Push(obj); } } //Added to freshly instantiated objects, so we can link back to the correct pool on despawn. class PoolMember : MonoBehaviour { public Pool myPool; } //All of our pools. static Dictionary<GameObject, Pool> pools; //Initialize our dictionary. static void Init (GameObject prefab=null, int qty = DEFAULT_POOL_SIZE) { if(pools == null) { pools = new Dictionary<GameObject, Pool>(); } if(prefab!=null && pools.ContainsKey(prefab) == false) { pools[prefab] = new Pool(prefab, qty); } } //If you want to preload a few copies of an object at the start of a scene, you can use this. Really not needed unless you're going to go from zero instances to 100+ very quickly. //Could technically be optimized more, but in practice the Spawn/Despawn sequence is going to be pretty darn quick and this avoids code duplication. static public void Preload(GameObject prefab, int qty = 1) { Init(prefab, qty); //Make an array to grab the objects we're about to pre-spawn. GameObject[] obs = new GameObject[qty]; for(int i = 0; i < qty; i++) { obs[i] = Spawn(prefab, Vector3.zero, Quaternion.identity); } //Now despawn them all. for(int i = 0; i < qty; i++) { Despawn(obs[i]); } } //Spawns a copy of the specified prefab (instantiating one if required). NOTE: Remember that Awake() or Start() will only run on the very first spawn and that member variables won't get reset. //OnEnable will run after spawning, but remember that toggling IsActive will also call that function. static public GameObject Spawn(GameObject prefab, Vector3 pos, Quaternion rot) { Init(prefab); return pools[prefab].Spawn(pos, rot); } //Despawn the specified gameobject back into its pool. static public void Despawn(GameObject obj) { PoolMember pm = obj.GetComponent<PoolMember>(); if(pm == null) { Debug.Log("Object '"+obj.name+"' wasn't spawned from a pool. Destroying it instead."); GameObject.Destroy(obj); } else { pm.myPool.Despawn(obj); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Planning { class CatchtInvaders { public int Size { get; private set; } public int Invaders { get; private set; } public CatchtInvaders(int iSize, int cInvaders) { Size = iSize; Invaders = cInvaders; } public void WriteProblem(string sPathName) { StreamWriter sw = new StreamWriter(sPathName + @"\p.Planning"); sw.WriteLine(GenerateProblem()); sw.Close(); } private string GenerateProblem() { string sProblem = "(define \n"; sProblem += "(problem " + Name + ")\n"; sProblem += "(:domain " + Name + ")\n"; //sProblem += GenerateObjects() + "\n"; sProblem += GetInitState() + "\n"; sProblem += GetGoalState() + "\n"; sProblem += ")"; return sProblem; } private string GetGoalState() { string sGoal = "(:goal (and"; for (int iInvader = 0; iInvader < Invaders; iInvader++) sGoal += " (caught i" + iInvader + ")"; sGoal += "))"; return sGoal; } private string GenerateConstants() { int iX = 0, iY = 0, iInvader = 0; string sObjects = "(:constants\n"; for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { sObjects += "\t p" + iX + "-" + iY + " - LOCATION\n"; } } for (iInvader = 0; iInvader < Invaders; iInvader++) { sObjects += "\t i" + iInvader + " - INVADER\n"; } sObjects += ")"; return sObjects; } private string GetInitState() { int iInvader = 0; int iX = 0, iY = 0, iOtherX = 0, iOtherY = 0; string sInit = "(:init\n"; sInit += "(and\n"; int iMiddle = Size / 2 + 1; sInit += "\t(agent-at p" + iMiddle + "-" + iMiddle + ")\n"; sInit += "\t(agent-on-ground)\n"; for (iInvader = 0; iInvader < Invaders; iInvader++) { sInit += "\t(oneof"; for(iX = 1; iX <= Size ; iX++) for(iY = 1; iY <= Size ; iY++) sInit += " (invader-at i" + iInvader + " p" + iX + "-" + iY + ")\n"; sInit += ")\n"; } for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { for (iOtherX = 1; iOtherX <= Size; iOtherX++) { for (iOtherY = 1; iOtherY <= Size; iOtherY++) { if (GetDistance(iX, iY, iOtherX, iOtherY) == 1) sInit += "\t(adj p" + iX + "-" + iY + " p" + iOtherX + "-" + iOtherY + ")\n"; //sInit += "\t(distance p" + iX + "-" + iY + " p" + iOtherX + "-" + iOtherY + " v" + iDistance + ")\n"; } } } } sInit += ")\n)\n"; return sInit; } private string GeneratePredicates() { string sPredicates = "(:predicates\n"; sPredicates += "\t(invader-at ?i - INVADER ?p - LOCATION)\n"; sPredicates += "\t(agent-at ?p - LOCATION)\n"; sPredicates += "\t(adj ?p1 - LOCATION ?p2 - LOCATION)\n"; sPredicates += "\t(agent-on-tree)\n"; sPredicates += "\t(agent-on-ground)\n"; sPredicates += "\t(caught ?i - INVADER)\n"; sPredicates += "\t(noise)\n"; sPredicates += "\t(sight)\n"; sPredicates += "\t(sight-at ?p - LOCATION)\n"; sPredicates += ")\n"; return sPredicates; } private string GenerateActions() { string sActions = ""; sActions += GenerateMoveAction() + "\n"; sActions += GenerateClimbActions() + "\n"; sActions += GenerateWatchOnGroundAction() + "\n"; sActions += GenerateWatchOnTreeAction() + "\n"; sActions += GenerateListenAction() + "\n"; sActions += GenerateObservationActions() + "\n"; sActions += GenerateCatchAction() + "\n"; return sActions; } private string GenerateClimbActions() { string sActions = "(:action climb-up\n"; sActions += ":precondition (agent-on-ground)\n"; sActions += ":effect (and (not (agent-on-ground)) (agent-on-tree)))\n"; sActions += "(:action climb-down\n"; sActions += ":precondition (agent-on-tree)\n"; sActions += ":effect (and (not (agent-on-tree)) (agent-on-ground)))\n"; return sActions; } private string GenerateListenAction() { int iX = 0, iY = 0, iOtherX = 0, iOtherY = 0; string sAction = "(:action listen\n"; sAction += ":effect (and\n"; for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { for (int iInvader = 0; iInvader < Invaders; iInvader++) { for (iOtherX = 1; iOtherX <= Size; iOtherX++) { for (iOtherY = 1; iOtherY <= Size; iOtherY++) { if (GetDistance(iX, iY, iOtherX, iOtherY) <= 3) { sAction += "\t(when (and (agent-at p" + iX + "-" + iY + ")"; sAction += " (invader-at i" + iInvader + " p" + iOtherX + "-" + iOtherY + ")) (noise))\n"; } } } } } } sAction += "))\n"; return sAction; } private string GenerateWatchOnGroundAction() { int iX = 0, iY = 0, iOtherX = 0, iOtherY = 0; string sAction = "(:action watch-on-ground\n"; sAction += ":precondition (agent-on-ground)\n"; sAction += ":effect (and\n"; for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { for (iOtherX = 1; iOtherX <= Size; iOtherX++) { for (iOtherY = 1; iOtherY <= Size; iOtherY++) { if (GetDistance(iX, iY, iOtherX, iOtherY) <= 1) { for (int iInvader = 0; iInvader < Invaders; iInvader++) { sAction += "\t(when (and (agent-at p" + iX + "-" + iY + ") "; sAction += " (invader-at i" + iInvader + " p" + iOtherX + "-" + iOtherY + "))"; sAction += " (and (sight-at p" + iOtherX + "-" + iOtherY + ") (sight)))\n"; } } } } } } sAction += "))\n"; return sAction; } private string GenerateWatchOnTreeAction() { int iX = 0, iY = 0, iOtherX = 0, iOtherY = 0; string sAction = "(:action watch-on-tree\n"; sAction += ":precondition (agent-on-tree)\n"; sAction += ":effect (and\n"; for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { for (iOtherX = 1; iOtherX <= Size; iOtherX++) { for (iOtherY = 1; iOtherY <= Size; iOtherY++) { if (GetDistance(iX, iY, iOtherX, iOtherY) <= 4) { for (int iInvader = 0; iInvader < Invaders; iInvader++) { sAction += "\t(when (and (agent-at p" + iX + "-" + iY + ")"; sAction += " (invader-at i" + iInvader + " p" + iOtherX + "-" + iOtherY + "))"; sAction += " (and (sight-at p" + iOtherX + "-" + iOtherY + ") (sight)))\n"; } } } } } } sAction += "))\n"; return sAction; } /* private string GenerateListenAction() { int iX = 0, iY = 0, iOtherX = 0, iOtherY = 0; string sAction = "(:action listen\n"; sAction += ":effect (and\n"; for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { sAction += "\t(when (and (agent-at p" + iX + "-" + iY + ") (or "; for (int iInvader = 0; iInvader < Invaders; iInvader++) { for (iOtherX = 1; iOtherX <= Size; iOtherX++) { for (iOtherY = 1; iOtherY <= Size; iOtherY++) { if (GetDistance(iX, iY, iOtherX, iOtherY) <= 3) { sAction += " (invader-at i" + iInvader + " p" + iOtherX + "-" + iOtherY + ")"; } } } } sAction += ")) (noise))\n"; } } sAction += "))\n"; return sAction; } private string GenerateWatchOnGroundAction() { int iX = 0, iY = 0, iOtherX = 0, iOtherY = 0; string sAction = "(:action watch-on-ground\n"; sAction += ":precondition (agent-on-ground)\n"; sAction += ":effect (and\n"; for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { for (iOtherX = 1; iOtherX <= Size; iOtherX++) { for (iOtherY = 1; iOtherY <= Size; iOtherY++) { if (GetDistance(iX, iY, iOtherX, iOtherY) <= 1) { sAction += "\t(when (and (agent-at p" + iX + "-" + iY + ") (or "; for (int iInvader = 0; iInvader < Invaders; iInvader++) { sAction += " (invader-at i" + iInvader + " p" + iOtherX + "-" + iOtherY + ")"; } sAction += ")) (and (sight-at p" + iOtherX + "-" + iOtherY + ") (sight)))\n"; } } } } } sAction += "))\n"; return sAction; } private string GenerateWatchOnTreeAction() { int iX = 0, iY = 0, iOtherX = 0, iOtherY = 0; string sAction = "(:action watch-on-tree\n"; sAction += ":precondition (agent-on-tree)\n"; sAction += ":effect (and\n"; for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { for (iOtherX = 1; iOtherX <= Size; iOtherX++) { for (iOtherY = 1; iOtherY <= Size; iOtherY++) { if (GetDistance(iX, iY, iOtherX, iOtherY) <= 4) { sAction += "\t(when (and (agent-at p" + iX + "-" + iY + ") (or "; for (int iInvader = 0; iInvader < Invaders; iInvader++) { sAction += " (invader-at i" + iInvader + " p" + iOtherX + "-" + iOtherY + ")"; } sAction += ")) (and (sight-at p" + iOtherX + "-" + iOtherY + ") (sight)))\n"; } } } } } sAction += "))\n"; return sAction; } */ private string GenerateCatchAction() { string sAction = "(:action catch-invader\n"; sAction += ":parameters (?p - LOCATION ?i - INVADER)\n"; sAction += ":precondition (and (agent-at ?p) (invader-at ?i ?p))\n"; sAction += ":effect (caught ?i))\n"; return sAction; } private string GenerateMoveAction() { int iX = 0, iY = 0, iOtherX = 0, iOtherY = 0; string sAction = "(:action move\n"; sAction += ":parameters (?pSource - LOCATION ?pTarget - LOCATION)\n"; sAction += ":precondition (and (agent-at ?pSource) (adj ?pSource ?pTarget) (agent-on-ground))\n"; sAction += ":effect (and (agent-at ?pTarget) (not (agent-at ?pSource)) (not (noise)) (not (sight))\n"; for (int iInvader = 0; iInvader < Invaders; iInvader++) { for (iX = 1; iX <= Size; iX++) { for (iY = 1; iY <= Size; iY++) { sAction += "\t(not (sight-at p" + iX + "-" + iY + "))\n"; sAction += "\t(when (invader-at i" + iInvader + " p" + iX + "-" + iY + ") (oneof"; for (iOtherX = 1; iOtherX <= Size; iOtherX++) { for (iOtherY = 1; iOtherY <= Size; iOtherY++) { if (GetDistance(iX, iY, iOtherX, iOtherY) <= 1) { if (iX != iOtherX || iY != iOtherY) { sAction += " (and (not (invader-at i" + iInvader + " p" + iX + "-" + iY + "))"; sAction += " (invader-at i" + iInvader + " p" + iOtherX + "-" + iOtherY + "))"; } else sAction += " (invader-at i" + iInvader + " p" + iOtherX + "-" + iOtherY + ")"; } } } sAction += "))\n"; } } } sAction += "))\n"; return sAction; } private double GetDistance(int iX, int iY, int iOtherX, int iOtherY) { int iDeltaX = iX - iOtherX, iDeltaY = iY - iOtherY; return Math.Sqrt(iDeltaX * iDeltaX + iDeltaY * iDeltaY); } private string GenerateObservationActions() { string sActions = ""; //sActions += "(:action observe-noise\n"; //sActions += ":observe (noise))\n"; sActions += "(:action observe-sight\n"; sActions += ":observe (sight))\n"; sActions += "(:action observe-sight-at\n"; sActions += ":parameters (?p - LOCATION)\n"; sActions += ":observe (sight-at ?p))\n"; /* sActions += "(:action observe-invader-at\n"; sActions += ":parameters (?p - LOCATION ?i - INVADER)\n"; sActions += ":precondition (agent-at ?p)\n"; sActions += ":observe (invader-at ?i ?p))\n"; */ return sActions; } public void WriteDomain(string sPath) { if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath); StreamWriter sw = new StreamWriter(sPath + @"\d.Planning"); sw.Write(GenerateDomain()); sw.Close(); } private string GenerateDomain() { string sDomain = "(define \n"; sDomain += "(domain " + Name + ")\n"; sDomain += "(:types LOCATION ROCK HEIGHT)\n"; sDomain += GenerateConstants() + "\n"; sDomain += GeneratePredicates(); sDomain += GenerateActions(); sDomain += ")"; return sDomain; } public string Name { get { return "CatchInvaders" + Size + "-" + Invaders; } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GameGK.Class { public class GameBoard { private int rows; private int cols; private int ROWS; private int COLS; private float score; private int linesFilled; private Tetramino curTetramino; private Tetramino nextTetramino; private PictureBox[,] BlockControls; private PictureBox[,] BlockShape; private bool gameOver = false; private int curNumber; private int nextNumber; private Random tetraminoRandom; static public Image NoImage = null; public GameBoard(Board board) { rows = board.GetMainGridRow; cols = board.GetMainGridCol; ROWS = board.GetExtraGridRow; COLS = board.GetExtraGridCol; tetraminoRandom = new Random(); curNumber = tetraminoRandom.Next(0, 7); nextNumber = tetraminoRandom.Next(0, 7); score = 0; linesFilled = 0; BlockControls = new PictureBox[cols, rows];// block trong main grid BlockShape = new PictureBox[COLS, ROWS];// block tiếp theo for (int h = 0; h < COLS; h++) { for (int k = 0; k < ROWS; k++) { BlockShape[h, k] = new PictureBox { BackgroundImage = NoImage, BackgroundImageLayout = ImageLayout.Stretch, BackColor = Color.Transparent, Width=27, Height=27, }; board.GetExtraGrid.Add(BlockShape[h, k], h, k); } } for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { BlockControls[i, j] = new PictureBox { BackgroundImage = NoImage, BackgroundImageLayout = ImageLayout.Stretch, Width = 27, Height = 27, BackColor = Color.Transparent, }; board.GetMainGrid.Add(BlockControls[i, j], i, j); } } curTetramino = new Tetramino(this.curNumber); nextTetramino = new Tetramino(nextNumber); CurTetraminoDraw(); NextTetraminoDraw(); } public float GetScore { get { return score; } set { score = value; } } public int GetLines { get { return linesFilled; } set { linesFilled = value; } } public void NextTetraminoDraw() { Point position = nextTetramino.GetPosition; Point[] Shape = nextTetramino.GetShape; Image Color = nextTetramino.GetColor; foreach (Point S in Shape) { BlockShape[(int)(S.X + position.X + 1), (int)(S.Y + position.Y) + 2].BackgroundImage = Color; } } private void CurTetraminoDraw() { Point position = curTetramino.GetPosition; Point[] Shape = curTetramino.GetShape; Image Color = curTetramino.GetColor; foreach (Point S in Shape) { BlockControls[(int)(S.X + position.X) + ((cols / 2) - 1), (int)(S.Y + position.Y) + 1].BackgroundImage = Color; } } private void NextTetraminoErase() { Point position = nextTetramino.GetPosition; Point[] Shape = nextTetramino.GetShape; foreach (Point S in Shape) { BlockShape[(int)(S.X + position.X + 1), (int)(S.Y + position.Y) + 2].BackgroundImage = NoImage; } } private void CurTetraminoErase() { Point position = curTetramino.GetPosition; Point[] Shape = curTetramino.GetShape; foreach (Point S in Shape) { BlockControls[(int)(S.X + position.X) + ((cols / 2) - 1), (int)(S.Y + position.Y) + 1].BackgroundImage = NoImage; } } private void CheckRows() { bool full; for (int i = rows - 1; i > 0; i--) { full = true; for (int j = 0; j < cols; j++) { if (BlockControls[j, i].BackgroundImage == NoImage) { full = false; } } if (full) { RemoveRow(ref i); score += 100; linesFilled += 1; } } } private void RemoveRow(ref int row) { for (int i = row; i > 0; i--) { for (int j = 0; j < cols; j++) { BlockControls[j, i].BackgroundImage = BlockControls[j, i - 1].BackgroundImage; } } row++; } public void CurTetraminoMovLeft() { Point Position = curTetramino.GetPosition; Point[] Shape = curTetramino.GetShape; bool move = true; CurTetraminoErase(); foreach (Point S in Shape) { if (((int)(S.X + Position.X) + ((cols / 2) - 1) - 1) < 0) { move = false; } else if (BlockControls[((int)(S.X + Position.X) + ((cols / 2) - 1) - 1), (int)(S.Y + Position.Y) + 1].BackgroundImage != NoImage) { move = false; } } if (move) { curTetramino.MoveLeft(); CurTetraminoDraw(); } else { CurTetraminoDraw(); } } public void CurTetraminoMovRight() { Point Position = curTetramino.GetPosition; Point[] Shape = curTetramino.GetShape; bool move = true; CurTetraminoErase(); foreach (Point S in Shape) { if (((int)(S.X + Position.X) + ((cols / 2) - 1) + 1) >= cols) { move = false; } else if (BlockControls[((int)(S.X + Position.X) + ((cols / 2) - 1) + 1), (int)(S.Y + Position.Y) + 1].BackgroundImage != NoImage) { move = false; } } if (move) { curTetramino.MoveRight(); CurTetraminoDraw(); } else { CurTetraminoDraw(); } } public void CurTetraminoMovDown() { Point Position = curTetramino.GetPosition; Point[] Shape = curTetramino.GetShape; bool move = true; CurTetraminoErase(); foreach (Point S in Shape) { if (((int)(S.Y + Position.Y) + 1 + 1) >= rows) { move = false; } else if (BlockControls[((int)(S.X + Position.X) + ((cols / 2) - 1)), (int)(S.Y + Position.Y) + 1 + 1].BackgroundImage != NoImage) { move = false; } } if (move) { curTetramino.MoveDown(); CurTetraminoDraw(); } else { CurTetraminoDraw(); CheckRows(); if ((int)Position.Y <= 1) { gameOver = true; } else { curNumber = nextNumber; nextNumber = tetraminoRandom.Next(0, 7); curTetramino = new Tetramino(curNumber); NextTetraminoErase(); nextTetramino = new Tetramino(nextNumber); NextTetraminoDraw(); } } } public void CurTetraminoMovRotate() { Point Position = curTetramino.GetPosition; Point[] S = new Point[4]; Point[] Shape = curTetramino.GetShape; bool move = true; Shape.CopyTo(S, 0); CurTetraminoErase(); for (int i = 0; i < S.Length; i++) { int x = S[i].X; S[i].X = S[i].Y * -1; S[i].Y = x; if (((int)((S[i].Y + Position.Y) + 1)) >= rows) { move = false; } else if (((int)(S[i].X + Position.X) + ((cols / 2) - 1)) < 0) { move = false; } else if (((int)(S[i].X + Position.X) + ((cols / 2) - 1)) >= cols) { move = false; } else if (BlockControls[((int)(S[i].X + Position.X) + ((cols / 2) - 1)), (int)(S[i].Y + Position.Y) + 1].BackgroundImage != NoImage) { move = false; } } if (move) { curTetramino.MovRotate(); CurTetraminoDraw(); } else { CurTetraminoDraw(); } } public bool GameOver() { return gameOver; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class DragbleImage : MonoBehaviour, IDragHandler, IPointerDownHandler { public NewBehaviourScript osnovnoySkript; public Canvas canvos; public RectTransform dragImage; int inIndexObject;//индекс того на что навели public Transform emptyObject;//пустышка которая создается в момент хватания Transform NewCriateObject;//UI объект который создали новый GameObject InputUiObject;//UI объект который схватили string nameAdress;//адрес UI обьекта Items BuferItems = null;// bool enabledd = false; public void OnPointerDown(PointerEventData eventData) { if(eventData.pointerEnter.transform.parent.transform.Find("InputFieldName")) { InputUiObject = eventData.pointerEnter.transform.parent.gameObject; nameAdress = InputUiObject.transform.Find("InputFieldName").GetComponent<InputField>().text; dragImage.position = eventData.pointerEnter.transform.position; dragImage.GetChild(0).GetChild(0).GetComponent<InputField>().text = nameAdress; dragImage.SetAsLastSibling(); if(InputUiObject.name == "Кнопка(Clone)") { //получаем индекс обьекта что схватили inIndexObject = int.Parse(eventData.pointerEnter.transform.parent.GetChild(0).GetComponent<Text>().text); //создаем пустышку NewCriateObject = Instantiate(emptyObject); //и наследуем ее в рейс NewCriateObject.SetParent(eventData.pointerEnter.transform.parent.parent); NewCriateObject.SetSiblingIndex(inIndexObject); //UI объект который схватили переносим в конец списка InputUiObject.transform.SetAsLastSibling(); if(NewCriateObject.parent.parent.parent.name == "Меню Рейс №1") { PolaReisUpdate(osnovnoySkript.polaReis, inIndexObject, true); } else { PolaReisUpdate(osnovnoySkript.polaReis2, inIndexObject, true); } //переносим иконку с адресом в самый конец всех элементов AlpfaCanalOff(InputUiObject, false); } } } public void OnDrag(PointerEventData eventData) { /*if(NewCriateObject && eventData.pointerCurrentRaycast.gameObject && eventData.pointerCurrentRaycast.gameObject.transform.name == "Меню Рейс №1" || NewCriateObject && eventData.pointerCurrentRaycast.gameObject && eventData.pointerCurrentRaycast.gameObject.transform.name == "Меню Рейс №2") { string acs1; string acs2; acs1 = NewCriateObject.parent.parent.parent.name; acs2 = eventData.pointerCurrentRaycast.gameObject.transform.name; if(acs1 == acs2) { // enabledd = true; } // else enabledd = false; }*/ if(NewCriateObject && eventData.pointerEnter.transform.parent && eventData.pointerEnter.transform.parent.name == "Кнопка(Clone)" ) { //получаем индекс обьекта что схватили inIndexObject = int.Parse(eventData.pointerEnter.transform.parent.GetChild(0).GetComponent<Text>().text); //переносим пустышку с авдресом в место индекса NewCriateObject.transform.SetSiblingIndex(inIndexObject); //передаем пустышке номер места куда поставить NewCriateObject.GetChild(0).GetComponent<Text>().text = inIndexObject.ToString(); } dragImage.anchoredPosition += eventData.delta / canvos.scaleFactor; } void Update () { if(Input.GetMouseButtonUp(0)) { if(NewCriateObject && NewCriateObject.parent.parent.parent) { string acs1 = NewCriateObject.parent.parent.parent.name; string acs2 = osnovnoySkript.acse; //Debug.Log("откуда= " + acs1 + " " + "где= " + acs2 + " " + enabledd); if(acs1 == acs2) { enabledd = true; } else { enabledd = false; // if(InputUiObject)AlpfaCanalOff(InputUiObject, true); } } dragImage.anchoredPosition = new Vector2(1000,1000); dragImage.GetChild(0).GetChild(0).GetComponent<InputField>().text =""; if(InputUiObject && InputUiObject.name == "Кнопка(Clone)" && enabledd) { //UI объект который схватили переносим в место индекса InputUiObject.transform.SetSiblingIndex(inIndexObject); if(NewCriateObject.parent.parent.parent.name == "Меню Рейс №1") { // Debug.Log("polaReis " + enabledd); PolaReisUpdate(osnovnoySkript.polaReis, inIndexObject, false); } else { // Debug.Log("polaReis2" + enabledd); PolaReisUpdate(osnovnoySkript.polaReis2, inIndexObject, false); } } if(InputUiObject && InputUiObject.name == "Кнопка(Clone)") { AlpfaCanalOff(InputUiObject, true); InputUiObject = null; if(NewCriateObject) { Destroy(NewCriateObject.gameObject); NewCriateObject = null; } } enabledd = false; } } void PolaReisUpdate(List<Items> array,int index , bool OnEnabled) { if(OnEnabled) { //делаем копию экземпляра массива в тот же класс Items BuferItems = array[index]; //удаляем экземпляр из масива array.RemoveAt(index); //создаем новый в конце экземпляр в массиве только в конце array.Add(BuferItems); //перезаполняем номаре UI обьектов для того чтобы можно было бы поставить на нулевую позицию for (int i = 0; i < array.Count; i++) { array[i].Polatrans.GetChild(0).GetComponent<Text>().text = i.ToString(); } } else { //вставляем новый экземпляр с местом индекса в массив array.Insert(index, BuferItems); //удаляем последний экземпляр из масива array.RemoveAt(array.Count -1 ); //пересчитывает индекс и устанавливает в UI for (int i = 0; i < array.Count; i++) { array[i].Polatrans.GetChild(0).GetComponent<Text>().text = i.ToString(); } } } void AlpfaCanalOff(GameObject InputUiObjectOff, bool OnEnabled) { Color alpfaCanal = InputUiObjectOff.GetComponent<Image>().color; if(OnEnabled) { alpfaCanal.a = 255f; InputUiObjectOff.GetComponent<Image>().color = alpfaCanal; }else { alpfaCanal.a = 0; InputUiObjectOff.GetComponent<Image>().color = alpfaCanal; } alpfaCanal = InputUiObjectOff.transform.GetChild(0).GetComponent<Text>().color; if(OnEnabled) { // alpfaCanal.r = 0; // alpfaCanal.g = 0; // alpfaCanal.b = 0; alpfaCanal.a = 255; InputUiObjectOff.transform.GetChild(0).GetComponent<Text>().color = alpfaCanal; }else { //alpfaCanal.r = 255; //alpfaCanal.g = 255; //alpfaCanal.b = 255; alpfaCanal.a = 0; InputUiObjectOff.transform.GetChild(0).GetComponent<Text>().color = alpfaCanal; } alpfaCanal = InputUiObjectOff.transform.GetChild(1).Find("Text").GetComponent<Text>().color; if(OnEnabled) { // alpfaCanal.r = 0; // alpfaCanal.g = 0; // alpfaCanal.b = 0; alpfaCanal.a = 255; InputUiObjectOff.transform.GetChild(1).Find("Text").GetComponent<Text>().color = alpfaCanal; }else { // alpfaCanal.r = 255; // alpfaCanal.g = 255; // alpfaCanal.b = 255; alpfaCanal.a = 0; InputUiObjectOff.transform.GetChild(1).Find("Text").GetComponent<Text>().color = alpfaCanal; } alpfaCanal = InputUiObjectOff.transform.GetChild(1).GetComponent<Image>().color; if(OnEnabled) { alpfaCanal.a = 255; InputUiObjectOff.transform.GetChild(1).GetComponent<Image>().color = alpfaCanal; }else { alpfaCanal.a = 0; InputUiObjectOff.transform.GetChild(1).GetComponent<Image>().color = alpfaCanal; } InputUiObjectOff.transform.GetChild(2).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(3).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(4).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(5).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(6).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(7).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(8).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(9).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(10).gameObject.SetActive(OnEnabled); InputUiObjectOff.transform.GetChild(11).gameObject.SetActive(OnEnabled); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; using UnityEngine; using UnityEngine.Networking; using VRC.SDKBase.Editor.BuildPipeline; using VRC.SDKBase.Validation.Performance; using VRC.SDKBase.Validation.Performance.Stats; using Object = UnityEngine.Object; namespace VRC.SDKBase.Editor { public class VRCSdkControlPanelAvatarBuilder : IVRCSdkControlPanelBuilder { protected VRCSdkControlPanel _builder; private VRC_AvatarDescriptor[] _avatars; private static VRC_AvatarDescriptor _selectedAvatar; private Vector2 _avatarListScrollPos; private Vector2 _scrollPos; protected const int MAX_ACTION_TEXTURE_SIZE = 256; private bool showAvatarPerformanceDetails { get => EditorPrefs.GetBool("VRC.SDKBase_showAvatarPerformanceDetails", false); set => EditorPrefs.SetBool("VRC.SDKBase_showAvatarPerformanceDetails", value); //Do we ever actually set this? } private static PropertyInfo _legacyBlendShapeNormalsPropertyInfo; private static PropertyInfo LegacyBlendShapeNormalsPropertyInfo { get { if (_legacyBlendShapeNormalsPropertyInfo != null) { return _legacyBlendShapeNormalsPropertyInfo; } Type modelImporterType = typeof(ModelImporter); _legacyBlendShapeNormalsPropertyInfo = modelImporterType.GetProperty( "legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public ); return _legacyBlendShapeNormalsPropertyInfo; } } public void ShowSettingsOptions() { EditorGUILayout.BeginVertical(VRCSdkControlPanel.boxGuiStyle); GUILayout.Label("Avatar Options", EditorStyles.boldLabel); bool prevShowPerfDetails = showAvatarPerformanceDetails; bool showPerfDetails = EditorGUILayout.ToggleLeft("Show All Avatar Performance Details", prevShowPerfDetails); if (showPerfDetails != prevShowPerfDetails) { showAvatarPerformanceDetails = showPerfDetails; _builder.ResetIssues(); } EditorGUILayout.EndVertical(); } public bool IsValidBuilder(out string message) { FindAvatars(); message = null; if (_avatars != null && _avatars.Length > 0) return true; #if VRC_SDK_VRCSDK2 message = "A VRC_SceneDescriptor or VRC_AvatarDescriptor\nis required to build VRChat SDK Content"; #elif VRC_SDK_VRCSDK3 message = "A VRCSceneDescriptor or VRCAvatarDescriptor\nis required to build VRChat SDK Content"; #endif return false; } public virtual void ShowBuilder() { if (_avatars.Length > 0) { if (!_builder.CheckedForIssues) { _builder.ResetIssues(); foreach (VRC_AvatarDescriptor t in _avatars) OnGUIAvatarCheck(t); _builder.CheckedForIssues = true; } bool drawList = true; if (_avatars.Length == 1) { drawList = false; _selectedAvatar = _avatars[0]; } if (drawList) { EditorGUILayout.BeginVertical(GUI.skin.GetStyle("HelpBox"), GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth), GUILayout.MaxHeight(150)); _avatarListScrollPos = EditorGUILayout.BeginScrollView(_avatarListScrollPos, false, false); for (int i = 0; i < _avatars.Length; ++i) { VRC_AvatarDescriptor av = _avatars[i]; EditorGUILayout.Space(); if (_selectedAvatar == av) { if (GUILayout.Button(av.gameObject.name, VRCSdkControlPanel.listButtonStyleSelected, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth - 50))) _selectedAvatar = null; } else { if (GUILayout.Button(av.gameObject.name, ((i & 0x01) > 0) ? (VRCSdkControlPanel.listButtonStyleOdd) : (VRCSdkControlPanel.listButtonStyleEven), GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth - 50))) _selectedAvatar = av; } } EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); } EditorGUILayout.BeginVertical(GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth)); _builder.OnGUIShowIssues(); EditorGUILayout.EndVertical(); EditorGUILayout.Separator(); if (_selectedAvatar != null) { EditorGUILayout.BeginVertical(VRCSdkControlPanel.boxGuiStyle); OnGUIAvatarSettings(_selectedAvatar); EditorGUILayout.EndVertical(); _scrollPos = EditorGUILayout.BeginScrollView(_scrollPos, false, false, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth)); _builder.OnGUIShowIssues(_selectedAvatar); EditorGUILayout.EndScrollView(); GUILayout.FlexibleSpace(); OnGUIAvatar(_selectedAvatar); } } else { EditorGUILayout.Space(); if (UnityEditor.BuildPipeline.isBuildingPlayer) { EditorGUILayout.Space(); EditorGUILayout.LabelField("Building – Please Wait ...", VRCSdkControlPanel.titleGuiStyle, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth)); } else { #if VRC_SDK_VRCSDK2 EditorGUILayout.LabelField( "A VRC_SceneDescriptor or VRC_AvatarDescriptor\nis required to build VRChat SDK Content", VRCSdkControlPanel.titleGuiStyle, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth)); #elif VRC_SDK_VRCSDK3 EditorGUILayout.LabelField( "A VRCSceneDescriptor or VRCAvatarDescriptor\nis required to build VRChat SDK Content", VRCSdkControlPanel.titleGuiStyle, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth)); #else EditorGUILayout.LabelField("A SceneDescriptor or AvatarDescriptor\nis required to build VRChat SDK Content", VRCSdkControlPanel.titleGuiStyle, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth)); #endif } } } public void RegisterBuilder(VRCSdkControlPanel baseBuilder) { _builder = baseBuilder; } public void SelectAllComponents() { List<Object> show = new List<Object>(Selection.objects); foreach (VRC_AvatarDescriptor a in _avatars) show.Add(a.gameObject); Selection.objects = show.ToArray(); } private void FindAvatars() { List<VRC_AvatarDescriptor> allAvatars = Tools.FindSceneObjectsOfTypeAll<VRC_AvatarDescriptor>().ToList(); // Select only the active avatars VRC_AvatarDescriptor[] newAvatars = allAvatars.Where(av => null != av && av.gameObject.activeInHierarchy).ToArray(); if (_avatars != null) { foreach (VRC_AvatarDescriptor a in newAvatars) if (_avatars.Contains(a) == false) _builder.CheckedForIssues = false; } _avatars = newAvatars; } public virtual void OnGUIAvatarCheck(VRC_AvatarDescriptor avatar) { string vrcFilePath = UnityWebRequest.UnEscapeURL(EditorPrefs.GetString("currentBuildingAssetBundlePath")); if (!string.IsNullOrEmpty(vrcFilePath) && ValidationHelpers.CheckIfAssetBundleFileTooLarge(ContentType.Avatar, vrcFilePath, out int fileSize)) { _builder.OnGUIWarning(avatar, ValidationHelpers.GetAssetBundleOverSizeLimitMessageSDKWarning(ContentType.Avatar, fileSize), delegate { Selection.activeObject = avatar.gameObject; }, null); } AvatarPerformanceStats perfStats = new AvatarPerformanceStats(); AvatarPerformance.CalculatePerformanceStats(avatar.Name, avatar.gameObject, perfStats); OnGUIPerformanceInfo(avatar, perfStats, AvatarPerformanceCategory.Overall, GetAvatarSubSelectAction(avatar, typeof(VRC_AvatarDescriptor)), null); OnGUIPerformanceInfo(avatar, perfStats, AvatarPerformanceCategory.PolyCount, GetAvatarSubSelectAction(avatar, new[] {typeof(MeshRenderer), typeof(SkinnedMeshRenderer)}), null); OnGUIPerformanceInfo(avatar, perfStats, AvatarPerformanceCategory.AABB, GetAvatarSubSelectAction(avatar, typeof(VRC_AvatarDescriptor)), null); if (avatar.lipSync == VRC_AvatarDescriptor.LipSyncStyle.VisemeBlendShape && avatar.VisemeSkinnedMesh == null) _builder.OnGUIError(avatar, "This avatar uses Visemes but the Face Mesh is not specified.", delegate { Selection.activeObject = avatar.gameObject; }, null); if (ShaderKeywordsUtility.DetectCustomShaderKeywords(avatar)) _builder.OnGUIWarning(avatar, "A Material on this avatar has custom shader keywords. Please consider optimizing it using the Shader Keywords Utility.", () => { Selection.activeObject = avatar.gameObject; }, () => { EditorApplication.ExecuteMenuItem("VRChat SDK/Utilities/Avatar Shader Keywords Utility"); }); VerifyAvatarMipMapStreaming(avatar); Animator anim = avatar.GetComponent<Animator>(); if (anim == null) { _builder.OnGUIWarning(avatar, "This avatar does not contain an Animator, and will not animate in VRChat.", delegate { Selection.activeObject = avatar.gameObject; }, null); } else if (anim.isHuman == false) { _builder.OnGUIWarning(avatar, "This avatar is not imported as a humanoid rig and will not play VRChat's provided animation set.", delegate { Selection.activeObject = avatar.gameObject; }, null); } else if (avatar.gameObject.activeInHierarchy == false) { _builder.OnGUIError(avatar, "Your avatar is disabled in the scene hierarchy!", delegate { Selection.activeObject = avatar.gameObject; }, null); } else { Transform lFoot = anim.GetBoneTransform(HumanBodyBones.LeftFoot); Transform rFoot = anim.GetBoneTransform(HumanBodyBones.RightFoot); if ((lFoot == null) || (rFoot == null)) _builder.OnGUIError(avatar, "Your avatar is humanoid, but its feet aren't specified!", delegate { Selection.activeObject = avatar.gameObject; }, null); if (lFoot != null && rFoot != null) { Vector3 footPos = lFoot.position - avatar.transform.position; if (footPos.y < 0) _builder.OnGUIWarning(avatar, "Avatar feet are beneath the avatar's origin (the floor). That's probably not what you want.", delegate { List<Object> gos = new List<Object> {rFoot.gameObject, lFoot.gameObject}; Selection.objects = gos.ToArray(); }, null); } Transform lShoulder = anim.GetBoneTransform(HumanBodyBones.LeftUpperArm); Transform rShoulder = anim.GetBoneTransform(HumanBodyBones.RightUpperArm); if (lShoulder == null || rShoulder == null) _builder.OnGUIError(avatar, "Your avatar is humanoid, but its upper arms aren't specified!", delegate { Selection.activeObject = avatar.gameObject; }, null); if (lShoulder != null && rShoulder != null) { Vector3 shoulderPosition = lShoulder.position - avatar.transform.position; if (shoulderPosition.y < 0.2f) _builder.OnGUIError(avatar, "This avatar is too short. The minimum is 20cm shoulder height.", delegate { Selection.activeObject = avatar.gameObject; }, null); else if (shoulderPosition.y < 1.0f) _builder.OnGUIWarning(avatar, "This avatar is short. This is probably shorter than you want.", delegate { Selection.activeObject = avatar.gameObject; }, null); else if (shoulderPosition.y > 5.0f) _builder.OnGUIWarning(avatar, "This avatar is too tall. The maximum is 5m shoulder height.", delegate { Selection.activeObject = avatar.gameObject; }, null); else if (shoulderPosition.y > 2.5f) _builder.OnGUIWarning(avatar, "This avatar is tall. This is probably taller than you want.", delegate { Selection.activeObject = avatar.gameObject; }, null); } if (AnalyzeIK(avatar, anim) == false) _builder.OnGUILink(avatar, "See Avatar Rig Requirements for more information.", VRCSdkControlPanel.AVATAR_RIG_REQUIREMENTS_URL); } ValidateFeatures(avatar, anim, perfStats); } public virtual void ValidateFeatures(VRC_AvatarDescriptor avatar, Animator anim, AvatarPerformanceStats perfStats) { // stub, used in SDK3A for Expression Menu, etc. } protected void OnGUIPerformanceInfo(VRC_AvatarDescriptor avatar, AvatarPerformanceStats perfStats, AvatarPerformanceCategory perfCategory, Action show, Action fix) { PerformanceRating rating = perfStats.GetPerformanceRatingForCategory(perfCategory); SDKPerformanceDisplay.GetSDKPerformanceInfoText(perfStats, perfCategory, out string text, out PerformanceInfoDisplayLevel displayLevel); switch (displayLevel) { case PerformanceInfoDisplayLevel.None: { break; } case PerformanceInfoDisplayLevel.Verbose: { if (showAvatarPerformanceDetails) { _builder.OnGUIStat(avatar, text, rating, show, fix); } break; } case PerformanceInfoDisplayLevel.Info: { _builder.OnGUIStat(avatar, text, rating, show, fix); break; } case PerformanceInfoDisplayLevel.Warning: { _builder.OnGUIStat(avatar, text, rating, show, fix); break; } case PerformanceInfoDisplayLevel.Error: { _builder.OnGUIStat(avatar, text, rating, show, fix); _builder.OnGUIError(avatar, text, delegate { Selection.activeObject = avatar.gameObject; }, null); break; } default: { _builder.OnGUIError(avatar, "Unknown performance display level.", delegate { Selection.activeObject = avatar.gameObject; }, null); break; } } } public virtual void OnGUIAvatar(VRC_AvatarDescriptor avatar) { EditorGUILayout.BeginVertical(VRCSdkControlPanel.boxGuiStyle); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(GUILayout.Width(300)); EditorGUILayout.Space(); GUILayout.Label("Online Publishing", VRCSdkControlPanel.infoGuiStyle); GUILayout.Label( "In order for other people to see your avatar in VRChat it must be built and published to our game servers.", VRCSdkControlPanel.infoGuiStyle); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUILayout.Width(200)); EditorGUILayout.Space(); GUI.enabled = _builder.NoGuiErrorsOrIssues() || Core.APIUser.CurrentUser.developerType == Core.APIUser.DeveloperType.Internal; if (GUILayout.Button(VRCSdkControlPanel.GetBuildAndPublishButtonString())) { bool buildBlocked = !VRCBuildPipelineCallbacks.OnVRCSDKBuildRequested(VRCSDKRequestedBuildType.Avatar); if (!buildBlocked) { if (Core.APIUser.CurrentUser.canPublishAvatars) { EnvConfig.FogSettings originalFogSettings = EnvConfig.GetFogSettings(); EnvConfig.SetFogSettings( new EnvConfig.FogSettings(EnvConfig.FogSettings.FogStrippingMode.Custom, true, true, true)); #if UNITY_ANDROID EditorPrefs.SetBool("VRC.SDKBase_StripAllShaders", true); #else EditorPrefs.SetBool("VRC.SDKBase_StripAllShaders", false); #endif #if VRC_SDK_VRCSDK2 VRC_SdkBuilder.shouldBuildUnityPackage = VRCSdkControlPanel.FutureProofPublishEnabled; VRC_SdkBuilder.ExportAndUploadAvatarBlueprint(avatar.gameObject); #endif EnvConfig.SetFogSettings(originalFogSettings); // this seems to workaround a Unity bug that is clearing the formatting of two levels of Layout // when we call the upload functions return; } else { VRCSdkControlPanel.ShowContentPublishPermissionsDialog(); } } } EditorGUILayout.EndVertical(); EditorGUILayout.Space(); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); GUI.enabled = true; } private static void OnGUIAvatarSettings(VRC_AvatarDescriptor avatar) { EditorGUILayout.BeginVertical(VRCSdkControlPanel.boxGuiStyle, GUILayout.Width(VRCSdkControlPanel.SdkWindowWidth)); string name = "Unpublished Avatar - " + avatar.gameObject.name; if (avatar.apiAvatar != null) name = (avatar.apiAvatar as Core.ApiAvatar)?.name; EditorGUILayout.Space(); EditorGUILayout.LabelField(name, VRCSdkControlPanel.titleGuiStyle); Core.PipelineManager pm = avatar.GetComponent<Core.PipelineManager>(); if (pm != null && !string.IsNullOrEmpty(pm.blueprintId)) { if (avatar.apiAvatar == null) { Core.ApiAvatar av = Core.API.FromCacheOrNew<Core.ApiAvatar>(pm.blueprintId); av.Fetch( c => avatar.apiAvatar = c.Model as Core.ApiAvatar, c => { if (c.Code == 404) { Core.Logger.Log( $"Could not load avatar {pm.blueprintId} because it didn't exist.", Core.DebugLevel.API); Core.ApiCache.Invalidate<Core.ApiWorld>(pm.blueprintId); } else Debug.LogErrorFormat("Could not load avatar {0} because {1}", pm.blueprintId, c.Error); }); avatar.apiAvatar = av; } } if (avatar.apiAvatar != null) { Core.ApiAvatar a = (avatar.apiAvatar as Core.ApiAvatar); DrawContentInfoForAvatar(a); VRCSdkControlPanel.DrawContentPlatformSupport(a); } VRCSdkControlPanel.DrawBuildTargetSwitcher(); EditorGUILayout.EndVertical(); } private static void DrawContentInfoForAvatar(Core.ApiAvatar a) { VRCSdkControlPanel.DrawContentInfo(a.name, a.version.ToString(), a.description, null, a.releaseStatus, a.tags); } protected static Action GetAvatarSubSelectAction(Component avatar, Type[] types) { return () => { List<Object> gos = new List<Object>(); foreach (Type t in types) { Component[] components = avatar.GetComponentsInChildren(t, true); foreach (Component c in components) gos.Add(c.gameObject); } Selection.objects = gos.Count > 0 ? gos.ToArray() : new Object[] {avatar.gameObject}; }; } protected static Action GetAvatarSubSelectAction(Component avatar, Type type) { List<Type> t = new List<Type> {type}; return GetAvatarSubSelectAction(avatar, t.ToArray()); } private void VerifyAvatarMipMapStreaming(Component avatar) { List<Object> badTextures = new List<Object>(); foreach (Renderer r in avatar.GetComponentsInChildren<Renderer>(true)) { foreach (Material m in r.sharedMaterials) { if (!m) continue; int[] texIDs = m.GetTexturePropertyNameIDs(); if (texIDs == null) continue; foreach (int i in texIDs) { Texture t = m.GetTexture(i); if (!t) continue; string path = AssetDatabase.GetAssetPath(t); if (string.IsNullOrEmpty(path)) continue; TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter; if (importer != null && importer.mipmapEnabled && !importer.streamingMipmaps) badTextures.Add(importer); } } } if (badTextures.Count == 0) return; _builder.OnGUIError(avatar, "This avatar has mipmapped textures without 'Streaming Mip Maps' enabled.", () => { Selection.objects = badTextures.ToArray(); }, () => { List<string> paths = new List<string>(); foreach (Object o in badTextures) { TextureImporter t = (TextureImporter) o; Undo.RecordObject(t, "Set Mip Map Streaming"); t.streamingMipmaps = true; t.streamingMipmapsPriority = 0; EditorUtility.SetDirty(t); paths.Add(t.assetPath); } AssetDatabase.ForceReserializeAssets(paths); AssetDatabase.Refresh(); }); } private bool AnalyzeIK(Object ad, Animator anim) { bool hasHead; bool hasFeet; bool hasHands; bool hasThreeFingers; bool correctSpineHierarchy; bool correctLeftArmHierarchy; bool correctRightArmHierarchy; bool correctLeftLegHierarchy; bool correctRightLegHierarchy; bool status = true; Transform head = anim.GetBoneTransform(HumanBodyBones.Head); Transform lFoot = anim.GetBoneTransform(HumanBodyBones.LeftFoot); Transform rFoot = anim.GetBoneTransform(HumanBodyBones.RightFoot); Transform lHand = anim.GetBoneTransform(HumanBodyBones.LeftHand); Transform rHand = anim.GetBoneTransform(HumanBodyBones.RightHand); hasHead = null != head; hasFeet = (null != lFoot && null != rFoot); hasHands = (null != lHand && null != rHand); if (!hasHead || !hasFeet || !hasHands) { _builder.OnGUIError(ad, "Humanoid avatar must have head, hands and feet bones mapped.", delegate { Selection.activeObject = anim.gameObject; }, null); return false; } Transform lThumb = anim.GetBoneTransform(HumanBodyBones.LeftThumbProximal); Transform lIndex = anim.GetBoneTransform(HumanBodyBones.LeftIndexProximal); Transform lMiddle = anim.GetBoneTransform(HumanBodyBones.LeftMiddleProximal); Transform rThumb = anim.GetBoneTransform(HumanBodyBones.RightThumbProximal); Transform rIndex = anim.GetBoneTransform(HumanBodyBones.RightIndexProximal); Transform rMiddle = anim.GetBoneTransform(HumanBodyBones.RightMiddleProximal); #if VRC_SDK_VRCSDK2 // Finger test, only for v2 hasThreeFingers = null != lThumb && null != lIndex && null != lMiddle && null != rThumb && null != rIndex && null != rMiddle; if (!hasThreeFingers) { // although its only a warning, we return here because the rest // of the analysis is for VR IK _builder.OnGUIWarning(ad, "Thumb, Index, and Middle finger bones are not mapped, Full-Body IK will be disabled.", delegate { Selection.activeObject = anim.gameObject; }, null); status = false; } #endif Transform pelvis = anim.GetBoneTransform(HumanBodyBones.Hips); Transform chest = anim.GetBoneTransform(HumanBodyBones.Chest); Transform upperChest = anim.GetBoneTransform(HumanBodyBones.UpperChest); Transform torso = anim.GetBoneTransform(HumanBodyBones.Spine); Transform neck = anim.GetBoneTransform(HumanBodyBones.Neck); Transform lClav = anim.GetBoneTransform(HumanBodyBones.LeftShoulder); Transform rClav = anim.GetBoneTransform(HumanBodyBones.RightShoulder); if (null == neck || null == lClav || null == rClav || null == pelvis || null == torso || null == chest) { string missingElements = ((null == neck) ? "Neck, " : "") + (((null == lClav) || (null == rClav)) ? "Shoulders, " : "") + ((null == pelvis) ? "Pelvis, " : "") + ((null == torso) ? "Spine, " : "") + ((null == chest) ? "Chest, " : ""); missingElements = missingElements.Remove(missingElements.LastIndexOf(',')) + "."; _builder.OnGUIError(ad, "Spine hierarchy missing elements, please map: " + missingElements, delegate { Selection.activeObject = anim.gameObject; }, null); return false; } if (null != upperChest) correctSpineHierarchy = lClav.parent == upperChest && rClav.parent == upperChest && neck.parent == upperChest; else correctSpineHierarchy = lClav.parent == chest && rClav.parent == chest && neck.parent == chest; if (!correctSpineHierarchy) { _builder.OnGUIError(ad, "Spine hierarchy incorrect. Make sure that the parent of both Shoulders and the Neck is the Chest (or UpperChest if set).", delegate { List<Object> gos = new List<Object> { lClav.gameObject, rClav.gameObject, neck.gameObject, null != upperChest ? upperChest.gameObject : chest.gameObject }; Selection.objects = gos.ToArray(); }, null); return false; } Transform lShoulder = anim.GetBoneTransform(HumanBodyBones.LeftUpperArm); Transform lElbow = anim.GetBoneTransform(HumanBodyBones.LeftLowerArm); Transform rShoulder = anim.GetBoneTransform(HumanBodyBones.RightUpperArm); Transform rElbow = anim.GetBoneTransform(HumanBodyBones.RightLowerArm); correctLeftArmHierarchy = lShoulder && lElbow && lShoulder.GetChild(0) == lElbow && lHand && lElbow.GetChild(0) == lHand; correctRightArmHierarchy = rShoulder && rElbow && rShoulder.GetChild(0) == rElbow && rHand && rElbow.GetChild(0) == rHand; if (!(correctLeftArmHierarchy && correctRightArmHierarchy)) { _builder.OnGUIWarning(ad, "LowerArm is not first child of UpperArm or Hand is not first child of LowerArm: you may have problems with Forearm rotations.", delegate { List<Object> gos = new List<Object>(); if (!correctLeftArmHierarchy && lShoulder) gos.Add(lShoulder.gameObject); if (!correctRightArmHierarchy && rShoulder) gos.Add(rShoulder.gameObject); if (gos.Count > 0) Selection.objects = gos.ToArray(); else Selection.activeObject = anim.gameObject; }, null); status = false; } Transform lHip = anim.GetBoneTransform(HumanBodyBones.LeftUpperLeg); Transform lKnee = anim.GetBoneTransform(HumanBodyBones.LeftLowerLeg); Transform rHip = anim.GetBoneTransform(HumanBodyBones.RightUpperLeg); Transform rKnee = anim.GetBoneTransform(HumanBodyBones.RightLowerLeg); correctLeftLegHierarchy = lHip && lKnee && lHip.GetChild(0) == lKnee && lKnee.GetChild(0) == lFoot; correctRightLegHierarchy = rHip && rKnee && rHip.GetChild(0) == rKnee && rKnee.GetChild(0) == rFoot; if (!(correctLeftLegHierarchy && correctRightLegHierarchy)) { _builder.OnGUIWarning(ad, "LowerLeg is not first child of UpperLeg or Foot is not first child of LowerLeg: you may have problems with Shin rotations.", delegate { List<Object> gos = new List<Object>(); if (!correctLeftLegHierarchy && lHip) gos.Add(lHip.gameObject); if (!correctRightLegHierarchy && rHip) gos.Add(rHip.gameObject); if (gos.Count > 0) Selection.objects = gos.ToArray(); else Selection.activeObject = anim.gameObject; }, null); status = false; } if (!(IsAncestor(pelvis, rFoot) && IsAncestor(pelvis, lFoot) && IsAncestor(pelvis, lHand) && IsAncestor(pelvis, rHand))) { _builder.OnGUIWarning(ad, "This avatar has a split hierarchy (Hips bone is not the ancestor of all humanoid bones). IK may not work correctly.", delegate { List<Object> gos = new List<Object> {pelvis.gameObject}; if (!IsAncestor(pelvis, rFoot)) gos.Add(rFoot.gameObject); if (!IsAncestor(pelvis, lFoot)) gos.Add(lFoot.gameObject); if (!IsAncestor(pelvis, lHand)) gos.Add(lHand.gameObject); if (!IsAncestor(pelvis, rHand)) gos.Add(rHand.gameObject); Selection.objects = gos.ToArray(); }, null); status = false; } // if thigh bone rotations diverge from 180 from hip bone rotations, full-body tracking/ik does not work well if (!lHip || !rHip) return status; { Vector3 hipLocalUp = pelvis.InverseTransformVector(Vector3.up); Vector3 legLDir = lHip.TransformVector(hipLocalUp); Vector3 legRDir = rHip.TransformVector(hipLocalUp); float angL = Vector3.Angle(Vector3.up, legLDir); float angR = Vector3.Angle(Vector3.up, legRDir); if (!(angL < 175f) && !(angR < 175f)) return status; string angle = $"{Mathf.Min(angL, angR):F1}"; _builder.OnGUIWarning(ad, $"The angle between pelvis and thigh bones should be close to 180 degrees (this avatar's angle is {angle}). Your avatar may not work well with full-body IK and Tracking.", delegate { List<Object> gos = new List<Object>(); if (angL < 175f) gos.Add(rFoot.gameObject); if (angR < 175f) gos.Add(lFoot.gameObject); Selection.objects = gos.ToArray(); }, null); status = false; } return status; } private static bool IsAncestor(Object ancestor, Transform child) { bool found = false; Transform thisParent = child.parent; while (thisParent != null) { if (thisParent == ancestor) { found = true; break; } thisParent = thisParent.parent; } return found; } protected void CheckAvatarMeshesForLegacyBlendShapesSetting(Component avatar) { if (LegacyBlendShapeNormalsPropertyInfo == null) { Debug.LogError( "Could not check for legacy blend shape normals because 'legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes' was not found."); return; } // Get all of the meshes used by skinned mesh renderers. HashSet<Mesh> avatarSkinnedMeshes = GetAllMeshesInGameObjectHierarchy(avatar.gameObject); HashSet<Mesh> incorrectlyConfiguredMeshes = ScanMeshesForIncorrectBlendShapeNormalsSetting(avatarSkinnedMeshes); if (incorrectlyConfiguredMeshes.Count > 0) { _builder.OnGUIError( avatar, "This avatar contains skinned meshes that were imported with Blendshape Normals set to 'Calculate' but aren't using 'Legacy Blendshape Normals'. This will significantly increase the size of the uploaded avatar. This must be fixed in the mesh import settings before uploading.", null, () => { EnableLegacyBlendShapeNormals(incorrectlyConfiguredMeshes); }); } } private static HashSet<Mesh> ScanMeshesForIncorrectBlendShapeNormalsSetting(IEnumerable<Mesh> avatarMeshes) { HashSet<Mesh> incorrectlyConfiguredMeshes = new HashSet<Mesh>(); foreach (Mesh avatarMesh in avatarMeshes) { // Can't get ModelImporter if the model isn't an asset. if (!AssetDatabase.Contains(avatarMesh)) { continue; } string meshAssetPath = AssetDatabase.GetAssetPath(avatarMesh); if (string.IsNullOrEmpty(meshAssetPath)) { continue; } ModelImporter avatarImporter = AssetImporter.GetAtPath(meshAssetPath) as ModelImporter; if (avatarImporter == null) { continue; } if (avatarImporter.importBlendShapeNormals != ModelImporterNormals.Calculate) { continue; } bool useLegacyBlendShapeNormals = (bool) LegacyBlendShapeNormalsPropertyInfo.GetValue(avatarImporter); if (useLegacyBlendShapeNormals) { continue; } if (!incorrectlyConfiguredMeshes.Contains(avatarMesh)) { incorrectlyConfiguredMeshes.Add(avatarMesh); } } return incorrectlyConfiguredMeshes; } private static HashSet<Mesh> GetAllMeshesInGameObjectHierarchy(GameObject avatar) { HashSet<Mesh> avatarMeshes = new HashSet<Mesh>(); foreach (SkinnedMeshRenderer avatarSkinnedMeshRenderer in avatar .GetComponentsInChildren<SkinnedMeshRenderer>(true)) { if (avatarSkinnedMeshRenderer == null) { continue; } Mesh skinnedMesh = avatarSkinnedMeshRenderer.sharedMesh; if (skinnedMesh == null) { continue; } if (avatarMeshes.Contains(skinnedMesh)) { continue; } avatarMeshes.Add(skinnedMesh); } foreach (MeshFilter avatarMeshFilter in avatar.GetComponentsInChildren<MeshFilter>(true)) { if (avatarMeshFilter == null) { continue; } Mesh skinnedMesh = avatarMeshFilter.sharedMesh; if (skinnedMesh == null) { continue; } if (avatarMeshes.Contains(skinnedMesh)) { continue; } avatarMeshes.Add(skinnedMesh); } foreach (ParticleSystemRenderer avatarParticleSystemRenderer in avatar .GetComponentsInChildren<ParticleSystemRenderer>(true)) { if (avatarParticleSystemRenderer == null) { continue; } Mesh[] avatarParticleSystemRendererMeshes = new Mesh[avatarParticleSystemRenderer.meshCount]; avatarParticleSystemRenderer.GetMeshes(avatarParticleSystemRendererMeshes); foreach (Mesh avatarParticleSystemRendererMesh in avatarParticleSystemRendererMeshes) { if (avatarParticleSystemRendererMesh == null) { continue; } if (avatarMeshes.Contains(avatarParticleSystemRendererMesh)) { continue; } avatarMeshes.Add(avatarParticleSystemRendererMesh); } } return avatarMeshes; } private static void EnableLegacyBlendShapeNormals(IEnumerable<Mesh> meshesToFix) { HashSet<string> meshAssetPaths = new HashSet<string>(); foreach (Mesh meshToFix in meshesToFix) { // Can't get ModelImporter if the model isn't an asset. if (!AssetDatabase.Contains(meshToFix)) { continue; } string meshAssetPath = AssetDatabase.GetAssetPath(meshToFix); if (string.IsNullOrEmpty(meshAssetPath)) { continue; } if (meshAssetPaths.Contains(meshAssetPath)) { continue; } meshAssetPaths.Add(meshAssetPath); } foreach (string meshAssetPath in meshAssetPaths) { ModelImporter avatarImporter = AssetImporter.GetAtPath(meshAssetPath) as ModelImporter; if (avatarImporter == null) { continue; } if (avatarImporter.importBlendShapeNormals != ModelImporterNormals.Calculate) { continue; } LegacyBlendShapeNormalsPropertyInfo.SetValue(avatarImporter, true); avatarImporter.SaveAndReimport(); } } protected void OpenAnimatorControllerWindow(object animatorController) { Assembly asm = Assembly.Load("UnityEditor.Graphs"); Module editorGraphModule = asm.GetModule("UnityEditor.Graphs.dll"); Type animatorWindowType = editorGraphModule.GetType("UnityEditor.Graphs.AnimatorControllerTool"); EditorWindow animatorWindow = EditorWindow.GetWindow(animatorWindowType, false, "Animator", false); PropertyInfo propInfo = animatorWindowType.GetProperty("animatorController"); if (propInfo != null) propInfo.SetValue(animatorWindow, animatorController, null); } protected static void ShowRestrictedComponents(IEnumerable<Component> componentsToRemove) { List<Object> gos = new List<Object>(); foreach (Component c in componentsToRemove) gos.Add(c.gameObject); Selection.objects = gos.ToArray(); } protected static void FixRestrictedComponents(IEnumerable<Component> componentsToRemove) { if (!(componentsToRemove is List<Component> list)) return; for (int v = list.Count - 1; v > -1; v--) { Object.DestroyImmediate(list[v]); } } public static void SelectAvatar(VRC_AvatarDescriptor avatar) { if (VRCSdkControlPanel.window != null) _selectedAvatar = avatar; } List<Transform> FindBonesBetween(Transform top, Transform bottom) { List<Transform> list = new List<Transform>(); if (top == null || bottom == null) return list; Transform bt = top.parent; while (bt != bottom && bt != null) { list.Add(bt); bt = bt.parent; } return list; } } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Yandex.Dialogs.Models.Cards { [JsonConverter(typeof(StringEnumConverter))] public enum CardType { BigImage, ItemsList } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Numerics; namespace HackerrankSolutionConsole { class fibonacci_modified : Challenge { public override void Main(string[] args) { String elements = Console.ReadLine(); String[] split_elements = elements.Split(' '); int a = Convert.ToInt32(split_elements[0]); int b = Convert.ToInt32(split_elements[1]); int n = Convert.ToInt32(split_elements[2]); BigInteger b1 = new BigInteger(b); BigInteger a1 = new BigInteger(a); for (int i = 3; i < n + 1; i++) { BigInteger temp = BigInteger.Pow(b1, 2) + a1; a1 = b1; b1 = temp; } var ans = new List<BigInteger>(); var p10 = BigInteger.Pow(10, 100); while (b1 != 0) { ans.Add(b1 % p10); b1 /= p10; } Console.Write(ans[ans.Count - 1]); var fmt = new string('0', 100); for (var i = ans.Count - 2; i >= 0; i--) { var str = ans[i].ToString(); Console.Write("{0}{1}", fmt.Substring(0, 100 - str.Length), str); } Console.WriteLine(); } public fibonacci_modified() { Name = "Fibonacci Modified"; Path = "fibonacci-modified"; Difficulty = Difficulty.Medium; Domain = Domain.Algorithms; Subdomain = Subdomain.DynamicProg; } } }
using GameLib; using Microsoft.Xna.Framework; using MonoGameUi; namespace JumpAndRun.ClientBase.GUI.Screens { class MainMenuScreen : Screen { public MainMenuScreen(BaseScreenComponent manager, BaseGame baseGame, GraphicsDeviceManager graphicsManager) : base(manager) { Background = new BorderBrush(Color.DarkGreen); var stack = new StackPanel(manager); Controls.Add(stack); var gameTitle = new Label(manager) { Text = ContentManager.Instance.Translation["JumpAndRun.App.Title"] }; stack.Controls.Add(gameTitle); var debugGameButton = Button.TextButton(manager, ContentManager.Instance.Translation["JumpAndRun.Client.Menu.DebugExternal"]); debugGameButton.LeftMouseClick += (s, e) => StartExternalGame(baseGame, graphicsManager); debugGameButton.TouchDown += (s, e) => StartExternalGame(baseGame, graphicsManager); debugGameButton.Height = 100; debugGameButton.Width = 500; stack.Controls.Add(debugGameButton); var debugWithServerGameButton = Button.TextButton(manager, ContentManager.Instance.Translation["JumpAndRun.Client.Menu.DebugInternal"]); debugWithServerGameButton.LeftMouseClick += (s, e) => StartInternalGame(baseGame, graphicsManager); debugWithServerGameButton.TouchDown += (s, e) => StartInternalGame(baseGame, graphicsManager); debugWithServerGameButton.Height = 100; debugWithServerGameButton.Width = 500; stack.Controls.Add(debugWithServerGameButton); var exitButton = Button.TextButton(manager, ContentManager.Instance.Translation["JumpAndRun.Client.Menu.Exit"]); exitButton.LeftMouseClick += (s, e) => ExitGame(); exitButton.TouchDown += (s, e) => ExitGame(); exitButton.Height = 100; exitButton.Width = 500; stack.Controls.Add(exitButton); } private void ExitGame() { Manager.Game.Exit(); } private void StartExternalGame(BaseGame baseGame, GraphicsDeviceManager graphicsManager) { GameContext.Instance.GameMode = "JumpAndRun.NoServer"; Manager.NavigateToScreen(new GameScreen(Manager, baseGame, graphicsManager)); } private void StartInternalGame(BaseGame baseGame, GraphicsDeviceManager graphicsManager) { GameContext.Instance.GameMode = "JumpAndRun.Server"; Manager.NavigateToScreen(new GameScreen(Manager, baseGame, graphicsManager)); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.WebJobs.Logging.ApplicationInsights; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Configuration; namespace Microsoft.Extensions.Logging { /// <summary> /// Extensions for ApplicationInsights configuration on an <see cref="ILoggingBuilder"/>. /// </summary> public static class ApplicationInsightsLoggingBuilderExtensions { [Obsolete("Use " + nameof(AddApplicationInsightsWebJobs) + " instead.", false)] public static ILoggingBuilder AddApplicationInsights( this ILoggingBuilder builder) { return AddApplicationInsightsWebJobs(builder); } [Obsolete("Use " + nameof(AddApplicationInsightsWebJobs) + " instead.", false)] public static ILoggingBuilder AddApplicationInsights( this ILoggingBuilder builder, Action<ApplicationInsightsLoggerOptions> configure) { return AddApplicationInsightsWebJobs(builder, configure); } /// <summary> /// Registers Application Insights and <see cref="ApplicationInsightsLoggerProvider"/> with an <see cref="ILoggingBuilder"/>. /// </summary> public static ILoggingBuilder AddApplicationInsightsWebJobs( this ILoggingBuilder builder) { return builder.AddApplicationInsightsWebJobs(null); } /// <summary> /// Registers Application Insights and <see cref="ApplicationInsightsLoggerProvider"/> with an <see cref="ILoggingBuilder"/>. /// </summary> public static ILoggingBuilder AddApplicationInsightsWebJobs( this ILoggingBuilder builder, Action<ApplicationInsightsLoggerOptions> configure) { builder.AddConfiguration(); builder.Services.AddApplicationInsights(configure); builder.Services.PostConfigure<LoggerFilterOptions>(o => { // We want all logs to flow through the logger so they show up in QuickPulse. // To do that, we'll hide all registered rules inside of this one. They will be re-populated // and used by the FilteringTelemetryProcessor further down the pipeline. string fullTypeName = typeof(ApplicationInsightsLoggerProvider).FullName; IList<LoggerFilterRule> matchingRules = o.Rules.Where(r => { return r.ProviderName == fullTypeName || r.ProviderName == ApplicationInsightsLoggerProvider.Alias; }).ToList(); foreach (var rule in matchingRules) { o.Rules.Remove(rule); } o.Rules.Add(new ApplicationInsightsLoggerFilterRule(matchingRules)); }); return builder; } } }
using DotNetNuke.Instrumentation; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Security.Principal; using System.Text; using System.Web; namespace QLHD { /// <summary> /// The HttpModule catches any unhandled exception by IIS and passes it to Log4NET. /// </summary> /// <remarks> /// Logging can be disabled by setting 'LogUnhandledExceptions' in app.config or web.config to 'false'. Alternatively, the HttpModule /// can simply be removed. It is possible to install the module on IIS as a global managed module, so that all unhandled exceptions /// for all methods can be logged. Use the files in the \Install folder to see how. /// </remarks> public class UnhandledExceptionModule : IHttpModule { private readonly ILog logger = LoggerSource.Instance.GetLogger(typeof(UnhandledExceptionModule).FullName); private bool logUnhandeldExceptions; public void Init(HttpApplication context) { bool success = bool.TryParse(ConfigurationManager.AppSettings["LogUnhandledExceptions"], out logUnhandeldExceptions); if (!success) { logUnhandeldExceptions = true; } context.Error += new EventHandler(OnError); } public void Dispose() { } private void OnError(object sender, EventArgs e) { try { if (!logUnhandeldExceptions) { return; } string userIp; string url; string exception; HttpContext context = HttpContext.Current; if (context != null) { userIp = context.Request.UserHostAddress; url = context.Request.Url.ToString(); // get last exception, but check if it exists Exception lastException = context.Server.GetLastError(); if (lastException != null) { exception = lastException.ToString(); } else { exception = "no error"; } } else { userIp = "no httpcontext"; url = "no httpcontext"; exception = "no httpcontext"; } logger.ErrorFormat("Unhandled exception occured. UserIp [{0}]. Url [{1}]. Exception [{2}]", userIp, url, exception); } catch (Exception ex) { logger.Error("Exception occured in OnError: [{0}]", ex); } } } }
namespace DesafioPassagens.Classes { public class Passagem { public string nomePassageiro{get; set;} public string Origem{get; set;} public string Destino{get; set;} public int DiaViagem{get; set;} public int mesViagem{get; set;} public int anoViagem{get; set;} } }
using System; using System.Collections.Generic; using System.Net.Http; using Newtonsoft.Json; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Api.Enroll.Helpers; using Api.Enroll.Interfaces; using Api.Enroll.Models; namespace Api.Enroll.Services { public class EnrollService : IEnrollsService { private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger<EnrollService> _logger; private readonly ICoursesService _coursesService; private readonly IUsersService _usersService; private readonly IEnrollsRepository _enrollsRepository; public EnrollService(IHttpClientFactory httpClientFactory, ILogger<EnrollService> logger, ICoursesService coursesService, IUsersService usersService, IEnrollsRepository enrollsRepository ) { _httpClientFactory = httpClientFactory; _logger = logger; _coursesService = coursesService; _usersService = usersService; _enrollsRepository = enrollsRepository; } // Guardar enrolled(enrolleTypeID, courseID, enrolledID) -> { isSuccess, enrolled public Task<Response> AddEnrolledAsync(int EnrolledId, int CourseId, int EnrollTypeId) => _enrollsRepository.AddEnrolledAsync(EnrolledId, CourseId, EnrollTypeId); // Obtener cursos por enrrolled (tech or studen) ( enrolledID ) -> [...Courses ] public async Task<Response> GetCoursesByEnrolledIdAsync(int EnrolledId) { try { // Getting list of EnrolledId records var CoursesId = await _enrollsRepository.GetCoursesByEnrolledIdAsync(EnrolledId); if (!CoursesId.IsSuccess) return CoursesId; List<CourseModel> result = new List<CourseModel>(); foreach (var id in CoursesId.Data) { // Fetch Course by Id var course = await _coursesService.GetCourseById(id); if (course.IsSuccess) { var responseData = JsonConvert.DeserializeObject<CourseModel>(Convert.ToString(course.Data) ); result.Add(responseData); } } var IsSuccess = result.ToArray().Length > 0; return new Response() { IsSuccess = IsSuccess, Data = IsSuccess ? result : null, ErrorMessage = IsSuccess ? string.Empty : "Courses was not found" }; } catch (Exception ex) { _logger?.LogError(ex.ToString()); return (new Response() { IsSuccess = false, ErrorMessage = ex.Message }); } } // Obtener enrolled por courseId ( courseId ) -> [...Id ] public Task<Response> GetEnrolledByIdAsync(int Id) => _enrollsRepository.GetEnrolledByIdAsync(Id); // Obtener usuarios registrados en un curso ( enrolleTypeID = 1 or 2, courseID ) -> [... Student or Teacher] public async Task<Response> GetEnrolledByTypeIdAndCourseIdAsync(int EnrollTypeId, int CourseId) { try { // Getting Enrolled records var enrolledId = await _enrollsRepository.GetEnrolledByTypeIdAndCourseIdAsync(EnrollTypeId, CourseId); if (!enrolledId.IsSuccess) return enrolledId; List<UserModel> users = new List<UserModel>(); foreach (var id in enrolledId.Data) { var resultResponse = await _usersService.GetUserById(id); if (resultResponse.IsSuccess) { var responseData = JsonConvert.DeserializeObject<UserModel>(Convert.ToString(resultResponse.Data)); users.Add(responseData); } } var isSuccess = users.ToArray().Length > 0; return (new Response() { IsSuccess = isSuccess, Data = isSuccess ? users : null, ErrorMessage = isSuccess ? string.Empty : "User was not found" }); } catch (Exception ex) { _logger?.LogError(ex.ToString()); return (new Response() { IsSuccess = false, ErrorMessage = ex.Message }); } } // Remover enrolled (courseID, enrolledID) -> { isSuccess, enrolled } public Task<Response> RemoveEnrolledAsync(int EnrolledId, int CourseId) => _enrollsRepository.RemoveEnrolledAsync(EnrolledId, CourseId); } }
using System.Collections.Generic; using Xamarin.Forms; namespace MCCForms { public class GridPinTiles : Grid { public List<PinTile> PinTiles { get; set; } public GridPinTiles () { PinTiles = new List<PinTile> (); for (int i = 0; i < 5; i++) { PinTiles.Add (new PinTile ()); } ChangeAppearenceBasedOnDeviceType (); Children.Add (PinTiles[0], 0, 0); Children.Add (PinTiles[1], 1, 0); Children.Add (PinTiles[2], 2, 0); Children.Add (PinTiles[3], 3, 0); Children.Add (PinTiles[4], 4, 0); HorizontalOptions = LayoutOptions.FillAndExpand; VerticalOptions = LayoutOptions.Fill; } void ChangeAppearenceBasedOnDeviceType() { if (DeviceTypeHelper.IsPhone) { ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); RowDefinitions.Add (new RowDefinition { Height = 65}); } else if (DeviceTypeHelper.IsTablet) { ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); RowDefinitions.Add (new RowDefinition { Height = 75 }); } } public void SetColorTheme(ColorTheme appTheme) { foreach (var item in PinTiles) { item.SetColorTheme (appTheme); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BindSourse { public partial class MySuperForm : Form { private BindingList<Man> lm; private bool _updFlag; public MySuperForm() { InitializeComponent(); _updFlag = false; lm = new BindingList<Man>(); bindingsComboBox.DataSource = lm; bindingsListBox.DataSource = lm; bindingsListBox.ValueMember = "Id"; bindingsComboBox.DisplayMember = "Name"; bindingsComboBox.ValueMember = "Id"; lm.Add(new Man("Vadim", 19)); lm.Add(new Man("Vasia", 20)); lm.Add(new Man("Petia", 18)); lm.Add(new Man("Kirill", 17)); } private void addButton_Click(object sender, EventArgs e) { Man m = new Man {Name = nameTextBox.Text }; int id = 0; int.TryParse(idTextBox.Text, out id); m.Id = id; lm.Add(m); this.BindingContext[lm].Position = lm.Count; } private void buttonRemove_Click(object sender, EventArgs e) { lm.RemoveAt(this.BindingContext[lm].Position); } private void buttonUpdate_Click(object sender, EventArgs e) { if (_updFlag) { _updFlag = false; idTextBox.DataBindings.Clear(); nameTextBox.DataBindings.Clear(); idTextBox.Text = String.Empty; nameTextBox.Text = String.Empty; (sender as Button).Text = "Update"; } else { _updFlag = true; idTextBox.DataBindings.Add("Text", lm, "Id", true, DataSourceUpdateMode.OnPropertyChanged); nameTextBox.DataBindings.Add("Text", lm, "Name", true, DataSourceUpdateMode.OnPropertyChanged); (sender as Button).Text = "Apply"; } } } }
using System; using System.Collections.Generic; using System.IO; namespace Indexer2 { internal class Program { private static readonly List<string> ValidDirs = new List<string>(); private static void Main(string[] args) { var currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += unHandledExceptionHandler; string[] configDirs = { AppConfig.SourceDirectory, AppConfig.SourceDirectory2, AppConfig.SourceDirectory3, AppConfig.SourceDirectory4, AppConfig.SourceDirectory5, AppConfig.SourceDirectory6, AppConfig.SourceDirectory7, AppConfig.SourceDirectory8, AppConfig.SourceDirectory9, AppConfig.SourceDirectory10 }; foreach (var configDir in configDirs) { if (configDir == null || configDir.Trim().Length == 0) continue; Console.WriteLine("SourceDirectory configured {0}", configDir); if (Directory.Exists(configDir) && !configDir.StartsWith("@")) { ValidDirs.Add(configDir); FileSystemExtension.TestWriteability(configDir); } else throw new DirectoryNotFoundException("The configured directory does not exist " + configDir); } var alldirsResult = new FileSystemExtension.IndexedDirectoryInfo(); foreach (var validDir in ValidDirs) { var res = FileSystemExtension.IndexDirectory(validDir); alldirsResult.DirectoryIndex.Append(res.DirectoryIndex); alldirsResult.FileIndex.Append(res.FileIndex); alldirsResult.DirectoryCount += res.DirectoryCount; alldirsResult.TotalFiles += res.TotalFiles; alldirsResult.TotalBytes += res.TotalBytes; alldirsResult.Exceptions.AddRange(res.Exceptions); alldirsResult.FileCount += res.FileCount; } File.WriteAllText("files.txt", alldirsResult.FileIndex.ToString()); File.WriteAllText("dirs.txt", alldirsResult.DirectoryIndex.ToString()); Console.Write("END"); // Console.ReadLine(); } private static void unHandledExceptionHandler(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(e.ExceptionObject); File.WriteAllText("err.txt", e.ToString()); // Console.ReadLine(); Environment.Exit(1); } } } //Delete from file_data; //LOAD DATA INFILE 'C:\\Program Files\\iisnode\\www\\FileSearch\\src\\Indexer2\\bin\\Release\\DEVSVR-019156_IDX00003942.txt' INTO TABLE file_data //fields terminated by '|' //(touch_date,machine_name,md5,oldest_date,full_path)
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class LevelMenu : MonoBehaviour { [SerializeField] string mouseHoverSoundName = "ButtonHover"; [SerializeField] string buttonPressSoundName = "ButtonPress"; AudioManager audioManager; private void Start() { audioManager = AudioManager.audioManInstance; if (audioManager == null) { Debug.LogError("No AudioManager in scene."); } } public void LoadSpaceLevel() { audioManager.PlaySound(buttonPressSoundName); SceneManager.LoadScene("SpaceShooterLevel"); } public void LoadMainLevel() { audioManager.PlaySound(buttonPressSoundName); SceneManager.LoadScene("MainLevel"); } public void LoadEnvironementShowcaseLevel() { audioManager.PlaySound(buttonPressSoundName); SceneManager.LoadScene("Forest"); } public void LoadLightingLevel() { audioManager.PlaySound(buttonPressSoundName); SceneManager.LoadScene("Lighting"); } public void OnMouseOver() { audioManager.PlaySound(mouseHoverSoundName); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BLL_DAL; using Guna.UI2.WinForms; namespace QLNHAHANG { public partial class frmNhapKho : Form { qlPhieuNhapKho_BLL_DAL qlnk = new qlPhieuNhapKho_BLL_DAL(); NguyenLieu_BLL_DAL nl = new NguyenLieu_BLL_DAL(); qlCTPhieuNhapKho_BLL_DAL ctpnk = new qlCTPhieuNhapKho_BLL_DAL(); NhanVien_BLL_DAL nVienBLL_DALL = new NhanVien_BLL_DAL(); qlNhaCungCap_BLL_DAL nCC_BLL_DAL = new qlNhaCungCap_BLL_DAL(); NHANVIEN nv; List<string> lstStringTextBox; List<Guna2TextBox> lstTextBox; string maPhieuDangChon; string tenNLDangChon; double tong; string maNLDangChon; internal void DangNhapNV(NHANVIEN nv) { this.nv = nv; BtnND.Text = nv.TENNV; } public frmNhapKho() { InitializeComponent(); } public frmNhapKho(bool show) { InitializeComponent(); } public void loadCBLoai() { cboNCC.DataSource = qlnk.loadAllNCC(); cboNCC.ValueMember = "MANCC"; cboNCC.DisplayMember = "TENNCC"; } public void databingding(int rowindex) { string mapnk = dataGridViewPhieuNhanHang.Rows[rowindex].Cells["MAPNK"].FormattedValue.ToString(); string manv = dataGridViewPhieuNhanHang.Rows[rowindex].Cells["MANV"].FormattedValue.ToString(); cboNCC.SelectedValue = dataGridViewPhieuNhanHang.Rows[rowindex].Cells["MANCC"].FormattedValue.ToString(); string ngaylap = dataGridViewPhieuNhanHang.Rows[rowindex].Cells["NGAYLAP"].FormattedValue.ToString(); string tongtien = dataGridViewPhieuNhanHang.Rows[rowindex].Cells["TONGTIEN"].FormattedValue.ToString(); txtMaPNK.Text = mapnk; txtMaNV.Text = manv; //txtMaNCC.Text = mancc; txt_NgayNhan.Text = ngaylap; txtTongTien.Text = tongtien; } public void databingding1(int rowindex) { string mapnk = dataGridViewChiTiet.Rows[rowindex].Cells["MAPNK12"].FormattedValue.ToString(); string manl = dataGridViewChiTiet.Rows[rowindex].Cells["MANL"].FormattedValue.ToString(); string soluong = dataGridViewChiTiet.Rows[rowindex].Cells["SOLUONG"].FormattedValue.ToString(); string gianhap = dataGridViewChiTiet.Rows[rowindex].Cells["GIANHAP"].FormattedValue.ToString(); txtMaPNK.Text = mapnk; } public bool isEmpty(List<string> lst) { int count = 0; foreach (string s in lst) { if (s.Length == 0) count++; } return count != 0; } public List<string> addListString() { lstStringTextBox = new List<string>(); lstStringTextBox.Add(txtMaPNK.Text); lstStringTextBox.Add(txtMaNV.Text); //lstStringTextBox.Add(txtMaNCC.Text); lstStringTextBox.Add(txt_NgayNhan.Text); lstStringTextBox.Add(txtTongTien.Text); lstStringTextBox.Add(txt_SoLuongNhap.Text); lstStringTextBox.Add(txt_DonGiaNhap.Text); return lstStringTextBox; } public List<Guna2TextBox> addListTextBox() { lstTextBox = new List<Guna2TextBox>(); lstTextBox.Add(txtMaPNK); lstTextBox.Add(txtMaNV); //lstTextBox.Add(txtMaNCC); lstTextBox.Add(txtTongTien); lstTextBox.Add(txt_SoLuongNhap); lstTextBox.Add(txt_DonGiaNhap); return lstTextBox; } public void setEnableTextBox(List<Guna2TextBox> lst, bool b) { foreach (Guna2TextBox s in lst) s.Enabled = b; } private void frmNhapKho_Load(object sender, EventArgs e) { dataGridViewPhieuNhanHang.DataSource = qlnk.loadDataGridViewPhieuNhapKho(); //dataGridViewNguyenLieu.DataSource = nl.loadNguyenLieu(); //dataGridViewChiTiet.DataSource = ctpnk.loadDataGridViewCTPhieuNhapKho(); btnThemNL.Enabled = false; btnThemPNK.Enabled = true; btnLuuPNK.Enabled = false; //btnXoaCTPNK.Enabled = false; lstTextBox = addListTextBox(); setEnableTextBox(lstTextBox, false); databingding(0); databingding1(0); loadCBLoai(); } private void btnThemPNK_Click(object sender, EventArgs e) { Random r = new Random(); int count = qlnk.demSoLuong() + 1; txtMaPNK.Text = "PNK00" + count + r.Next(0, 100); txtMaPNK.ReadOnly = true; txtMaNV.ReadOnly = true; txtMaNV.Text = nv.MANV; txtTongTien.Text = "0"; setEnableTextBox(lstTextBox, true); txtTongTien.ReadOnly = true; if (btnLuuPNK.Enabled == true) { DialogResult result; result = MessageBox.Show("Bạn chưa lưu phiếu nhập kho " + txtMaPNK.Text + ". Bạn có muốn lưu lại ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.Yes) btnLuuPNK_Click(sender, e); else return; } else btnLuuPNK.Enabled = true; } private void btnLuuPNK_Click(object sender, EventArgs e) { if (qlnk.kT(txtMaPNK.Text) == true) { qlnk.themPhieuNhapKho(txtMaPNK.Text,nv.MANV, cboNCC.SelectedValue.ToString(), txt_NgayNhan.Value, Convert.ToInt32(txtTongTien.Text)); MessageBox.Show("Thêm thành công"); frmNhapKho_Load(sender, e); } else { MessageBox.Show("Lỗi hệ thống"); } frmNhapKho_Load(sender, e); } private void dataGridViewPhieuNhanHang_CellClick(object sender, DataGridViewCellEventArgs e) { if (dataGridViewPhieuNhanHang.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) { dataGridViewPhieuNhanHang.CurrentRow.Selected = true; databingding(e.RowIndex); } } private void dataGridViewChiTiet_CellClick(object sender, DataGridViewCellEventArgs e) { if (dataGridViewChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) { dataGridViewChiTiet.CurrentRow.Selected = true; databingding1(e.RowIndex); //btnXoaCTPNK.Enabled = true; } } private void dataGridViewNguyenLieu_CellClick(object sender, DataGridViewCellEventArgs e) { //if (dataGridViewNguyenLieu.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) //{ // dataGridViewNguyenLieu.CurrentRow.Selected = true; // databingding2(e.RowIndex); // btnThemNL.Enabled = true; // txt_SoLuongNhap.Enabled = true; // txt_DonGiaNhap.Enabled = true; //} } void load_DataGridView() { // dgv Nguyen Lieu dataGridViewNguyenLieu.DataSource = nl.loadNguyenLieu(); // load dgv phiếu nhận //dataGridViewPhieuNhanHang.DataSource = qlnk.loadDataGridViewPhieuNhapKho(); // load dgv chi tiết dataGridViewChiTiet.DataSource = ctpnk.chiTietPhieuNhap(maPhieuDangChon); } private void btnThemNL_Click(object sender, EventArgs e) { if (ctpnk.ktTrung(maNLDangChon, maPhieuDangChon) == true) { if (kiemTraNhapChiTiet() == true) { ctpnk.themCTPhieuNhapKho(maPhieuDangChon, maNLDangChon, Convert.ToInt32(txt_SoLuongNhap.Text), Convert.ToInt32(txt_DonGiaNhap.Text)); dataGridViewChiTiet.DataSource = ctpnk.chiTietPhieuNhap(maPhieuDangChon); tinhTong(); //qlnk.capNhatTong(maPhieuDangChon, (int)tong); MessageBox.Show("Thêm thành công"); load_DataGridView(); frmNhapKho_Load(sender, e); } } else MessageBox.Show("Nguyên liệu này đã đặt, bạn cần chọn nguyên liệu khác"); } void tinhTong() { tong = 0; for (int i = 0; i <= dataGridViewChiTiet.Rows.Count - 1; i++) { tong = Convert.ToDouble(dataGridViewChiTiet.Rows[i].Cells["SOLUONG"].Value.ToString().Trim()) * Convert.ToDouble(dataGridViewChiTiet.Rows[i].Cells["GIANHAP"].Value.ToString().Trim()) + tong; } txtTongTien.Text = tong.ToString(); } // Kiểm tra các textbox vs combobox private bool kiemTraNhapChiTiet() { if (txt_SoLuongNhap.Text != "") { if (txt_DonGiaNhap.Text != "") { return true; } else { MessageBox.Show("Không được để trống đơn giá"); return false; } } else { MessageBox.Show("Không được để trống số lượng"); return false; } } private void btnXoaCTPNK_Click(object sender, EventArgs e) { ctpnk.xoaCTPhieuNhapKho(maPhieuDangChon, maNLDangChon); dataGridViewChiTiet.DataSource = ctpnk.chiTietPhieuNhap(maPhieuDangChon); tinhTong(); // qlnk.capNhatTong(maPhieuDangChon, (int)tong); MessageBox.Show("Xóa thành công"); frmNhapKho_Load(sender, e); } private void RP_PNK_Click(object sender, EventArgs e) { if (dataGridViewPhieuNhanHang.SelectedCells.Count > 0) { int vt = dataGridViewPhieuNhanHang.SelectedCells[0].RowIndex; maPhieuDangChon = dataGridViewPhieuNhanHang.Rows[vt].Cells["MAPNK"].Value.ToString().Trim(); frm_rpLocPhieuNhapKho rp = new frm_rpLocPhieuNhapKho(maPhieuDangChon); rp.Show(); } else { frm_rpNhapKho rp = new frm_rpNhapKho(); rp.Show(); } } private void dataGridViewPhieuNhanHang_SelectionChanged(object sender, EventArgs e) { if (dataGridViewPhieuNhanHang.SelectedCells.Count > 0) { int vt = dataGridViewPhieuNhanHang.SelectedCells[0].RowIndex; maPhieuDangChon = dataGridViewPhieuNhanHang.Rows[vt].Cells["MAPNK"].Value.ToString().Trim(); txtMaPNK.Text = maPhieuDangChon; //txt_NgayNhan.Value = Convert.ToDateTime(dataGridViewPhieuNhanHang.Rows[vt].Cells["NGAYNHAP"].Value.ToString().Trim()); txtTongTien.Text = dataGridViewPhieuNhanHang.Rows[vt].Cells["TONGTIEN"].Value.ToString().Trim(); dataGridViewChiTiet.DataSource = ctpnk.chiTietPhieuNhap(txtMaPNK.Text); } } private void btnNhapChiTietPhieu_Click(object sender, EventArgs e) { dataGridViewNguyenLieu.DataSource = nl.loadNguyenLieu(); btnThemNL.Enabled = true; } private void dataGridViewChiTiet_SelectionChanged(object sender, EventArgs e) { if (dataGridViewChiTiet.SelectedCells.Count > 0) { int vt = dataGridViewChiTiet.SelectedCells[0].RowIndex; //maPhieuDangChon = dataGridViewChiTiet.Rows[vt].Cells["MAPNK"].Value.ToString().Trim(); maNLDangChon = dataGridViewChiTiet.Rows[vt].Cells["MANL"].Value.ToString().Trim(); txt_SoLuongNhap.Text = dataGridViewChiTiet.Rows[vt].Cells["SOLUONG"].Value.ToString().Trim(); txt_DonGiaNhap.Text = dataGridViewChiTiet.Rows[vt].Cells["GIANHAP"].Value.ToString().Trim(); } } private void dataGridViewNguyenLieu_SelectionChanged(object sender, EventArgs e) { txt_DonGiaNhap.Enabled = true; txt_SoLuongNhap.Enabled = true; txt_DonViTinh.Enabled = false; if (dataGridViewNguyenLieu.SelectedCells.Count > 0) { txt_SoLuongNhap.Text = ""; txt_DonGiaNhap.Text = ""; int vitri = dataGridViewNguyenLieu.SelectedCells[0].RowIndex; maNLDangChon = dataGridViewNguyenLieu.Rows[vitri].Cells["MANL"].Value.ToString().Trim(); tenNLDangChon = dataGridViewNguyenLieu.Rows[vitri].Cells[1].Value.ToString().Trim(); txt_DonViTinh.Text = dataGridViewNguyenLieu.Rows[vitri].Cells["DVT"].Value.ToString().Trim(); } } private void groupBox5_Enter(object sender, EventArgs e) { } //private void xoaToolStripMenuItem_Click(object sender, EventArgs e) //{ // // xóa chi tiết phiếu nhập kho // ctpnk.xoaCTPhieuNhapKho(txtMaPNK.Text, txtMaNL.Text); // qlnk.xoaPhieuNhapKho(txtMaPNK.Text); // frmNhapKho_Load(sender, e); // MessageBox.Show("xóa thành công"); // // xóa phiếu nhập kho //} } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using FactoryMethodPattern; namespace UnitTests { [TestClass] public class FactoryMethodTests { [TestMethod] public void FactoryMethod() { IObjectFactory factory = new ObjectFactory(); var intObj = factory.MakeObject<int>(); var strObj = factory.MakeObject<string>(); Assert.IsInstanceOfType(intObj.Value, typeof(int)); Assert.IsInstanceOfType(strObj.Value, typeof(string)); Assert.AreNotEqual(intObj.Identifier, strObj.Identifier); } } }
using System.Collections; namespace Fano { public class WordFrequency { private BitArray _word; private int _frequency = 0; public WordFrequency(int bitsWordSize) { _word = new BitArray(bitsWordSize); } public WordFrequency(BitArray bitWord) { _word = new BitArray(bitWord); IncrementFrequency(); } public void IncrementFrequency() => _frequency++; public int Frequency => _frequency; public BitArray Word { get { return _word; } set { _word = value; } } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace TelesalesSchedule.Models.ViewModels { public class AnonsViewModel { public int Id { get; set; } [Required] [StringLength(50)] public string Title { get; set; } [Required] public string Content { get; set; } public string Tags { get; set; } public ICollection<Anons> Anonses { get; set; } public string AuthorId { get; set; } } }
using System; namespace doob.Scripter.Shared { public interface IScripterContext { IScripterContext AddScripterEngine<TEngine>() where TEngine : class, IScriptEngine; IScripterContext AddScripterEngine(Type engineType); IScripterContext AddScripterEngine<TEngine>(Func<IServiceProvider, TEngine> factory) where TEngine : class, IScriptEngine; IScripterContext AddScripterEngine(Type engineType, Func<IServiceProvider, object> factory); IScripterContext AddScripterModule<TModule>() where TModule : class, IScripterModule; IScripterContext AddScripterModule(Type moduleType); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SideSphere_PanelLights : MonoBehaviour { public AudioController_V2 aC; public int _band; public float _startScale; public float _scaleMultiplier; public bool _useBuffer; private float maxScale = 400; private float currentscale; // Update is called once per frame void Update () { if (_useBuffer == true) { this.transform.position = new Vector3(318, 10 + (_band * 20), 186 - ((aC._audioBandBuffer[_band] * _scaleMultiplier) + _startScale)); } if (_useBuffer == false) { this.transform.position = new Vector3(318, 10 + (_band * 20), 186 - ((aC._AmplitudeBuffer * _scaleMultiplier) + _startScale)); } } }