text
stringlengths
13
6.01M
using Autofac; using EmberKernel.Services.Command.Attributes; using EmberKernel.Services.Command.Components; using EmberKernel.Services.Command.HelpGenerator; using EmberKernel.Services.Command.Models; using EmberKernel.Services.Command.Parsers; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace EmberKernel.Services.Command { public class CommandContainerManager : ICommandContainerManager { private class CommandHandlerInfo { public MethodInfo CommandHandler { get; set; } public Type HandlerParserType { get; set; } public bool IsAwaitable { get; set; } } private ILogger<CommandContainerManager> Logger { get; } private ICommandContainer CommandContainer { get; } private Type CommandContainerType { get; } private readonly Dictionary<string, CommandHandlerInfo> commandHandlers = new Dictionary<string, CommandHandlerInfo>(); private readonly Dictionary<Type, IParser> parsers = new Dictionary<Type, IParser>() { { typeof(DefaultParser), new DefaultParser() }, }; private ILifetimeScope CurrentScope { get; } public CommandContainerManager(ILifetimeScope scope, ICommandContainer container, ILogger<CommandContainerManager> logger) { CommandContainer = container; CommandContainerType = container.GetType(); Logger = logger; CurrentScope = scope; } IEnumerable<(MethodInfo, CommandHandlerAttribute, Type)> ICommandContainerManager.ResolveHandlers() => ResolveHandlers(); private IEnumerable<(MethodInfo, CommandHandlerAttribute, Type)> ResolveHandlers() { var type = CommandContainer.GetType(); foreach (var method in type.GetMethods()) { if (method.GetCustomAttribute<CommandHandlerAttribute>() is CommandHandlerAttribute attr) { var parser = method.GetCustomAttribute<CommandParserAttribute>()?.Parser ?? typeof(DefaultParser); yield return (method, attr, parser); } } } public void InitializeHandlers(Action<string, CommandHandlerAttribute> globalCommandRegister) { foreach (var (method, cmdAttr, parserType) in ResolveHandlers()) { // Get a safe command name to take command duplicate situation var safeCommandName = cmdAttr.Command; var cmdIndex = 0; while (commandHandlers.ContainsKey(safeCommandName)) { safeCommandName = $"{safeCommandName}{++cmdIndex}"; } if (cmdIndex > 0) { Logger.LogWarning($"Command {safeCommandName} was duplicated! Rename to '{safeCommandName}'"); } // Add command handlers to dictionary var commandHandlerInfo = new CommandHandlerInfo { CommandHandler = method, IsAwaitable = method.ReturnType.GetMethods().Any((method) => method.Name == "GetAwaiter"), }; // Add parser instance to dictionary // Check parser assignable if (!typeof(IParser).IsAssignableFrom(parserType)) { Logger.LogWarning($"Command handler parser type not implement IParse interface!"); } // Add 'commandHandler' as Parser if (parserType == CommandContainerType) { parsers.Add(parserType, CommandContainer as IParser); } // Create new parser instance in Arrtibute else if (parserType != typeof(DefaultParser) && !parsers.ContainsKey(parserType)) { parsers.Add(parserType, Activator.CreateInstance(parserType) as IParser); } // Associate command and parser commandHandlerInfo.HandlerParserType = parserType; commandHandlers.Add(safeCommandName, commandHandlerInfo); // if command has CommandAlias attribute, register as global command if (method.GetCustomAttribute<CommandAliasAttribute>() is CommandAliasAttribute attr) { globalCommandRegister(attr.Alias, cmdAttr); } } } public void RemoveHandlers() { foreach (var command in commandHandlers.Keys) { commandHandlers.Remove(command); } } public void Dispose() { commandHandlers.Clear(); parsers.Clear(); } public async ValueTask Invoke(CommandArgument argument) { var currentArgument = argument; if (argument.Command == null) { if (!CommandContainer.TryAssignCommand(argument, out var nextArgument)) { Logger.LogWarning($"Unknown command {argument.Command}"); return; } else currentArgument = nextArgument; } if (currentArgument.Command == "help" && CurrentScope.TryResolve<ICommandHelp>(out var help)) { help.HandleHelp(argument); return; } if (!commandHandlers.TryGetValue(currentArgument.Command, out var handlerInfo) || handlerInfo == null) { Logger.LogWarning($"Unknown command {argument.Command}"); return; } object ret; if (handlerInfo.CommandHandler.GetParameters().Length == 0) { ret = handlerInfo.CommandHandler.Invoke(CommandContainer, null); } else { var parser = parsers[handlerInfo.HandlerParserType]; ret = handlerInfo.CommandHandler.Invoke(CommandContainer, parser.ParseCommandArgument(argument).ToArray()); } if (ret != null && handlerInfo.IsAwaitable) { switch (ret) { case Task task: await task; return; case ValueTask valueTask: await valueTask; return; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /* * Author : Elio Valenzuela * Create on : 31-05-2018 * Credits : Sebastian League */ [RequireComponent(typeof(BoxCollider2D))] public class RaycastController : MonoBehaviour { public LayerMask collisionMask; public const float skin_width = 0.015f; const float dstBetweenRays = 0.25f; [HideInInspector] public int horRaycount; [HideInInspector] public int verRaycount; [HideInInspector] public float horRayspacing; [HideInInspector] public float verRayspacing; [HideInInspector] public BoxCollider2D collider2D; public RaycastOrigins raycastOrigins; public virtual void Awake() { collider2D = GetComponent<BoxCollider2D>(); CalculateRayspacing(); } public virtual void Start() { CalculateRayspacing(); } /* * Actualiza los puntos de origen de los rayos generados */ public void UpdateRaycastOrigins() { Bounds bounds = collider2D.bounds; bounds.Expand(skin_width * -2); raycastOrigins.bottomLeft = new Vector2(bounds.min.x, bounds.min.y); raycastOrigins.bottomRight = new Vector2(bounds.max.x, bounds.min.y); raycastOrigins.topLeft = new Vector2(bounds.min.x, bounds.max.y); raycastOrigins.topRight = new Vector2(bounds.max.x, bounds.max.y); } /* * Calcula el espacio entre cada rayo generado */ public void CalculateRayspacing() { Bounds bounds = collider2D.bounds; bounds.Expand(skin_width * -2); float boundsWidth = bounds.size.x; float boundsheight = bounds.size.y; horRaycount = Mathf.RoundToInt( boundsheight / dstBetweenRays); verRaycount = Mathf.RoundToInt(boundsWidth / dstBetweenRays); horRayspacing = bounds.size.y / (horRaycount - 1); verRayspacing = bounds.size.x / (verRaycount - 1); } /* * Struct que almacena la informacion de los 4 extremos del Box2D */ public struct RaycastOrigins { public Vector2 topLeft; public Vector2 topRight; public Vector2 bottomLeft; public Vector2 bottomRight; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggerCat : MonoBehaviour { public GameObject kittenPrefab; public GameObject kitten; public Transform spawn; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } private void OnTriggerEnter(Collider other) { if (other.CompareTag("MainCamera")) { if (kitten == null) { kitten = Instantiate(kittenPrefab, spawn.position, Quaternion.Euler(0,-90,0)); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Separation : BoidBehavior { public override bool UpdateDirection() { Vector2 middle = Vector2.zero; float totalWeight = 0; foreach(Boid b in this.boid.closestBoids){ if(!b) continue; middle +=(Vector2) (b.transform.position); totalWeight += 1f; } if((totalWeight) ==0) return false; middle /= totalWeight; dir = ((Vector2)transform.position - middle).normalized; Debug.DrawLine(transform.position, middle); Debug.DrawRay(transform.position, dir * 10f, Color.yellow); Debug.DrawRay(transform.position,dir,debugColor); return true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; #region Additional Namespaces using Chinook.Data.Entities; using ChinookSystem.BLL; using Chinook.UI; #endregion public partial class SamplePages_CRUDReview : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SelectedTitle.Text = ""; } protected void Search_Click(object sender, EventArgs e) { //clear out the old album information on the Maintain tab Clear_Click(sender, e); if(string.IsNullOrEmpty(SearchArg.Text)) { MessageUserControl1.ShowInfo("Enter an Album title or part of the title."); } else { //dol a look of the data in the db via the controller //all actions that are external to the webpage should be done in a try/catch //for friendly error handling //we will use message user control to handle the error messages for this semester MessageUserControl1.TryRun(() => { //coding block I wish message user control to try and run and checking //for any error catching the errors, and displaying said errors fro me //in its error panel //what is left for me to do; Simply the logic for the event //standard lookup AlbumController sysmgr = new AlbumController(); List<Album> albumlist = sysmgr.Albums_GetbyTitle(SearchArg.Text); if (albumlist.Count == 0) { MessageUserControl1.ShowInfo("Search Result", "No data for album title or partial title " + SearchArg.Text); AlbumList.DataSource = null; AlbumList.DataBind(); } else { MessageUserControl1.ShowInfo("Search Result", "Select the desired album for title" + SearchArg.Text); AlbumList.DataSource = null; AlbumList.DataBind(); } }); } } protected void AlbumList_SelectedIndexChanged(object sender, EventArgs e) { } protected void AddAlbum_Click(object sender, EventArgs e) { } protected void UpdateAlbum_Click(object sender, EventArgs e) { } protected void DeleteAlbum_Click(object sender, EventArgs e) { } protected void Clear_Click(object sender, EventArgs e) { AlbumID.Text = ""; AlbumTitle.Text = ""; AlbumReleaseYear.Text = ""; AlbumReleaseLabel.Text = ""; ArtistList.SelectedIndex = 0; } protected void CheckForException(object sender, ObjectDataSourceStatusEventArgs e) { MessageUserControl.HandleDataBoundException(e); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using WebsiteQuanLyPhatHanhSach.Models; using WebsiteQuanLyPhatHanhSach.ViewModels; namespace WebsiteQuanLyPhatHanhSach.Controllers { public class BooksController : Controller { private QLPhatHanhSachEntities db = new QLPhatHanhSachEntities(); // GET: Books public ActionResult Index() { var books = db.Books.Include(b => b.Publishing)/*.Include(b => b.BookPrices)*/; return View(books.ToList()); } // GET: Books/Details/5 public ActionResult Details(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Book book = db.Books.Find(id); if (book == null) { return HttpNotFound(); } return View(book); } // GET: Books/Create public ActionResult Create() { ViewBag.PubID = new SelectList(db.Publishings, "PubID", "PubName"); return View(); } // POST: Books/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(BookVM B) { //bool status = false; if (ModelState.IsValid) { Book book = new Book { ISBN = B.ISBN, BookName = B.BookName, BookCategory = B.BookCategory, PubID = B.PubID, BookAuthor = B.BookAuthor, BookPages = B.BookPages, BookDescribe = B.BookDescribe }; BookPrice bookprice = new BookPrice { ISBN = B.ISBN, DateCreate = DateTime.Now, PurchasePrice = B.PurchasePrice, SellingPrice = B.SellingPrice }; book.BookPrices.Add(bookprice); db.Books.Add(book); //db.BookPrices.Add(bookprice); db.SaveChanges(); //status = true; return RedirectToAction("Index"); } //return new JsonResult { Data = new { status = status } }; ViewBag.PubID = new SelectList(db.Publishings, "PubID", "PubName", B.PubID); return View(B); } // GET: Books/Edit/5 public ActionResult Edit(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Book book = db.Books.Find(id); if (book == null) { return HttpNotFound(); } ViewBag.PubID = new SelectList(db.Publishings, "PubID", "PubName", book.PubID); return PartialView(book); } // POST: Books/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ISBN,BookName,BookCategory,PubID,BookAuthor,BookPages,BookDescribe")] Book book) { if (ModelState.IsValid) { db.Entry(book).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.PubID = new SelectList(db.Publishings, "PubID", "PubName", book.PubID); return View(book); } // GET: Books/Delete/5 public ActionResult Delete(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Book book = db.Books.Find(id); if (book == null) { return HttpNotFound(); } return PartialView(book); } // POST: Books/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(long id) { Book book = db.Books.Find(id); db.Books.Remove(book); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; namespace Hni.TestMVC6.Models { public partial class PartReceived { public int PartReceivedId { get; set; } public int AuditorId { get; set; } public decimal DateCode { get; set; } public DateTime IncomingDate { get; set; } public string IndividualPartComments { get; set; } public int InspectionTypeId { get; set; } public decimal InspectorNum { get; set; } public decimal? InspectorNum2 { get; set; } public int PartId { get; set; } public string RedTagNum { get; set; } public DateTime SampleInspectionEntryDate { get; set; } public string SerialNumber { get; set; } public int VendorId { get; set; } public short WasTestedId { get; set; } public int WhereFoundId { get; set; } public virtual ValveTestResults ValveTestResults { get; set; } public virtual Auditor Auditor { get; set; } public virtual InspectionType InspectionType { get; set; } public virtual Part Part { get; set; } public virtual Vendor Vendor { get; set; } public virtual WasTested WasTested { get; set; } public virtual WhereFound WhereFound { get; set; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices.ComTypes; using System.Security.Authentication.ExtendedProtection; using System.Threading.Tasks; using LanguageExt; using Tema6-18; using Tema6-18.Outputs; using Access.Primitives.IO; using Tema6-18.Adapters; namespace Tema6_18 { class Program { static void Main(string[] args) { var wf = from createReplyResult in BoundedContextDSL.ValidateReply(100, 1, "InternetOfThings") let validReply = (CreateReplyResult.ReplyValid)createReplyResult from checkLanguageResult in BoundedContextDSL.CheckLanguage(validReply.Reply.Answer) from ownerAck in BoundedContextDSL.SendAckToOwner(checkLanguageResult) from authorAck in BoundedContextDSL.SendAckToAuthor(checkLanguageResult) select (validReply, checkLanguageResult, ownerAck, authorAck); var serviceProvider = new ServiceCollection() .AddOperations(typeof(ValidateReplyAdapter).Assembly) .AddOperations(typeof(CheckLanguageAdapter).Assembly) .AddOperations(typeof(SenAckToQuestionOwnerAdapter).Assembly) .AddTransient<IInterpreterAsync>(sp => new LiveInterpreterAsync(sp)) .BuildServiceProvider(); Console.WriteLine("Hello World!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using System.ComponentModel; namespace KartSystem { public class ProductionGoodSpecRecord : DocGoodSpecRecord { [DisplayName("Коэффициент преобразования")] public double Factor { get; set; } } }
using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Projeto.Models; namespace Projeto.Controllers { [Authorize(Roles = "Admin")] public class PerfilController : Controller { private RoleManager<IdentityRole> _roleManager; public PerfilController(RoleManager<IdentityRole> roleManager) { _roleManager = roleManager; } public ViewResult Index() { var roles = _roleManager.Roles; return View(roles); } public IActionResult Create() => View(); [HttpPost] public async Task<IActionResult> Create([Required] string name) { if (ModelState.IsValid) { var result = await _roleManager.CreateAsync(new IdentityRole(name)); if (result.Succeeded) { //Serilog.Log.Information("Ação: Create; Objeto: Perfil; Perfil: {0}; Usuario: {1}; ", name, User.Identity.Name); return RedirectToAction("Index"); } else Errors(result); } return View(name); } private void Errors(IdentityResult result) { foreach (IdentityError error in result.Errors) ModelState.AddModelError("", error.Description); } public async Task<IActionResult> Edit(string id) { var modelo = await _roleManager.FindByIdAsync(id); return View(modelo); } [HttpPost] public async Task<IActionResult> Edit(string id, IdentityRole modelo) { if (id != modelo.Id) return NotFound(); if (!ModelState.IsValid) return NotFound(); try { await _roleManager.UpdateAsync(modelo); //Serilog.Log.Information("Ação: Update; Objeto: Perfil; Perfil: {0}; Usuario: {1}; ", modelo.Name, User.Identity.Name); } catch (DbUpdateConcurrencyException) { if (!ModelExist(modelo.Id).Result) return NotFound(); else throw; } return RedirectToAction("Index"); } public async Task<IActionResult> Delete(string id) { var modelo = await _roleManager.FindByIdAsync(id); if (modelo == null) return NotFound(); return View(modelo); } [HttpPost] public async Task<IActionResult> DeleteConfirm(string id) { var modelo = await _roleManager.FindByIdAsync(id); if (modelo != null) { var result = await _roleManager.DeleteAsync(modelo); if (result.Succeeded) { //Serilog.Log.Information("Ação: Delete; Objeto: Perfil; Perfil: {0}; Usuario: {1}; ", modelo.Name, User.Identity.Name); return RedirectToAction("Index"); } else Errors(result); } else ModelState.AddModelError("", "No role found"); return View("Index", _roleManager.Roles); } public async Task<IActionResult> Details(string id) { var modelo = await _roleManager.FindByIdAsync(id); if (modelo == null) return NotFound(); return View(modelo); } private async Task<bool> ModelExist(string id) { var modelo = await _roleManager.FindByIdAsync(id); return await _roleManager.RoleExistsAsync(modelo.Name); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Missile : MonoBehaviour { [Range(4,15)]public float missileSpeed; private Rigidbody2D rb; private AudioSource audioSource; public List<AudioClip> sounds; private void Start() { rb = GetComponent<Rigidbody2D>(); audioSource = GetComponent<AudioSource>(); audioSource.clip = sounds[0]; audioSource.Play(); } private void Update() { rb.velocity = transform.up * missileSpeed; } private void OnTriggerEnter2D(Collider2D collision) { if(collision.gameObject.CompareTag("Car")) { rb.isKinematic = true; audioSource.clip = sounds[1]; audioSource.Play(); collision.gameObject.GetComponent<CarMovement>().StartCoroutine("GetDamaged"); Destroy(this.gameObject, 0.2f); } else if (collision.gameObject.CompareTag("Border")) { Destroy(this.gameObject); } } }
/* * Created by SharpDevelop. * User: Admin * Date: 5/6/2019 * Time: 6:45 AM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; namespace proyeto_poo { /// <summary> /// Description of Simple. /// </summary> public class Simple : Room { public Simple(int Hour) { if (Convert.ToInt32(Hour) >= 12 && Convert.ToInt32(Hour) < 13) { PriceRoom = 400; } else{ PriceRoom = 500; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSVHandler { class OnlinePayment : Transaction { protected String vendor, onlinePayRef; public OnlinePayment(String transDate, String transType, String vendor, String onlinePayRef, double transValue, double accBalance) : base(transDate, transType, transValue, accBalance){ this.vendor = vendor; this.onlinePayRef = onlinePayRef; // Constructor } public override String getVendor(){ return this.vendor; } public String getOnlinePayRef(){ return this.onlinePayRef; } public override String toString() { return "Online Payment To: " + vendor + " Ref: " + onlinePayRef + " on " + transDate + " for $" + String.Format("{0:0,0.00}", this.transValue); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReviveComponent : MonoBehaviour { public float timeToRevive = 5.0f; private float timer = -1.0f; private bool isRevived = false; private bool isReviving = false; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (isReviving && !isRevived) { Debug.Log("Now reviving. Please wait..."); if (timer > 0) { timer -= Time.deltaTime; } else if (timer <= 0) { timer = -1.0f; isRevived = true; isReviving = false; Debug.Log("Revive Successful"); // TODO: substitute with thing that happens } } } public void Revive() { // create a timer for the revive timer = timeToRevive; isReviving = true; } }
namespace _01._StudentsByGroup { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { string input = Console.ReadLine(); List<Student> students = new List<Student>(); while (input != "END") { string[] inputParts = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string firstName = inputParts[0]; string lastName = inputParts[1]; int group = int.Parse(inputParts[2]); Student student = new Student(firstName, lastName, group); students.Add(student); input = Console.ReadLine(); } IEnumerable<IGrouping<int, Student>> studentsGroup = students .GroupBy(g => g.Group) .Where(g => g.Key == 2); foreach (IGrouping<int, Student> grouping in studentsGroup) { foreach (Student student in grouping.OrderBy(s => s.FirstName)) { Console.WriteLine($"{student.FirstName} {student.LastName}"); } } } } }
using PagedList; using SQLServerBackupTool.Lib.Annotations; using SQLServerBackupTool.Web.Lib.Mvc; using SQLServerBackupTool.Web.ViewModels; using System; using System.Configuration; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; namespace SQLServerBackupTool.Web.Controllers { [Authorize(Roles = @"Admin")] public class UsersController : ApplicationController { private const int NumberItemsPerPage = 30; private static MembershipProvider Provider { get { return Membership.Provider; } } private static Type MembershipProviderUserKeyType { get { return typeof(Guid); } } protected override void Initialize(RequestContext r) { base.Initialize(r); if (!Provider.EnablePasswordReset || Provider.RequiresQuestionAndAnswer) { throw new ConfigurationErrorsException( "UsersController requires membership configuration options : enablePasswordReset -> true and requiresQuestionAndAnswer -> false" ); } } /** * Index */ public ActionResult Index() { int pageIndex; if (!int.TryParse(Request.Params[@"page"], out pageIndex)) { pageIndex = 1; } int totalRecords; var users = Provider.GetAllUsers(pageIndex - 1, NumberItemsPerPage, out totalRecords); var list = users.Cast<MembershipUser>(); return View(list.ToPagedList(pageIndex, NumberItemsPerPage)); } /** * Create */ public ActionResult Create() { return View(new MembershipEditViewModel { IsApproved = true, Roles = new string[] { } }); } [ValidateAntiForgeryToken, HttpPost] public ActionResult Create(MembershipEditViewModel u) { if (ModelState.IsValid) { try { MembershipCreateStatus mStatus; var userName = u.UserName; var newUser = Membership.CreateUser( userName, u.Password, u.Email, null, null, u.IsApproved, out mStatus ); if (mStatus == MembershipCreateStatus.Success && newUser != null) { if (newUser.Comment != u.Comment) { newUser.Comment = u.Comment; Provider.UpdateUser(newUser); } HandleRoles(u); AddFlashMessage(string.Format("User '{0}' successfully created", userName), FlashMessageType.Success); return RedirectToAction("Edit", new { id = newUser.ProviderUserKey }); } var status = GetMembershipCreateStatusMessage(mStatus); AddFlashMessage( string.Format("An error occurred during user creation : {0}", status), FlashMessageType.Error ); } catch (Exception ex) { Logger.ErrorException("An error occurred", ex); AddFlashMessage("An error occurred during user creation", FlashMessageType.Error); } } else { DebugModelStateErrors(); AddFlashMessage("Unable to create user with provided values, please correct errors", FlashMessageType.Warning); } u.Roles = u.Roles ?? new string[] { }; return View(u); } /** * Edit */ public ActionResult Edit(string id) { var uKey = GetRealProviderUserKey(id); if (uKey == null) { return HttpNotFound(); } var u = Membership.GetUser(uKey); if (u == null) { return HttpNotFound(string.Format("User : {0} not found", u.UserName)); } return View(new MembershipEditViewModel(u) { ForEdit = true, }); } [ValidateAntiForgeryToken, HttpPost] public ActionResult Edit(MembershipEditViewModel u) { var username = u.UserName; var mem = Membership.GetUser(username); if (mem == null) { return HttpNotFound(string.Format("User : {0} not found", username)); } try { if (!string.IsNullOrWhiteSpace(u.Password) && u.Password == u.PasswordConfirmation) { mem.ChangePassword(mem.ResetPassword(), u.Password); } if (mem.Comment != u.Comment) { mem.Comment = u.Comment; Provider.UpdateUser(mem); } HandleRoles(u); AddFlashMessage("User successfully modified", FlashMessageType.Success); return RedirectToAction("Index"); } catch (Exception ex) { AddFlashMessage("An error occurred during user modification", FlashMessageType.Error); Logger.ErrorException("An error occurred", ex); } u.ForEdit = true; return View(u); } /** * User delete */ [HttpPost, ValidateAntiForgeryToken] public ActionResult Delete(string id) { var uKey = GetRealProviderUserKey(id); if (uKey == null) { return HttpNotFound(); } var mem = Membership.GetUser(uKey); if (mem == null) { return HttpNotFound(); } var userName = mem.UserName; try { if (Provider.DeleteUser(userName, true)) { AddFlashMessage(string.Format("User '{0}' successfully deleted", userName), FlashMessageType.Success); } else { AddFlashMessage(string.Format("Unable to delete user '{0}'", userName), FlashMessageType.Warning); } } catch (Exception ex) { AddFlashMessage(string.Format("An error occurred while deleting user {0}", userName), FlashMessageType.Error); Logger.ErrorException("An error occurred", ex); } return RedirectToAction("Index"); } /** * Random password generator */ public ActionResult GeneratePassword() { return Content( Membership.GeneratePassword( Membership.MinRequiredPasswordLength, Membership.MinRequiredNonAlphanumericCharacters ), "text/plain" ); } /// <summary> /// Transforms <see cref="id"/> into the real under-laying <see cref="MembershipUser.ProviderUserKey"/> type /// </summary> /// <param name="id">Key as string</param> /// <returns>A trans-typed object or what was initially given</returns> protected static object GetRealProviderUserKey(string id) { object realProviderUserKey = null; if (MembershipProviderUserKeyType == typeof(Guid)) { try { realProviderUserKey = Guid.Parse(id); } // ReSharper disable EmptyGeneralCatchClause : What can we do anyway ? catch (Exception) { } // ReSharper restore EmptyGeneralCatchClause } else if (MembershipProviderUserKeyType == typeof(int)) { try { realProviderUserKey = int.Parse(id); } // ReSharper disable EmptyGeneralCatchClause : What can we do anyway ? catch (Exception) { } // ReSharper restore EmptyGeneralCatchClause } else { realProviderUserKey = id; } return realProviderUserKey; } /// <summary> /// When roles are enabled adds/removes roles /// </summary> /// <param name="u"><see cref="MembershipEditViewModel"/> to get the roles from</param> protected static void HandleRoles([NotNull] MembershipEditViewModel u) { if (u == null) { throw new ArgumentNullException("u"); } if (!Roles.Enabled) { return; } var rolesForUser = Roles.GetRolesForUser(u.UserName); if (rolesForUser != null && rolesForUser.Length > 0) { Roles.RemoveUserFromRoles(u.UserName, rolesForUser); } if (u.Roles != null && u.Roles.Any()) { Roles.AddUserToRoles(u.UserName, u.Roles.ToArray()); } } /// <summary> /// Translates a <see cref="MembershipCreateStatus"/> to a human readable string /// </summary> /// <param name="status">The status to translate</param> /// <returns>A status string</returns> /// <exception cref="ArgumentOutOfRangeException">Unknown status type</exception> protected static string GetMembershipCreateStatusMessage(MembershipCreateStatus status) { switch (status) { case MembershipCreateStatus.Success: return "The user was successfully created."; case MembershipCreateStatus.InvalidUserName: return "The user name was not found in the database."; case MembershipCreateStatus.InvalidPassword: return "The password is not formatted correctly."; case MembershipCreateStatus.InvalidQuestion: return "The password question is not formatted correctly."; case MembershipCreateStatus.InvalidAnswer: return "The password answer is not formatted correctly."; case MembershipCreateStatus.InvalidEmail: return "The e-mail address is not formatted correctly."; case MembershipCreateStatus.DuplicateUserName: return "The user name already exists in the database for the application."; case MembershipCreateStatus.DuplicateEmail: return "The e-mail address already exists in the database for the application."; case MembershipCreateStatus.UserRejected: return "The user was not created, for a reason defined by the provider."; case MembershipCreateStatus.InvalidProviderUserKey: return "The provider user key is of an invalid type or format."; case MembershipCreateStatus.DuplicateProviderUserKey: return "The provider user key already exists in the database for the application."; case MembershipCreateStatus.ProviderError: return "The provider returned an error that is not described by other MembershipCreateStatus enumeration values."; } throw new ArgumentOutOfRangeException("status"); } } }
using neptune.game; public class Game : NGame { #region Singleton Instance private static Game _instance = null; public static Game Instance { get { return _instance; } } #endregion #region OnAwake protected override void OnAwake() { #region DontDestroyOnLoad if (_instance != null) { Destroy(gameObject); } else { _instance = this; DontDestroyOnLoad(gameObject); } #endregion base.OnAwake(); DataManagers.Instance.Create(); DataManagers.Instance.Init(); DataManagers.Instance.Load(); } #endregion #region Game: Save public void Save() { DataManagers.Instance.Save(); } #endregion #region Game: Reset public void Reset() { DataManagers.Instance.Reset(); } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityS4.Data; using Microsoft.EntityFrameworkCore; namespace IdentityS4.Services { public class AdminService: BaseService<Admin>, IAdminService { public AdminService(EFContext _efContext) { db = _efContext; } public async Task<Admin> GetByStr(string username, string pwd) { Admin m=await db.Admin.Where(a => a.UserName == username && a.Password == pwd).SingleOrDefaultAsync(); if (m!=null) { return m; } else { return null; } } } }
using MathApplication.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; namespace MathApplication.Models { public class AppRoleProvider : RoleProvider { public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void CreateRole(string roleName) { throw new NotImplementedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } public override string[] GetAllRoles() { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { UserContext db = new UserContext(); int dataID = db.UserAccounts.Where(x => x.Username == username).FirstOrDefault().UserRole; string dataLabel = db.UserRoles.Where(x => x.ID == dataID).FirstOrDefault().Label; string[] result = { dataLabel }; return result; } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } public override bool IsUserInRole(string username, string roleName) { throw new NotImplementedException(); } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override bool RoleExists(string roleName) { throw new NotImplementedException(); } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TaskNF { [Table("Publisher")] public class Publisher { [Key] public int PublishedId { get; set; } public string PublisherName { get; set; } public virtual ICollection<Book> Books { get; set; } public int CountryId { get; set; } public virtual Country Country { get; set; } public virtual ICollection<EmailAddress> EmailAddresses { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Linq; using System.Web; namespace MVCPrueba.Models { public class Docente { public Docente() { this.Materias = new HashSet<Materia>(); } [Key] public int Code_Docente { get; set; } public string Nombre_Docente { get; set; } public virtual ICollection<Materia> Materias { get; set; } public void Guardar() { //var docente = new Docente(); try { using (CDBContext db = new CDBContext()) { if (this.Code_Docente == 0) { db.Entry(this).State = EntityState.Added; foreach (var m in this.Materias) { db.Entry(m).State = EntityState.Unchanged; } } db.SaveChanges(); } } catch (Exception ex) { throw new Exception(ex.Message); } } public List<Docente> allDocentes() { var docente = new List<Docente>(); try { using (CDBContext db = new CDBContext()) { docente = db.Docentes.ToList(); } } catch (Exception ex) { throw new Exception(ex.Message); } return docente; } public Docente getConsulta(int id) { var docente = new Docente(); try { using (CDBContext db = new CDBContext()) { docente = db.Docentes .Include("Materia") .Where(x => x.Code_Docente == id) .Single(); } } catch (Exception ex) { throw new Exception(ex.Message); } return docente; } } }
using UnityEngine; namespace DChild.Gameplay.Objects.Characters.Enemies { public interface IMovingEnemy { void MoveTo(Vector2 destination); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SwitchScene : MonoBehaviour { [SerializeField] string _stageName; public void OnResult() { Application.Instance.GameMain.NextSceneName = _stageName; SceneManager.LoadScene(_stageName); } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using Castle.Services.Transaction; using com.Sconit.Facility.Persistence; using com.Sconit.Facility.Entity; using NHibernate.Expression; using com.Sconit.Service.Ext.Criteria; using com.Sconit.Entity; using com.Sconit.Facility.Service.Ext; //TODO: Add other using statements here. namespace com.Sconit.Facility.Service.Impl { [Transactional] public class FacilityStockMasterMgr : FacilityStockMasterBaseMgr, IFacilityStockMasterMgr { public ICriteriaMgrE criteriaMgrE { get; set; } public IFacilityStockDetailMgrE facilityStockDetailMgr { get; set; } #region Customized Methods [Transaction(TransactionMode.Requires)] public override void CreateFacilityStockMaster(FacilityStockMaster facilityStockMaster) { base.CreateFacilityStockMaster(facilityStockMaster); #region 根据条件把明细生成好 DetachedCriteria criteria = DetachedCriteria.For(typeof(FacilityMaster)); if (!string.IsNullOrEmpty(facilityStockMaster.FacilityCategory)) { criteria.Add(Expression.In("Category", facilityStockMaster.FacilityCategory.Split(','))); } if (!string.IsNullOrEmpty(facilityStockMaster.ChargeSite)) { criteria.Add(Expression.In("ChargeSite", facilityStockMaster.ChargeSite.Split(','))); } if (!string.IsNullOrEmpty(facilityStockMaster.ChargeOrg)) { criteria.Add(Expression.In("ChargeOrganization", facilityStockMaster.ChargeOrg.Split(','))); } if (!string.IsNullOrEmpty(facilityStockMaster.ChargePerson)) { criteria.Add(Expression.In("CurrChargePerson", facilityStockMaster.ChargePerson.Split(','))); } if (!string.IsNullOrEmpty(facilityStockMaster.AssetNo)) { criteria.Add(Expression.Like("AssetNo", facilityStockMaster.AssetNo, MatchMode.Anywhere)); } //转让,报废,盘亏状态的不显示在明细中 criteria.Add(Expression.Not(Expression.In("Status", new string[] { FacilityConstants.CODE_MASTER_FACILITY_STATUS_SCRAP, FacilityConstants.CODE_MASTER_FACILITY_STATUS_LOSE, FacilityConstants.CODE_MASTER_FACILITY_STATUS_SELL }))); IList<FacilityMaster> facilityMasterList = criteriaMgrE.FindAll<FacilityMaster>(criteria); if (facilityMasterList != null && facilityMasterList.Count > 0) { foreach (FacilityMaster f in facilityMasterList) { FacilityStockDetail d = new FacilityStockDetail(); d.StNo = facilityStockMaster.StNo; d.FacilityMaster = f; d.InvQty = 1; d.Qty = 0; d.DiffQty = d.InvQty - d.Qty; d.CreateDate = facilityStockMaster.CreateDate; d.CreateUser = facilityStockMaster.CreateUser; d.LastModifyDate = facilityStockMaster.CreateDate; d.LastModifyUser = facilityStockMaster.CreateUser; facilityStockDetailMgr.CreateFacilityStockDetail(d); } } #endregion } public void ConfirmStockTakeDetail(IList<int> stockTakeDetailList) { foreach (int id in stockTakeDetailList) { FacilityStockDetail d = this.FindById<FacilityStockDetail>(id); d.Qty = d.InvQty; d.DiffQty = 0; //d.LastModifyDate = DateTime.Now; //d.LastModifyUser = this.Update(d); } } public IList<FacilityStockDetail> GetUnConfirmedStockDetailList(string stNo) { DetachedCriteria criteria = DetachedCriteria.For(typeof(FacilityStockDetail)); criteria.Add(Expression.Eq("StNo",stNo)); criteria.Add(Expression.Gt("DiffQty", Decimal.Zero)); return criteriaMgrE.FindAll<FacilityStockDetail>(criteria); } #endregion Customized Methods } } #region Extend Class namespace com.Sconit.Facility.Service.Ext.Impl { [Transactional] public partial class FacilityStockMasterMgrE : com.Sconit.Facility.Service.Impl.FacilityStockMasterMgr, IFacilityStockMasterMgrE { } } #endregion Extend Class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shipping { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to Package Express. Please follow the instructions below."); Console.WriteLine("Please enter the package weight:"); Decimal pkgWeight = Convert.ToDecimal(Console.ReadLine()); if (pkgWeight > 50) { Console.WriteLine("Package too heavy to be shipped via Package Express. Have a good day."); Console.ReadLine(); System.Environment.Exit(0); } Console.ReadLine(); Console.WriteLine("Please enter the package width:"); Decimal pkgWidth = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("Please enter the package height:"); Decimal pkgHeight = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("Please enter the package length:"); Decimal pkgLength = Convert.ToDecimal(Console.ReadLine()); Decimal pkgDim = (pkgHeight + pkgLength + pkgWidth); if (pkgDim > 50) { Console.WriteLine("Package too big to be shipped via Package Express."); Console.ReadLine(); System.Environment.Exit(0); } Decimal totalCost = ((pkgDim * pkgWeight) / 100); Decimal Cost = Convert.ToDecimal(totalCost); Console.WriteLine("Your estimated total for shipping is: " + totalCost.ToString("C")); Console.ReadLine(); } } }
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 Entidades; using System.IO; namespace MainCorreo { public partial class Form1 : Form { private Correo correo; public Form1() { InitializeComponent(); correo = new Correo(); } /// <summary> /// Agrega un paquete al correo y va cambiando el estado. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAgregar_Click(object sender, EventArgs e) { if (txtBoxDireccion.Text != "" && maskedTextBoxTrackingID.Text != "") { Paquete paquete = new Paquete(txtBoxDireccion.Text, maskedTextBoxTrackingID.Text); paquete.InformaEstado += paq_InformaEstado; try { correo += paquete; ActulizarEstado(); } catch (TrackingIdRepetidoException exception) { MessageBox.Show(exception.Message); } } else { MessageBox.Show("Favor de Completar los 2 campos"); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnMostrarTodos_Click(object sender, EventArgs e) { this.MostrarInformacion<List<Paquete>>((IMostrar<List<Paquete>>)correo); } /// <summary> /// Actualiza los estados de los paquetes /// </summary> private void ActulizarEstado() { listBoxIngresado.Items.Clear(); listBoxEnViaje.Items.Clear(); listBoxEntregado.Items.Clear(); foreach (Paquete aux in correo.Paquetes) { switch (aux.Estado) { case Paquete.EEstado.Ingresado: listBoxIngresado.Items.Add(aux); break; case Paquete.EEstado.EnViaje: listBoxEnViaje.Items.Add(aux); break; case Paquete.EEstado.Entregado: listBoxEntregado.Items.Add(aux); break; } } } /// <summary> /// Carga el formulario /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { } /// <summary> /// Metodo que informa el estado del paquete /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void paq_InformaEstado(object sender, EventArgs e) { if (this.InvokeRequired) { Paquete.DelegadoEstado d = new Paquete.DelegadoEstado(paq_InformaEstado); this.Invoke(d, new object[] { sender, e }); } else { ActulizarEstado(); } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="elemento"></param> private void MostrarInformacion<T>(IMostrar<T> elemento) { if (elemento != null) { if (elemento is Correo) { richTextBoxMostrar.Text = elemento.MostrarDatos(elemento); } if (elemento is Paquete) { richTextBoxMostrar.Text = ((Paquete)elemento).ToString(); } } // creo archivo txt en el escritorio string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"salida.txt"); richTextBoxMostrar.Text.Guardar(filePath); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mostrarToolStripMenuItem_Click(Object sender, EventArgs e) { this.MostrarInformacion<Paquete>((IMostrar<Paquete>)listBoxEntregado.SelectedItem); } /// <summary> /// Cierra todos los hilos . /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_FormClosing(object sender, FormClosingEventArgs e) { correo.FinEntregas(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Strategy.Cars { public class CarContext { private ICar _car = null; public CarContext(ICar car) { _car = car; } public void ShowMaxSpeed() { Console.WriteLine("Max speed: {0}", _car.GetMaxSpeed()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CTF { class ExA : ExX { public ExA(string name) : base(name) { } public override string solve ( string question ) { return "-3"; } } }
using System; using System.Collections; using System.Collections.Generic; //TODO: Add other using statements here namespace com.Sconit.Entity.MRP.TRANS { public partial class RccpTransGroup { public string Model { get; set; } public Double ModelRate { get; set; } public int TotalAps { get; set; } public string ItemDescription { get; set; } public bool IsDown { get; set; } } }
using System; using System.Collections.Generic; using Fingo.Auth.DbAccess.Models; using Fingo.Auth.DbAccess.Repository.Interfaces.GenericInterfaces; namespace Fingo.Auth.DbAccess.Repository.Interfaces { public interface IProjectRepository : IGenericRepository<Project> { IEnumerable<User> GetAllUsersFromProject(int id); Project GetByIdWithAll(int id); Project GetByGuid(Guid guid); Project GetByIdWithCustomDatas(int projectId); Project GetByIdWithPolicies(int id); } }
using System; namespace TemplateMethod { class ConcreteClass : Abstract { public override void PrimitivOperation1() { Console.WriteLine("ConcreteClass1 . primitive1"); } public override void PrimitivOperation2() { Console.WriteLine("ConcreteClass1. primitive2"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ScaleGenerator.DAL; using ScaleGenerator.Model; namespace ScaleGenerator.BLL { public class ScaleController { MusicalNotesContainer mN = null; public ScaleController() { MusicalNotesContainer mN = new MusicalNotesContainer(); } public Scale getMajorScale(string key) { var scale = new Scale(); scale.First = key; scale.Second = GetYWholeStepsUpFromX(key, 1); scale.Third = GetYWholeStepsUpFromX(scale.Second, 1); scale.Fourth = GetYHalfStepsUpFromX(scale.Third, 1); scale.Fifth = GetYWholeStepsUpFromX(scale.Fourth, 1); scale.Sixth = GetYWholeStepsUpFromX(scale.Fifth, 1); scale.Seventh = GetYHalfStepsUpFromX(scale.Sixth, 1); return scale; } public Scale getMinorScale(string key) { var scale = new Scale(); scale.First = key; scale.Second = GetYWholeStepsUpFromX(key, 1); scale.Third = GetYHalfStepsUpFromX(scale.Second, 1); scale.Fourth = GetYWholeStepsUpFromX(scale.Third, 1); scale.Fifth = GetYWholeStepsUpFromX(scale.Fourth, 1); scale.Sixth = GetYHalfStepsUpFromX(scale.Fifth, 1); scale.Seventh = GetYWholeStepsUpFromX(scale.Sixth, 1); return scale; } private string GetYHalfStepsUpFromX(string x, int y) { string halfStepUp = mN.getOneHalfNoteUp(x); if (y == 1) { return halfStepUp; } else { y--; GetYHalfStepsUpFromX(halfStepUp, y); } throw new ArgumentOutOfRangeException("!(y<1)"); } private string GetYWholeStepsUpFromX(string x, int y) { string wholeStepUp = mN.getOneWholeNoteUp(x); if (y == 1) { return wholeStepUp; } else { y--; GetYWholeStepsUpFromX(wholeStepUp, y); } throw new ArgumentOutOfRangeException("!(y<1)"); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Cake : MonoBehaviour { [SerializeField] private int _profit; private CakeLayer[] _layers; private int _createdLayers; public int Profit => _profit; public bool Done => _createdLayers == _layers.Length; public event UnityAction CakeDone; public event UnityAction<float, float> LayerCookingProgress; private void Start() { _layers = GetComponentsInChildren<CakeLayer>(); _createdLayers = 0; } public void OnClick() { if (!Done) { if (TryBakeLayer()) { if (Done) { //Debug.Log("Cake done"); CakeDone?.Invoke(); } } } } private bool TryBakeLayer() { CakeLayer cakeLayer = _layers[_createdLayers]; cakeLayer.IncreaseCookingProgress(); LayerCookingProgress?.Invoke(cakeLayer.CookingProgress,cakeLayer.ClicksBeforeCooking); if (cakeLayer.TryCookLayer()) { _createdLayers++; return true; } else return false; } }
using System; using System.Collections.Generic; namespace EPI.Recursion { /// <summary> /// Enumerate the power set of an array with distinct elements /// </summary> /// <example> /// {A,B,C} results in { {}, {A}, {B}, {C}, {A,B}, {B,C}, {A,C} {A,B,C} } /// </example> public static class EnumeratePowerSet { public static List<List<char>> ListPowerSet(char[] array) { List<List<char>> result = new List<List<char>>(); result.Add(new List<char>()); PowerSetHelper(array, 0, result); return result; } private static void PowerSetHelper(char[] array, int index, List<List<char>> result) { // base case: if we've reached the end of the array if (index < array.Length) { int resultLength = result.Count; for (int i = 0; i < resultLength; i++) { List<char> newSubSet = new List<char>(result[i]); newSubSet.Add(array[index]); result.Add(newSubSet); } PowerSetHelper(array, index + 1, result); } } public static List<List<char>> ListPowerSetViaBitManipulation(char[] array) { if (array.Length > 64) { throw new ArgumentException("we can only support arrays upto length 64"); } List<List<char>> result = new List<List<char>>(); long length = Convert.ToInt64(Math.Pow(2, array.Length)); for (int i = 0; i < length; i++) { List<char> subSet = new List<char>(); int itemIndex = 0; int number = i; while (number > 0) { if ((number & 1) == 1) //LSB is 1 { subSet.Add(array[itemIndex]); } number >>= 1; itemIndex++; } result.Add(subSet); } return result; } } }
using System.Collections.Generic; namespace Wordbook.Data { public class Setting { public IList<string> Databases { get; set; } public string CurrentDatabase { get; set; } } }
using System; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace IzBone.Common { /** プロパティのラベル部分を指定の文字列に変更する属性 */ internal sealed class LabelAttribute : PropertyAttribute { readonly public string label; public LabelAttribute(string label) { this.label = label; } } #if UNITY_EDITOR /** * プロパティのラベル部分を指定の文字列に変更する */ [ CustomPropertyDrawer( typeof( LabelAttribute ) ) ] sealed class LabelDrawer : PropertyDrawer { public override void OnGUI(Rect rect, SerializedProperty prop, GUIContent lbl) { var attr = (LabelAttribute)attribute; EditorGUI.PropertyField( rect, prop, new GUIContent(attr.label), true ); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return EditorGUI.GetPropertyHeight(property, true); } } #endif }
using System; using System.Collections.Generic; namespace DemoApp.Entities { public partial class Degrees { public Degrees() { SchoolStaffDegrees = new HashSet<SchoolStaffDegrees>(); } public Guid Id { get; set; } public string Name { get; set; } public bool IsActive { get; set; } public virtual ICollection<SchoolStaffDegrees> SchoolStaffDegrees { get; set; } } }
using _7DRL_2021.Behaviors; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DRL_2021.Results { class ActionKeepMoving : IActionHasOrigin, ITickable { public bool Done => true; public ICurio Origin { get; set; } public int Decelerate; public bool Stab; public ActionKeepMoving(ICurio origin, int decelerate = -1, bool stab = false) { Origin = origin; Stab = stab; Decelerate = decelerate; } public void Run() { TryMove(); } public void Tick(SceneGame scene) { TryMove(); } private void TryMove() { var passive = Origin.GetActionHolder(ActionSlot.Passive); var player = Origin.GetBehavior<BehaviorPlayer>(); if (player != null && passive.Done) { var actions = new List<ActionWrapper>(); if (Decelerate < 0) actions.Add(new ActionChangeMomentum(Origin, Decelerate).InSlot(ActionSlot.Passive)); player.AddDefaultMove(actions); if (Stab) player.AddDefaultStab(actions); actions.Apply(Origin); } } } }
using System.Collections.Generic; using System.ServiceModel; using Phenix.Core.Security; namespace Phenix.Services.Contract.Wcf { [ServiceContract] public interface IDownloadFiles { [OperationContract] [UseNetDataContract] object GetDownloadFileInfos(string applicationName, IList<string> searchPatterns, UserIdentity identity); [OperationContract] [UseNetDataContract] object GetDownloadFile(string directoryName, string sourceDirectoryName, string fileName, int chunkNumber); } }
using DataLayer.Contracts; using DataLayer.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataLayer.Repositories { public class AccountRepository : IAccountRepository { private readonly RegAppContext _context; public AccountRepository(RegAppContext context) { _context = context; } public User GetUserById(int id) { return _context.Users.Find(id); } public User GetUserByUsername(string username) { return _context.Users.FirstOrDefault(u=>u.Username == username); } public void CreateUser(User user) { _context.Users.Add(user); _context.SaveChanges(); } public void EditUser(User user) { _context.Users.Update(user); _context.SaveChanges(); } } }
using UnityEngine; using System.Linq; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections.Generic; /// <summary> /// This class manages everything about Hand Pointer and Player Controls. /// /// Can be found attached in Canvas -> LHand and RHand /// </summary> public class HandPointer : MonoBehaviour { /// <summary> /// Enumeration to determine this is left or right hand pointer. /// </summary> public enum Hands { left = 0, right = 1 }; /// <summary> /// Knife Projectile Prefab for player to throw. /// </summary> [Tooltip("Knife Projectile Prefab for player to throw.\n" + "\n" + "Can be found in Assets -> Prefabs -> Projectile")] [SerializeField] private GameObject ProjectilePrefab; [Header ("Visualization")] [Space(5)] /// <summary> /// Open Hand Pointer Sprite. /// </summary> [Tooltip("Open Hand Pointer Sprite.\n" + "\n" + "Can be found in Assets -> UI")] [SerializeField] private Sprite defaultSprite; /// <summary> /// Closed Hand Pointer Sprite. /// </summary> [Tooltip("Closed Hand Pointer Sprite.\n" + "\n" + "Can be found in Assets -> UI")] [SerializeField] private Sprite pressSprite; [Space(5)] [Header("References to Menus")] [Space(5)] /// <summary> /// Food List Panel(A menu used to select the food to cook). /// </summary> [Tooltip("Food List Panel.\n" + "Can be found in Canvas")] [SerializeField] private GameObject foodListPanel; /// <summary> /// Ingredient List Panel(A menu used to select the ingredient to cook). /// </summary> [Tooltip("Ingredient List Panel.\n" + "Can be found in Canvas")] [SerializeField] private GameObject ingredientListPanel; [Space(5)] [Header("Hand Pointer Data")] [Space(5)] /// <summary> /// Enumeration to determine this is left or right hand pointer. /// </summary> [Tooltip("Enumeration to determine this is left or right hand pointer.")] public Hands currentHand; /// <summary> /// A float that determines the time to trigger the button. /// /// Default: 0.5 /// </summary> [Tooltip("A float that determines the time to trigger the button.\n" + "Default: 0.5")] [SerializeField] private float handTimer = 0.5f; /// <summary> /// A float that determines the time to throw knife. /// /// Defualt: 0.15 /// </summary> [Tooltip("A float that determines the time to throw knife.\n" + "Default: 0.15")] [SerializeField] private float shootingTimer = 0.15f; /// <summary> /// A float that determines how big the circle is, for the flower image to move according to. /// /// Default: 80 /// </summary> [Tooltip("A float that determines how big the circle is, for the flower image to move according to.\n" + "\n" + "Default: 80")] [SerializeField] private float radius = 80f; /// <summary> /// RectTransform Component of this GameObject. /// </summary> private RectTransform baseRect; /// <summary> /// Image Component of this GameObject. /// </summary> private Image background; /// <summary> /// A boolean that determine if this GameObject is active. /// </summary> private bool active = false; /// <summary> /// A boolean that determine if Player is performing Grab Gesture. /// </summary> private bool press = false; /// <summary> /// Main Camera in the game. /// </summary> private Camera cam; /// <summary> /// The button this GameObject is currently triggering. /// </summary> private Button selectedButton; /// <summary> /// Raycasting variable. /// </summary> private PointerEventData eventData = new PointerEventData(null); /// <summary> /// List of Raycast Results. /// </summary> private List<RaycastResult> raycastResults = new List<RaycastResult>(); /// <summary> /// A Transform that stores previously Highlighted GameObject. /// </summary> private Transform hitTransform; /// <summary> /// A FoodSO that stores Grabbed food. /// </summary> private FoodSO foodSO; /// <summary> /// A Cooking Appliance that stores a reference to which Appliance did this GameObject Grabbed from. /// </summary> private GameObject cookingAppliance; /// <summary> /// A float timer used to Trigger button by handTimer above /// </summary> private float handElapsedTime; /// <summary> /// A float timer used to Throw Knife by shootingTimer above /// </summary> private float shootingElapsedTime; /// <summary> /// An Image Component of Frame image of this GameObject. /// </summary> private Image timerImage; /// <summary> /// An Image Component of Flower image of this GameObject /// </summary> private Image timerImage2; /// <summary> /// A float that determines how big the circle is, for the flower image to move according to. /// /// Default: 0 /// </summary> private float angle = 0f; private void Awake() { baseRect = GetComponent<RectTransform>(); background = GetComponent<Image>(); timerImage = transform.GetChild(0).GetComponent<Image>(); timerImage2 = transform.GetChild(1).GetComponent<Image>(); } private void Start() { NuitrackManager.onHandsTrackerUpdate += NuitrackManager_onHandsTrackerUpdate; // Initialise this GameObject's sprite background.sprite = defaultSprite; cam = Player.Instance.transform.GetChild(0).GetComponent<Camera>(); } private void OnDestroy() { NuitrackManager.onHandsTrackerUpdate -= NuitrackManager_onHandsTrackerUpdate; } /// <summary> /// Drops currently held food, Change Sprite back to Hand, Reset references to cooking appliance and food. /// </summary> /// <param name="item"> The Item to Drop. </param> public void DropItem(GameObject item) { // Change Ingredient Sprite back to Hand Sprite background.sprite = defaultSprite; // If item is Null, do not do anything if (item == null) { return; } // Disable highlight on selected ingredient var o = item.GetComponentsInChildren<Outline>(); foreach (var oL in o) { oL.selected = false; oL.color = 0; } if (item == cookingAppliance) { // Reset Food cookingAppliance = null; foodSO = null; } } /// <summary> /// Highlight the passed in GameObject. /// </summary> /// <param name="parent"> THe GameObject to Highlight. </param> private void ShowOutline(GameObject parent) { // Enable highlight for hit object and its children var outlines = parent.GetComponentsInChildren<Outline>(); foreach (var outline in outlines) { outline.enabled = true; } } private void NuitrackManager_onHandsTrackerUpdate(nuitrack.HandTrackerData handTrackerData) { active = false; press = false; // Set Hand Pointer Data if can detect hand if (handTrackerData != null) { nuitrack.UserHands userHands = handTrackerData.GetUserHandsByID(CurrentUserTracker.CurrentUser); if (userHands != null) { if (currentHand == Hands.right && userHands.RightHand != null) { baseRect.anchoredPosition = new Vector2(userHands.RightHand.Value.X * Screen.width, -userHands.RightHand.Value.Y * Screen.height); active = true; press = userHands.RightHand.Value.Click; } else if (currentHand == Hands.left && userHands.LeftHand != null) { baseRect.anchoredPosition = new Vector2(userHands.LeftHand.Value.X * Screen.width, -userHands.LeftHand.Value.Y * Screen.height); active = true; press = userHands.LeftHand.Value.Click; } } } // Show Image background.enabled = active; if(active) { // Change back to Hand Sprite if not holding food if(!foodSO) { background.sprite = defaultSprite; } } else { // Do not do anything if not active return; } // Raycast from Screen Space to World Space var pointOnScreenPosition = (Vector2)cam.WorldToScreenPoint(transform.position); eventData.delta = pointOnScreenPosition - eventData.position; eventData.position = pointOnScreenPosition; raycastResults.Clear(); EventSystem.current.RaycastAll(eventData, raycastResults); Button newButton = null; for (int i = 0; i < raycastResults.Count && newButton == null; i++) newButton = raycastResults[i].gameObject.GetComponent<Button>(); if (newButton != selectedButton) { // When current selected button is not previous sselected button if (selectedButton != null) { selectedButton.OnPointerExit(eventData); // Reset Hand Timer, Frame and Flower handElapsedTime = 0f; timerImage.fillAmount = 0f; timerImage2.gameObject.SetActive(false); angle = -(timerImage.fillAmount * 360f + 90f) * Mathf.Deg2Rad; var offset = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * radius; timerImage2.transform.localPosition = new Vector3(offset.x, offset.y, 0f); // If previous selected button is Ingredient Panel, stop zooming if (selectedButton.GetComponent<IngredientPanel>()) selectedButton.GetComponent<IngredientPanel>().Zoomasaurus(false); // If any of the cooking appliance's hover hint is active, close it if (LevelManager.Instance.cookingAppliances.Any(x => x.hoverHint.activeSelf)) { foreach (var app in LevelManager.Instance.cookingAppliances) { if (app.hoverHint.activeSelf) { app.OpenCloseHint(false); app.OpenCloseCanvas(false); } } } } // Updates selected buttpon selectedButton = newButton; if (selectedButton != null) { selectedButton.OnPointerEnter(eventData); // If selected button is Ingredient Panel, start zooming if (selectedButton.GetComponent<IngredientPanel>()) selectedButton.GetComponent<IngredientPanel>().Zoomasaurus(true); } } else if (selectedButton != null) { // Runs timer handElapsedTime += Time.deltaTime; // Reduce fillAmount of Timer Filler Image(visual feedback) over waitTiming timerImage.fillAmount += (1f / handTimer) * Time.deltaTime; // Shows Flower Image and Move it in a circle timerImage2.gameObject.SetActive(true); angle = -(timerImage.fillAmount * 360f + 90f) * Mathf.Deg2Rad; var offset = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * radius; timerImage2.transform.localPosition = new Vector3(offset.x, offset.y, 0f); #region Highlight Code // If previously got hit other object if (hitTransform) { // Disable highlight for hit object and its children var o = hitTransform.GetComponentsInChildren<Outline>(); foreach (var oL in o) { if (!oL.selected) { oL.enabled = false; } } } // When the game is not paused, menus not active and selected button is not pause nor guide image if (PauseManager.Instance != null && !PauseManager.Instance.isPaused && !foodListPanel.activeSelf && !ingredientListPanel.activeSelf && selectedButton.name != "Pause" && selectedButton.name != "GuideImage") { // If selecting Cooking Appliance(Frying Pan, Pot 1, Pot 2) if (LevelManager.Instance.cookingAppliances.Any(x => x.gameObject.GetInstanceID() == selectedButton.transform.parent.parent.gameObject.GetInstanceID())) { var something = LevelManager.Instance.cookingAppliances.Where(x => x.gameObject.GetInstanceID() == selectedButton.transform.parent.parent.gameObject.GetInstanceID()).ToList(); if (something.Count != 1) return; var app = something[0].GetComponent<CookingAppliance>(); app.OpenCloseHint(true); app.OpenCloseCanvas(true); } // When Carrying food else if (foodSO) { // If selecting customer if (CustomerSpawner.Instance.customerDic.Any(x => x.Value.gameObject.GetInstanceID() == selectedButton.transform.parent.parent.gameObject.GetInstanceID())) { var something = CustomerSpawner.Instance.customerDic.Where(x => x.Value.gameObject.GetInstanceID() == selectedButton.transform.parent.parent.gameObject.GetInstanceID()).ToList(); if (something.Count != 1) return; var customer = something[0].Value.GetComponent<Customer>(); hitTransform = customer.transform; ShowOutline(customer.gameObject); } } } #endregion Highlight Code // When hand timer reach limit if (handElapsedTime >= handTimer) { // Reset Hand Timer, Frame, and Flower image handElapsedTime = 0f; timerImage.fillAmount = 0f; timerImage2.gameObject.SetActive(false); angle = -(timerImage.fillAmount * 360f + 90f) * Mathf.Deg2Rad; var offset1 = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * radius; timerImage2.transform.localPosition = new Vector3(offset1.x, offset1.y, 0f); selectedButton.OnPointerClick(eventData); // When the game is not paused, menus not active and selected button is not pause if (PauseManager.Instance != null && !PauseManager.Instance.isPaused && !foodListPanel.activeSelf && !ingredientListPanel.activeSelf && selectedButton.name != "Pause") { // Do not do anything if haven't finish guiding about intro and order if (selectedButton.name == "GuideImage") { if (!selectedButton.GetComponent<Guide>().finishedIntro || !selectedButton.GetComponent<Guide>().finishedOrder) { return; } } // If selecting Cooking Appliance(Frying Pan, Pot 1, Pot 2) else if (LevelManager.Instance.cookingAppliances.Any(x => x.gameObject.GetInstanceID() == selectedButton.transform.parent.parent.gameObject.GetInstanceID())) { var something = LevelManager.Instance.cookingAppliances.Where(x => x.gameObject.GetInstanceID() == selectedButton.transform.parent.parent.gameObject.GetInstanceID()).ToList(); if (something.Count != 1) return; var app = something[0].GetComponent<CookingAppliance>(); // Haven't done cooking food if (!app.isDone) { // Open up Food list to choose "food to cook" app.OpenCloseFoodMenu(true); // If the game is in Tutorial Scene and Guide Image is not active if (Menu_Manager.Instance.Tutorial_Mode && !Guide.Instance.gameObject.activeSelf) { // If haven't guide cook, start guiding if(!Guide.Instance.CheckIfGuidedCook()) { Guide.Instance.Show(); } } } // Done cooking food else { // If previously selected another cooking Appliance if (cookingAppliance) { DropItem(cookingAppliance); } // Select food and store it for serving customer cookingAppliance = app.gameObject; foodSO = app.TakeFood(); // Allow interactions with customer when holding food foreach(var pair in CustomerSpawner.Instance.customerDic) { pair.Value.AllowHover(true); } // Change Hand Sprite to Food Sprite background.sprite = foodSO.sprite; } } // When Carrying food else if (foodSO) { // If selecting customer if (CustomerSpawner.Instance.customerDic.Any(x => x.Value.gameObject.GetInstanceID() == selectedButton.transform.parent.parent.gameObject.GetInstanceID())) { var something = CustomerSpawner.Instance.customerDic.Where(x => x.Value.gameObject.GetInstanceID() == selectedButton.transform.parent.parent.gameObject.GetInstanceID()).ToList(); if (something.Count != 1) return; var customer = something[0].Value.GetComponent<Customer>(); // When customer is not fighting if (!customer.fighting) { // Serve Correct if (foodSO == customer.foodOrdered) { // Set customer's animations and sound effect customer.SetAnim(customer.idle, false); customer.SetAnim(customer.happy, true); customer.SetClip(Audio_Manager.Instance.audioDictionary["Coin Drop"]); // Served correct food, Add Score Score.Instance.Profit(customer.foodOrdered, customer.timerImage.fillAmount); // Customer leaves customer.Leave(); } // Serve Wrong else { // Set customer's animations customer.SetAnim(customer.idle, false); customer.SetAnim(customer.angry, true); // Served wrong food, Decrease Rate Score.Instance.rate -= 0.1f; customer.fighting = true; foreach (CookingAppliance appliance in LevelManager.Instance.cookingAppliances) if (!appliance.isDone) appliance.NewFood(); customer.player = Player.Instance.transform; // If the game is in Tutorial Scene if (Guide.Instance != null) { Guide.Instance.gameObject.SetActive(true); } } // Disable interactions with customer foreach(var pair in CustomerSpawner.Instance.customerDic) { pair.Value.AllowHover(false); } // Reset cooking Appliance status CookingAppliance app = cookingAppliance.GetComponent<CookingAppliance>(); app.NewFood(); // Drop food DropItem(cookingAppliance); } } } } } } else { // Disable highlight for every objects that have outline var ol = FindObjectsOfType<Outline>(); foreach (var oL in ol) { if (!oL.selected) { oL.enabled = false; } } } // If any customer is fighting with player if (CustomerSpawner.Instance.customerDic.Any(x => x.Value.fighting == true)) { // If the game is in Pause Status, do not do anything if (PauseManager.Instance != null && PauseManager.Instance.isPaused) { return; } var something = CustomerSpawner.Instance.customerDic.Where(x => x.Value.fighting == true).ToList(); foreach(var pair in something) { var customer = pair.Value.GetComponent<Customer>(); // Set player transform for customer to have a target to shoot at if (!customer.player) { customer.player = Player.Instance.transform; } } // If menus are inactive and player is performing Grab Gesture if (!foodListPanel.activeSelf && !ingredientListPanel.activeSelf && press) { // Runs timer shootingElapsedTime += Time.deltaTime; // When timer reach limit if (shootingElapsedTime >= shootingTimer) { // Reset timer shootingElapsedTime = 0f; // Shoot bullet towards hand icon GameObject Projectile = ObjectPool.Instance.GetPooledObject(ProjectilePrefab); // If projectile is not Null if (!Projectile) { return; } // Initialise position and direction of projectile Projectile.transform.position = transform.position; Projectile.GetComponent<Projectile>().dir = (transform.position - cam.transform.position).normalized; } } } } }
using System; using System.Collections.Generic; using GeoAPI.Extensions.Coverages; using GeoAPI.Extensions.Networks; using GisSharpBlog.NetTopologySuite.Geometries; using NetTopologySuite.Extensions.Coverages; using NetTopologySuite.Extensions.Networks; using NUnit.Framework; namespace NetTopologySuite.Extensions.Tests.Coverages { [TestFixture] public class NetworkCoverageHelperTest { private static Network GetNetwork() { var network = new Network(); var node1 = new Node("node1"); var node2 = new Node("node2"); var node3 = new Node("node3"); var geometry1 = new LineString(new[] { new Coordinate(0, 0), new Coordinate(0, 100) }); var geometry2 = new LineString(new[] { new Coordinate(0, 100), new Coordinate(0, 200) }); IBranch branch1 = new Branch(node1, node2, 100) { Geometry = geometry1, Name = "branch1" }; IBranch branch2 = new Branch(node2, node3, 100) { Geometry = geometry2, Name = "branch2" }; network.Nodes.Add(node1); network.Nodes.Add(node2); network.Nodes.Add(node3); network.Branches.Add(branch1); network.Branches.Add(branch2); return network; } [Test] public void UpdateSegmentsForRoute() { var network = GetNetwork(); NetworkCoverage route = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.RouteBetweenLocations }; // [---------------------------------------------------] // 5 60 route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 5.0)); route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 60.0)); // expected result // [5-----------------------60] Assert.AreEqual(1, route.Segments.Values.Count); Assert.AreEqual(5.0, route.Segments.Values[0].Offset); Assert.AreEqual(60.0, route.Segments.Values[0].EndOffset); } [Test] public void UpdateSegmentsForSegmentBetweenLocations() { var network = GetNetwork(); NetworkCoverage route = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; // [---------------------------------------------------] // 5 60 // 40 route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 5.0)); route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 60.0)); route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 40.0)); // expect location to be sorted uysing offset // [ 5-----40 // 40-----------------60 Assert.AreEqual(2, route.Segments.Values.Count); Assert.AreEqual(5.0, route.Segments.Values[0].Offset); Assert.AreEqual(40.0, route.Segments.Values[0].EndOffset); Assert.AreEqual(40.0, route.Segments.Values[1].Offset); Assert.AreEqual(60.0, route.Segments.Values[1].EndOffset); } [Test] public void UpdateSegmentsForSegmentBetweenLocationsReversed() { var network = GetNetwork(); NetworkCoverage route = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.SegmentBetweenLocations }; route.Locations.IsAutoSorted = false; route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 60.0)); route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 40.0)); route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 5.0)); // expect location not to be sorted // [ 60-----40 // 40-----------------5 //NetworkCoverageHelper.UpdateSegments(route); Assert.AreEqual(2, route.Segments.Values.Count); Assert.AreEqual(60.0, route.Segments.Values[0].Offset); Assert.AreEqual(40.0, route.Segments.Values[0].EndOffset); Assert.IsFalse(route.Segments.Values[0].DirectionIsPositive); Assert.AreEqual(40.0, route.Segments.Values[1].Offset); Assert.AreEqual(5.0, route.Segments.Values[1].EndOffset); Assert.IsFalse(route.Segments.Values[1].DirectionIsPositive); } [Test] public void UpdateSegmentsForSegmentBetweenLocationsReversedForRouteBetweenLocation() { var network = GetNetwork(); NetworkCoverage route = new NetworkCoverage { Network = network, SegmentGenerationMethod = SegmentGenerationMethod.RouteBetweenLocations }; route.Locations.IsAutoSorted = false; route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 60.0)); route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 40.0)); route.Locations.Values.Add(new NetworkLocation(network.Branches[0], 5.0)); // expect location not to be sorted // [ 60-----40 // 40-----------------5 //NetworkCoverageHelper.UpdateSegments(route); Assert.AreEqual(2, route.Segments.Values.Count); Assert.AreEqual(60.0, route.Segments.Values[0].Offset); Assert.AreEqual(40.0, route.Segments.Values[0].EndOffset); Assert.IsFalse(route.Segments.Values[0].DirectionIsPositive); Assert.AreEqual(40.0, route.Segments.Values[1].Offset); Assert.AreEqual(5.0, route.Segments.Values[1].EndOffset); Assert.IsFalse(route.Segments.Values[1].DirectionIsPositive); } [Test] [ExpectedException(typeof(ArgumentException))] public void ExtraTimeSliceFromNonTimeDependentNetworkCoverage() { var network = GetNetwork(); var networkCoverage = new NetworkCoverage("test", false) { Network = network }; networkCoverage[new NetworkLocation(network.Branches[0], 10.0)] = 10.0; networkCoverage[new NetworkLocation(network.Branches[0], 90.0)] = 90.0; networkCoverage[new NetworkLocation(network.Branches[1], 10.0)] = 110.0; networkCoverage[new NetworkLocation(network.Branches[1], 90.0)] = 190.0; // networkcoverage is not time dependent thus expect an argumentexception NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, DateTime.Now); } [Test] [ExpectedException(typeof(ArgumentException))] public void ExtractNonExistingTimeSliceFromNetworkCoverage() { var network = GetNetwork(); var networkCoverage = new NetworkCoverage("test", true) { Network = network }; DateTime dateTime = DateTime.Now; networkCoverage[dateTime, new NetworkLocation(network.Branches[0], 10.0)] = 10.0; networkCoverage[dateTime, new NetworkLocation(network.Branches[0], 90.0)] = 90.0; networkCoverage[dateTime, new NetworkLocation(network.Branches[1], 10.0)] = 110.0; networkCoverage[dateTime, new NetworkLocation(network.Branches[1], 90.0)] = 190.0; // networkcoverage is time dependent but queried time is not available. NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, dateTime + new TimeSpan(1, 0, 0)); } [Test] public void ExtractTimeSlice() { var network = GetNetwork(); var networkCoverage = new NetworkCoverage("test", true) { Network = network }; DateTime []dateTimes = new DateTime[10]; for (int i = 0; i < 10; i++) { dateTimes[i] = new DateTime(2000, 1, 1, 1, /* minute */i, 0); networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[0], 10.0)] = 10.0 + i; networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[0], 90.0)] = 90.0 + i; networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[1], 10.0)] = 110.0 + i; networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[1], 90.0)] = 190.0 + i; } INetworkCoverage slice = NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, new DateTime(2000, 1, 1, 1, /* minute */0, 0)); Assert.AreEqual(false, slice.IsTimeDependent); Assert.AreEqual(10.0 + 0, slice.Evaluate(new NetworkLocation(network.Branches[0], 10.0))); Assert.AreEqual(90.0 + 0, slice.Evaluate(new NetworkLocation(network.Branches[0], 90.0))); Assert.AreEqual(110.0 + 0, slice.Evaluate(new NetworkLocation(network.Branches[1], 10.0))); Assert.AreEqual(190.0 + 0, slice.Evaluate(new NetworkLocation(network.Branches[1], 90.0))); //slice = NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, new DateTime(2000, 1, 1, 1, /* minute */9, 0)); slice = new NetworkCoverage(networkCoverage.Name, false); NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, slice, new DateTime(2000, 1, 1, 1, /* minute */9, 0), true); Assert.AreEqual(false, slice.IsTimeDependent); Assert.AreEqual(10.0 + 9, slice.Evaluate(new NetworkLocation(network.Branches[0], 10.0))); Assert.AreEqual(90.0 + 9, slice.Evaluate(new NetworkLocation(network.Branches[0], 90.0))); Assert.AreEqual(110.0 + 9, slice.Evaluate(new NetworkLocation(network.Branches[1], 10.0))); Assert.AreEqual(190.0 + 9, slice.Evaluate(new NetworkLocation(network.Branches[1], 90.0))); // just repeat the previous action; refilling a coverage should also work NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, slice, new DateTime(2000, 1, 1, 1, /* minute */9, 0), true); Assert.AreEqual(false, slice.IsTimeDependent); Assert.AreEqual(10.0 + 9, slice.Evaluate(new NetworkLocation(network.Branches[0], 10.0))); Assert.AreEqual(90.0 + 9, slice.Evaluate(new NetworkLocation(network.Branches[0], 90.0))); Assert.AreEqual(110.0 + 9, slice.Evaluate(new NetworkLocation(network.Branches[1], 10.0))); Assert.AreEqual(190.0 + 9, slice.Evaluate(new NetworkLocation(network.Branches[1], 90.0))); } /// <summary> /// Extract values from coverage but use networklocation from the target coverage. /// </summary> [Test] [Ignore] public void ExtractTimeSliceUseLocationsFromTarget() { var network = GetNetwork(); var networkCoverage = new NetworkCoverage("test", true) { Network = network }; DateTime[] dateTimes = new DateTime[10]; for (int i = 0; i < 10; i++) { dateTimes[i] = new DateTime(2000, 1, 1, 1, /* minute */i, 0); networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[0], 10.0)] = 10.0 + i; networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[0], 50.0)] = 50.0 + i; networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[0], 90.0)] = 90.0 + i; networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[1], 10.0)] = 110.0 + i; networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[1], 50.0)] = 150.0 + i; networkCoverage[dateTimes[i], new NetworkLocation(network.Branches[1], 90.0)] = 190.0 + i; } var slice = new NetworkCoverage("slice", false) { Network = network }; Assert.AreEqual(false, slice.IsTimeDependent); slice[new NetworkLocation(network.Branches[0], 20.0)] = 2; slice[new NetworkLocation(network.Branches[0], 80.0)] = 8; slice[new NetworkLocation(network.Branches[1], 20.0)] = 12; slice[new NetworkLocation(network.Branches[1], 80.0)] = 18; NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, slice, new DateTime(2000, 1, 1, 1, /* minute */0, 0), false); // expected results at time step 0 are 20 80 120 180; this are interpolated values Assert.AreEqual(4, slice.Locations.Values.Count); Assert.AreEqual(10 /*20*/, slice.Evaluate(new NetworkLocation(network.Branches[0], 20.0)), 1.0e-6); Assert.AreEqual(50 /*80*/, slice.Evaluate(new NetworkLocation(network.Branches[0], 80.0)), 1.0e-6); Assert.AreEqual(90 /*120*/, slice.Evaluate(new NetworkLocation(network.Branches[1], 20.0)), 1.0e-6); Assert.AreEqual(110 /*180*/, slice.Evaluate(new NetworkLocation(network.Branches[1], 80.0)), 1.0e-6); NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, slice, new DateTime(2000, 1, 1, 1, /* minute */3, 0), false); // expected results at time step 3 are 23 83 123 183; this are interpolated values Assert.AreEqual(4, slice.Locations.Values.Count); Assert.AreEqual(13 /*23*/, slice.Evaluate(new NetworkLocation(network.Branches[0], 20.0)), 1.0e-6); Assert.AreEqual(53 /*83*/, slice.Evaluate(new NetworkLocation(network.Branches[0], 80.0)), 1.0e-6); Assert.AreEqual(93 /*123*/, slice.Evaluate(new NetworkLocation(network.Branches[1], 20.0)), 1.0e-6); Assert.AreEqual(113 /*183*/, slice.Evaluate(new NetworkLocation(network.Branches[1], 80.0)), 1.0e-6); } /// <summary> /// test if the nodatavalues - magic values - aree also copied from source to target. /// </summary> [Test] public void ExtractTimeSliceNoDataValues() { var network = GetNetwork(); var networkCoverage = new NetworkCoverage("test", true) { Network = network }; DateTime dateTime = DateTime.Now; networkCoverage[dateTime, new NetworkLocation(network.Branches[0], 10.0)] = 10.0; networkCoverage[dateTime, new NetworkLocation(network.Branches[0], 90.0)] = 90.0; networkCoverage[dateTime, new NetworkLocation(network.Branches[1], 10.0)] = 110.0; networkCoverage[dateTime, new NetworkLocation(network.Branches[1], 90.0)] = 190.0; networkCoverage.Components[0].NoDataValues.Add(16.0); INetworkCoverage slice = NetworkCoverageHelper.ExtractTimeSlice(networkCoverage, dateTime); Assert.AreEqual(networkCoverage.Components[0].NoDataValues.Count, slice.Components[0].NoDataValues.Count); for (int i = 0; i < slice.Components[0].NoDataValues.Count; i++) { Assert.AreEqual(networkCoverage.Components[0].NoDataValues[i], slice.Components[0].NoDataValues[i]); } } } }
using System; using System.Linq.Expressions; using cyrka.api.common.queries; using cyrka.api.domain.customers.commands; using cyrka.api.domain.customers.commands.change; using cyrka.api.domain.customers.commands.changeTitle; using cyrka.api.domain.customers.commands.register; using cyrka.api.domain.customers.commands.registerTitle; using cyrka.api.domain.customers.commands.removeTitle; using cyrka.api.domain.customers.commands.retire; namespace cyrka.api.domain.customers.queries { public class CustomerPlainRegistrator { public void RegisterIn(QueryEventProcessor processor) { processor.RegisterEventProcessing<CustomerRegistered, CustomerPlain>(UpdateByEventData, IdFilterByEventData); processor.RegisterEventProcessing<CustomerChanged, CustomerPlain>(UpdateByEventData, IdFilterByEventData); processor.RegisterEventProcessing<CustomerRetired, CustomerPlain>(UpdateByEventData, IdFilterByEventData); processor.RegisterEventProcessing<TitleRegistered, CustomerPlain>(UpdateByEventData, IdFilterByEventData); processor.RegisterEventProcessing<TitleChanged, CustomerPlain>(UpdateByEventData, IdFilterByEventData); processor.RegisterEventProcessing<TitleRemoved, CustomerPlain>(UpdateByEventData, IdFilterByEventData); } public Expression<Func<CustomerPlain, bool>> IdFilterByEventData(CustomerEventData eventData) { return c => c.Id == eventData.AggregateId; } public CustomerPlain UpdateByEventData(CustomerRegistered eventData, CustomerPlain source) { return new CustomerPlain { Id = eventData.AggregateId, Name = eventData.Name, Description = eventData.Description }; } public CustomerPlain UpdateByEventData(CustomerChanged eventData, CustomerPlain source) { return new CustomerPlain { Id = source.Id, Name = eventData.Name ?? source.Name, Description = eventData.Description ?? source.Description, Titles = source.Titles }; } public CustomerPlain UpdateByEventData(TitleRegistered eventData, CustomerPlain source) { source.Titles.Add(new TitlePlain { Id = eventData.TitleId, Name = eventData.Name, NumberOfSeries = eventData.NumberOfSeries, Description = eventData.Description }); return source; } public CustomerPlain UpdateByEventData(TitleChanged eventData, CustomerPlain source) { source.Titles.RemoveAll(t => t.Id == eventData.TitleId); source.Titles.Add(new TitlePlain { Id = eventData.TitleId, Name = eventData.Name, NumberOfSeries = eventData.NumberOfSeries, Description = eventData.Description }); return source; } public CustomerPlain UpdateByEventData(CustomerRetired eventData, CustomerPlain source) { return null; } public CustomerPlain UpdateByEventData(TitleRemoved eventData, CustomerPlain source) { source.Titles.RemoveAll(t => t.Id == eventData.TitleId); return source; } } }
using Allyn.Application.Dto.Manage.Basic; using Allyn.Application.Dto.Manage.Front; using Allyn.Application.Front; using Allyn.Infrastructure; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; namespace Allyn.MvcApp.Controllers.Manage { //会员组织 public class OrganizeController : Controller { // // GET: /Manage/Organize/ public ActionResult Index() { IOrganizeService service = ServiceLocator.Instance.GetService<IOrganizeService>(); var organizes = service.GetPrOrganizes(1, 20); ViewBag.Organizes = JsonConvert.SerializeObject(organizes); return View(); } public ActionResult Update(Guid id) { if (id == Guid.Empty) { throw new ArgumentException("参数无效", "id"); } IOrganizeService service = ServiceLocator.Instance.GetService<IOrganizeService>(); OrganizeEditDto model = service.GetOrganizeEditDto(id); ViewBag.Organize = JsonConvert.SerializeObject(model); return View("Edit"); } public ActionResult Add(Guid? id) { OrganizeAddDto model = new OrganizeAddDto(); ViewBag.Organize = JsonConvert.SerializeObject(model); IOrganizeService service = ServiceLocator.Instance.GetService<IOrganizeService>(); return View("Edit"); } [HttpPost, ValidateAntiForgeryToken] public JsonResult AddAjax(OrganizeAddDto model) { if (ModelState.IsValid) { IOrganizeService service = ServiceLocator.Instance.GetService<IOrganizeService>(); UserDto user = User.Identity.GetDetails<UserDto>(); model.Creater = user.Id; service.AddOrganize(model); return Json(new { status = true, urlReferrer = "/manage/organize" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } else { string msg = string.Empty; ModelState.Keys.ToList().ForEach(m => { ModelState[m].Errors.ToList().ForEach(s => { msg = s.ErrorMessage; return; }); if (msg.Length > 0) { return; } }); throw new Exception(msg); } } [HttpPost, ValidateAntiForgeryToken] public JsonResult UpdateAjax(OrganizeEditDto model) { if (ModelState.IsValid) { IOrganizeService service = ServiceLocator.Instance.GetService<IOrganizeService>(); UserDto user = User.Identity.GetDetails<UserDto>(); model.Modifier = user.Id; service.UpdateOrganize(model); return Json(new { status = true, urlReferrer = "/manage/organize" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } else { string msg = string.Empty; ModelState.Keys.ToList().ForEach(m => { ModelState[m].Errors.ToList().ForEach(s => { msg = s.ErrorMessage; return; }); if (msg.Length > 0) { return; } }); throw new Exception(msg); } } [HttpPost, ValidateAntiForgeryToken] public JsonResult DeleteAjax(List<Guid> keys) { if (keys != null && keys.Count > 0) { IOrganizeService service = ServiceLocator.Instance.GetService<IOrganizeService>(); service.DeleteOrganize(keys); return Json(new { status = true, urlReferrer = "/manage/organize" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } else { throw new ArgumentException("要删除的菜单标识不能为空!", "keys"); } } } }
using System.Collections; public class LoginInfo { internal string s_openId = "123456"; internal string s_openKey = "openkey_openkey_"; internal string s_token = null; internal ulong s_accountId = 0; internal ulong s_roleId = 0; }; public class RoleInfo { public int createTime; // 帐号创建时间 public int currentExp; // 当前经验值 public int currentGold; // 当前金币数量 public int currentDiamond; // 当前钻石数量 public int currentPower; // 当前体力值 public int powerCountdownTime; // 体力恢复倒计时(上次开始倒计时时刻) //public EAnimal currentAnimal; // 当前所带的宠物(宠物代表技能) }
namespace TheMapToScrum.Back.DTO { public class DeveloperDTO : BaseEntityDTO { public string LastName { get; set; } public string FirstName { get; set; } } }
using System; using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201304041656)] public class AddCareerFlags : Migration { public override void Down() { Delete.Column("Defected").FromTable("PRF_Career"); Delete.Column("Acting").FromTable("PRF_Career"); Delete.Column("FunctionID").FromTable("PRF_Career_AUD"); Delete.Column("Defected").FromTable("PRF_Career_AUD"); Delete.Column("Acting").FromTable("PRF_Career_AUD"); } public override void Up() { Alter.Table("PRF_Career").AddColumn("Defected").AsBoolean().NotNullable().WithDefaultValue(false); Alter.Table("PRF_Career").AddColumn("Acting").AsBoolean().NotNullable().WithDefaultValue(false); Alter.Table("PRF_Career_AUD").AddColumn("FunctionID").AsInt32().Nullable(); Alter.Table("PRF_Career_AUD").AddColumn("Defected").AsBoolean().Nullable(); Alter.Table("PRF_Career_AUD").AddColumn("Acting").AsBoolean().Nullable(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.UI.WebControls; using Sind.BLL; using Sind.Model; using Sind.Web.Publico.Helpers; namespace Sind.Web.Cadastros { public partial class ListaValor : System.Web.UI.Page { #region[ PROPRIEDADES ] private int IdVisao { get { return (int)ViewState["ID_VISAO"]; } set { ViewState["ID_VISAO"] = value; } } private IList<Indicador> listaIndicadores { get { return SessionHelper.ListIndicadores; } set { SessionHelper.ListIndicadores = value; } } private Usuario usuarioLogado { get { return SessionHelper.UsuarioLogado; } set { SessionHelper.UsuarioLogado = value; } } #endregion #region [ Eventos ] protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) CarregarPrimeiroAcesso(); txtMesAno.Focus(); } catch (Exception ex) { ExceptionHelper.PresentationErrorTreatment(ex); } } protected void btnFiltrar_Click(object sender, EventArgs e) { FiltrarGrid(); } protected void tabMenu_MenuItemClick(object sender, MenuEventArgs e) { this.IdVisao = Convert.ToInt32(e.Item.Value); CarregarGrid(); } #endregion #region [ Métodos ] private void CarregarPrimeiroAcesso() { CarregarComboFiliais(); CarregarComboTipobase(); } private void CarregarComboFiliais() { var listaFiliais = new ManterFilial().FindByUsuario(usuarioLogado); ddlFiliais.DataSource = listaFiliais.OrderBy(l => l.Nome); ddlFiliais.DataTextField = "Nome"; ddlFiliais.DataValueField = "Id"; ddlFiliais.DataBind(); ddlFiliais.Items.Insert(0, new ListItem("Selecione", "")); } private void CarregarComboTipobase() { ddlTipoBase.Items.Clear(); ddlTipoBase.Items.Insert(0, new ListItem("Realizado", "1")); if (usuarioLogado.Perfil == PerfilEnum.GestorSede) { ddlTipoBase.Items.Insert(1, new ListItem("Orçado", "2")); ddlTipoBase.Items.Insert(2, new ListItem("Revisão 1", "3")); ddlTipoBase.Items.Insert(3, new ListItem("Revisão 2", "4")); ddlTipoBase.Items.Insert(4, new ListItem("Revisão 3", "5")); } } private void FiltrarGrid() { CarregarAbasVisoes(); CarregarGrid(); } private void CarregarAbasVisoes() { var visoesUsuario = usuarioLogado.GrupoVisao.Visoes .Where(i => i.Ativo) .OrderBy(i => i.Nome); tabVisoes.Items.Clear(); foreach (Visao visao in visoesUsuario) { tabVisoes.Items.Add(new MenuItem(visao.Nome, visao.Id.ToString())); } this.IdVisao = Convert.ToInt32(tabVisoes.Items[0].Value); } private void CarregarGrid() { var manterVisao = new ManterVisao(); Visao visaoAtual = manterVisao.FindById(this.IdVisao); this.listaIndicadores = visaoAtual.Indicadores .OrderBy(i => i.Nome) .Where(i => i.Visivel).ToList(); var genericList = (listaIndicadores).Select(indicador => new { indicador.TipoCalculo, indicador.Id, indicador.Nome, indicador.UnidadeMedida, Valor = obterValorMovimentacao(indicador) }); gridValores.DataSource = genericList; gridValores.DataBind(); } private double obterValorMovimentacao(Indicador indicador) { Movimentacao movimentacao = new Movimentacao(); movimentacao.Indicador = indicador; movimentacao.DataMovimentacao = Convert.ToDateTime(txtMesAno.Text); movimentacao.Usuario = usuarioLogado; movimentacao.Filial = new ManterFilial().FindById(Convert.ToInt32(ddlFiliais.SelectedValue)); //var valor = new MovimentacaoController( // movimentacao.Indicador, // movimentacao.DataMovimentacao, // movimentacao.Usuario, // movimentacao.Filial // ).ObterMovimentacao().Valor; return 0; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FichaTecnica.Dominio.Repositorio { public interface IComentarioRepositorio { Comentario BuscarPorId(int id); List<Comentario> BuscarComentariosPorMembro(int id); int Criar(Comentario comentario); int AtualizarComentario(Comentario comentario); } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.MonoHooks.Editor { /// <summary> /// Event property drawer of type `CollisionGameObject`. Inherits from `AtomDrawer&lt;CollisionGameObjectEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(CollisionGameObjectEvent))] public class CollisionGameObjectEventDrawer : AtomDrawer<CollisionGameObjectEvent> { } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using GrubTime.Models; using Microsoft.Extensions.Options; using System.Net; using System.IO; using System.Text; using Newtonsoft.Json; namespace GrubTime.Controllers { /// <summary> /// Directions to your restaurant of liking from given coordinates /// </summary> [Produces("application/json")] [Route("api/Directions")] public class DirectionsController : Controller { readonly private Google _google; /// <summary> /// Google API query to navigate to your chosen restaurant /// </summary> /// <param name="optionsAccessor"></param> public DirectionsController(IOptions<Google> optionsAccessor) { _google = optionsAccessor.Value; } /// <summary> /// Directions to the restaurant from given coordinates /// </summary> /// <param name="location"></param> /// <param name="placeId"></param> /// <returns></returns> [HttpGet] public async Task<object> DirectionsAsync(string location, string placeId) { var DirectionApiUrl = string.Format(_google.Directions, location, placeId); HttpWebRequest query = (HttpWebRequest)WebRequest.Create(DirectionApiUrl); WebResponse response = await query.GetResponseAsync(); var raw = String.Empty; using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8, true, 1024, true)) { raw = reader.ReadToEnd(); } var allresults = JsonConvert.DeserializeObject<DirectionsRootObject>(raw); return allresults; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using HealthVault.Sample.Xamarin.Core.Models; using HealthVault.Sample.Xamarin.Core.Services; using Microsoft.HealthVault.Clients; using Microsoft.HealthVault.Connection; using Microsoft.HealthVault.ItemTypes; using Microsoft.HealthVault.Record; using Microsoft.HealthVault.Thing; using NodaTime.Extensions; using Xamarin.Forms; namespace HealthVault.Sample.Xamarin.Core.ViewModels { public class ProfileViewModel : ViewModel { private readonly IHealthVaultConnection _connection; private BasicV2 _basicInformation; private Personal _personalInformation; private IThingClient _thingClient; private Guid _recordId; public ProfileViewModel( IHealthVaultConnection connection, INavigationService navigationService) : base(navigationService) { _connection = connection; SaveCommand = new Command(async () => await SaveProfileAsync()); Genders = new List<string> { StringResource.Gender_Male, StringResource.Gender_Female, }; LoadState = LoadState.Loading; } public ICommand SaveCommand { get; } private ImageSource _imageSource; public ImageSource ImageSource { get { return _imageSource; } set { _imageSource = value; OnPropertyChanged(); } } private string _firstName; public string FirstName { get { return _firstName; } set { _firstName = value; OnPropertyChanged(); } } private string _lastName; public string LastName { get { return _lastName; } set { _lastName = value; OnPropertyChanged(); } } private DateTime _birthDate; public DateTime BirthDate { get { return _birthDate; } set { _birthDate = value; OnPropertyChanged(); } } public List<string> Genders { get; } private int _genderIndex; public int GenderIndex { get { return _genderIndex; } set { _genderIndex = value; OnPropertyChanged(); } } public override async Task OnNavigateToAsync() { await LoadAsync(async () => { var person = await _connection.GetPersonInfoAsync(); _thingClient = _connection.CreateThingClient(); HealthRecordInfo record = person.SelectedRecord; _recordId = record.Id; _basicInformation = (await _thingClient.GetThingsAsync<BasicV2>(_recordId)).FirstOrDefault(); _personalInformation = (await _thingClient.GetThingsAsync<Personal>(_recordId)).FirstOrDefault(); ImageSource profileImageSource = await GetImageAsync(); if (_personalInformation.BirthDate != null) { BirthDate = _personalInformation.BirthDate.ToLocalDateTime().ToDateTimeUnspecified(); } else { BirthDate = DateTime.Now; } FirstName = _personalInformation.Name?.First ?? string.Empty; LastName = _personalInformation.Name?.Last ?? string.Empty; GenderIndex = _basicInformation.Gender != null && _basicInformation.Gender.Value == Gender.Female ? 1 : 0; ImageSource = profileImageSource; await base.OnNavigateToAsync(); }); } private async Task<ImageSource> GetImageAsync() { var query = new ThingQuery(PersonalImage.TypeId) { View = { Sections = ThingSections.Xml | ThingSections.BlobPayload | ThingSections.Signature } }; var things = await _thingClient.GetThingsAsync(_recordId, query); IThing firstThing = things?.FirstOrDefault(); if (firstThing == null) { return null; } PersonalImage image = (PersonalImage)firstThing; return ImageSource.FromStream(() => image.ReadImage()); } private async Task SaveProfileAsync() { LoadState = LoadState.Loading; try { // Name property could be null. Construct it if we need to. if (_personalInformation.Name == null && (!string.IsNullOrEmpty(FirstName) || !string.IsNullOrEmpty(LastName))) { _personalInformation.Name = new Name(); } if (_personalInformation.Name != null) { // Only set first and last name if we have it if (!string.IsNullOrEmpty(FirstName)) { _personalInformation.Name.First = FirstName; } if (!string.IsNullOrEmpty(LastName)) { _personalInformation.Name.Last = LastName; } } _basicInformation.BirthYear = BirthDate.Year; _basicInformation.Gender = GenderIndex == 0 ? Gender.Male : Gender.Female; _personalInformation.BirthDate = new HealthServiceDateTime(BirthDate.ToLocalDateTime()); await _thingClient.UpdateThingsAsync(_recordId, new List<IThing> { _basicInformation, _personalInformation }); await NavigationService.NavigateBackAsync(); } catch (Exception exception) { await DisplayAlertAsync(StringResource.ErrorDialogTitle, exception.ToString()); } finally { LoadState = LoadState.Loaded; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public delegate Vector2 DetermineDesiredPositionDelegate(); public delegate Vector2 MoveTowardDesiredPosition(Vector2 desiredPosition);
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using TestProject_Aarif.BusinessLayer; using TestProject_Aarif.CustomAttributes; using TestProject_Aarif.Models; namespace TestProject_Aarif.Controllers { public class EmployeeController : ApiController { private readonly PayslipService _payslip; private const int FINENCIAL_YEAR = 2018; public EmployeeController() { this._payslip = new PayslipService(FINENCIAL_YEAR); } [HttpPost] [ValidateModel] public HttpResponseMessage Post([FromBody] EmployeeModel empModel) { try { if (ModelState.IsValid) { var result = this._payslip.GetPayslip(empModel); return Request.CreateResponse(HttpStatusCode.OK, result); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InterfaceTest : InheritanceT, ITest { //overwrittent function for inheritated function from InheritanceTest class, changing what is debugged. //can be used in AI building, where all AI have a base function to run off of, but can be overwritten // to do other things when that function is activated. public override void Test1() { Debug.Log("Test 1: InterfaceTest activated: CHILD FUNCTION"); } //running the base class of the inheritatenceTest function Test2(); public override void Test2() { base.Test2(); } public void Test3() { Debug.Log("Interface function: Test3 activated."); } public void Test4() { Debug.Log("Interface function: Test4 activated."); } } // Inheritance abstract class that InterfaceTest will inherit from. // Using virtuals allows base parent functions to run, but also allows children to override them. // functions inside of the parents Class are referred to as base functions, as they run normal if you don't // change anything in them. public abstract class InheritanceT { public virtual void Test1() { Debug.Log("Test 1: Inheritance activated, PARENT FUNCTION"); } public virtual void Test2() { Debug.Log("Test 2: Inheritance activated, PARENT FUNCTION"); } } //Interface public interface ITest { void Test3(); void Test4(); }
namespace TransactionRegistry.Core { using System.Collections.Concurrent; using System.Collections.Generic; using TransactionRegistry.Core.Models; using System.Threading; public class Registry { private readonly ConcurrentDictionary<string, Data> story = new ConcurrentDictionary<string, Data>(); public void Save(string serviceType, ServiceState serviceState) { var storyService = GetServiceStory(serviceType); var newTransactionNumber = UpdateDeviceTransactionNumber(storyService, serviceState); if (newTransactionNumber.ProcessedTransactionNumber == serviceState.ProcessedTransactionNumber) { UpdateSearchList(storyService, serviceState); } } public IEnumerable<ServiceState> Find(string serviceType, ulong transactionNumberFrom) { if (!story.ContainsKey(serviceType)) { return new ServiceState[0]; } var savedList = Interlocked.CompareExchange(ref story[serviceType].List, null, null); var list = savedList.GetViewBetween( new ServiceState(null, transactionNumberFrom), new ServiceState(null, ulong.MaxValue)); return list; } private Data GetServiceStory(string serviceType) { return story.GetOrAdd( serviceType, new Data { Key = new ConcurrentDictionary<string, ServiceState>(), List = new SortedSet<ServiceState>() }); } private ServiceState UpdateDeviceTransactionNumber(Data serviceStory, ServiceState serviceState) { return serviceStory.Key.AddOrUpdate( serviceState.Id, serviceState, (key, value) => value.ProcessedTransactionNumber > serviceState.ProcessedTransactionNumber ? value : serviceState); } private void UpdateSearchList(Data serviceStory, ServiceState serviceState) { SortedSet<ServiceState> savedList, newList; do { savedList = Interlocked.CompareExchange(ref serviceStory.List, null, null); newList = new SortedSet<ServiceState>(serviceStory.Key.Values, new ServiceStateComparer()); if (IsDeviceTransactionNumberInvalidate(serviceStory, serviceState)) { break; } } while (Interlocked.CompareExchange(ref serviceStory.List, newList, savedList) != savedList); } private bool IsDeviceTransactionNumberInvalidate(Data serviceStory, ServiceState serviceState) { var currentServiceState = serviceStory.Key.GetOrAdd(serviceState.Id, serviceState); return currentServiceState.ProcessedTransactionNumber > serviceState.ProcessedTransactionNumber; } } }
using MyMovies.Domain.Enums; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MyMovies.Domain.Entities { public class Tag : Entity { [Required] [ForeignKey("Movie")] public Guid MovieId { get; set; } public string TagText { get; set; } public AccessLevel AccessLevel { get; set; } public Language Language { get; set; } } }
using System; class ControlNumber { static void Main() { int n = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); int control = int.Parse(Console.ReadLine()); int sum = 0; int moves = 0; for (int i = 1; i <= n; i++) { for (int k = m; k >= 1; k--) { sum += i * 2 + k * 3; moves++; if (sum >= control) { Console.WriteLine(moves + " moves"); Console.WriteLine("Score: {0} >= {1}", sum, control); return; } } } Console.WriteLine(moves + " moves"); } }
using lsc.Dal; using lsc.Model; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace lsc.Bll { /// <summary> /// 工作计划相关操作 /// </summary> public class WorkPlanBll { public async Task<int> AddAsync(WorkPlan workPlan) { return await WorkPlanDal.Ins.AddAsync(workPlan); } public async Task DelAsync(WorkPlan workPlan) { await WorkPlanDal.Ins.DelAsync(workPlan); } public async Task UpdateAsync(WorkPlan workPlan) { await WorkPlanDal.Ins.UpdateAsync(workPlan); } public async Task<WorkPlan> GetAsync(int id) { return await WorkPlanDal.Ins.GetAsync(id); } public async Task<Tuple<List<WorkPlan>, long>> TupleAsync(int userid, int pageIndex, int pageSize) { return await WorkPlanDal.Ins.TupleAsync(userid,pageIndex,pageSize); } /// <summary> /// 获取最近五天未完成的计划 /// </summary> /// <param name="userid"></param> /// <returns></returns> public async Task<List<WorkPlan>> ListAsync(int userid) { return await WorkPlanDal.Ins.ListAsync(userid); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using KartObjects; using KartLib; namespace KartSystem { public partial class UserRoleEditor : XBaseDictionaryEditor { public UserRoleEditor() { InitializeComponent(); InitView(); } public UserRoleEditor(UserRole role, IList<UserRoleRight> rights) { InitializeComponent(); _editableRole = role; _rights = rights ?? new List<UserRoleRight>(); InitView(); } private UserRole _editableRole; private IList<UserRoleRight> _rights; private Dictionary<UserRoleRight, bool> _changedRights = new Dictionary<UserRoleRight, bool>(); public override void InitView() { textBox1.Text = _editableRole.Name; userRoleRightBindingSource.DataSource = _rights; //Созданные правила IList<SimpleNamedEntity> objectTypes = EnumExt.ToList(typeof(ObjectType)); repositoryItemLookUpEdit1.DataSource = objectTypes; //Правила из класса //Собираем разницу двух списков, на выходе правила, которых нету в ролях IList<SimpleNamedEntity> newlist = (from o in objectTypes where !(_rights.Any(q => q.ObjType == o.Id)) select o).ToList(); if (newlist.Count > 0) { if (_editableRole.Rights == null) _editableRole.Rights = new List<UserRoleRight>(); foreach (SimpleNamedEntity s in newlist) { UserRoleRight urr = new UserRoleRight() { IdRole = _editableRole.Id, ObjType = s.Id }; Saver.SaveToDb<UserRoleRight>(urr); _editableRole.Rights.Add(urr); } userRoleRightBindingSource.DataSource = _editableRole.Rights; } _changedRights.Clear(); } protected override bool CheckForValidation() { if (gvUserRoleRight.EditingValueModified) { gvUserRoleRight.SetFocusedValue(gvUserRoleRight.EditingValue); } bool result = gvUserRoleRight.ValidateEditor() && gvUserRoleRight.UpdateCurrentRow(); if (string.IsNullOrWhiteSpace(textBox1.Text)) { NotValidDataMessage = "Не задано наименование роли."; return false; } return result; } protected override void SaveData() { _editableRole.Name = textBox1.Text; _editableRole.Rights = ReferencePresenter.UpdateChildDBEntities<UserRoleRight>(_changedRights, "IdRole=" + _editableRole.Id); Saver.SaveToDb<UserRole>(_editableRole); } private void userRoleRightBindingSource_AddingNew(object sender, AddingNewEventArgs e) { UserRoleRight newRR = new UserRoleRight(); newRR.IdRole = _editableRole.Id; _changedRights.Add(newRR, true); e.NewObject = newRR; } private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e) { if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Remove) { UserRoleRight urr = userRoleRightBindingSource.Current as UserRoleRight; if (_changedRights.ContainsKey(urr)) { _changedRights[urr] = false; } else { _changedRights.Add(urr, false); } } } private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e) { UserRoleRight uRR = e.Row as UserRoleRight; if (!_changedRights.ContainsKey(uRR)) { _changedRights.Add(uRR, true); } e.Valid = true; } private void gridView1_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e) { if (gvUserRoleRight.FocusedColumn.Name == "colObjType") { long idObjType = (long)e.Value; if (_changedRights.Keys.FirstOrDefault(or => { return or.ObjType == idObjType; }) != null) { e.ErrorText = "Для объектов этого типа ограничения уже заданы"; e.Valid = false; } } } } }
using System.Collections.Generic; using AudioText.DAL; using System.Linq; namespace AudioText.Models.ViewModels { public class ViewCartViewModel { public ShoppingCartModels cart { get; private set; } public List<InventoryItem> otherItemsToBuy { get; private set; } public ViewCartViewModel(ShoppingCartModels cart) { RepositoryManager manager = new RepositoryManager(); this.cart = cart; this.otherItemsToBuy = manager.InventoryRepository.Get().Take(3).ToList(); } } }
using BugTracker.Entities; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugTracker.BusinessLayer { class ConsultarStockController { List<Stock> stock = new List<Stock>(); DBHelper dbContext = DBHelper.GetDBHelper(); public ConsultarStockController() { DataTable tablaProducto = dbContext.ConsultaSQL("select * from Stock"); foreach (DataRow row in tablaProducto.Rows) { int codProd = int.Parse(row["codProducto"].ToString()); int cantActual = int.Parse(row["cantActual"].ToString()); int cantMin = int.Parse(row["cantMin"].ToString()); Stock s = new Stock(codProd, cantActual, cantMin); stock.Add(s); } } public int consultarStockActualDelProducto(Producto p) { Stock stockProd = stock.ElementAt(p.getIdProducto()-1); return stockProd.cantidadDelProducto(); } } }
namespace BettingSystem.Watchdog { using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; public class Startup { public void ConfigureServices(IServiceCollection services) => services .AddHealthChecksUI() .AddInMemoryStorage(); public void Configure(IApplicationBuilder app, IWebHostEnvironment env) => app .UseRouting() .UseEndpoints(endpoints => endpoints .MapHealthChecksUI(healthChecks => healthChecks .UIPath = "/health")); } }
using System.Collections; using System.Collections.Generic; using GooglePlayGames; using GooglePlayGames.BasicApi; using TMPro; using UnityEngine; public class GameManager : MonoBehaviour { public static GameManager instance = null; public GameObject destroyParticles; public GameObject endGameCanvas; public List<ShipDefinition> ships; public List<TrailDefinition> trails; public int currentShip = 0; public int currentTrail; public List<GameObject> enableObjectsAtGameStart; public List<GameObject> objectsToEnableAtRestart; public GameObject menu; public float distance; public float totalDistance; public float credits; public float recordDistance; public float distanceMultiplier = 0.5f; bool counting = false; public ObstacleSpawner spawner; public List<Color> colors; public GameObject credit; public GameObject newRecordText; public GameObject unlockedText; public GameObject distanceTextInGame; int lastDistance; void Awake () { if (instance == null) instance = this; else if (instance != this) Destroy (gameObject); DontDestroyOnLoad (gameObject); PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder () .RequestIdToken () .Build (); PlayGamesPlatform.InitializeInstance (config); // recommended for debugging: PlayGamesPlatform.DebugLogEnabled = true; // Activate the Google Play Games platform PlayGamesPlatform.Activate (); StartCoroutine (LogInWithDelay (0.35f)); try { DataManager.LoadData (); } catch { DataManager.SaveData (); } try { DataManager.LoadDistanceAndCredits (); } catch { DataManager.SaveDistanceAndCredits (); } FindObjectOfType<UnlocksManager> ().CheckUnlocks (); } public static void SpawnDeathParticles (Vector3 position) { Instantiate (instance.destroyParticles, position, Quaternion.identity); } IEnumerator LogInWithDelay (float delay) { yield return new WaitForSeconds (delay); PlayGamesPlatform.Instance.Authenticate (FindObjectOfType<MenuUIController> ().LoggedUser); } public void EndGame () { counting = false; spawner.gameObject.SetActive (false); if (distance > recordDistance) { recordDistance = distance; newRecordText.SetActive (true); } else { newRecordText.SetActive (false); } endGameCanvas.SetActive (true); totalDistance += distance; DataManager.SaveDistanceAndCredits (); if (FindObjectOfType<UnlocksManager> ().CheckUnlocks ()) { unlockedText.SetActive (true); } else { unlockedText.SetActive (false); } } public void Restart () { lastDistance = 0; endGameCanvas.GetComponent<EndGameMenu> ().lastCredits = instance.credits; spawner.RestartSpawner (); distance = 0; endGameCanvas.SetActive (false); foreach (ObstacleLogic ol in FindObjectsOfType<ObstacleLogic> ()) { Destroy (ol.gameObject); } foreach (GameObject go in objectsToEnableAtRestart) { go.SetActive (true); } counting = true; } public void StartGame () { endGameCanvas.GetComponent<EndGameMenu> ().lastCredits = instance.credits; distance = 0; counting = true; foreach (GameObject go in enableObjectsAtGameStart) { go.SetActive (true); } } public void GoBackToMenu () { menu.SetActive (true); endGameCanvas.SetActive (false); foreach (GameObject go in enableObjectsAtGameStart) { go.SetActive (false); } } public void ShowDistanceText (int distanceToShow) { distanceTextInGame.GetComponentInChildren<TextMeshProUGUI> ().text = distanceToShow.ToString () + " m"; distanceTextInGame.SetActive (true); } private void Update () { if (counting) { distance += Time.deltaTime * distanceMultiplier; } if (lastDistance + 50 <= distance) { lastDistance += 50; ShowDistanceText (lastDistance); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfApplication1 { /// <summary> /// Interaction logic for Auction.xaml /// </summary> public partial class Auction : Window { public List<Player> Comp = new List<Player>(); public Int32 currentBet = 10; public Player fp; public Auction() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Int32 bid = 0; try { bid = Convert.ToInt32(NextBid.Text); } catch { MessageBox.Show("Ставка должна быть целым числом!"); } if (bid < 0) { MessageBox.Show("Ставку можно только повысить!"); } else { NextBid.Text = ""; currentBet += bid; Log.Items.Add(fp.name + " повышает цену до " + Convert.ToString(currentBet)); foreach (Player c in Comp) { if (c.budget < currentBet) { Log.Items.Add(c.name+ " заканчивает аукцион: мало средств"); var d = Comp.Count(); var s = "comp" + Convert.ToString(d); var b = (Rectangle)FindName(s); b.Visibility = Visibility.Hidden; c.isalive = false; } } Comp.RemoveAll(x => x.isalive == false); foreach (Player c in Comp) { var s = "comp" + Convert.ToString(Comp.IndexOf(c)+1); var b = (Rectangle)FindName(s); b.Fill = new SolidColorBrush(c.c); } if (Comp.Count<2) { var yyy = MainWindow.cdata.cells[MainWindow.cdata.cPlayer.position]; var gPlayer = MainWindow.cdata.players[fp.playerid]; yyy.prop.ownerplayer = gPlayer; gPlayer.budget -= currentBet; gPlayer.property.Add(yyy.prop); var str = "p" + Convert.ToString(yyy.y) + Convert.ToString(yyy.x) + "4"; Rectangle r = (Rectangle)MainWindow.cdata.wnd.Board.FindName(str); r.Fill = new SolidColorBrush(gPlayer.c); if (gPlayer.HasMono(yyy.card.color)) { gPlayer.mono.Add(yyy.card.color); }; MainWindow.cdata.wnd.MainLog.Items.Insert(0, gPlayer.name + " купил " + yyy.prop.name + " за " + currentBet + ". Оставшийся бюджет " + Convert.ToString(gPlayer.budget) + "."); Close(); } var ind = Comp.IndexOf(fp); if (ind+1 == Comp.Count) { fp = Comp.First(); } else { fp = Comp[Comp.IndexOf(fp) + 1]; } cComp.Fill = new SolidColorBrush(fp.c); var prt = (Image)FindName("portrait"); prt.Source = fp.face.Source; PInfo.Content = fp.name + ", " + Convert.ToString(fp.budget); } } private void Cancel(object sender, RoutedEventArgs e) { var c = Comp.Find(x=>x.playerid==fp.playerid); //MainWindow.cdata.wnd.Main Log.Items.Add(c.name + " выходит из аукциона по доброй воле"); var s = "comp" + Convert.ToString(Comp.Count());//IndexOf(c) + 1); var b = (Rectangle)FindName(s); b.Visibility = Visibility.Hidden; c.isalive = false; Comp.RemoveAll(x => x.isalive == false); foreach (Player comp in Comp) { s = "comp" + Convert.ToString(Comp.IndexOf(comp)+1); b = (Rectangle)FindName(s); b.Fill = new SolidColorBrush(comp.c); } var ind = Comp.IndexOf(fp); if (ind + 1 == Comp.Count) { fp = Comp.First(); } else { fp = Comp[Comp.IndexOf(fp) + 1]; } cComp.Fill = new SolidColorBrush(fp.c); var prt = (Image)FindName("portrait"); prt.Source = fp.face.Source; PInfo.Content = fp.name + ", " + Convert.ToString(fp.budget); if (Comp.Count < 2) { var yyy = MainWindow.cdata.cells[MainWindow.cdata.cPlayer.position]; var gPlayer = MainWindow.cdata.players[fp.playerid]; yyy.prop.ownerplayer = gPlayer; gPlayer.budget -= currentBet; gPlayer.property.Add(yyy.prop); var str = "p" + Convert.ToString(yyy.y) + Convert.ToString(yyy.x) + "4"; Rectangle r = (Rectangle)MainWindow.cdata.wnd.Board.FindName(str); r.Fill = new SolidColorBrush(gPlayer.c); if (gPlayer.HasMono(yyy.card.color)) { gPlayer.mono.Add(yyy.card.color); }; MainWindow.cdata.wnd.MainLog.Items.Insert(0, gPlayer.name + " купил " + yyy.prop.name + " за " + currentBet + ". Оставшийся бюджет " + Convert.ToString(gPlayer.budget) + "."); Close(); } } public void AU_Init() { Log.Items.Clear(); Comp.Clear(); currentBet = 10; foreach (Player p in MainWindow.cdata.players) { if (p == MainWindow.cdata.cPlayer) { Log.Items.Add(p.name + " , начальная ставка: 10"); } else { if (p.isalive && p.budget >= currentBet) Comp.Add(new Player(p.playerid,p.code,p.c,p.face) {name=p.name,budget=p.budget,isalive=true,mono=p.mono,property=p.property,position=p.position } ); } } if (Comp.Count == 0) { MainWindow.cdata.wnd.MainLog.Items.Insert(0, "Аукцион не состоялся: у игроков недостаточно средств"); Close(); } else { fp = Comp.First(); if (Comp.Count == 1) { var yyy = MainWindow.cdata.cells[MainWindow.cdata.cPlayer.position]; var gPlayer = MainWindow.cdata.players[fp.playerid]; yyy.prop.ownerplayer = gPlayer; gPlayer.budget -= currentBet; gPlayer.property.Add(yyy.prop); var str = "p" + Convert.ToString(yyy.y) + Convert.ToString(yyy.x) + "4"; Rectangle r = (Rectangle)MainWindow.cdata.wnd.Board.FindName(str); r.Fill = new SolidColorBrush(gPlayer.c); if (gPlayer.HasMono(yyy.card.color)) { gPlayer.mono.Add(yyy.card.color); }; MainWindow.cdata.wnd.MainLog.Items.Insert(0, "Аукцион не состоялся: только " + Comp.First().name + " имеет достаточно средств"); MainWindow.cdata.wnd.MainLog.Items.Insert(0, Comp.First().name + " купил " + yyy.prop.name + " за " + currentBet + ". Оставшийся бюджет " + Convert.ToString(gPlayer.budget) + "."); Close(); } foreach (Player c in Comp) { var s = "comp" + Convert.ToString(Comp.IndexOf(c) + 1); var v = (Rectangle)FindName(s); v.Fill = new SolidColorBrush(c.c); v.Visibility = Visibility.Visible; } cComp.Fill = new SolidColorBrush(fp.c); var prt = (Image)FindName("portrait"); prt.Source = fp.face.Source; PInfo.Content = fp.name + ", " + Convert.ToString(fp.budget); } } } }
using System; using System.Collections.Generic; using Alabo.Web.Mvc.ViewModel; namespace Alabo.Industry.Shop.Orders.ViewModels.OrderEdit { /// <summary> /// 发货 /// </summary> public class OrderEditDelivery : BaseViewModel { /// <summary> /// 订单Id /// </summary> public long OrderId { get; set; } /// <summary> /// 发货人员Id /// </summary> public long AdminUserId { get; set; } /// <summary> /// 快递公司guid /// </summary> public Guid ExpressGuid { get; set; } /// <summary> /// 物流单号 /// </summary> public string ExpressNumber { get; set; } /// <summary> /// 发货数量Json /// </summary> public string DeliveryProducts { get; set; } // 发货数量 public IList<OrderEditDeliveryProduct> DeliveryProductSkus { get; set; } } /// <summary> /// 发货数量 /// </summary> public class OrderEditDeliveryProduct { /// <summary> /// 商品SKu /// </summary> public long SkuId { get; set; } /// <summary> /// 发货数量 /// </summary> public long Count { get; set; } } }
using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201307231655)] public class FixCareerProcOrdering : Migration { public override void Down() { } public override void Up() { Execute.EmbeddedScript("201305151739_GetPersonProfile_CareerInformation.sql"); Execute.EmbeddedScript("201305151740_GetPersonProfile_CurrentPosition.sql"); } } }
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 Core.BIZ; using Core.DAL; namespace WinForm.Views { public partial class FrmDanhMucPhieuXuat : Form { public FrmDanhMucPhieuXuat() { InitializeComponent(); } private List<PhieuXuat> _DSPX; private List<DaiLy> _DSDLy; private void LoadPX() { _DSPX = PhieuXuatManager.getAll(); gdvXuat.DataSource = _DSPX; } private void LoadDaiLy() { _DSDLy = DaiLyManager.getAll(); cmbDaiLy.DataSource = _DSDLy; cmbDaiLy.DisplayMember = "TenDaiLy"; cmbDaiLy.ValueMember = "MaSoDaiLy"; } private void LoadPXChuaDuyet() { _DSPX = PhieuXuatManager.getUnaproved(); gdvXuat.DataSource = _DSPX; } private void FrmDanhMucPhieuXuat_Load(object sender, EventArgs e) { LoadDaiLy(); btDuyet.Enabled = false; btXoa.Enabled = false; } private void btLoadAll_Click(object sender, EventArgs e) { LoadPX(); } private void btChuaDuyet_Click(object sender, EventArgs e) { LoadPXChuaDuyet(); } private void gdvXuat_SelectionChanged(object sender, EventArgs e) { txbMaPhieuXuat.Text = gdvXuat.CurrentRow.Cells[0].Value.ToString(); cmbDaiLy.SelectedValue = int.Parse(gdvXuat.CurrentRow.Cells[1].Value.ToString()); txbNguoiNhan.Text = gdvXuat.CurrentRow.Cells[4].Value.ToString(); string day = gdvXuat.CurrentRow.Cells[3].Value.ToString(); DateTime thedate = DateTime.Parse(day); String dateString = thedate.ToString("yyyy/MM/dd"); day = dateString; char[] cut = day.ToCharArray(); string nam = ""; for (int i = 0; i < 4; i++) { nam += cut[i]; } string thang = ""; for (int i = 5; i < 7; i++) { thang += cut[i]; } string ngay = ""; for (int i = 8; i < 10; i++) { ngay += cut[i]; } dtpNgayXuat.Value = new DateTime(int.Parse(nam), int.Parse(thang), int.Parse(ngay)); lbTongTien.Text = gdvXuat.CurrentRow.Cells[5].Value.ToString(); int trangthai = int.Parse(gdvXuat.CurrentRow.Cells[6].Value.ToString()); if (trangthai == 1) { btDuyet.Text = "Đã duyệt"; btDuyet.Enabled = false; btXoa.Enabled = false; } if (trangthai == 0) { btDuyet.Text = "Duyệt phiếu xuất"; btDuyet.Enabled = true; btXoa.Enabled = true; } } private void btnThoat_Click(object sender, EventArgs e) { this.Close(); } private void btXoa_Click(object sender, EventArgs e) { if (!txbMaPhieuXuat.Text.Equals("")) { PhieuXuat pn = new PhieuXuat(); int x = int.Parse(txbMaPhieuXuat.Text.ToString()); var phieu = PhieuXuatManager.find(x); if (phieu.TrangThai != 1) { if (PhieuXuatManager.delete(phieu.MaSoPhieuXuat)) { MessageBox.Show("Đã xóa thành công"); LoadPX(); } else MessageBox.Show("Không xóa được"); } else MessageBox.Show("..."); } else MessageBox.Show("Chọn phiếu xuất cần xóa"); } private void btDuyet_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Bạn có muốn duyệt phiếu này", "Thông báo", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { if (!txbMaPhieuXuat.Text.Equals("")) { int maso = int.Parse(txbMaPhieuXuat.Text.ToString()); var phieu = PhieuXuatManager.find(maso); if (phieu != null) { var result = phieu.accept(); switch (result) { case PhieuXuat.AcceptStatus.Success: MessageBox.Show("Đã duyệt thành công"); LoadPX(); return; case PhieuXuat.AcceptStatus.Error: MessageBox.Show("Sách tồn không đủ để duyệt! Phiếu xuất yêu cầu được hủy!"); return; case PhieuXuat.AcceptStatus.Limited: MessageBox.Show("Tiền nợ đã vượt quá mức cho phép, vui lòng thanh toán trước khi đặt tiếp"); return; default: MessageBox.Show("Duyệt không thành công"); return; } } } else MessageBox.Show("Chưa chọn phiếu xuất cần duyệt"); } else if (dialogResult == DialogResult.No) { return; } } private void panelContainer_Paint(object sender, PaintEventArgs e) { } private void gdvXuat_CellContentClick(object sender, DataGridViewCellEventArgs e) { } } }
using DrivingSchool_Api; using Microsoft.EntityFrameworkCore; using Models.ViewModels; using Repository.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Repository.Implementations { public class BookingPackageRepository : IBookingPackageRepository { private readonly DrivingSchoolDbContext _db; private readonly IDapperBaseRepository _dapperBaseRepository; public BookingPackageRepository(DrivingSchoolDbContext db,IDapperBaseRepository dapperBaseRepository) { _db = db; _dapperBaseRepository = dapperBaseRepository; } public void Add(BookingPackage bookingPackage) { _db.BookingPackage.Add(bookingPackage); _db.SaveChanges(); } public void Delete(int? bookingPackageId) { var dbRecord = _db.BookingPackage.Find(bookingPackageId); _db.BookingPackage.Remove(dbRecord); _db.SaveChanges(); } public BookingPackage Find(int? bookingPackageId) { return _db.BookingPackage.Find(bookingPackageId); /// } public IQueryable<BookingPackage> GetAll() { return _db.BookingPackage.AsQueryable(); } public BookingPackage GetSingleRecord(int? bkPId) { var parameter = new { bkPId }; string qeury = "GetSinglePackage"; return _dapperBaseRepository.QuerySingl<BookingPackage>(qeury, parameter); } public IQueryable<BookingPackageVm> GetVmDetails(int? bookingTypeId) { var parameter = new { bookingTypeId }; string command = "PackagesView"; return _dapperBaseRepository.QueryWithParameter<BookingPackageVm>(command, parameter); } public void Update(BookingPackage bookingPackage) { _db.Entry(bookingPackage).State = EntityState.Modified; _db.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebsiteManagerPanel.Framework.Exceptions; namespace WebsiteManagerPanel.Framework.Exceptions { public class Argument { public static void CheckIfNull(object checkObject, string paramName) { if (checkObject == null) { throw new WorkflowException($"Parametre boş bırakılamaz. Parametre Adı: {paramName}"); } } public static void CheckIfNull(object checkObject, string paramName, string message) { if (checkObject == null) { throw new WorkflowException(message); } } public static void ThrowWorkflowException(string message) { throw new WorkflowException(message); } public static void CheckIfNullOrEmpty(string checkObject, string paramName) { if (string.IsNullOrEmpty(checkObject)) { throw new WorkflowException($"Parametre boş bırakılamaz. Parametre Adı: {paramName}"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chess { class Pawn : ChessPiece { public Pawn(bool pieceColor) : base(pieceColor) { variableDistance = false; if (color) { pieceImage = Chess.Properties.Resources.whitepawn; } else pieceImage = Chess.Properties.Resources.blackpawn; moveset = new List<int[]>(4); if (color) { moveset = new List<int[]>(4) { new int[] { -1, 0 }, new int[] { -2, 0 }, //attacking new int[] { -1, 1 }, new int[] { -1, -1 } }; } else { moveset = new List<int[]>(4) { new int[] { 1, 0 }, new int[] { 2, 0 }, //attacking new int[] { 1, 1 }, new int[] { 1, -1 } }; } } public override string ToString() { return "[P]"; } } }
using System; using AIMLbot.AIMLTagHandlers; using AIMLbot.Utils; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AIMLbot.UnitTest.TagTests { [TestClass] public class SizeTagTests { private ChatBot _chatBot; public static int Size = 16; private AIMLLoader _loader; private Size _tagHandler; [TestInitialize] public void Setup() { _chatBot = new ChatBot(); ChatBot.Size = 0; _loader = new AIMLLoader(); var path = $@"{Environment.CurrentDirectory}\AIML\Salutations.aiml"; _loader.LoadAIML(path); } [TestMethod] public void TestWithBadXml() { var testNode = StaticHelpers.GetNode("<soze/>"); _tagHandler = new Size(testNode); Assert.AreEqual("", _tagHandler.ProcessChange()); } [TestMethod] public void TestWithValidData() { var testNode = StaticHelpers.GetNode("<size/>"); _tagHandler = new Size(testNode); Assert.AreEqual(Convert.ToString(Size), _tagHandler.ProcessChange()); } } }
using BL; using DAL.Models; using MVVM_Core; using System; using System.Linq; using System.Windows.Input; namespace Main.ViewModels { public class DetailInfoViewModel : BasePageViewModel { private readonly IAutoListService listService; private readonly UserService userService; private readonly DeclarationService declarationService; public bool HasActiveOwn { get; set; } public bool HasActiveOther { get; set; } public bool HasActive { get; set; } public bool NoDeclarations => !HasActiveOther && !HasActiveOwn; public bool NeedAutorize { get; set; } public DetailInfoViewModel(PageService pageservice, BL.IAutoListService listService, UserService userService, DeclarationService declarationService) : base(pageservice) { this.listService = listService; this.userService = userService; this.declarationService = declarationService; Evac = listService.SelectedEvac; init(); } public bool IsOther { get; set; } public bool IsBorderVisible => NeedAutorize || HasActiveOther; private async void init() { Hours = (int)Math.Round((DateTime.Now - Evac.DateTimeEvac).TotalHours); Points = new string('.', 45); ParkingCost = Evac.Parking.CostByHour * Hours; HasActive = await declarationService.SetupEvac(Evac.Id); FullCost = declarationService.GetCost(); if (HasActive) { NeedAutorize = !userService.IsAutorized; if (userService.IsAutorized) { HasActiveOther = userService.CurrentUser.Id != declarationService.ProfileId; HasActiveOwn = !HasActiveOther; } } } protected override void Next(object param) { if (userService.IsAutorized) { pageservice.ChangePage<Pages.DeclarationPage>(PoolIndex, DisappearAndToSlideAnim.ToLeft); } else { pageservice.SetupNext<Pages.DeclarationPage>(PoolIndex, DisappearAndToSlideAnim.ToLeft); pageservice.ChangePage<Pages.ProfilePage>(PoolIndex, DisappearAndToSlideAnim.ToLeft); } //if (HasActive) //{ // pageservice.ChangePage<Pages.LoginPage>(PoolIndex, DisappearAndToSlideAnim.ToLeft); //} //else //{ // pageservice.ChangePage<Pages.DeclarationPage>(PoolIndex, DisappearAndToSlideAnim.ToLeft); //} } public string Points { get; set; } public override int PoolIndex => Rules.Pages.MainPool; public Evacuation Evac { get; } public Evacuation Evacuation { get; } public string EvacPlace { get; } public double ParkingCost { get; set; } public int FullCost { get; set; } public int Hours { get; set; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using GooglePlayGames; using GooglePlayGames.BasicApi; using GooglePlayGames.BasicApi.SavedGame; using System; public class MainMenuNavigation : MonoBehaviour { public AudioClip clicSound; public bool music =true; public bool sound = true; public GameObject SoundButton; public GameObject MusicButton; public GameObject Music; public GameObject Sound; public Sprite SoundOffSprite; public Sprite SoundOnSprite; public Sprite MusicOffSprite; public Sprite MusicOnSprite; int SoundIndex=1; int MusicIndex=1; public bool quitvisible = false; public GameObject QuitMenu; public GameObject canvasMenu; public GameObject BigCanvas; public static bool about = false; public static bool store = false; public GameObject AboutPanel; public GameObject LeftButton; public GameObject RightButton; public GameObject MainButton; public GameObject Image1; public GameObject Image2; public GameObject Message1; public GameObject Message2; public GameObject StorePanel; public GameObject Pack1; public GameObject Loly1Selected; public GameObject Loly1Unselected; public GameObject Loly2Locked; public GameObject Loly2Selected; public GameObject Loly2Unselected; public GameObject Loly3Locked; public GameObject Loly3Selected; public GameObject Loly3Unselected; public GameObject Loly4Locked; public GameObject Loly4Selected; public GameObject Loly4Unselected; public GameObject Loly5Locked; public GameObject Loly5Selected; public GameObject Loly5Unselected; public GameObject Loly6Locked; public GameObject Loly6Selected; public GameObject Loly6Unselected; public GameObject Loly7Locked; public GameObject Loly7Selected; public GameObject Loly7Unselected; public GameObject Loly8Locked; public GameObject Loly8Selected; public GameObject Loly8Unselected; public GameObject Loly9Locked; public GameObject Loly9Selected; public GameObject Loly9Unselected; public GameObject Loly10Locked; public GameObject Loly10Selected; public GameObject Loly10Unselected; public GameObject Loly11Locked; public GameObject Loly11Selected; public GameObject Loly11Unselected; public GameObject Loly12Locked; public GameObject Loly12Selected; public GameObject Loly12Unselected; public GameObject Loly13Locked; public GameObject Loly13Selected; public GameObject Loly13Unselected; public GameObject Loly14Locked; public GameObject Loly14Selected; public GameObject Loly14Unselected; public GameObject Loly15Locked; public GameObject Loly15Selected; public GameObject Loly15Unselected; public GameObject Loly16Locked; public GameObject Loly16Selected; public GameObject Loly16Unselected; public GameObject Loly17Locked; public GameObject Loly17Selected; public GameObject Loly17Unselected; public GameObject Loly18Locked; public GameObject Loly18Selected; public GameObject Loly18Unselected; public GameObject Loly19Locked; public GameObject Loly19Selected; public GameObject Loly19Unselected; public GameObject Loly20Locked; public GameObject Loly20Selected; public GameObject Loly20Unselected; public GameObject Loly21Locked; public GameObject Loly21Selected; public GameObject Loly21Unselected; public GameObject Loly22Locked; public GameObject Loly22Selected; public GameObject Loly22Unselected; public GameObject Loly23Locked; public GameObject Loly23Selected; public GameObject Loly23Unselected; public GameObject Loly24Locked; public GameObject Loly24Selected; public GameObject Loly24Unselected; public GameObject MainMenuScore; public GameObject Pack2; public GameObject Pack3; public GameObject RightButtonStore; public GameObject LeftButtonStore; public GameObject MainButtonStore; public GameObject Title; int SkinSelected; int Unlocked2; int Unlocked3; int Unlocked4; int Unlocked5; int Unlocked6; int Unlocked7; int Unlocked8; int Unlocked9; int Unlocked10; int Unlocked11; int Unlocked12; int Unlocked13; int Unlocked14; int Unlocked15; int Unlocked16; int Unlocked17; int Unlocked18; int Unlocked19; int Unlocked20; int Unlocked21; int Unlocked22; int Unlocked23; int Unlocked24; int Total_nb_candy; int pos2; public static bool playClicked; //SoundSource.playOnAwake = false; //SoundSource.rolloffMode = AudioRolloffMode.Logarithmic; //SoundSource.loop = true; } void Start() { PlayGamesPlatform.Activate(); Social.localUser.Authenticate((bool success) => { // handle success or failure }); pos2 = 1; quitvisible = false; about = false; store = false; playClicked = false; } void Update() { if (PlayerPrefs.GetInt("UnlockedSkins", 0) == 7) { Social.ReportProgress("CgkIy9_U8-4JEAIQCA", 100.0f, (bool success) => { // handle success or failure }); } if (PlayerPrefs.GetInt("UnlockedSkins", 0) == 15) { Social.ReportProgress("CgkIy9_U8-4JEAIQCQ", 100.0f, (bool success) => { // handle success or failure }); } if (PlayerPrefs.GetInt("UnlockedSkins", 0) == 23) { Social.ReportProgress("CgkIy9_U8-4JEAIQCg", 100.0f, (bool success) => { // handle success or failure }); } Total_nb_candy = PlayerPrefs.GetInt("Total_Candy", 0); SkinSelected = PlayerPrefs.GetInt("SkinSelected",1); Unlocked2 = PlayerPrefs.GetInt("Loly2lock", 0); Unlocked3 = PlayerPrefs.GetInt("Loly3lock", 0); Unlocked4 = PlayerPrefs.GetInt("Loly4lock", 0); Unlocked5 = PlayerPrefs.GetInt("Loly5lock", 0); Unlocked6 = PlayerPrefs.GetInt("Loly6lock", 0); Unlocked7 = PlayerPrefs.GetInt("Loly7lock", 0); Unlocked8 = PlayerPrefs.GetInt("Loly8lock", 0); Unlocked9 = PlayerPrefs.GetInt("Loly9lock", 0); Unlocked10 = PlayerPrefs.GetInt("Loly10lock", 0); Unlocked11 = PlayerPrefs.GetInt("Loly11lock", 0); Unlocked12 = PlayerPrefs.GetInt("Loly12lock", 0); Unlocked13 = PlayerPrefs.GetInt("Loly13lock", 0); Unlocked14 = PlayerPrefs.GetInt("Loly14lock", 0); Unlocked15 = PlayerPrefs.GetInt("Loly15lock", 0); Unlocked16 = PlayerPrefs.GetInt("Loly16lock", 0); Unlocked17 = PlayerPrefs.GetInt("Loly17lock", 0); Unlocked18 = PlayerPrefs.GetInt("Loly18lock", 0); Unlocked19 = PlayerPrefs.GetInt("Loly19lock", 0); Unlocked20 = PlayerPrefs.GetInt("Loly20lock", 0); Unlocked21 = PlayerPrefs.GetInt("Loly21lock", 0); Unlocked22 = PlayerPrefs.GetInt("Loly22lock", 0); Unlocked23 = PlayerPrefs.GetInt("Loly23lock", 0); Unlocked24 = PlayerPrefs.GetInt("Loly24lock", 0); if (Unlocked2 == 1) { Loly2Locked.SetActive(false); } else { Loly2Locked.SetActive(true); } if (Unlocked3 == 1) { Loly3Locked.SetActive(false); } else { Loly3Locked.SetActive(true); } if (Unlocked4 == 1) { Loly4Locked.SetActive(false); } else { Loly4Locked.SetActive(true); } if (Unlocked5 == 1) { Loly5Locked.SetActive(false); } else { Loly5Locked.SetActive(true); } if (Unlocked6 == 1) { Loly6Locked.SetActive(false); } else { Loly6Locked.SetActive(true); } if (Unlocked7 == 1) { Loly7Locked.SetActive(false); } else { Loly7Locked.SetActive(true); } if (Unlocked8 == 1) { Loly8Locked.SetActive(false); } else { Loly8Locked.SetActive(true); } if (Unlocked9 == 1) { Loly9Locked.SetActive(false); } else { Loly9Locked.SetActive(true); } if (Unlocked10 == 1) { Loly10Locked.SetActive(false); } else { Loly10Locked.SetActive(true); } if (Unlocked11 == 1) { Loly11Locked.SetActive(false); } else { Loly11Locked.SetActive(true); } if (Unlocked12 == 1) { Loly12Locked.SetActive(false); } else { Loly12Locked.SetActive(true); } if (Unlocked13 == 1) { Loly13Locked.SetActive(false); } else { Loly13Locked.SetActive(true); } if (Unlocked14 == 1) { Loly14Locked.SetActive(false); } else { Loly14Locked.SetActive(true); } if (Unlocked15 == 1) { Loly15Locked.SetActive(false); } else { Loly15Locked.SetActive(true); } if (Unlocked16 == 1) { Loly16Locked.SetActive(false); } else { Loly16Locked.SetActive(true); } if (Unlocked17 == 1) { Loly17Locked.SetActive(false); } else { Loly17Locked.SetActive(true); } if (Unlocked18 == 1) { Loly18Locked.SetActive(false); } else { Loly18Locked.SetActive(true); } if (Unlocked19 == 1) { Loly19Locked.SetActive(false); } else { Loly19Locked.SetActive(true); } if (Unlocked20 == 1) { Loly20Locked.SetActive(false); } else { Loly20Locked.SetActive(true); } if (Unlocked21 == 1) { Loly21Locked.SetActive(false); } else { Loly21Locked.SetActive(true); } if (Unlocked22 == 1) { Loly22Locked.SetActive(false); } else { Loly22Locked.SetActive(true); } if (Unlocked23 == 1) { Loly23Locked.SetActive(false); } else { Loly23Locked.SetActive(true); } if (Unlocked24 == 1) { Loly24Locked.SetActive(false); } else { Loly24Locked.SetActive(true); } switch (SkinSelected) { case 1: Loly1Selected.SetActive(true); Loly1Unselected.SetActive(false); if (Unlocked2 == 1) { Loly2Selected.SetActive(false); Loly2Unselected.SetActive(true); } if (Unlocked3 == 1) { Loly3Selected.SetActive(false); Loly3Unselected.SetActive(true); } if (Unlocked4 == 1) { Loly4Selected.SetActive(false); Loly4Unselected.SetActive(true); } if (Unlocked5 == 1) { Loly5Selected.SetActive(false); Loly5Unselected.SetActive(true); } if (Unlocked6 == 1) { Loly6Selected.SetActive(false); Loly6Unselected.SetActive(true); } if (Unlocked7 == 1) { Loly7Selected.SetActive(false); Loly7Unselected.SetActive(true); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 2: if (Unlocked2 == 1) { Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly2Selected.SetActive(true); Loly2Unselected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Unselected.SetActive(true); Loly8Selected.SetActive(false); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 3: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly3Selected.SetActive(true); Loly3Unselected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Unselected.SetActive(true); Loly8Selected.SetActive(false); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 4: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly4Selected.SetActive(true); Loly4Unselected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Unselected.SetActive(true); Loly8Selected.SetActive(false); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 5: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly5Selected.SetActive(true); Loly5Unselected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Unselected.SetActive(true); Loly8Selected.SetActive(false); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 6: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly6Selected.SetActive(true); Loly6Unselected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Unselected.SetActive(true); Loly8Selected.SetActive(false); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 7: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly7Selected.SetActive(true); Loly7Unselected.SetActive(false); } if (Unlocked8 == 1) { Loly8Unselected.SetActive(true); Loly8Selected.SetActive(false); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 8: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly8Selected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 9: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly9Selected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 10: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly10Selected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 11: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly11Selected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 12: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly12Selected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 13: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly13Selected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 14: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly14Selected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 15: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly15Selected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 16: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly16Selected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 17: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly17Selected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 18: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly18Selected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 19: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly19Selected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 20: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly20Selected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 21: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly21Selected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 22: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly22Selected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 23: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly23Selected.SetActive(true); } if (Unlocked24 == 1) { Loly24Selected.SetActive(false); Loly24Unselected.SetActive(true); } break; case 24: if (Unlocked2 == 1) { Loly2Unselected.SetActive(true); Loly2Selected.SetActive(false); } if (Unlocked3 == 1) { Loly3Unselected.SetActive(true); Loly3Selected.SetActive(false); } if (Unlocked4 == 1) { Loly4Unselected.SetActive(true); Loly4Selected.SetActive(false); } if (Unlocked5 == 1) { Loly5Unselected.SetActive(true); Loly5Selected.SetActive(false); } if (Unlocked6 == 1) { Loly6Unselected.SetActive(true); Loly6Selected.SetActive(false); } if (Unlocked7 == 1) { Loly7Unselected.SetActive(true); Loly7Selected.SetActive(false); } if (Unlocked8 == 1) { Loly8Selected.SetActive(false); Loly8Unselected.SetActive(true); } if (Unlocked9 == 1) { Loly9Selected.SetActive(false); Loly9Unselected.SetActive(true); } if (Unlocked10 == 1) { Loly10Selected.SetActive(false); Loly10Unselected.SetActive(true); } if (Unlocked11 == 1) { Loly11Selected.SetActive(false); Loly11Unselected.SetActive(true); } if (Unlocked12 == 1) { Loly12Selected.SetActive(false); Loly12Unselected.SetActive(true); } if (Unlocked13 == 1) { Loly13Selected.SetActive(false); Loly13Unselected.SetActive(true); } if (Unlocked14 == 1) { Loly14Selected.SetActive(false); Loly14Unselected.SetActive(true); } if (Unlocked15 == 1) { Loly15Selected.SetActive(false); Loly15Unselected.SetActive(true); } if (Unlocked16 == 1) { Loly16Selected.SetActive(false); Loly16Unselected.SetActive(true); } if (Unlocked17 == 1) { Loly17Selected.SetActive(false); Loly17Unselected.SetActive(true); } if (Unlocked18 == 1) { Loly18Selected.SetActive(false); Loly18Unselected.SetActive(true); } if (Unlocked19 == 1) { Loly19Selected.SetActive(false); Loly19Unselected.SetActive(true); } if (Unlocked20 == 1) { Loly20Selected.SetActive(false); Loly20Unselected.SetActive(true); } if (Unlocked21 == 1) { Loly21Selected.SetActive(false); Loly21Unselected.SetActive(true); } if (Unlocked22 == 1) { Loly22Selected.SetActive(false); Loly22Unselected.SetActive(true); } if (Unlocked23 == 1) { Loly23Selected.SetActive(false); Loly23Unselected.SetActive(true); } if (Unlocked24 == 1) { Loly24Unselected.SetActive(false); Loly1Unselected.SetActive(true); Loly1Selected.SetActive(false); Loly24Selected.SetActive(true); } break; } /* if (about) { if (time > 0) { time -= Time.deltaTime; // canvasMenu.rigidbody2D.transform.Translate(new Vector2(40, 0), Space.World); // } // else // { //} }*/ /* if (canvasMenu.transform.position.x == 900) { about = false; }*/ SoundIndex = PlayerPrefs.GetInt("Sound", 1); MusicIndex = PlayerPrefs.GetInt("Music", 1); if (Input.GetKeyDown("escape")) { if (!playerController.Dead) { if (!about&&!store) { if (SoundIndex == 1) { Sound.GetComponent<AudioSource>().Play(); } if (!quitvisible) { QuitMenu.SetActive(true); // canvas.SetActive(false); quitvisible = true; if (MusicIndex == 1) { Music.GetComponent<AudioSource>().volume = 0.3f; } } else if (quitvisible) { QuitMenu.SetActive(false); // canvas.SetActive(true); quitvisible = false; if (MusicIndex == 1) { Music.GetComponent<AudioSource>().volume = 0.8f; } } } } } } public void Navigate(string buttonName) { // audio.PlayOneShot(clicSound, 0.1F); switch (buttonName) { case "Play": playClicked = true; //Invoke("loadgame", 0.3f); AutoFade.LoadLevel("sceneGame", 0.2f, 1, Color.black); break; case "Yes": Application.Quit(); QuitMenu.SetActive(false); if (MusicIndex == 1) { GameObject.Find("Music").GetComponent<AudioSource>().volume = 0.8f; } break; case "No": QuitMenu.SetActive(false); // canvas.SetActive(true); quitvisible = false; if (MusicIndex == 1) { GameObject.Find("Music").GetComponent<AudioSource>().volume = 0.8f; } break; case "Sound": if (sound) { // SoundButton.GetComponent<SpriteRenderer>().sprite = Resources.Load("soundoff", typeof(Sprite)) as Sprite; SoundButton.GetComponent<Button>().image.sprite=SoundOffSprite; GetComponent<AudioSource>().enabled=false; sound = false; PlayerPrefs.SetInt("Sound", 0); } else { SoundButton.GetComponent<Button>().image.sprite = SoundOnSprite; GetComponent<AudioSource>().enabled = true; sound = true; PlayerPrefs.SetInt("Sound", 1); } break; case "Music": if (PlayerPrefs.GetInt("Music", 0)==1) { Music.GetComponent<AudioSource>().volume = 0; MusicButton.GetComponent<Button>().image.sprite = MusicOffSprite; music = false; PlayerPrefs.SetInt("Music", 0); } else { Music.GetComponent<AudioSource>().enabled = true; Music.GetComponent<AudioSource>().volume = 0.8f; MusicButton.GetComponent<Button>().image.sprite = MusicOnSprite; music = true; PlayerPrefs.SetInt("Music", 1); } break; case "FB": // WWW www = new WWW("fb://page/DroidBoy-Games"); //StartCoroutine(WaitForRequest(www)); Application.OpenURL("fb://page/502024229946633"); break; case "TW": Application.OpenURL("twitter://user?user_id=3381721191"); break; case "Store": store = true; canvasMenu.SetActive(false); StorePanel.SetActive(true); Pack1.SetActive(true); // Title.SetActive(false); LeftButtonStore.SetActive(false); break; case "Achiev": Social.localUser.Authenticate((bool success) => { // handle success or failure }); Social.ShowAchievementsUI(); break; case "Leader": Social.localUser.Authenticate((bool success) => { // handle success or failure }); Social.ShowLeaderboardUI(); break; case "About": about = true; // canvasMenu.rigidbody2D.velocity = new Vector3(9.5f , 0, 0); canvasMenu.SetActive(false); AboutPanel.SetActive(true); Image1.SetActive(true); Message1.SetActive(true); LeftButton.SetActive(false); break; case "Left": RightButton.SetActive(true); LeftButton.SetActive(false); MainButton.SetActive(false); Image1.SetActive(true); Message1.SetActive(true); Image2.SetActive(false); Message2.SetActive(false); break; case "Right": LeftButton.SetActive(true); Image1.SetActive(false); Message1.SetActive(false); Image2.SetActive(true); Message2.SetActive(true); MainButton.SetActive(true); RightButton.SetActive(false); break; case "Main": AboutPanel.SetActive(false); canvasMenu.SetActive(true); MainButton.SetActive(false); RightButton.SetActive(true); LeftButton.SetActive(false); Image1.SetActive(true); Message1.SetActive(true); Image2.SetActive(false); Message2.SetActive(false); about = false; break; case "Rate": // Application.OpenURL("http://play.google.com/store/apps/details?id=droidboy.lolyjump.loly"); Application.OpenURL("market://details?id=droidboy.lolyjump.loly"); break; case "LeftStore": if (pos2==3){ RightButtonStore.SetActive(true); Pack3.SetActive(false); Pack2.SetActive(true); pos2=2; } else if (pos2==2){ LeftButtonStore.SetActive(false); Pack2.SetActive(false); Pack1.SetActive(true); pos2=1; } break; case "RightStore": if (pos2==1){ LeftButtonStore.SetActive(true); Pack1.SetActive(false); Pack2.SetActive(true); pos2=2; } else if (pos2==2){ RightButtonStore.SetActive(false); Pack2.SetActive(false); Pack3.SetActive(true); pos2=3; } break; case "MainStore": canvasMenu.SetActive(true); StorePanel.SetActive(false); Pack1.SetActive(false); Title.SetActive(true); store = false; Pack3.SetActive(false); Pack2.SetActive(false); LeftButtonStore.SetActive(false); RightButtonStore.SetActive(true); pos2=1; break; case "Loly1Select": PlayerPrefs.SetInt("SkinSelected",1); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly2Unlock": if (Total_nb_candy >= 5) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly2lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy-5); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly2Select": PlayerPrefs.SetInt("SkinSelected", 2); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly3Unlock": if (Total_nb_candy >= 10) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly3lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 10); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly3Select": PlayerPrefs.SetInt("SkinSelected", 3); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly4Unlock": if (Total_nb_candy >= 15) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly4lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 15); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly4Select": PlayerPrefs.SetInt("SkinSelected", 4); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly5Unlock": if (Total_nb_candy >= 20) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly5lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 20); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly5Select": PlayerPrefs.SetInt("SkinSelected",5); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly6Unlock": if (Total_nb_candy >= 25) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly6lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 25); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly6Select": PlayerPrefs.SetInt("SkinSelected",6); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly7Unlock": if (Total_nb_candy >= 30) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly7lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 30); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly7Select": PlayerPrefs.SetInt("SkinSelected", 7); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly8Unlock": if (Total_nb_candy >= 35) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly8lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 35); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly8Select": PlayerPrefs.SetInt("SkinSelected", 8); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly9Unlock": if (Total_nb_candy >= 50) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly9lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 50); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly9Select": PlayerPrefs.SetInt("SkinSelected", 9); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly10Unlock": if (Total_nb_candy >= 50) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly10lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 50); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly10Select": PlayerPrefs.SetInt("SkinSelected", 10); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly11Unlock": if (Total_nb_candy >= 100) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly11lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 100); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly11Select": PlayerPrefs.SetInt("SkinSelected", 11); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly12Unlock": if (Total_nb_candy >= 100) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly12lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 100); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly12Select": PlayerPrefs.SetInt("SkinSelected", 12); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly13Unlock": if (Total_nb_candy >= 150) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly13lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 150); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly13Select": PlayerPrefs.SetInt("SkinSelected", 13); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly14Unlock": if (Total_nb_candy >= 150) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly14lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 150); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly14Select": PlayerPrefs.SetInt("SkinSelected", 14); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly15Unlock": if (Total_nb_candy >= 200) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly15lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 200); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly15Select": PlayerPrefs.SetInt("SkinSelected", 15); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly16Unlock": if (Total_nb_candy >= 300) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly16lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 300); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly16Select": PlayerPrefs.SetInt("SkinSelected", 16); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly17Unlock": if (Total_nb_candy >= 350) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly17lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 350); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly17Select": PlayerPrefs.SetInt("SkinSelected", 17); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly18Unlock": if (Total_nb_candy >= 400) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly18lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 400); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly18Select": PlayerPrefs.SetInt("SkinSelected", 18); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly19Unlock": if (Total_nb_candy >= 500) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly19lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 450); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly19Select": PlayerPrefs.SetInt("SkinSelected", 19); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly20Unlock": if (Total_nb_candy >= 600) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly20lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 500); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly20Select": PlayerPrefs.SetInt("SkinSelected", 20); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly21Unlock": if (Total_nb_candy >= 700) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly21lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 600); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly21Select": PlayerPrefs.SetInt("SkinSelected", 21); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly22Unlock": if (Total_nb_candy >= 800) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly22lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 800); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly22Select": PlayerPrefs.SetInt("SkinSelected", 22); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly23Unlock": if (Total_nb_candy >= 900) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0) + 1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly23lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 900); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly23Select": PlayerPrefs.SetInt("SkinSelected", 23); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; case "Loly24Unlock": if (Total_nb_candy >= 1000) { PlayerPrefs.SetInt("UnlockedSkins", PlayerPrefs.GetInt("UnlockedSkins", 0)+1); (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); PlayerPrefs.SetInt("Loly24lock", 1); PlayerPrefs.SetInt("Total_Candy", Total_nb_candy - 1000); if (SoundIndex == 1) { GameObject.Find("UnlockSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } else { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = true; Invoke("StopShake", 0.5f); if (SoundIndex == 1) { GameObject.Find("CantSound").GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } } break; case "Loly24Select": PlayerPrefs.SetInt("SkinSelected", 24); if (SoundIndex == 1) { BigCanvas.GetComponent<AudioSource>().GetComponent<AudioSource>().Play(); } break; } } void OnDestroy() { PlayerPrefs.SetInt("MainMenuFade", 0); } void StopShake() { (MainMenuScore.GetComponent(typeof(Shake2)) as Shake2).enabled = false; } public void loadgame() { // GameObject.Find("GM").GetComponent<FadeScript>().BeginFade(1); //PlayerPrefs.SetInt("MainMenuFade", 0); //Application.LoadLevel("sceneGame"); } void Awake() { about = false; store = false; if( PlayerPrefs.GetInt("MainMenuFade", 0)==1) GameObject.Find("GM").GetComponent<FadeScript>().enabled=true; // PlayerPrefs.SetInt("Total_Candy", 0); // PlayerPrefs.SetInt("highScore", 602); // PlayerPrefs.SetInt("Total_Candy", 187); /* PlayerPrefs.SetInt("Loly2lock", 0); PlayerPrefs.SetInt("Loly3lock", 0); PlayerPrefs.SetInt("Loly4lock", 0); PlayerPrefs.SetInt("Loly5lock", 0); PlayerPrefs.SetInt("Loly6lock", 0); PlayerPrefs.SetInt("Loly7lock", 0); PlayerPrefs.SetInt("Loly8lock", 0); PlayerPrefs.SetInt("Loly9lock", 0); PlayerPrefs.SetInt("Loly10lock", 0); PlayerPrefs.SetInt("Loly11lock", 0); PlayerPrefs.SetInt("Loly12lock", 0); PlayerPrefs.SetInt("Loly13lock", 0); PlayerPrefs.SetInt("Loly14lock", 0); PlayerPrefs.SetInt("Loly15lock", 0); PlayerPrefs.SetInt("Loly16lock", 0); PlayerPrefs.SetInt("Loly17lock", 0); PlayerPrefs.SetInt("Loly18lock", 0); PlayerPrefs.SetInt("Loly19lock", 0); PlayerPrefs.SetInt("Loly20lock", 0); PlayerPrefs.SetInt("Loly21lock", 0); PlayerPrefs.SetInt("Loly22lock", 0); PlayerPrefs.SetInt("Loly23lock", 0); PlayerPrefs.SetInt("Loly24lock", 0);*/ Total_nb_candy = PlayerPrefs.GetInt("Total_Candy", 0); SkinSelected = PlayerPrefs.GetInt("SkinSelected",1); Unlocked2 = PlayerPrefs.GetInt("Loly2lock", 0); Unlocked3 = PlayerPrefs.GetInt("Loly3lock", 0); Unlocked4 = PlayerPrefs.GetInt("Loly4lock", 0); Unlocked5 = PlayerPrefs.GetInt("Loly5lock", 0); Unlocked6 = PlayerPrefs.GetInt("Loly6lock", 0); Unlocked7 = PlayerPrefs.GetInt("Loly7lock", 0); Unlocked8 = PlayerPrefs.GetInt("Loly8lock", 0); Unlocked9 = PlayerPrefs.GetInt("Loly9lock", 0); Unlocked10 = PlayerPrefs.GetInt("Loly10lock", 0); Unlocked11 = PlayerPrefs.GetInt("Loly11lock", 0); Unlocked12 = PlayerPrefs.GetInt("Loly12lock", 0); Unlocked13 = PlayerPrefs.GetInt("Loly13lock", 0); Unlocked14 = PlayerPrefs.GetInt("Loly14lock", 0); Unlocked15 = PlayerPrefs.GetInt("Loly15lock", 0); Unlocked16 = PlayerPrefs.GetInt("Loly16lock", 0); Unlocked17 = PlayerPrefs.GetInt("Loly17lock", 0); Unlocked18 = PlayerPrefs.GetInt("Loly18lock", 0); Unlocked19 = PlayerPrefs.GetInt("Loly19lock", 0); Unlocked20 = PlayerPrefs.GetInt("Loly20lock", 0); Unlocked21 = PlayerPrefs.GetInt("Loly21lock", 0); Unlocked22 = PlayerPrefs.GetInt("Loly22lock", 0); Unlocked23 = PlayerPrefs.GetInt("Loly23lock", 0); Unlocked24 = PlayerPrefs.GetInt("Loly24lock", 0); Music.GetComponent<AudioSource>().enabled = false; SoundIndex = PlayerPrefs.GetInt("Sound", 1); MusicIndex = PlayerPrefs.GetInt("Music", 1); if (SoundIndex == 0) { SoundButton.GetComponent<Button>().image.sprite = SoundOffSprite; GetComponent<AudioSource>().enabled = false; sound = false; } else if (SoundIndex == 1) { SoundButton.GetComponent<Button>().image.sprite = SoundOnSprite; GetComponent<AudioSource>().enabled = true; sound = true; } if (MusicIndex == 0) { Music.GetComponent<AudioSource>().enabled = true; Music.GetComponent<AudioSource>().volume = 0; MusicButton.GetComponent<Button>().image.sprite = MusicOffSprite; music = false; } else if (MusicIndex == 1) { Music.GetComponent<AudioSource>().enabled = true; Music.GetComponent<AudioSource>().Stop(); Invoke("volume", 0.3f); MusicButton.GetComponent<Button>().image.sprite = MusicOnSprite; music = true; } } void volume() { Music.GetComponent<AudioSource>().volume = 0.8f; Music.GetComponent<AudioSource>().Play(); } }
namespace Uintra.Features.Permissions.Models { public class PermissionUpdateModel { public IntranetMemberGroup Group { get; } public PermissionSettingIdentity SettingIdentity { get; } public PermissionSettingValues SettingValues { get; } public PermissionUpdateModel( IntranetMemberGroup group, PermissionSettingValues settingValues, PermissionSettingIdentity settingIdentity) { Group = group; SettingIdentity = settingIdentity; SettingValues = settingValues; } } }
using CoingeckoPriceData; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using UnityEngine; public sealed class BlockChainTransactionModel : TransactionModelBase { private static readonly string API_KEYS_PATH = CryptoService.TRANSACTIONS_FOLDER_PATH + "/BlockChainSpecific/APIKeys.json"; private readonly static string[] FULL_TAX = new string[] { "Atomic Wallet Staking Rewards Distribution" }; private string _address; private string _transactionId; public override string WalletName => "Transactions from blockchain"; private BlockChainTransactionModel() { } public static async Task<List<ITransactionModel>> InitFromData(string fileName, string entryData, Func<string, Type, object> convertFromString) { TransactionTracking transactionTracking = JsonConvert.DeserializeObject<TransactionTracking>(entryData); foreach (AddressInfo addressInfo in transactionTracking.TransactionHistory) { foreach (TransactionIdAndType markedTransaction in addressInfo.MarkedTransactions) { //value.TransactionType } } BlockChainTransactionModel blockChainTransactionModel = new BlockChainTransactionModel(); return new List<ITransactionModel>(); } /// <summary> /// Set the _transactionId, _address, _blockChainToCall and the TimeStamp before calling this part of the initialization. /// </summary> /// <param name="coinId"></param> /// <returns></returns> private async Task<List<ITransactionModel>> Init(string coinId) { string date = TimeStamp.ToString("dd-MM-yyyy"); using (CallRateLimiter apiCallRateLimiter = new CallRateLimiter("CoinGeckoPrice", 10, TimeSpan.FromSeconds(1))) { HttpResponseMessage httpResponse = await apiCallRateLimiter.GetDataAsync($"http://api.coingecko.com/api/v3/coins/{coinId}/history?date={date}&localization=false"); if (httpResponse.IsSuccessStatusCode) { CoinInformation coinData = JsonConvert.DeserializeObject<CoinInformation>(await httpResponse.Content.ReadAsStringAsync()); if (coinData.Market_data.Current_price.ContainsKey(MainComponent.Instance.TargetCurrency.ToLower())) { NativeCurrency = MainComponent.Instance.TargetCurrency; ValueForOneCryptoTokenInNative = coinData.Market_data.Current_price[MainComponent.Instance.TargetCurrency.ToLower()]; //switch (_blockChainToCall) //{ // case BlockChain.Binance: // return await InitFromBinanceApi(); // case BlockChain.Ethereum: // return await InitFromEthereumApi(); //} } } else { Debug.Log("Coingecko Call failed with code: " + httpResponse.StatusCode + " and message: " + await httpResponse.Content.ReadAsStringAsync()); } } return new List<ITransactionModel>(); } //private static async Task<List<ITransactionModel>> InitFromBinanceApi(string address) //{ // using(CallRateLimiter explorerBinanceLimiter = new CallRateLimiter("BinanceExplorerApi", 10, TimeSpan.FromSeconds(1))) // { // HttpResponseMessage transactionsAmount = await explorerBinanceLimiter.GetDataAsync($"https://explorer.binance.org/api/v1/txs?page=1&rows=1&address={address}"); // } // List<ITransactionModel> transactionModels = new List<ITransactionModel> { this }; // using (CallRateLimiter apiCallRateLimiter = new CallRateLimiter("BinanceApiCall", 10, TimeSpan.FromSeconds(1))) // { // HttpResponseMessage httpResponse = await apiCallRateLimiter.GetDataAsync($"https://dex.binance.org/api/v1/tx/{transactionId}?format=json"); // if (httpResponse.IsSuccessStatusCode) // { // BinanceChain.TransactionFromHash transactionFromHash = JsonConvert.DeserializeObject<BinanceChain.TransactionFromHash>(await httpResponse.Content.ReadAsStringAsync()); // if (transactionFromHash.Ok) // { // if (FULL_TAX.Contains(transactionFromHash.Tx.Value.Memo)) // { // IsFullyTaxed = true; // } // foreach (BinanceChain.TransactionInformationMessage transactionInformationMessage in transactionFromHash.Tx.Value.Msg) // { // List<BinanceChain.TransactionAddressAndCoins> transactionInformationMessageValues = transactionInformationMessage.Value.Outputs.Where(b => b.Address == _address).ToList(); // if (transactionInformationMessageValues.Count > 0) // { // for (int i = 1; i < transactionInformationMessageValues.Count; i++) // { // ITransactionModel blockChainTransactionModel = Clone(); // foreach (BinanceChain.TransactionCoin coin in transactionInformationMessageValues[i].Coins) // { // blockChainTransactionModel.NativeAmount += ValueForOneCryptoTokenInNative * coin.Amount; // blockChainTransactionModel.CryptoCurrency += coin.Denom + "|"; // } // blockChainTransactionModel.CryptoCurrency.Remove(blockChainTransactionModel.CryptoCurrency.Length - 1); // transactionModels.Add(blockChainTransactionModel); // } // BinanceChain.TransactionAddressAndCoins first = transactionInformationMessageValues[0]; // NativeAmount = 0; // foreach (BinanceChain.TransactionCoin coin in first.Coins) // { // CryptoCurrency = coin.Denom; // CryptoCurrencyAmount += coin.Amount; // NativeAmount += ValueForOneCryptoTokenInNative * coin.Amount; // } // } // } // } // } // else // { // Debug.Log("Binance api call failed with code: " + httpResponse.StatusCode + " and message " + await httpResponse.Content.ReadAsStringAsync()); // } // } // return transactionModels; //} private async Task<List<ITransactionModel>> InitFromEthereumApi() { List<ITransactionModel> transactionModels = new List<ITransactionModel> { this }; APIKeys keys; using (StreamReader streamReader = new StreamReader(API_KEYS_PATH)) { string apiKeys = await streamReader.ReadToEndAsync(); keys = JsonConvert.DeserializeObject<APIKeys>(apiKeys); } using (CallRateLimiter apiCallRateLimiter = new CallRateLimiter("EtherScan", 5, TimeSpan.FromSeconds(1))) { HttpResponseMessage etherTransactionsResponse = await apiCallRateLimiter.GetDataAsync($"https://api.etherscan.io/api?module=account&action=txlist&address={_address}&sort=asc&apikey={keys.EtherScanKey}"); HttpResponseMessage erc20TransactionsResponse = await apiCallRateLimiter.GetDataAsync($"https://api.etherscan.io/api?module=account&action=tokentx&address={_address}&sort=asc&apikey={keys.EtherScanKey}"); if (etherTransactionsResponse.IsSuccessStatusCode && erc20TransactionsResponse.IsSuccessStatusCode) { EthereumChain.EtherAddressTransactions etherAddressTransactions = JsonConvert.DeserializeObject<EthereumChain.EtherAddressTransactions>(await etherTransactionsResponse.Content.ReadAsStringAsync()); EthereumChain.Erc20AddressTransactions erc20AddressTransactions = JsonConvert.DeserializeObject<EthereumChain.Erc20AddressTransactions>(await erc20TransactionsResponse.Content.ReadAsStringAsync()); List<EthereumChain.IEtherScanTransaction> transactions = new List<EthereumChain.IEtherScanTransaction>(); transactions.AddRange(erc20AddressTransactions.Result); foreach (var ethTransaction in etherAddressTransactions.Result) { if (!transactions.Any(t => t.Hash == ethTransaction.Hash)) { transactions.Add(ethTransaction); } } if (transactions.Count > 0) { for (int i = 1; i < transactions.Count; i++) { ITransactionModel blockChainTransactionModel = Clone(); NativeAmount = transactions[i].Value * ValueForOneCryptoTokenInNative; CryptoCurrency = transactions[i].TokenSymbol; CryptoCurrencyAmount = transactions[i].Value; } EthereumChain.IEtherScanTransaction first = transactions[0]; NativeAmount = first.Value * ValueForOneCryptoTokenInNative; CryptoCurrency = first.TokenSymbol; CryptoCurrencyAmount = first.Value; } } else { Debug.Log("Etherscan api call finished with code: " + etherTransactionsResponse.StatusCode + " and message " + await etherTransactionsResponse.Content.ReadAsStringAsync()); Debug.Log("Etherscan api call finished with code: " + erc20TransactionsResponse.StatusCode + " and message " + await erc20TransactionsResponse.Content.ReadAsStringAsync()); } } return transactionModels; } public override ITransactionModel Clone() { return (BlockChainTransactionModel)MemberwiseClone(); } }
using Terraria.ID; using Terraria.ModLoader; using Terraria; using static Terraria.ModLoader.ModContent; using System; namespace ReducedGrinding.NPCs { [AutoloadHead] public class StationaryMerchant : ModNPC { public override string Texture => "ReducedGrinding/NPCs/StationaryMerchant"; public override string[] AltTextures => new[] { "ReducedGrinding/NPCs/StationaryMerchant_alt" }; public static bool baseshop = false; public override void SetStaticDefaults() { DisplayName.SetDefault("Stationary Merchant"); } public override void SetDefaults() { npc.townNPC = true; npc.friendly = true; npc.width = 32; //His hitbox, the visual width/height is affected by frame count below. npc.height = 50; npc.aiStyle = 7; npc.damage = 10; npc.defense = 15; npc.lifeMax = 250; npc.HitSound = SoundID.NPCHit1; npc.DeathSound = SoundID.NPCDeath1; npc.knockBackResist = 0.5f; Main.npcFrameCount[npc.type] = 26; animationType = NPCID.Guide; NPCID.Sets.HatOffsetY[npc.type] = 12; } public override bool CanTownNPCSpawn(int numTownNPCs, int money) { if (GetInstance<ETravelingAndStationaryMerchantConfig>().StationaryMerchant) return true; else return false; } public override string TownNPCName() { switch (Main.rand.Next(4)) //Names are requrest by sprite artist, Lonley Star; don't change them. { case 0: return "Albert"; case 1: return "Archibald"; case 2: return "Graham"; default: return "Gray"; } } public override string GetChat() { bool TravellingMerchantExists = false; for (int i = 0; i < Terraria.Main.npc.Length; i++) { if (Terraria.Main.npc[i].type == NPCID.TravellingMerchant) { TravellingMerchantExists = true; break; } } int SaleType; if (GetInstance<ETravelingAndStationaryMerchantConfig>().S_MerchantPriceMultiplierDuringSale < GetInstance<ETravelingAndStationaryMerchantConfig>().S_MerchantPriceMultiplier) SaleType = 1; else if (GetInstance<ETravelingAndStationaryMerchantConfig>().S_MerchantPriceMultiplierDuringSale > GetInstance<ETravelingAndStationaryMerchantConfig>().S_MerchantPriceMultiplier) SaleType = -1; else SaleType = 0; if ((TravellingMerchantExists && SaleType == 1) || (!TravellingMerchantExists && SaleType == -1)) return "Everything is on sale!"; else { if (Terraria.GameContent.Events.BirthdayParty.PartyIsUp && Main.rand.Next(3) == 0) { return "I bet travelers miss parties a lot."; } else { switch (Main.rand.Next(2)) { case 0: return "Don't worry, I'm not going anywhere!"; default: if (SaleType == 1) return "I like to have a sales when traveling merchants arrive."; else if (SaleType == -1) return "I like to have sales when traveling merchants are away."; else return "My prices never change."; } } } } public override void SetChatButtons(ref string button, ref string button2) { button = "Shop"; button2 = "Decor Shop"; } public override void OnChatButtonClicked(bool firstButton, ref bool shop) { if (firstButton) { shop = true; baseshop = true; } else //Docor Shop { shop = true; baseshop = false; } } public override void SetupShop(Chest shop, ref int nextSlot) { bool TravellingMerchantExists = false; float BaseMultiplier; for (int i = 0; i < Terraria.Main.npc.Length; i++) { if (Terraria.Main.npc[i].type == NPCID.TravellingMerchant) { TravellingMerchantExists = true; break; } } if (TravellingMerchantExists) BaseMultiplier = GetInstance<ETravelingAndStationaryMerchantConfig>().S_MerchantPriceMultiplierDuringSale; else BaseMultiplier = GetInstance<ETravelingAndStationaryMerchantConfig>().S_MerchantPriceMultiplier; float RarityMultiplier = GetInstance<ETravelingAndStationaryMerchantConfig>().S_MerchantRarityFee; int Rarity; int MaxPrice = 999999999; if (baseshop) { Rarity = 1; shop.item[nextSlot].SetDefaults(ItemID.DPSMeter); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.LifeformAnalyzer); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.Stopwatch); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.Sake); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.Pho); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 30) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PadThai); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 20) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; Rarity = 2; shop.item[nextSlot].SetDefaults(ItemID.UltrabrightTorch); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 3) * BaseMultiplier * (1 + RarityMultiplier * (Rarity-1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PaintSprayer); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 10) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.BrickLayer); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 10) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PortableCementMixer); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 10) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.ExtendoGrip); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 10) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.ActuationAccessory); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 10) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.Katana); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 4) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; Rarity = 3; shop.item[nextSlot].SetDefaults(ItemID.AmmoBox); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 15) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.MagicHat); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 3) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.GypsyRobe); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 3, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.Gi); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 2) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; if (NPC.downedBoss1) { shop.item[nextSlot].SetDefaults(ItemID.Code1); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } if (NPC.downedMechBossAny) { shop.item[nextSlot].SetDefaults(ItemID.Code2); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 25) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } if (WorldGen.shadowOrbSmashed) { shop.item[nextSlot].SetDefaults(ItemID.Revolver); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 10) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } shop.item[nextSlot].SetDefaults(ItemID.Fez); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 3, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; Rarity = 4; shop.item[nextSlot].SetDefaults(ItemID.CelestialMagnet); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 15) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.YellowCounterweight); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.SittingDucksFishingRod); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 35) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; if (NPC.downedPlantBoss) { shop.item[nextSlot].SetDefaults(ItemID.PulseBow); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 45) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } shop.item[nextSlot].SetDefaults(ItemID.DiamondRing); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(2) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.WinterCape); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.RedCape); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.CrimsonCloak); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.MysteriousCape); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.WaterGun); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 1, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.CompanionCube); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; Rarity = 5; shop.item[nextSlot].SetDefaults(ItemID.BlackCounterweight); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 5) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; if (Main.hardMode) { shop.item[nextSlot].SetDefaults(ItemID.Gatligator); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 35) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } shop.item[nextSlot].SetDefaults(ItemID.Kimono); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; Rarity = 6; shop.item[nextSlot].SetDefaults(ItemID.AngelHalo); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 40) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } else //Docor Shop { Rarity = 1; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockRed); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockRedPlatform); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockYellow); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockYellowPlatform); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockGreen); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockGreenPlatform); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockBlue); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockBluePlatform); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockPink); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockPinkPlatform); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockWhite); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TeamBlockWhitePlatform); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.SteampunkCup); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.FancyDishes); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 20) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.DynastyWood); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.RedDynastyShingles); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.BlueDynastyShingles); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.ZebraSkin); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.LeopardSkin); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.TigerSkin); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 1) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; Rarity = 3; if (Main.xMas) { shop.item[nextSlot].SetDefaults(ItemID.PaintingTheSeason); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PaintingSnowfellas); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PaintingColdSnap); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PaintingCursedSaint); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PaintingAcorns); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } if (NPC.downedMartians) { shop.item[nextSlot].SetDefaults(ItemID.PaintingTheTruthIsUpThere); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 2) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PaintingMartiaLisa); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 2) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; shop.item[nextSlot].SetDefaults(ItemID.PaintingCastleMarsberg); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 2) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } if (NPC.downedMoonlord) { shop.item[nextSlot].SetDefaults(ItemID.MoonLordPainting); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 3) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } Rarity = 5; shop.item[nextSlot].SetDefaults(ItemID.ArcaneRuneWall); shop.item[nextSlot].shopCustomPrice = (int)Math.Min(MaxPrice, Item.buyPrice(0, 0, 2, 50) * BaseMultiplier * (1 + RarityMultiplier * (Rarity - 1))); nextSlot++; } } } }
using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Framework.Basic.Grades.Domain.Entities; using MongoDB.Bson; namespace Alabo.Framework.Basic.Grades.Domain.Repositories { public class UpgradeRecordRepository : RepositoryMongo<UpgradeRecord, ObjectId>, IUpgradeRecordRepository { public UpgradeRecordRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
using System.Collections.Generic; using Igorious.StardewValley.ShowcaseMod.Data; namespace Igorious.StardewValley.ShowcaseMod.ModConfig { public sealed class GlowConfig { public bool ShowGlows { get; set; } = true; public bool ShowLights { get; set; } = true; public List<GlowEffect> Glows { get; set; } = new List<GlowEffect>(); public GlowEffect GoldQualityGlow { get; set; } public GlowEffect IridiumQualityGlow { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using System.Collections; /* * 单例模式 */ public abstract class AbsBehaviour<T> : MonoBehaviour where T : class ,new() { static T _instance = null; public static T Instance { get { return _instance ?? (_instance = new T()); } } void Awake() { Debug.Log("AbsBehaviour"); _instance = this as T; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GasValve : MonoBehaviour { //Author: Alecksandar Jackowicz //To activate the gas pipe assigned to this gameobject when triggered public GasPipe gasPipe; public void ActivateGas(){ gasPipe.hasGas = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IconCreator.Core.Models.Models { public class IconColor { public IconColor(string id, string background, string foreground, string name) { this.Id = id; this.Background = background; this.Foreground = foreground; this.Name = name; } public string Id { get; set; } public string Name { get; set; } public string Foreground { get; set; } public string Background { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using StringReplicator.Core.Operations; using StringReplicator.Core.Operations.Format; using Voodoo; namespace StringReplicator.Tests.Operations.String { [TestClass] public class FormatHelperTests { [TestMethod] public void Format_TwoStrings_IsOk() { var request = new LineFormattingRequest {FormatString = "{0},{1}", Arguments = new object[] {"a", "b"}}; var helper = new LineFormattingOperation(request); var response = helper.Execute(); Assert.AreEqual("a,b", response.Text); } [TestMethod] public void Format_TwoStringFirstIsFormattedToFriendlyString_IsOk() { const string format = "{0:!},{1}"; var data = new object[] {"RedBlue", "b"}; var request = new LineFormattingRequest {FormatString = format, Arguments = data}; var helper = new LineFormattingOperation(request); var response = helper.Execute().Text; Assert.AreEqual("Red Blue,b", response); } [TestMethod] public void Format_TwoStringFirstIsDate_IsOk() { const string format = "{0:yyyy},{1}"; var data = new object[] {"1/1/2010".To<DateTime>(), "b"}; var request = new LineFormattingRequest {FormatString = format, Arguments = data}; var helper = new LineFormattingOperation(request); var response = helper.Execute().Text; var standardResponse = string.Format(format, data); Assert.AreEqual("2010,b", standardResponse); Assert.AreEqual("2010,b", response); } [TestMethod] public void Format_TwoStringFirstIsPaddedFormattedInt_IsOk() { const string format = "{0,12:N0},{1}"; var data = new object[] {"1504277".To<int>(), "b"}; var request = new LineFormattingRequest {FormatString = format, Arguments = data}; var helper = new LineFormattingOperation(request); var response = helper.Execute().Text; var standardResponse = string.Format(format, data); Assert.AreEqual(" 1,504,277,b", standardResponse); Assert.AreEqual(" 1,504,277,b", response); } [TestMethod] public void Format_TwoStringFirstIsPaddedFormattedIntBadWhiteSpace_IsOk() { const string format = "{0, 12:N0},{1}"; var data = new object[] {"1504277".To<int>(), "b"}; var request = new LineFormattingRequest {FormatString = format, Arguments = data}; var helper = new LineFormattingOperation(request); var response = helper.Execute().Text; var standardResponse = string.Format(format, data); Assert.AreEqual(" 1,504,277,b", standardResponse); Assert.AreEqual(" 1,504,277,b", response); } [TestMethod] public void Format_TwoStringFirstIsLeftPaddedFormattedInt_IsOk() { const string format = "{0,-12:N0},{1}"; var data = new object[] {"1504277".To<int>(), "b"}; var request = new LineFormattingRequest {FormatString = format, Arguments = data}; var helper = new LineFormattingOperation(request); var response = helper.Execute().Text; var standardResponse = string.Format(format, data); Assert.AreEqual("1,504,277 ,b", standardResponse); Assert.AreEqual("1,504,277 ,b", response); } [TestMethod] public void Format_MissingParameter_IsNotOk() { const string format = "{0}{1}{2}"; var data = new object[] {"a", "b"}; var request = new LineFormattingRequest {FormatString = format, Arguments = data}; var helper = new LineFormattingOperation(request); var response = helper.Execute().Text; Assert.AreEqual(response, Messages.WrongNumberOfArguments); } [TestMethod] public void Format_UnescapedOpenSquiggle_IsNotOk() { const string format = "public {0} {1} {get;set;"; var data = new object[] {"a", "b"}; var request = new LineFormattingRequest {FormatString = format, Arguments = data}; var helper = new LineFormattingOperation(request); var response = helper.Execute().Text; Assert.AreEqual(response, Messages.FormatError); } [TestMethod] public void Format_UnescapedClosedSquiggle_IsNotOk() { const string format = "public {0} {1} get;set;}"; var data = new object[] {"a", "b"}; var request = new LineFormattingRequest {FormatString = format, Arguments = data}; var helper = new LineFormattingOperation(request); var response = helper.Execute().Text; Assert.AreEqual(response, Messages.FormatError); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; [RequireComponent(typeof(Button))] public class ButtonSound : MonoBehaviour { private ButtonAudioSource btnAudioSource; private void Awake() { this.btnAudioSource = GameObject.FindObjectOfType<ButtonAudioSource>(); if(this.btnAudioSource != null) { Button btn = this.GetComponent<Button>(); btn.onClick.AddListener(() => { this.btnAudioSource.play(); }); } else { Debug.LogWarning("Could not find ButtonAudioSource script. Button sounds will be disabled."); } } }
namespace Core { public class Category { public int CategoryId { get; } public string CategoryName { get; } /// <summary> /// конструктор /// </summary> /// <param name="id">ID категории</param> /// <param name="name">Название категории</param> public Category(int id, string name) { CategoryId = id; CategoryName = name; } /// <summary> /// переопределённый ToString /// </summary> /// <returns>название категории</returns> public override string ToString() { return CategoryName; } public override bool Equals(object obj) { if(obj == null) return false; if (GetType() != obj.GetType()) return false; var o = obj as Category; if (CategoryId != o.CategoryId || !CategoryName.Equals(o.CategoryName)) return false; else return true; } public override int GetHashCode() { return base.GetHashCode(); } } }
using ScriptableObjectFramework.Events.UnityEvents; using UnityEngine; namespace ScriptableObjectFramework.Events { [CreateAssetMenu(fileName = "NewFloatEvent", menuName = "Scriptable Objects/Events/Float")] public class FloatEventBacking : BaseEventBacking<float, FloatUnityEvent> { } }
using System.Text; namespace Hz.Infrastructure.Common { public static class Pinyin { /// <summary> /// 取中文文本的拼音首字母 /// </summary> /// <param name="text">编码为UTF8的文本</param> /// <returns>返回中文对应的拼音首字母</returns> public static string GetInitials (string text) { text = text.Trim (); StringBuilder chars = new StringBuilder (); for (var i = 0; i < text.Length; ++i) { string py = GetPinyin (text[i]); if (py != "") chars.Append (py[0]); } return chars.ToString ().ToUpper (); } /// <summary> /// 取中文文本的拼音首字母 /// </summary> /// <param name="text">文本</param> /// <param name="encoding">源文本的编码</param> /// <returns>返回encoding编码类型中文对应的拼音首字母</returns> public static string GetInitials (string text, Encoding encoding) { string temp = ConvertEncoding (text, encoding, Encoding.UTF8); return ConvertEncoding (GetInitials (temp), Encoding.UTF8, encoding); } /// <summary> /// 取中文文本的拼音 /// </summary> /// <param name="text">编码为UTF8的文本</param> /// <returns>返回中文文本的拼音</returns> public static string GetPinyin (string text) { StringBuilder sbPinyin = new StringBuilder (); for (var i = 0; i < text.Length; ++i) { string py = GetPinyin (text[i]); if (py != "") sbPinyin.Append (py); sbPinyin.Append (" "); } return sbPinyin.ToString ().Trim (); } /// <summary> /// 取中文文本的拼音 /// </summary> /// <param name="text">文本</param> /// <param name="encoding">源文本的编码</param> /// <returns>返回encoding编码类型的中文文本的拼音</returns> public static string GetPinyin (string text, Encoding encoding) { string temp = ConvertEncoding (text.Trim (), encoding, Encoding.UTF8); return ConvertEncoding (GetPinyin (temp), Encoding.UTF8, encoding); } /// <summary> /// 取和拼音相同的汉字列表 /// </summary> /// <param name="pinyin">编码为UTF8的拼音</param> /// <returns>取拼音相同的汉字列表,如拼音“ai”将会返回“唉爱……”等</returns> public static string GetChineseText (string pinyin) { string key = pinyin.Trim ().ToLower (); foreach (string str in PyCode.codes) { if (str.StartsWith (key + " ") || str.StartsWith (key + ":")) return str.Substring (7); } return ""; } /// <summary> /// 取和拼音相同的汉字列表,编码同参数encoding /// </summary> /// <param name="pinyin">编码为encoding的拼音</param> /// <param name="encoding">编码</param> /// <returns>返回编码为encoding的拼音为pinyin的汉字列表,如拼音“ai”将会返回“唉爱……”等</returns> public static string GetChineseText (string pinyin, Encoding encoding) { string text = ConvertEncoding (pinyin, encoding, Encoding.UTF8); return ConvertEncoding (GetChineseText (text), Encoding.UTF8, encoding); } /// <summary> /// 返回单个字符的汉字拼音 /// </summary> /// <param name="ch">编码为UTF8的中文字符</param> /// <returns>ch对应的拼音</returns> public static string GetPinyin (char ch) { short hash = GetHashIndex (ch); for (var i = 0; i < PyHash.hashes[hash].Length; ++i) { short index = PyHash.hashes[hash][i]; var pos = PyCode.codes[index].IndexOf (ch, 7); if (pos != -1) return PyCode.codes[index].Substring (0, 6).Trim (); } return ch.ToString (); } /// <summary> /// 返回单个字符的汉字拼音 /// </summary> /// <param name="ch">编码为encoding的中文字符</param> /// <returns>编码为encoding的ch对应的拼音</returns> public static string GetPinyin (char ch, Encoding encoding) { ch = ConvertEncoding (ch.ToString (), encoding, Encoding.UTF8) [0]; return ConvertEncoding (GetPinyin (ch), Encoding.UTF8, encoding); } /// <summary> /// 转换编码 /// </summary> /// <param name="text">文本</param> /// <param name="srcEncoding">源编码</param> /// <param name="dstEncoding">目标编码</param> /// <returns>目标编码文本</returns> public static string ConvertEncoding (string text, Encoding srcEncoding, Encoding dstEncoding) { byte[] srcBytes = srcEncoding.GetBytes (text); byte[] dstBytes = Encoding.Convert (srcEncoding, dstEncoding, srcBytes); return dstEncoding.GetString (dstBytes); } /// <summary> /// 取文本索引值 /// </summary> /// <param name="ch">字符</param> /// <returns>文本索引值</returns> private static short GetHashIndex (char ch) { return (short) ((uint) ch % PyCode.codes.Length); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoneConstaint : MonoBehaviour { [SerializeField] private bool _constrainX; [SerializeField] private bool _constrainY; [SerializeField] private bool _constrainZ; [SerializeField] private float _minX; [SerializeField] private float _maxX; [SerializeField] private float _minY; [SerializeField] private float _maxY; [SerializeField] private float _minZ; [SerializeField] private float _maxZ; [SerializeField] private Transform _lookAt; private Vector3 _offset; private Quaternion _initialRotation; // Start is called before the first frame update void Start() { _offset = transform.localEulerAngles; _initialRotation = transform.localRotation; } // Update is called once per frame void FixedUpdate() { if (_lookAt != null) { transform.LookAt(_lookAt); transform.localRotation = transform.localRotation * _initialRotation; } var rotation = transform.localEulerAngles; if (_constrainX) { rotation.x = _offset.x; } else if (_minX != 0 || _maxX != 0) { rotation.x = _offset.x + Mathf.Clamp(rotation.x - _offset.x, _minX, _maxX); } if (_constrainY) { rotation.y = _offset.y; } else if (_minY != 0 || _maxY != 0) { rotation.y = _offset.y + Mathf.Clamp(rotation.y - _offset.y, _minY, _maxY); } if (_constrainZ) { rotation.z = _offset.z; } else if (_minZ != 0 || _maxZ != 0) { rotation.z = _offset.z + Mathf.Clamp(rotation.z - _offset.z, _minZ, _maxZ); } transform.localEulerAngles = rotation; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Camera))] public class DynamicCamera : MonoBehaviour { //camera position offset public Vector3 offset; public Vector3 velocity; public float smoothTime; private Camera cam; public float minSize; public float maxSize; private void Start() { cam = GetComponent<Camera>(); } private void LateUpdate() { if(Game.Instance.Player.Count != 0) { transform.position = Vector3.SmoothDamp(transform.position, GetCenterPoint() + offset, ref velocity, smoothTime); cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, GetOptimalCameraSize(), Time.deltaTime * 2); } } private Vector3 GetCenterPoint() { Bounds bounds = new Bounds(Game.Instance.Player[1].transform.position, Vector3.zero); for(int i = 0; i < 1; i++) { if (Game.Instance.Player[i].Alive) { bounds.Encapsulate(Game.Instance.Player[i].transform.position); } } return bounds.center; } private float GetOptimalCameraSize() { Bounds bounds = new Bounds(Game.Instance.ship.transform.position, Vector3.zero); for (int i = 0; i < Game.Instance.Player.Count; i++) { if (Game.Instance.Player[i].Alive) { bounds.Encapsulate(Game.Instance.Player[i].transform.position); } } return Mathf.Clamp(Mathf.Max(bounds.size.x, bounds.size.y * 1.78f ) * .75f , minSize, maxSize); } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class Walk { private GameObject m_owner; private float rotationSpeed = 10f; // @ Constructor public Walk (GameObject owner) { this.m_owner = owner; } // @ Handle any locomotion input and assign it to the animator public void Listen () { float vertical = GetVerticalInput(); float horizontal = GetHorizontalInput(); // @ Update animator Animator animator = m_owner.GetComponent<Animator>(); animator.SetFloat(Constants.VERTICAL, vertical); animator.SetFloat(Constants.HORIZONTAL, horizontal); // @ Calculate desired rotation if (horizontal != 0f || vertical != 0f) { m_owner.transform.rotation = GetDesiredRotation(vertical, horizontal); } } // @ AI Method public void Move (float vertical, float horizontal, bool isRunning = false) { // @ Update animator Animator animator = m_owner.GetComponent<Animator>(); animator.SetFloat(Constants.VERTICAL, vertical); } // @ Return vertical input private float GetVerticalInput () { return Input.GetAxis(Constants.VERTICAL); } // @ Return horizontal input private float GetHorizontalInput () { return Input.GetAxis(Constants.HORIZONTAL); } // @ Handles rotation based on input private Quaternion GetDesiredRotation (float vertical, float horizontal) { Vector3 targetDirection = new Vector3(-1 * horizontal, 0f, -1 * vertical); Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up); Quaternion desiredRotation = Quaternion.Lerp(m_owner.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime); return desiredRotation; } }
// Copyright © 2020 Void-Intelligence All Rights Reserved. using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Nomad.Core; using Vortex.Normalization.Kernels; namespace VortexTests { [TestClass] public class Normalization { [TestMethod] public void NoNormalizationTest() { var a = new Matrix(5, 5); a.InRandomize(); var norm = new NoNorm(); Assert.IsTrue(Math.Abs(a.FrobeniusNorm() - norm.Normalize(a).FrobeniusNorm()) < 0.1, norm.Type().ToString() + " Normalization!"); } } }
using System; using System.Linq; using System.Text.Json; using System.Threading.Tasks; namespace DotNetStandardLibrary { public class ExampleClass { public string Test { get; } public ExampleClass(string test) { Test = test; } /// <summary> /// Uses the Span type /// </summary> public ExampleClass WriteSpans() { var spans = new Span<string>(new string[] { "One", "Two" }); foreach (var span in spans) { Console.WriteLine(span); } return this; } /// <summary> /// Use an Async foreach with IAsyncEnumerable /// </summary> public static async Task DoAsyncNumbersAsync() { var asyncEnumerable = AsyncEnumerable.Range(0, 10); await foreach (var number in asyncEnumerable) { Console.WriteLine($"Awaited Number: {number}"); } } /// <summary> /// Serialize and Deserialize with System.Text.Json /// </summary> public ExampleClass DoSerialize() { var dailyTemperature = new DailyTemperature(10, 20); var json = JsonSerializer.Serialize(dailyTemperature); dailyTemperature = JsonSerializer.Deserialize<DailyTemperature>(json); if (dailyTemperature == null) { throw new InvalidOperationException(); } Console.WriteLine($"Json: {json}\r\nHigh: {dailyTemperature.HighTemp} Low: {dailyTemperature.LowTemp}"); return this; } } public static class Extensions { /// <summary> /// C# Pattern matching example /// </summary> public static bool IsLetter(this char c) => c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z'); } /// <summary> /// IAsyncDisposable Example /// </summary> public class AsyncDisposable : IAsyncDisposable { public ValueTask DisposeAsync() => new ValueTask(Task.FromResult(true)); } /// <summary> /// Record example /// </summary> public record DailyTemperature(double HighTemp, double LowTemp); }
using System; using System.Data.SQLite; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Griffin.Core.Data; using Griffin.Core.Data.Mapper; using Griffin.Core.Data.Mapper.CommandBuilders; using Griffin.Data.Sqlite; namespace Sqlite { class Program { static void Main(string[] args) { CommandBuilderFactory.Assign(mapper => new SqliteCommandBuilder(mapper)); string cs = "URI=file:test.db"; var connection = new SQLiteConnection(cs); connection.Open(); if (!connection.TableExists("Users")) { using (var uow = new AdoNetUnitOfWork(connection)) { uow.Execute( "CREATE TABLE Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, FirstName TEXT, LastName text, CreatedAtUtc INTEGER)"); uow.SaveChanges(); } } var users = connection.ToList<User>(new {FirstName = "Gau%"}); var first = connection.First<User>(new {Id = 1}); // clear old data using (var uow = new AdoNetUnitOfWork(connection)) { using (var cmd = uow.CreateCommand()) { cmd.CommandText = "SELECT * FROM Users"; cmd.AddParameter("id", "983498043903"); foreach (var entity in cmd.ToEnumerable<User>()) { Console.WriteLine(entity.FirstName); } } uow.Truncate<User>(); for (int i = 0; i < 100; i++) { uow.Insert(new User { FirstName = "Arne" + i }); } uow.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio12 { class DiasDosMeses { static void Main(string[] args) { { Console.Write("Três primeiras letras do mês? "); string Mes = Console.ReadLine().ToUpper(); int Dias; switch (Mes) { case "FEV": Dias = 28; break; case "ABR": case "JUN": case "SET": case "NOV": Dias = 30; break; default: Dias = 31; break; } Console.WriteLine("{0} tem {1} dias", Mes, Dias); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Npgsql; namespace Lucky13_Milestone2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { curUserSelected curUser = new curUserSelected(); public MainWindow() { InitializeComponent(); addFriendsDataColums2Grid(); addFriendsTipDataColums2Grid(); addColums2Grid(); addStates(); addSortResultsList(); friendRecommendationsButton.IsEnabled = false; } private string buildConnectionString() { return "Host = localhost; Username = postgres; Database = 415Project; password = 605027"; } private void addFriendsDataColums2Grid() { DataGridTextColumn col1 = new DataGridTextColumn(); col1.Binding = new Binding("friend_name"); col1.Header = "Name"; col1.Width = 80; friendsDataGrid.Columns.Add(col1); DataGridTextColumn col2 = new DataGridTextColumn(); col2.Binding = new Binding("friend_total_likes"); col2.Header = "Total Likes"; col2.Width = 60; friendsDataGrid.Columns.Add(col2); DataGridTextColumn col3 = new DataGridTextColumn(); col3.Binding = new Binding("friend_stars"); col3.Header = "Avg Stars"; col3.Width = 60; friendsDataGrid.Columns.Add(col3); DataGridTextColumn col4 = new DataGridTextColumn(); col4.Binding = new Binding("yelping_since"); col4.Header = "Yelping Since"; col4.Width = 288; friendsDataGrid.Columns.Add(col4); } private void addFriendsTipDataColums2Grid() { DataGridTextColumn col1 = new DataGridTextColumn(); col1.Binding = new Binding("user_name"); col1.Header = "User Name"; col1.Width = 70; friendsTipsDataGrid.Columns.Add(col1); DataGridTextColumn col2 = new DataGridTextColumn(); col2.Binding = new Binding("business_name"); col2.Header = "Business"; col2.Width = 90; friendsTipsDataGrid.Columns.Add(col2); DataGridTextColumn col3 = new DataGridTextColumn(); col3.Binding = new Binding("city"); col3.Header = "City"; col3.Width = 60; friendsTipsDataGrid.Columns.Add(col3); DataGridTextColumn col4 = new DataGridTextColumn(); col4.Binding = new Binding("tipText"); col4.Header = "Text"; col4.Width = 288; friendsTipsDataGrid.Columns.Add(col4); DataGridTextColumn col5 = new DataGridTextColumn(); col5.Binding = new Binding("tipDate"); col5.Header = "Date"; col5.Width = 288; friendsTipsDataGrid.Columns.Add(col5); } private void addColums2Grid() { DataGridTextColumn col1 = new DataGridTextColumn(); col1.Binding = new Binding("name"); col1.Header = "BuisnessName"; col1.Width = 138; businessGrid.Columns.Add(col1); DataGridTextColumn col2 = new DataGridTextColumn(); col2.Binding = new Binding("address"); col2.Header = "Address"; col2.Width = 140; businessGrid.Columns.Add(col2); DataGridTextColumn col3 = new DataGridTextColumn(); col3.Binding = new Binding("city"); col3.Header = "City"; col3.Width = 50; businessGrid.Columns.Add(col3); DataGridTextColumn col4 = new DataGridTextColumn(); col4.Binding = new Binding("state"); col4.Header = "State"; col4.Width = 30; businessGrid.Columns.Add(col4); DataGridTextColumn col5 = new DataGridTextColumn(); col5.Binding = new Binding("distance"); col5.Header = "Distance\n(miles) "; col5.Width = 50; businessGrid.Columns.Add(col5); DataGridTextColumn col6 = new DataGridTextColumn(); col6.Binding = new Binding("star"); col6.Header = "Stars"; col6.Width = 45; businessGrid.Columns.Add(col6); DataGridTextColumn col7 = new DataGridTextColumn(); col7.Binding = new Binding("numTips"); col7.Header = "# of Tips"; col7.Width = 55; businessGrid.Columns.Add(col7); //DataGridTextColumn col8 = new DataGridTextColumn(); //col8.Binding = new Binding("totalCheckins"); //col8.Header = "Total Checkins"; //col8.Width = 60; //businessGrid.Columns.Add(col8); //DataGridTextColumn col9 = new DataGridTextColumn(); //col9.Binding = new Binding("bid"); //col9.Header = ""; //col9.Width = 0; //businessGrid.Columns.Add(col9); } private void addSortResultsList() { sortResultsList.Items.Add("Name"); sortResultsList.Items.Add("Highest rated"); sortResultsList.Items.Add("Most number of tips"); //sortResultsList.Items.Add("Most checkins"); sortResultsList.Items.Add("Nearest"); } private void inputUserTextBox_TextChanged(object sender, TextChangedEventArgs e) { if (listBox.SelectedIndex == -1 || inputUserTextBox.Text == "") friendRecommendationsButton.IsEnabled = false; listBox.Items.Clear(); clearUserData(); friendsDataGrid.Items.Clear(); friendsTipsDataGrid.Items.Clear(); if (inputUserTextBox.Text.Length > 0) { using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "SELECT distinct user_id FROM users WHERE name like '" + inputUserTextBox.Text + "' ORDER BY user_id asc"; using (var reader = cmd.ExecuteReader()) try { while (reader.Read()) { listBox.Items.Add(reader.GetString(0)); } } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } } } private void clearUserData() { nameTextBox.Text = ""; starsTextBox.Text = ""; fansTextBox.Text = ""; yelpSinceTxt.Text = ""; funnyTxt.Text = ""; coolTxt.Text = ""; usefulTxt.Text = ""; tipCountTxt.Text = ""; totalTipLikesTxt.Text = " "; latTxt.Text = ""; longTxt.Text = ""; } private int[] updateCounts(string userID) { int[] totals = new int[2]; using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "SELECT COUNT(tip_text), COALESCE(SUM(likes), 0) AS TotalLikes FROM tip WHERE user_id = '" + userID + "'; "; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { totals[0] = reader.GetInt32(0); totals[1] = reader.GetInt32(1); } } cmd.CommandText = "UPDATE users SET tipcount = " + totals[0] + ", total_likes = " + totals[1] + " WHERE user_id = '" + userID + "' ;"; cmd.ExecuteNonQuery(); } connection.Close(); } return totals; } private DateTime convertToDate(int y, int m, int d, int hr, int min, int sec) { string date = y.ToString() + "-" + m.ToString() + "-" + d.ToString() + " " + hr.ToString() + ":" + min.ToString() + ":" + sec.ToString(); return Convert.ToDateTime(date); } private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if(listBox.SelectedIndex != -1) friendRecommendationsButton.IsEnabled = true; clearUserData(); friendsDataGrid.Items.Clear(); friendsTipsDataGrid.Items.Clear(); List<string> friendIds = new List<string>(); if (listBox.SelectedIndex > -1) { using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; int[] counts = updateCounts(listBox.SelectedItem.ToString()); // cur user cmd.CommandText = "SELECT * FROM users WHERE user_id = '" + listBox.SelectedItem.ToString() + "' ORDER BY user_id"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { starsTextBox.Text = reader.GetDouble(0).ToString(); coolTxt.Text = reader.GetInt32(1).ToString(); fansTextBox.Text = reader.GetInt32(2).ToString(); funnyTxt.Text = reader.GetInt32(3).ToString(); usefulTxt.Text = reader.GetInt32(4).ToString(); curUser.name = reader.GetString(5); nameTextBox.Text = curUser.name; tipCountTxt.Text = reader.GetInt32(6).ToString(); curUser.userID = reader.GetString(7); yelpSinceTxt.Text = reader.GetString(8); totalTipLikesTxt.Text = reader.GetInt32(9).ToString(); } } cmd.CommandText = "SELECT distinct * FROM users, (SELECT DISTINCT friends.friend_id FROM friends " + "WHERE friends.user_id = '" + listBox.SelectedItem.ToString() + "') as fri WHERE fri.friend_id = users.user_id; "; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { string id = reader.GetString(7); // string stars = reader.GetDouble(0).ToString(); // string nme = reader.GetString(5); // string since = reader.GetString(8); // int totLik = reader.GetInt16(9); friendIds.Add(id); friendsDataGrid.Items.Add(new Friend { friend_id = id, friend_name = nme, friend_stars = stars, yelping_since = since, friend_total_likes = totLik }); } } cmd.CommandText = "SELECT * FROM (SELECT tip.user_id, users.name, business.name, business.city, tip.tip_text, tip.year, " + "tip.month, tip.day, tip.hour, tip.minute, tip.second FROM users, business, tip, (SELECT distinct user_id FROM users, " + "(SELECT DISTINCT friend_id FROM friends WHERE user_id = '" + listBox.SelectedItem.ToString() + "') as a " + "WHERE a.friend_id = users.user_id) as b WHERE b.user_id = users.user_id and business.business_id = tip.business_id " + "and tip.user_id = b.user_id) as ti ORDER BY year DESC, month DESC, day DESC, hour DESC, minute DESC, second DESC LIMIT 25"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { DateTime date = convertToDate(reader.GetInt32(5), reader.GetInt32(6), reader.GetInt32(7), reader.GetInt32(8), reader.GetInt32(9), reader.GetInt32(10)); friendsTipsDataGrid.Items.Add(new Tip { user_name = reader.GetString(1), business_name = reader.GetString(2), city = reader.GetString(3), tipText = reader.GetString(4), tipDate = date.ToString() }); } } } connection.Close(); } } } private void editLocationButton_Click(object sender, RoutedEventArgs e) { latTxt.IsReadOnly = false; longTxt.IsReadOnly = false; } private void updateLocationButton_Click(object sender, RoutedEventArgs e) { latTxt.IsReadOnly = true; longTxt.IsReadOnly = true; if (latTxt.Text != "" && longTxt.Text != "") { curUser.latitude = Convert.ToDouble(latTxt.Text); curUser.longitude = Convert.ToDouble(longTxt.Text); } } private void nameTextBox_TextChanged(object sender, TextChangedEventArgs e) { } private void addStates() { using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "SELECT distinct state FROM business ORDER BY state"; try { var reader = cmd.ExecuteReader(); while (reader.Read()) StateList.Items.Add(reader.GetString(0)); } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } } private void StateList_SelectionChanged(object sender, SelectionChangedEventArgs e) { CityList.Items.Clear(); if (StateList.SelectedIndex > -1) { using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; //cmd.CommandText = "SELECT distinct city FROM business WHERE state = '" + StateList.SelectedItem.ToString() + "' ORDER BY city"; cmd.CommandText = "SELECT distinct (SELECT INITCAP (city)) AS tempCity FROM business WHERE state = '" + StateList.SelectedItem.ToString() + "' ORDER BY tempCity"; try { var reader = cmd.ExecuteReader(); while (reader.Read()) CityList.Items.Add(reader.GetString(0)); } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } } } private void CityList_SelectionChanged(object sender, SelectionChangedEventArgs e) { ZipList.Items.Clear(); if (CityList.SelectedIndex > -1) { using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "SELECT distinct zipcode FROM business WHERE city = '" + CityList.SelectedItem.ToString() + "' ORDER BY zipcode"; try { var reader = cmd.ExecuteReader(); while (reader.Read()) ZipList.Items.Add(reader.GetString(0)); } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } } } private void ZipList_SelectionChanged(object sender, SelectionChangedEventArgs e) { categorylistBox.Items.Clear(); categorySelectedListBox.Items.Clear(); businessGrid.Items.Clear(); selectedBusinessDetailsListBox.Items.Clear(); numOfBusinesses.Content = "# of businesses: 0"; BusNameTextBlock.Text = "Business Name"; addresseBusTextBlock.Text = "Address"; hoursBusTextBlock.Text = "Today: Opens / Closes "; if (ZipList.SelectedIndex > -1) { using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "SELECT DISTINCT LTRIM(category) AS LeftTrimmedString FROM business, categories " + "WHERE business.state = '" + StateList.SelectedItem.ToString() + "' and business.city = '" + CityList.SelectedItem.ToString() + "' " + "and business.zipcode = '" + ZipList.SelectedItem.ToString() + "' and business.business_id = categories.business_id ORDER BY LeftTrimmedString ASC;"; try { var reader = cmd.ExecuteReader(); while (reader.Read()) categorylistBox.Items.Add(reader.GetString(0)); } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } } } private void categorylistBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void addCatButton_Click(object sender, RoutedEventArgs e) { if (categorylistBox.SelectedIndex > -1) { if (!categorySelectedListBox.Items.Contains(categorylistBox.SelectedItem)) categorySelectedListBox.Items.Add(categorylistBox.SelectedItem); } } private void removeCatButton_Click(object sender, RoutedEventArgs e) { categorySelectedListBox.Items.Remove(categorySelectedListBox.SelectedItem); } private List<Business> calDistance(Business bis) { List<Business> listBusinesses = new List<Business>(); if (curUser.latitude != 0.0 && curUser.longitude != 0.0) // if user latitude exists { using (var comm = new NpgsqlConnection(buildConnectionString())) { comm.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = comm; string buisLoc = "(SELECT latitude, longitude FROM business " + "WHERE state ='" + StateList.SelectedItem.ToString() + "' and city ='" + CityList.SelectedItem.ToString() + "' " + "and zipcode = '" + ZipList.SelectedItem.ToString() + "' and business.business_id = '" + bis.bid + "' ) as busi"; string dis = "(SELECT 2 * 3961 * asin(sqrt((sin(radians((" + curUser.latitude + " - LOC1.latitude) / 2))) ^ 2 " + "+ cos(radians(LOC1.latitude)) * cos(radians(" + curUser.latitude + ")) * " + "(sin(radians((" + curUser.longitude + " - LOC1.longitude) / 2))) ^ 2)) as DISTANCE FROM (SELECT latitude, longitude FROM " + buisLoc.ToString() + ") as LOC1) as dis"; cmd.CommandText = "SELECT dis.* FROM " + dis; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { int i = businessGrid.Items.IndexOf(bis); if (i != -1) businessGrid.Items.Remove(bis); bis.distance = Math.Round(reader.GetDouble(0), 2); listBusinesses.Add(bis); } } comm.Close(); } } } return listBusinesses; } private void sortByDistance() { List<Business> listBusinesses = new List<Business>(); for (int i = 0; i < businessGrid.Items.Count; i++) { listBusinesses.Add(businessGrid.Items.GetItemAt(i) as Business); } listBusinesses = listBusinesses.OrderBy(item => item.distance).ToList(); businessGrid.Items.Clear(); foreach (var obj in listBusinesses) { businessGrid.Items.Add(obj); } } private void searchBusinessesButton_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void insertCategoriesAttribute(Business B) // inserts categories into selected business category box { selectedBusinessDetailsListBox.Items.Clear(); using (var comm = new NpgsqlConnection(buildConnectionString())) { List<string> cat = new List<string>(); comm.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = comm; cmd.CommandText = "SELECT * FROM categories WHERE business_id = '" + B.bid + "' ORDER BY category"; selectedBusinessDetailsListBox.Items.Add("Categories"); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { cat.Add(reader.GetString(1)); selectedBusinessDetailsListBox.Items.Add("\t" + reader.GetString(1)); } } cmd.CommandText = "SELECT * FROM attributes WHERE business_id = '" + B.bid + "' " + "AND attribute != 'False' AND attribute != 'none' ORDER BY attribute_key; "; selectedBusinessDetailsListBox.Items.Add("Attributes"); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { selectedBusinessDetailsListBox.Items.Add("\t" + reader.GetString(1)); } } comm.Close(); } } } private void businessGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (businessGrid.Items.Count > 0) { Business B = businessGrid.Items[businessGrid.SelectedIndex] as Business; BusNameTextBlock.Text = B.name; addresseBusTextBlock.Text = B.address + ", " + B.city + ", " + B.state; DayOfWeek today = DateTime.Today.DayOfWeek; using (var comm = new NpgsqlConnection(buildConnectionString())) { comm.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = comm; cmd.CommandText = "SELECT day, open_time, close_time FROM hours WHERE business_id = '" + B.bid + "' "; List<Hours> busHours = new List<Hours>(); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { busHours.Add(new Hours(reader.GetString(0), reader.GetString(1), reader.GetString(2))); } } comm.Close(); bool hoursExist = false; foreach (var buis in busHours) { if (buis.day_week == today.ToString()) { hoursBusTextBlock.Text = "Today (" + today.ToString() + "): Opens: " + buis.open_time + " Closes: " + buis.close_time; hoursExist = true; } } if (!hoursExist) hoursBusTextBlock.Text = "Today (" + today.ToString() + "): Closed"; } } insertCategoriesAttribute(B); } } private void showTipsButton_Click(object sender, RoutedEventArgs e) { if (businessGrid.SelectedIndex >= 0) { Business B = businessGrid.Items[businessGrid.SelectedIndex] as Business; if ((B.bid != null) && (B.bid.ToString().CompareTo("") != 0)) { BusinessTips tipWindow = new BusinessTips(B, curUser); tipWindow.Show(); } } } private void sortResultsList_SelectionChanged(object sender, SelectionChangedEventArgs e) { updateBusinessGridWithAttributes(); } private void showReviewsButton_Click(object sender, RoutedEventArgs e) { if (businessGrid.SelectedIndex > -1 && curUser.userID != "") { BusinessReviews reviews = new BusinessReviews((Business)businessGrid.SelectedItem, curUser); reviews.Show(); } else if(businessGrid.SelectedIndex > -1 && curUser.userID == "") { MessageBox.Show("Must Select User"); } } private string sortingBy() { string sortBy = " ORDER BY name ASC"; if (sortResultsList.SelectedIndex > -1) // if sorting selection changed in drop-down menu { switch (sortResultsList.SelectedItem.ToString()) { case "Name": sortBy = " ORDER BY name ASC"; break; case "Highest rated": sortBy = " ORDER BY stars DESC"; break; case "Most number of tips": sortBy = " ORDER BY numtips DESC"; break; //case "Most checkins": // sortBy = " ORDER BY numcheckins DESC"; // break; case "Nearest": sortBy = " "; break; default: break; } } return sortBy; } private string getAttributes_Price() { string cmdstr = ""; if (oneMoneyBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='RestaurantsPriceRange2' AND attribute='1')"; else if (twoMoneyBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='RestaurantsPriceRange2' AND attribute='2')"; else if (threeMoneyBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='RestaurantsPriceRange2' AND attribute='3')"; else if (fourMoneyBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='RestaurantsPriceRange2' AND attribute='4')"; return cmdstr; } private string getAttributes_Main() { string cmdstr = ""; if (acceptsCardBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key = 'BusinessAcceptsCreditCards' AND attribute = 'True')"; if (takesReservBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='RestaurantsReservations' AND attribute='True')"; if (wheelchairBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='WheelchairAccessible' AND attribute='True')"; if (outdoorSeatingBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='OutdoorSeating' AND attribute='True')"; if (kidsBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='GoodForKids' AND attribute='True')"; if (groupsBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='RestaurantsGoodForGroups' AND attribute='True')"; if (deliveryBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='RestaurantsDelivery' AND attribute='True')"; if (takeOutBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='WiFi' AND attribute='free')"; if (bikeParkingBox.IsChecked == true) cmdstr += " AND business_id IN (SELECT business_id FROM attributes WHERE attribute_key='BikeParking' AND attribute='True')"; return cmdstr; } //private string getAttributes_Meal() //{ // string cmdstr = ""; // if (breakfastBox.IsChecked == true) // cmdstr += " AND business_id IN ( select business_id from attributes where attribute_key='breakfast' AND attribute='True')"; // if (brunchBox.IsChecked == true) // cmdstr += " AND business_id IN ( select business_id from attributes where attribute_key='brunch' AND attribute='True')"; // if (lunchBox.IsChecked == true) // cmdstr += " AND business_id IN ( select business_id from attributes where attribute_key='lunch' AND attribute='True')"; // if (dinnerBox.IsChecked == true) // cmdstr += " AND business_id IN ( select business_id from attributes where attribute_key='dinner' AND attribute='True')"; // if (dessertBox.IsChecked == true) // cmdstr += " AND business_id IN ( select business_id from attributes where attribute_key='dessert' AND attribute='True')"; // if (lateNightBox.IsChecked == true) // cmdstr += " AND business_id IN ( select business_id from attributes where attribute_key='latenight' AND attribute='True')"; // return cmdstr; //} private string getAttributes() { string cmdstr = ""; cmdstr += getAttributes_Price(); cmdstr += getAttributes_Main(); //cmdstr += getAttributes_Meal(); return cmdstr; } private string getCommandStr() { String cmdstr = ""; if (categorySelectedListBox.Items.Count > 0) // if 1+ categories selected { cmdstr = "SELECT DISTINCT * FROM business where business_id IN (SELECT business_ID FROM categories WHERE category IN ("; for (int i = 0; i < categorySelectedListBox.Items.Count; i++) { cmdstr += "'" + categorySelectedListBox.Items[i] + "'"; if (categorySelectedListBox.Items.Count - 1 > i) // if multiple categories selected cmdstr += ", "; } cmdstr += ")) AND"; } else // if no categories selected cmdstr = "SELECT DISTINCT * FROM business WHERE "; cmdstr += " state = '" + StateList.SelectedItem.ToString() + "'"; cmdstr += " AND city = '" + CityList.SelectedItem.ToString() + "'"; cmdstr += " AND zipcode = '" + ZipList.SelectedItem.ToString() + "'"; cmdstr += getAttributes(); // sees if any attributes are selected cmdstr += sortingBy(); // sort by name, most tips, most checkins, distance, Highest rated return cmdstr; } private void updateBusinessGridWithAttributes() { selectedBusinessDetailsListBox.Items.Clear(); if (CityList.SelectedIndex > -1 && StateList.SelectedIndex > -1 && ZipList.SelectedIndex > -1) { businessGrid.Items.Clear(); using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = getCommandStr(); try { var reader = cmd.ExecuteReader(); while (reader.Read()) { int numTips = reader.GetInt32(9); Business b = new Business() { bid = reader.GetString(0), name = reader.GetString(1), address = reader.GetString(2), city = reader.GetString(3), state = reader.GetString(4), zip = reader.GetString(5), lat = reader.GetDouble(6), lon = reader.GetDouble(7), star = reader.GetDouble(8), //totalCheckins = reader.GetInt32(11), numTips = numTips }; List<Business> listBusinesses = calDistance(b); if (b.numTips < 1) b.numTips = getNumTips(b.bid); businessGrid.Items.Add(b); } } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } numOfBusinesses.Content = "# of businesses: " + businessGrid.Items.Count.ToString(); if (sortResultsList.SelectedIndex != -1) if (sortResultsList.SelectedItem.ToString() == "Nearest") sortByDistance(); } } private void insertNumTips(string bid, int count) // inserts updated tip count for business in db { using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "UPDATE business SET numtips = " + count + " WHERE business_id = '" + bid + "';"; try { cmd.ExecuteNonQuery(); } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } } private int getNumTips(string bid) // counts number of tips for business and updates db value { int total = 0; using (var connection = new NpgsqlConnection(buildConnectionString())) { connection.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = connection; cmd.CommandText = "SELECT COUNT(tip_text) FROM tip WHERE business_id = '" + bid + "'"; try { var reader = cmd.ExecuteReader(); while (reader.Read()) total = reader.GetInt32(0); } catch (NpgsqlException ex) { Console.WriteLine(ex.Message.ToString()); MessageBox.Show("SQL Error - " + ex.Message.ToString()); } finally { connection.Close(); } } } if (total > 0) insertNumTips(bid, total); return total; } private void oneMoneyBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void twoMoneyBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void threeMoneyBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void fourMoneyBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void acceptsCardBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void takesReservBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void wheelchairBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void outdoorSeatingBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void kidsBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void groupsBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void deliveryBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void takeOutBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void wifiBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void bikeParkingBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void breakfastBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void lunchBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void brunchBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void dinnerBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void dessertBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void lateNightBox_Click(object sender, RoutedEventArgs e) { updateBusinessGridWithAttributes(); } private void friendRecommendationsButton_Click(object sender, RoutedEventArgs e) { FriendRecommendations freindRec = new FriendRecommendations(curUser); freindRec.Show(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Threading; namespace pjank.BossaAPI.DemoConsole.Modules { class BosAccountData : IDemoModule { public char MenuKey { get { return '5'; } } public string Description { get { return "BossaAPI basics, account info"; } } public void Execute() { // połączenie z NOLem, zalogowanie użytkownika Bossa.ConnectNOL3(); try { // tu powinniśmy chwilę zaczekać, aż NOL przyśle nam "wyciąg" Console.WriteLine("Press any key... to read account info"); Console.ReadKey(true); Console.WriteLine(); // wyświetlenie informacji o dostępnych rachunkach foreach (var account in Bossa.Accounts) { Trace.WriteLine(string.Format("Account: {0}", account.Number)); Trace.WriteLine(string.Format("- porfolio value: {0}", account.PortfolioValue)); Trace.WriteLine(string.Format("- deposit blocked: {0}", account.DepositBlocked)); Trace.WriteLine(string.Format("- available funds: {0}", account.AvailableFunds)); Trace.WriteLine(string.Format("- available cash: {0}", account.AvailableCash)); // spis papierów wartościowych na danym rachunku if (account.Papers.Count > 0) { Trace.WriteLine("- papers: "); foreach (var paper in account.Papers) Trace.WriteLine(string.Format(" {0,5} x {1}", paper.Quantity, paper.Instrument)); } // spis aktywnych zleceń na tym rachunku if (account.Orders.Count > 0) { Trace.WriteLine("- orders: "); foreach (var order in account.Orders) Trace.WriteLine(string.Format(" {0}: {1} {2} x {3} - {4}", order.Instrument, order.Side, order.Quantity, order.Price, order.StatusReport)); } Trace.WriteLine(""); } Console.WriteLine("Press any key... to exit"); Console.ReadKey(true); } finally { Bossa.Disconnect(); Bossa.Clear(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Robot.Backend { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); var usageFilter = new ApiUsageFilter(); services.AddSingleton(usageFilter); services.AddControllers(config => { config.Filters.Add(usageFilter); }); services.AddSession(options => { // TODO - check these options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddApiVersioning(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); }); } } }
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; [Serializable] public class SelfCareActivityList { public SelfCareActivity[] selfCareActivities; public SelfCareActivity GetRandomActivity(){ return selfCareActivities[UnityEngine.Random.Range(0, selfCareActivities.Length)]; } public override string ToString() { string activityPrint = "SELF CARE ACTIVITIES\n"; foreach (var activity in selfCareActivities) { activityPrint += string.Format("Name: {0}\nTime: {1}:{2}\nPath: {3}\n\n", activity.name, activity.timeMinutes, activity.timeSeconds, activity.pathToAudio); } return activityPrint; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Tomelt.ContentManagement.Records; namespace UEditor.Models { public class AlbumPartRecord:ContentPartRecord { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Carrinho { class Program { static Loja _loja = new Loja(); static List<Product> _basket = new List<Product>(); static void Main(string[] args) { Console.WriteLine("-- Bem-vindo ao Carrinho de Compras!"); string response = "S"; while (string.Equals(response, "S", StringComparison.InvariantCultureIgnoreCase)) { AddProduct(); Console.Write("-> Deseja adicionar outro produto [S/n]?"); response = Console.ReadLine(); } ListProducts(); Console.WriteLine("Total: {0}", CalculateTotal()); Console.ReadKey(); } private static void ListProducts() { foreach (var product in _basket) { Console.WriteLine("{0}\t{1}\t{2}", product.Id, product.Name, product.Price); } } private static decimal CalculateTotal() { return _basket.Sum(x => x.Price); } private static void AddProduct() { Console.Write("-> Digite o ID do produto que deseja adicionar:"); string p = Console.ReadLine(); int id; if (!int.TryParse(p, out id)) { Console.WriteLine("ID incorreto: '{0}'", p); } else { var product = _loja.Search(id); if (product == null) { Console.WriteLine("Produto '{0}' não existe.", id); } else { _basket.Add(product); Console.WriteLine("O produto '{0}' foi adicionado!", product.Name); } } } } }