text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2015 { public class Problem23 : AdventOfCodeBase { private List<Instruction> _instructions; private Dictionary<string, uint> _registers; private enum enumInstructionType { hlf, tpl, inc, jmp, jie, jio } public override string ProblemName => "Advent of Code 2015: 23"; public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private uint Answer1(List<string> input) { GetInstructions(input); SetRegisters(); Perform(); return _registers["b"]; } private uint Answer2(List<string> input) { GetInstructions(input); SetRegisters(); _registers["a"] = 1; Perform(); return _registers["b"]; } private void SetRegisters() { _registers = new Dictionary<string, uint>(); _registers.Add("a", 0); _registers.Add("b", 0); } private void Perform() { int lineNum = 0; do { var next = _instructions[lineNum]; int value = 0; switch (next.InstructionType) { case enumInstructionType.hlf: _registers[next.Value1] /= 2; lineNum++; break; case enumInstructionType.tpl: _registers[next.Value1] *= 3; lineNum++; break; case enumInstructionType.inc: _registers[next.Value1]++; lineNum++; break; case enumInstructionType.jmp: value = Convert.ToInt32(next.Value1); lineNum += value; break; case enumInstructionType.jie: if (_registers[next.Value1] % 2 == 0) { value = Convert.ToInt32(next.Value2); lineNum += value; } else { lineNum++; } break; case enumInstructionType.jio: if (_registers[next.Value1] == 1) { value = Convert.ToInt32(next.Value2); lineNum += value; } else { lineNum++; } break; } } while (lineNum < _instructions.Count && lineNum >= 0); } private void GetInstructions(List<string> input) { _instructions = input.Select(line => { var instruction = new Instruction(); var split = line.Split(' '); switch (split[0]) { case "hlf": instruction.InstructionType = enumInstructionType.hlf; break; case "tpl": instruction.InstructionType = enumInstructionType.tpl; break; case "inc": instruction.InstructionType = enumInstructionType.inc; break; case "jmp": instruction.InstructionType = enumInstructionType.jmp; break; case "jie": instruction.InstructionType = enumInstructionType.jie; break; case "jio": instruction.InstructionType = enumInstructionType.jio; break; } instruction.Value1 = split[1].Replace(",", ""); if (split.Length == 3) { instruction.Value2 = split[2]; } return instruction; }).ToList(); } private class Instruction { public enumInstructionType InstructionType { get; set; } public string Value1 { get; set; } public string Value2 { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Quizlet_Server.Entities { public class LoginRequest { public string TenNguoiDung { get; set; } public string MatKhau { get; set; } public bool RememberMe { get; set; } } }
using Microsoft.Xna.Framework.Graphics; namespace SuperMario.Entities.Mario.PlayerTexturePacks { public class SmallLuigiTexturePack: IPlayerTexturePack { public Texture2D CrouchingLeft => WinterLuigiTextureStorage.SmallLuigiStandStillLeftWinter; public Texture2D CrouchingRight => WinterLuigiTextureStorage.SmallLuigiStandStillRightWinter; public Texture2D Dead => WinterLuigiTextureStorage.DeadLuigiWinter; public Texture2D FacingLeft => WinterLuigiTextureStorage.SmallLuigiStandStillLeftWinter; public Texture2D FacingRight => WinterLuigiTextureStorage.SmallLuigiStandStillRightWinter; public Texture2D JumpingLeft => WinterLuigiTextureStorage.SmallLuigiJumpingLeftWinter; public Texture2D JumpingRight => WinterLuigiTextureStorage.SmallLuigiJumpingRightWinter; public Texture2D RunningLeft => WinterLuigiTextureStorage.SmallLuigiLeftMoveWinter; public Texture2D RunningRight => WinterLuigiTextureStorage.SmallLuigiRightMoveWinter; } }
using System.Web.Http; using Microsoft.Owin; using Owin; using ServerApi.OwinMiddleware.Authentication; [assembly: OwinStartup(typeof(ServerApi.Startup))] namespace ServerApi { public class Startup { public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); app.Use<DeviceGuidAuthenticationMiddleware>(new DeviceGuidTokenAuthenticationOptions()); app.Use<AdminGuidAuthenticationMiddleware>(new AdminGuidTokenAuthenticationOptions()); app.Use<SkautIsAuthenticationMiddleware>(new SkautIsAuthenticationOptions()); app.UseBasicAuthentication(new AdminBasicAuthenticationOptions()); app.UseWebApi(config); } } }
namespace KK.AspNetCore.EasyAuthAuthentication { /// <summary> /// Default values related to Azure EasyAuth authentication handler. /// </summary> public static class EasyAuthAuthenticationDefaults { /// <summary> /// Default scheme to identify the EasyAuth authentication. /// </summary> public const string AuthenticationScheme = "EasyAuth"; /// <summary> /// Default name to identify the EasyAuth authentication. /// </summary> public const string DisplayName = "Azure Easy Auth"; } }
using System; using System.Threading.Tasks; namespace Bounce.Services { public interface IImageProcessor { Task<byte[]> NormalizeAsync(byte[] imageData, float quality); Task<byte[]> ResizeAsync(byte[] imageData, int maxWidth, int maxHeight, float quality); } }
using System; using System.IO; using System.Windows.Forms; using static _7zipExample.LoggerClass; namespace _7zipExample { public partial class ReleaseNotesForm : Form { public ReleaseNotesForm() { InitializeComponent(); } private void ReleaseNotesForm_Load(object sender, EventArgs e) { Logger.WriteLine(" *** Release Notes Form Show Success [ReleaseNotesForm] *** "); try { richTextBox1.Text = File.ReadAllText("Textfiles/ReleaseNotes.txt"); } catch (Exception ex) { //MessageBox.Show(ex.ToString(), "ReleaseNotes Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "ReleaseNotes Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } private void button1_Click(object sender, EventArgs e) { Logger.WriteLine(" *** Close Clicked [ReleaseNotesForm] *** "); Close(); } } }
using AdminWebsite.Configuration; using AdminWebsite.Contracts.Responses; using AdminWebsite.Controllers; using FluentAssertions; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using NUnit.Framework; namespace AdminWebsite.UnitTests { public class ConfigSettingsControllerTests { [Test] public void Should_return_response_with_settings() { var azureAdConfiguration = new AzureAdConfiguration { ClientId = "ClientId", TenantId = "TenantId", ClientSecret = "ClientSecret", Authority = "Authority", RedirectUri = "https://vh-admin-web.com", PostLogoutRedirectUri = "https://vh-admin-web.com/" }; var testSettings = new TestUserSecrets { TestUsernameStem = "@hmcts.net" }; var kinlyConfiguration = new KinlyConfiguration { ConferencePhoneNumber = "1111111", JoinByPhoneFromDate= "2021-02-03" }; var applicationInsightsConfiguration = new ApplicationInsightsConfiguration(); var httpContext = new DefaultHttpContext(); httpContext.Request.Scheme = "https"; httpContext.Request.Host = new HostString("vh-admin-web.com"); httpContext.Request.PathBase = ""; var controllerContext = new ControllerContext { HttpContext = httpContext }; var configSettingsController = new ConfigSettingsController( Options.Create(azureAdConfiguration), Options.Create(kinlyConfiguration), Options.Create(applicationInsightsConfiguration), Options.Create(testSettings)) { ControllerContext = controllerContext }; var actionResult = (OkObjectResult)configSettingsController.Get().Result; var clientSettings = (ClientSettingsResponse)actionResult.Value; clientSettings.ClientId.Should().Be(azureAdConfiguration.ClientId); clientSettings.TenantId.Should().Be(azureAdConfiguration.TenantId); clientSettings.RedirectUri.Should().Be(azureAdConfiguration.RedirectUri); clientSettings.PostLogoutRedirectUri.Should().Be(azureAdConfiguration.PostLogoutRedirectUri); clientSettings.ConferencePhoneNumber.Should().Be(kinlyConfiguration.ConferencePhoneNumber); clientSettings.JoinByPhoneFromDate.Should().Be(kinlyConfiguration.JoinByPhoneFromDate); clientSettings.TestUsernameStem.Should().Be(testSettings.TestUsernameStem); } } }
using System; using System.Threading; namespace Smajlici { class ExperimentalImageSolver :ImageSolver, IImageSolver { private readonly Uri _uriToImage; private readonly Thread[] _threadArray; private readonly MyRef<bool> _solved = new MyRef<bool>() {Value=false}; private readonly MyRef<SplittedImage> _result = new MyRef<SplittedImage>(); private readonly int[] _defaultImagePosition; private readonly int _numberOfThreads; private readonly object _mutex; public ExperimentalImageSolver(Uri uriToImage,bool cheater) { _uriToImage = uriToImage; _result.Value = new SplittedImage(uriToImage, false); _threadArray = new Thread[_numberOfThreads]; _numberOfThreads = Environment.ProcessorCount; _mutex = new object(); if (cheater) { _defaultImagePosition = new int[9] { 0, 3, 8, 6, 1, 2, 5, 4, 7 }; } else { _defaultImagePosition = new int[9] { 0,1,2,3,4,5,6,7,8 }; } } public new SplittedImage Solve() { PrepareThreads(); return _result.Value; } private void PrepareThreads() { Console.WriteLine($"Start {DateTime.Now}"); DateTime date = DateTime.Now; object[] parametres = new object[7]; parametres[2] = _numberOfThreads; parametres[3] = _mutex; parametres[4] = _solved; parametres[5] = _result; int move = 0; for (int i = 0; i < _numberOfThreads; i++) { parametres[1] = _defaultImagePosition; SplittedImage tmpSplittedImage = new SplittedImage(_uriToImage, false); parametres[0] = tmpSplittedImage; parametres[6] = move; _threadArray[i] = new Thread(ThreadJob) { Name = $"Smajlici_Thread_#{i}" }; _threadArray[i].Start((object)parametres); NextPermutation(_defaultImagePosition); move++; } foreach (var threads in _threadArray) { threads.Join(); } TimeSpan duration = DateTime.Now - date; Console.WriteLine($"Threads Ended {DateTime.Now} in {move} moves, duration: {duration}"); } static void ThreadJob(object param) { object[] paramArray = (object[]) param; SplittedImage splittedImage = (SplittedImage)paramArray[0]; int[] nextImagePosition = (int[]) paramArray[1]; int skips = (int) paramArray[2]; object zamek = paramArray[3]; MyRef<bool> solved = (MyRef<bool>)paramArray[4]; MyRef<SplittedImage> result = (MyRef<SplittedImage>)paramArray[5]; int move = (int) paramArray[6]; int modulator = 0; int[] internalnextImagePosition; lock (zamek) { internalnextImagePosition = nextImagePosition; } int[] actualImagePositions = new int[9]; void GetActualImagePosition(SplittedImage splittedImag, int[] imagePositionArray) { for (int a = 0; a < 9; a++) { imagePositionArray[a] = splittedImag.GetImagePart((SplittedImage.ImagePosittion)a).Id; } } do { lock (zamek) { move++; if (splittedImage.CheckImageCorectness() && solved.Value == false) { solved.Value = true; GetActualImagePosition(result.Value, actualImagePositions); GetActualImagePosition(splittedImage, internalnextImagePosition ); for (int a = 0; a < 9; a++) { if (actualImagePositions[a] != internalnextImagePosition[a]) { int index; for (index = 0; index < 9; index++) { if (internalnextImagePosition[a] == actualImagePositions[index]) break; } result.Value.MoveImagePart((SplittedImage.ImagePosittion)index, (SplittedImage.ImagePosittion)a); GetActualImagePosition(result.Value, actualImagePositions); } result.Value.GetImagePart((SplittedImage.ImagePosittion) a).Rotation = splittedImage .GetImagePart((SplittedImage.ImagePosittion) a) .Rotation; if (result.Value.CheckImageCorectness()) break; } break; } else if (solved.Value == true) { break; } } modulator++; if (modulator %10 == 0) { Console.WriteLine($"{Thread.CurrentThread.Name} -- {move}"); } GetActualImagePosition(splittedImage, actualImagePositions); for (int a = 0; a < 9; a++) { if (actualImagePositions[a] != internalnextImagePosition[a]) { int index; for (index = 0; index < 9; index++) { if (internalnextImagePosition[a] == actualImagePositions[index]) break; } splittedImage.MoveImagePart((SplittedImage.ImagePosittion)index, (SplittedImage.ImagePosittion)a); GetActualImagePosition(splittedImage, actualImagePositions); } if (splittedImage.CheckImageCorectness()) break; } do { if (splittedImage.CheckImageCorectness()) break; } while (NextRotate(splittedImage)); } while (NextPermutation(internalnextImagePosition)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using Excel=Microsoft.Office.Interop.Excel; using System.Reflection; namespace AxiReports { /// <summary> /// Экспорт списка сущностей в эксел /// </summary> ///<remarks>по свойствам через рефлексию</remarks> public class ExcelSaver { Excel.Application xlsApp; Excel.Workbook xlsWB; Excel.Worksheet xlsWSh; string reportTitle; public ExcelSaver(string ReportTitle) { xlsApp = new Excel.Application(); xlsWB = xlsApp.Workbooks.Add(); xlsWSh = xlsWB.ActiveSheet; reportTitle = ReportTitle; } string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; PropertyInfo[] propInfos; public void DoExport<T>(List<T> ListItems) where T:Entity { if (ListItems.Count > 0) { //получаем информацию о свойстве propInfos = ListItems[0].GetType().GetProperties().OrderBy(q => q.Name).ToArray(); xlsWSh.get_Range("D1", "D1").Value = reportTitle; xlsWSh.get_Range("D1", "D1").Font.Size = 20; int i = 0; foreach (PropertyInfo pi in propInfos) { string addParam = ""; foreach (var vitem in pi.GetCustomAttributes(true)) { if ((vitem.GetType() == typeof(System.ComponentModel.DisplayNameAttribute))) { addParam = (vitem as System.ComponentModel.DisplayNameAttribute).DisplayName; } } if (addParam == "") xlsWSh.get_Range(Alphabet[i] + "2", Alphabet[i] + "2").Value = pi.Name; else xlsWSh.get_Range(Alphabet[i] + "2", Alphabet[i] + "2").Value = addParam; i++; } int j = 3; foreach (Entity item in ListItems) { ExportRecord(item, j); j++; } xlsApp.Visible = true; } } public void AddWorkBook() { xlsWB = xlsApp.Workbooks.Add(); xlsWSh = xlsWB.ActiveSheet; } private void ExportRecord(Entity item, int j) { int i = 0; foreach (PropertyInfo pi in propInfos) { if (pi.GetValue(item, null)!=null) xlsWSh.get_Range(Alphabet[i] + j.ToString(), Alphabet[i] + j.ToString()).Value = pi.GetValue(item, null).ToString(); i++; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem95 : ProblemBase { private int[] _nums; public override string ProblemName { get { return "95: Amicable chains"; } } public override string GetAnswer() { BuildNums(); return Solve().ToString(); } private void BuildNums() { _nums = new int[1000000 + 1]; for (int num = 1; num <= 1000000; num++) { for (int composite = 2; composite * num <= 1000000; composite++) { _nums[composite * num] += num; } } } private int Solve() { HashSet<int> distinct = new HashSet<int>(); int max = 0; int lowest = 0; for (int num = 2; num <= 1000000; num++) { distinct.Clear(); distinct.Add(num); int next = _nums[num]; int min = Math.Min(next, num); int length = 0; bool chainFound = false; while (next != 1) { distinct.Add(next); length++; if (next < min) { min = next; } if (next > 1000000) { break; } if (_nums[next] == next) { break; } next = _nums[next]; if (distinct.Contains(next)) { if (next == num) { chainFound = true; } break; } } if (chainFound && length > max) { max = length; lowest = min; } } return lowest; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Runtime.TagHelpers; using Microsoft.AspNetCore.Razor.TagHelpers; namespace lesson9.Infrastructure.TagHelpers { [HtmlTargetElement("current-time")] public class TimerTagHelper : TagHelper { public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "p"; output.TagMode = TagMode.StartTagAndEndTag; output.Content.SetContent($"Current time is {DateTime.Now.ToString()}"); } } }
using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Testing; using Xunit; namespace TennisBookings.Merchandise.Api.IntegrationTests.Controllers { public class CategoriesControllerTests : IClassFixture<WebApplicationFactory<Startup>> { private readonly HttpClient _client; public CategoriesController(WebApplicationFactory<Startup> factory) { _client = factory.CreateDefaultClient(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace com.Sconit.Entity.MRP.TRANS { [Serializable] public partial class MrpMiPlanDetail : EntityBase { #region O/R Mapping Properties public int Id { get; set; } public int PlanId { get; set; } [Display(Name = "MrpMiPlan_ParentItem", ResourceType = typeof(Resources.MRP.MrpMiPlan))] public string ParentItem { get; set; } [Display(Name = "MrpMiPlan_SourceFlow", ResourceType = typeof(Resources.MRP.MrpMiPlan))] public string SourceFlow { get; set; } [Display(Name = "MrpMiPlan_SourceParty", ResourceType = typeof(Resources.MRP.MrpMiPlan))] public string SourceParty { get; set; } [Display(Name = "MrpMiPlan_Qty", ResourceType = typeof(Resources.MRP.MrpMiPlan))] public double Qty { get; set; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FinishTrigger : MonoBehaviour { private void OnTriggerEnter(Collider other) { if(other.transform.GetComponent<AlienController>() != null) { LevelManager.instance.GameFinished(); } } }
using System; using Compiler.TreeStructure.Expressions; using Compiler.TreeStructure.MemberDeclarations; using Compiler.TreeStructure.Statements; namespace Compiler.TreeStructure.Visitors { /// <summary> /// Makes all traverse across the tree /// </summary> // Рекурсивно пробегает по всему дереву, никаких изменений он не делает public class BaseVisitor: IVisitor { public virtual void Visit(Class @class) { @class.SelfClassName.Accept(this); foreach (var classMemberDeclaration in @class.MemberDeclarations) classMemberDeclaration.Accept(this); } public virtual void Visit(VariableDeclaration variableDeclaration) { variableDeclaration.Expression.Accept(this); } public virtual void Visit(Expression expression) { expression.PrimaryPart.Accept(this); foreach (var call in expression.Calls) call.Accept(this); } public virtual void Visit(RealLiteral realLiteral) { } public virtual void Visit(IntegerLiteral integerLiteral) { } public virtual void Visit(BooleanLiteral booleanLiteral) { } public virtual void Visit(Object obj) { } public virtual void Visit(MethodDeclaration methodDeclaration) { foreach (var parameter in methodDeclaration.Parameters) parameter.Accept(this); foreach (var element in methodDeclaration.Body) element.Accept(this); } public virtual void Visit(Assignment assignment) { assignment.Expression.Accept(this); } public virtual void Visit(IfStatement ifStatement) { ifStatement.Expression.Accept(this); foreach (var body in ifStatement.Body) body.Accept(this); foreach (var elseBody in ifStatement.ElseBody) elseBody.Accept(this); } public virtual void Visit(ReturnStatement returnStatement) { returnStatement.Expression?.Accept(this); } public virtual void Visit(WhileLoop whileLoop) { foreach (var body in whileLoop.Body) body.Accept(this); whileLoop.Expression.Accept(this); } public virtual void Visit(ConstructorDeclaration constructorDeclaration) { foreach (var parameter in constructorDeclaration.Parameters) parameter.Accept(this); foreach (var body in constructorDeclaration.Body) body.Accept(this); } public virtual void Visit(ParameterDeclaration parameter) { parameter.Type.Accept(this); } public virtual void Visit(ClassName className) { for (var i = 0; i < className.Specification.Count; i++) { var name = className.Specification[i]; name.Accept(this); } } public virtual void Visit(Base @base) { throw new NotImplementedException(); } public virtual void Visit(This @this) { throw new NotImplementedException(); } public virtual void Visit(Call call) { foreach (var argument in call.Arguments) argument.Accept(this); } public virtual void Visit(FieldCall fieldCall) { } public virtual void Visit(LocalCall localCall) { if (localCall.Arguments == null) return; foreach (var localCallArgument in localCall.Arguments) localCallArgument.Accept(this); } public virtual void Visit(ConstructorCall constructorCall) { constructorCall.ClassName.Accept(this); constructorCall.Arguments.ForEach(arg => arg.Accept(this)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AxisPosCore.Common; using KartObjects; namespace AxisPosCore { public class POSLogOnState:POSAbstractState { /// <summary> /// Диалог авторизации был отменен /// </summary> private bool _DialogCanceled; public bool dialogCanceled { get { return _DialogCanceled; } set { _DialogCanceled = value; if (value) { if (WasCashier!=null) POSEnvironment.Cashier = WasCashier; } } } public override event POSStateDelegate OnStateEnter; Cashier WasCashier; public override void ExecState(PosCore core) { model = core; WasCashier = POSEnvironment.Cashier; if (OnStateEnter != null) OnStateEnter(this); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class QuarantineSpecialist : Role { public QuarantineSpecialist(){ id = Vals.QUARANTINE_SPECIALIST; name = Vals.ROLES[id]; } }
using gView.Framework.Data; using gView.Framework.Data.Filters; using gView.Framework.Geometry; using gView.Framework.OGC.WFS; using System; using System.Threading.Tasks; using System.Xml; namespace gView.Framework.OGC.GML { public class FeatureCursor : gView.Framework.Data.FeatureCursor { private XmlNodeList _features = null; private XmlNamespaceManager _ns; private IQueryFilter _filter; private int _pos = 0; private IFeatureClass _fc; private bool _checkGeometryRelation = true; private GmlVersion _gmlVersion; public FeatureCursor(IFeatureClass fc, XmlNode featureCollection, XmlNamespaceManager ns, IQueryFilter filter, GmlVersion gmlVersion) : base((fc != null) ? fc.SpatialReference : null, (filter != null) ? filter.FeatureSpatialReference : null) { _ns = ns; _filter = filter; _fc = fc; _gmlVersion = gmlVersion; if (featureCollection == null || ns == null || fc == null) { return; } try { _features = featureCollection.SelectNodes("GML:featureMember/myns:" + XML.Globals.TypeWithoutPrefix(fc.Name), ns); } catch { _features = null; } } public FeatureCursor(IFeatureClass fc, XmlNode featureCollection, XmlNamespaceManager ns, IQueryFilter filter, GmlVersion gmlVersion, Filter_Capabilities filterCapabilities) : this(fc, featureCollection, ns, filter, gmlVersion) { // // wenn Filter schon geometry operation implementiert // ist es hier nicht noch einmal zu vergleichen... // if (filterCapabilities != null && _filter is ISpatialFilter && filterCapabilities.SupportsSpatialOperator(((ISpatialFilter)_filter).SpatialRelation)) { _checkGeometryRelation = false; } } #region IFeatureCursor Member public override Task<IFeature> NextFeature() { while (true) { if (_features == null || _pos >= _features.Count) { return Task.FromResult<IFeature>(null); } XmlNode featureNode = _features[_pos++]; Feature feature = new Feature(); if (featureNode.Attributes["fid"] != null) { feature.OID = XML.Globals.IntegerFeatureID(featureNode.Attributes["fid"].Value); } foreach (XmlNode fieldNode in featureNode.SelectNodes("myns:*", _ns)) { string fieldName = fieldNode.Name.Split(':')[1]; if (fieldName == _fc.ShapeFieldName.Replace("#", "")) { feature.Shape = GeometryTranslator.GML2Geometry(fieldNode.InnerXml, _gmlVersion); } else { FieldValue fv = new FieldValue(fieldName, fieldNode.InnerText); feature.Fields.Add(fv); try { if (fieldName == _fc.IDFieldName) { feature.OID = Convert.ToInt32(fieldNode.InnerText); } } catch { } } } if (feature.Shape == null) { foreach (XmlNode gmlNode in featureNode.SelectNodes("GML:*", _ns)) { feature.Shape = GeometryTranslator.GML2Geometry(gmlNode.OuterXml, _gmlVersion); if (feature.Shape != null) { break; } } } if (feature.Shape != null && _filter is ISpatialFilter && _checkGeometryRelation) { if (!SpatialRelation.Check(_filter as ISpatialFilter, feature.Shape)) { continue; } } Transform(feature); return Task.FromResult<IFeature>(feature); } } #endregion #region IDisposable Member public override void Dispose() { base.Dispose(); } #endregion } public class FeatureCursor2 : gView.Framework.Data.FeatureCursor { private XmlTextReader _reader = null; private XmlNamespaceManager _ns; private IQueryFilter _filter; private IFeatureClass _fc; private bool _checkGeometryRelation = true; private GmlVersion _gmlVersion; public FeatureCursor2(IFeatureClass fc, XmlTextReader reader, XmlNamespaceManager ns, IQueryFilter filter, GmlVersion gmlVersion) : base((fc != null) ? fc.SpatialReference : null, (filter != null) ? filter.FeatureSpatialReference : null) { _ns = ns; _filter = filter; _fc = fc; _gmlVersion = gmlVersion; if (reader == null || ns == null || fc == null) { return; } try { _reader = reader; } catch { _reader = null; } } public FeatureCursor2(IFeatureClass fc, XmlTextReader reader, XmlNamespaceManager ns, IQueryFilter filter, GmlVersion gmlVersion, Filter_Capabilities filterCapabilities) : this(fc, reader, ns, filter, gmlVersion) { // // wenn Filter schon geometry operation implementiert // ist es hier nicht noch einmal zu vergleichen... // if (filterCapabilities != null && _filter is ISpatialFilter && filterCapabilities.SupportsSpatialOperator(((ISpatialFilter)_filter).SpatialRelation)) { _checkGeometryRelation = false; } } #region IFeatureCursor Member public override Task<IFeature> NextFeature() { while (true) { if (_reader == null) { return Task.FromResult<IFeature>(null); } if (!_reader.ReadToFollowing(_fc.Name, _ns.LookupNamespace("myns"))) { return Task.FromResult<IFeature>(null); } string featureString = _reader.ReadOuterXml(); XmlDocument doc = new XmlDocument(); doc.LoadXml(featureString); XmlNode featureNode = doc.ChildNodes[0]; Feature feature = new Feature(); if (featureNode.Attributes["fid"] != null) { feature.OID = XML.Globals.IntegerFeatureID(featureNode.Attributes["fid"].Value); } foreach (XmlNode fieldNode in featureNode.SelectNodes("myns:*", _ns)) { string fieldName = fieldNode.Name.Split(':')[1]; if (fieldName == _fc.ShapeFieldName.Replace("#", "")) { feature.Shape = GeometryTranslator.GML2Geometry(fieldNode.InnerXml, _gmlVersion); } else { FieldValue fv = new FieldValue(fieldName, fieldNode.InnerText); feature.Fields.Add(fv); try { if (fieldName == _fc.IDFieldName) { feature.OID = Convert.ToInt32(fieldNode.InnerText); } } catch { } } } if (feature.Shape == null) { foreach (XmlNode gmlNode in featureNode.SelectNodes("GML:*", _ns)) { feature.Shape = GeometryTranslator.GML2Geometry(gmlNode.OuterXml, _gmlVersion); if (feature.Shape != null) { break; } } } if (feature.Shape != null && _filter is ISpatialFilter && _checkGeometryRelation) { if (!SpatialRelation.Check(_filter as ISpatialFilter, feature.Shape)) { continue; } } Transform(feature); return Task.FromResult<IFeature>(feature); } } #endregion #region IDisposable Member public override void Dispose() { base.Dispose(); if (_reader != null) { _reader.Close(); } _reader = null; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace A_day_at_the_Races { class Guy { public string Name; public Bet MyBet; public int Cash; public RadioButton MyRadioButton; public Label MyLabel; public void UpdateLabels() { MyLabel.Text = MyBet.GetDescription(); MyRadioButton.Text = Name + " has " + Cash + " bucks"; } public bool PlaceBet(int BetAmount, int DogToWin) { if (BetAmount>Cash) { MessageBox.Show("You have too little cash to place this bet."); return false; } else if ((BetAmount < Form1.minimumBetVal)&&BetAmount!=0) { MessageBox.Show("You must place a bet of atleast " + Form1.minimumBetVal + " bucks."); return false; } else { MyBet = new Bet() { Amount = BetAmount, Dog = DogToWin, Bettor = this }; UpdateLabels(); return true; } } public void ClearBet() { PlaceBet(0, 1); } public int Collect(int Winner) { Cash += MyBet.PayOut(Winner); return MyBet.PayOut(Winner); } } class Bet { public int Amount, Dog; public Guy Bettor; public string GetDescription() { string description; if (Amount > 0) description = Bettor.Name + " bets " + Amount + " bucks on dog #" + Dog + '.'; else description = Bettor.Name + " hasn't placed a bet yet."; return description; } public int PayOut(int Winner) { if (Winner == Dog) return 2 * Amount; else return -Amount; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 기본공격. 데미지를 주고 밀어내는 스킬들의 기본이된다. /// </summary> public class Push : Skill { public override void Activate(GameObject obj) { Entity entity = obj.GetComponent<Entity>(); entity.StartCoroutine(Attack(obj, 0, 2, 0.2f, "Attack")); } /// <summary> /// 적을 밀쳐내는 기본 공격 /// </summary> /// <param name="obj">사용자</param> /// <param name="diraction">공격하는 방향</param> /// <param name="power">공격력</param> /// <param name="range">공격범위</param> /// <param name="duration">적이 밀리는 시간</param> /// <returns></returns> public IEnumerator Attack(GameObject obj, float damage, float range, float duration, string animationTrigger) { Entity entity = obj.GetComponent<Entity>(); damage += entity.power; //사용자가 플레이어면 오른쪽으로, 적이면 왼쪽으로 공격한다. Vector2 diraction = obj.GetComponent<Entity>() is Player ? Vector2.right : Vector2.left; //같이 밀려나지 않게 부모를 없앤다. obj.transform.SetParent(null); //애니메이션을 실행한다. obj.GetComponent<Animator>().SetTrigger(animationTrigger); //사용자 콜라이더의 중간지점에서 레이캐스트 한다. Vector2 rayOrigin = obj.transform.position; BoxCollider2D col = obj.GetComponent<BoxCollider2D>(); rayOrigin.y += col.size.y / 2; col.enabled = false; float time = 0; RaycastHit2D hit = Physics2D.Raycast(rayOrigin, diraction, range); Debug.DrawRay(rayOrigin, diraction, Color.red, 1f); if (hit) { hit.transform.GetComponent<Entity>().TakeDamage(damage); ////한방에 안죽었으면 밀어낸다. //if (!hit.transform.gameObject) //{ while (time < duration) { hit.transform.Translate(diraction * 0.1f); time += Time.deltaTime; yield return null; } // } } col.enabled = true; } }
using UnityEngine; using System.Collections; public class MainMenu : MonoBehaviour { public void EngageMainMenu() { gameObject.SetActive( true ); } public void SwitchProfile() { //TODO Animation stuff gameObject.SetActive( false ); TitleMenuManager.instance.StartProfilePage(); } public void StartMultiplayer() { //TODO Animation Stuff gameObject.SetActive( false ); TitleMenuManager.instance.StartMultiplayer(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace AreaOfCircle { class Program { static string radius; static double area; static void Main(string[] args) { Console.WriteLine("Enter the radius of the circle: "); radius= Console.ReadLine(); try { area = Convert.ToDouble(radius) * Convert.ToDouble(radius) * 3.124; } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("Area of the circle: "+ Convert.ToString(area)); Console.ReadLine(); } } }
using DataLayer.Models; using System; using System.Collections.Generic; namespace DataLayer.Repositories { public interface ICityRepository : IRepository<City> { IEnumerable<DefaultCity> GetAllCities(); void AddCity(DefaultCity city); bool RemoveCity(DefaultCity city); } }
/****************************************************************************************** Queue using Two Stacks *******************************************************************************************/ using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static void Main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */ Queue<long> myq = new Queue<long>(); int n = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < n; i++) { string str = Console.ReadLine(); // Console.WriteLine(str); var arr = str.Split(new char[] { ' ' }); long[] iArr = arr.Select(long.Parse).ToArray(); if (iArr[0] == 1) { myq.Enqueue(iArr[1]); } else if (iArr[0] == 2) { myq.Dequeue(); } else if (iArr[0] == 3) { Console.WriteLine(myq.Peek()); } } } } /****************************************************************************************** Castle on the Grid *******************************************************************************************/ using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { public class Point { int _x; int _y; public Point() { } public Point(int a, int b) { _x = a; _y = b; } public int x { get { return _x; } } public int y { get { return _y; } } } static List<Point> pointFromPoint(int N, string[,] grid, Point point) { int x = point.x; int y = point.y; List<Point> points = new List<Point>(); while (x > 0) { x -= 1; if (grid[x, y] == "X") break; points.Add(new Point(x, y)); } x = point.x; while (x < N - 1) { x += 1; if (grid[x, y] == "X") break; points.Add(new Point(x, y)); } x = point.x; while (y > 0) { y -= 1; if (grid[x, y] == "X") break; points.Add(new Point(x, y)); } y = point.y; while (y < N - 1) { y += 1; if (grid[x, y] == "X") break; points.Add(new Point(x, y)); } return points; } static int minimumMoves(int N, string[,] grid, int startX, int startY, int goalX, int goalY) { List<Point> q = new List<Point>(); Point start = new Point(startX, startY); Point end = new Point(goalX, goalY); q.Add(start); grid[startX, startY] = "0"; while (q.Count() > 0) { var currPoint = q[q.Count() - 1];//q.Dequeue(); q.RemoveAt(q.Count() - 1); var currdist = Convert.ToInt32(grid[currPoint.x, currPoint.y]); var points = pointFromPoint(N, grid, currPoint); foreach (var p in points) { if (grid[p.x, p.y] == ".") { grid[p.x, p.y] = (currdist + 1).ToString(); q.Insert(0, p); if (p.x == end.x && p.y == end.y) return Convert.ToInt32(currdist) + 1; } } } // Complete this function return -1; } static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); // Console.WriteLine(n); string[,] grid = new string[n, n]; for (int i = 0; i < n; i++) { string str = Console.ReadLine(); for (int j = 0; j < n; j++) grid[i, j] = str[j].ToString(); // Console.WriteLine(str+ "Length" + str.Length.ToString()); // grid[i]=str; } string[] tokens_startX = Console.ReadLine().Split(' '); // foreach(var str in tokens_startX){ // Console.Write(str+" "); // } int startX = Convert.ToInt32(tokens_startX[0]); int startY = Convert.ToInt32(tokens_startX[1]); int goalX = Convert.ToInt32(tokens_startX[2]); int goalY = Convert.ToInt32(tokens_startX[3]); int result = minimumMoves(n, grid, startX, startY, goalX, goalY); Console.WriteLine(result); } } /****************************************************************************************** Down to Zero || Some test case are failing *******************************************************************************************/ using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static List<bool> vis = new List<bool>(); static void InitVis() { vis = new List<bool>(); for (int i = 0; i < 1001010; i++) { vis.Add(false); } } static void bfs(ref Tuple<int, int> curr, ref Queue<Tuple<int, int>> q) { int m = curr.Item1; for (int i = 2; i <= Math.Sqrt(m); i++) { if (m % i == 0) { int nxt = Math.Max(i, m / i); if (!vis[nxt]) { vis[nxt] = true; q.Enqueue(Tuple.Create(nxt, curr.Item2 + 1)); } } } if (m > 0 && !vis[m - 1]) { vis[m - 1] = true; q.Enqueue(Tuple.Create(m - 1, curr.Item2 + 1)); } } static void Main(String[] args) { int Q = Convert.ToInt32(Console.ReadLine()); for (int a0 = 0; a0 < Q; a0++) { int N = Convert.ToInt32(Console.ReadLine()); // Console.WriteLine(N); InitVis(); Queue<Tuple<int, int>> q = new Queue<Tuple<int, int>>(); int ans = 0; q.Enqueue(Tuple.Create(N, 0)); while (q.Count() > 0) { var curr = q.Dequeue(); if (curr.Item1 == 0) { ans = curr.Item2; break; } bfs(ref curr, ref q); } Console.WriteLine(ans); } } } /****************************************************************************************** Truck Tour *******************************************************************************************/ using System; using System.Collections.Generic; using System.IO; class Solution { struct Station { public long fuel; public long distance; } static bool checkPath(List<Station> list, int start, int N) { long fuel = 0; long i = start; while (i < N) { fuel += list[(int)i].fuel; fuel -= list[(int)i].distance; if (fuel < 0) return false; i++; if (start > 0) { if (i == start) return true; else if (i == N) i = 0; } } return true; } static void Main(String[] args) { List<Station> list = new List<Station>(); /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */ int n = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < n; i++) { string str = Console.ReadLine(); string[] strs = str.Split(new char[] { ' ' }); Station st = new Station(); st.fuel = Convert.ToInt32(strs[0]); st.distance = Convert.ToInt32(strs[1]); list.Add(st); } // Console.WriteLine(str+ "Length" + str.Length.ToString()); // grid[i]=str; int rot = -1; while (rot++ < n) { if (checkPath(list, rot, n)) break; } Console.WriteLine(rot); } } /****************************************************************************************** Queries with Fixed Length -Time out in test *******************************************************************************************/ using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static long searchArr(int n, long[] values, int d) { List<Tuple<int, int>> list = new List<Tuple<int, int>>(); List<long> maxVals = new List<long>(); for (int i = 0; i < n; i++) { if ((i + d - 1) <= n - 1) { int start = i; int end = i + d - 1; long mx = values.Skip(start).Take(d).Max(); maxVals.Add(mx); } } return maxVals.Min(); } static void Main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */ string str = Console.ReadLine(); string[] strs = str.Split(new char[] { ' ' }); int n = Convert.ToInt32(strs[0]); int d = Convert.ToInt32(strs[1]); // Console.WriteLine(n); // Console.WriteLine(d); str = Console.ReadLine(); // Console.WriteLine(str); strs = str.Split(new char[] { ' ' }); long[] values = Array.ConvertAll(strs, long.Parse); for (int i = 0; i < d; i++) { str = Console.ReadLine(); int dval = Convert.ToInt32(str); //List<Tuple<int, int>> searchList = searchArr(n, values, dval); //List<long> finalValues = getMaxValues(searchList, values); //long result = finalValues.Min(); long result = searchArr(n, values, dval); Console.WriteLine(result); } } }
using evrostroy.Domain; using evrostroy.Web.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace evrostroy.Web.Controllers { public class CatalogController : Controller { private DataManager datamanager; public CatalogController(DataManager datamanager) { this.datamanager = datamanager; } private string novinka = "новинка"; private string ycenka = "уценка"; private string skidka = "скидка"; [HttpGet] public ActionResult Price() { IEnumerable<string> cat = datamanager.ProductsRepository.GetAllProducts().Select(x => x.Категория).Distinct().OrderBy(x => x); return View(cat); } //про акционные товары скидка уценка новинка [HttpGet] public ActionResult ProductStock(int page = 1, string metka = null, int PageSize = 50) { MainCharacteristicProductModels model = new MainCharacteristicProductModels(); model.Products = datamanager.ProductsRepository.GetAllProducts().Where(x => x.Метка == metka.ToLower()).OrderBy(x => x.ИдТовара).Skip((page - 1) * PageSize).Take(PageSize); int TotalItemsProduct = datamanager.ProductsRepository.GetAllProducts().Where(x => x.Метка == metka.ToLower()).Count(); List<SelectListItem> CountItemPerPage = new List<SelectListItem>(); CountItemPerPage.Add(new SelectListItem { Text = "50", Value = "50" }); CountItemPerPage.Add(new SelectListItem { Text = "100", Value = "100" }); CountItemPerPage.Add(new SelectListItem { Text = "150", Value = "150" }); CountItemPerPage.Add(new SelectListItem { Text = "200", Value = "200" }); model.PageList = CountItemPerPage; model.PagingInfo = new PagingInfo() { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = TotalItemsProduct }; model.Category = metka; model.NameCategory = metka; model.Route = metka; return View(model); } [HttpPost] public ActionResult ProductStock(MainCharacteristicProductModels model) { return RedirectToAction("ProductStock", new { metka = model.NameCategory, PageSize = model.PagingInfo.ItemsPerPage }); } //обработка нового меню для дверей [HttpGet] public ActionResult ProductCat(int page = 1, int num = -1, string name = null, string cat = null, string podcat = null, int PageSize = 50) { MainCharacteristicProductModels model = new MainCharacteristicProductModels(); int TotalItemsProduct = 0; string podcat2 = null; if (cat!=null && num==-1) { IEnumerable<Товары> categor = datamanager.ProductsRepository.GetAllProducts().Where(x => x.Категория == cat).OrderBy(x => x.Название); if (podcat != null) { IEnumerable<Товары> podcattov = categor.Where(x => x.Подкатегория1 == podcat).OrderBy(x => x.Название); if(podcat==name) //выбор подкатегории в хлебных крошках { model.Products = podcattov.Skip((page - 1) * PageSize).Take(PageSize); TotalItemsProduct = podcattov.Count(); name = podcat; model.NameCategory = name; model.Route = cat + "/" + podcat; } else { if ((podcattov.First() != null || podcattov.Last() != null) || name != null) { model.Products = podcattov.Where(x => x.Подкатегория2 == name).OrderBy(x => x.Название).Skip((page - 1) * PageSize).Take(PageSize); TotalItemsProduct = podcattov.Where(x => x.Подкатегория2 == name).OrderBy(x => x.Название).Count(); model.NameCategory = name; model.Route = cat + "/" + podcat + "/" + name; podcat2 = name; } } } } switch (num) { case 0://входные двери производитель { model.Products = datamanager.ProductsRepository.GetAllProducts().Where(x => x.Категория == "Входные двери").Where(x => x.Производитель == name).OrderBy(x => x.Название).Skip((page - 1) * PageSize).Take(PageSize); TotalItemsProduct = datamanager.ProductsRepository.GetAllProducts().Where(x => x.Категория == "Входные двери").Where(x => x.Производитель == name).Count(); model.NameCategory = name; model.Route = "Входные двери/Производитель/" + name; cat = "Входные двери"; //podcat = "Производитель"; podcat2 = name; break; } case 2://межкомнатные двери производитель { model.Products = datamanager.ProductsRepository.GetAllProducts().Where(x => x.Категория == "Межкомнатные двери").Where(x => x.Производитель == name).OrderBy(x => x.Название).Skip((page - 1) * PageSize).Take(PageSize); TotalItemsProduct = datamanager.ProductsRepository.GetAllProducts().Where(x => x.Категория == "Межкомнатные двери").Where(x => x.Производитель == name).Count(); model.NameCategory = name; cat = "Межкомнатные двери"; //podcat = "Производитель"; podcat2 = name; model.Route = "Межкомнатные двери/Производитель/" + name; break; } case 1://выбор категории { IEnumerable<Товары> categor = datamanager.ProductsRepository.GetAllProducts().Where(x => x.Категория == name).OrderBy(x => x.Название); model.Products = categor.Skip((page - 1) * PageSize).Take(PageSize); TotalItemsProduct = categor.Count(); model.NameCategory = name; model.Route = name; cat = name; break; } default: break; } List<SelectListItem> CountItemPerPage = new List<SelectListItem>(); CountItemPerPage.Add(new SelectListItem { Text = "50", Value = "50" }); CountItemPerPage.Add(new SelectListItem { Text = "100", Value = "100" }); CountItemPerPage.Add(new SelectListItem { Text = "150", Value = "150" }); CountItemPerPage.Add(new SelectListItem { Text = "200", Value = "200" }); model.PageList = CountItemPerPage; model.PagingInfo = new PagingInfo() { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = TotalItemsProduct }; model.Podcategory2 = podcat2; model.Podcategory1 = podcat; model.Category = cat; model.Num = num; return View(model); } [HttpPost] public ActionResult ProductCat(MainCharacteristicProductModels model) { return RedirectToAction("ProductCat", new {page = (model.PagingInfo.CurrentPage>0)?model.PagingInfo.CurrentPage:1 ,num = model.Num, name = model.NameCategory, cat = model.Category, podcat=model.Podcategory1, PageSize = model.PagingInfo.ItemsPerPage }); } // хлебные крошки public PartialViewResult BreadCrumbs(MainCharacteristicProductModels mod, string additem=null) { return PartialView(mod); } //Информация о выбранном товаре [HttpGet] public ActionResult TovarInfo(int id=0,int num=-1, string cat = null, string podcat1 = null, string podcat2 = null ) {//создаем модель для передачи в хлебные крошки MainCharacteristicProductModels mod = new MainCharacteristicProductModels(); mod.Num = num; mod.Category = cat; mod.Tov = datamanager.ProductsRepository.GetProductByID(id); if ((cat != novinka.ToUpper() && cat != ycenka.ToUpper()&&cat != skidka.ToUpper())&&(podcat1 == null || podcat1 == "")) { mod.Podcategory1 = mod.Tov.Подкатегория1; if (podcat2 == null || podcat2 == "") { mod.Podcategory2 = mod.Tov.Подкатегория2; } else { mod.Podcategory2 = podcat2; } } else { mod.Podcategory1 = podcat1; if (podcat2 == null || podcat2 == "") { //mod.Podcategory2 = mod.Tov.Подкатегория2; mod.Podcategory2 = podcat2; } else { mod.Podcategory2 = podcat2; } } mod.ID = id; return View(mod); } } }
using System; namespace SharpMap.UI.Snapping { [Flags] public enum SnapRole { Free, FreeAtObject, Start, End, StartEnd, AllTrackers, TrackersNoStartNoEnd, None } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Docller.Core.Models { public class FileHistory { public File File { get; set; } public IEnumerable<Transmittal> Transmittals { get; set; } } }
using System; using Foundation; using UIKit; namespace DateAndTime05 { public partial class ViewController : UIViewController { protected ViewController(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. btnDateTime.TouchUpInside += BtnDateTime_TouchUpInside; btnNSDate.TouchUpInside += BtnNSDate_TouchUpInside; } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } #region Interactions void BtnDateTime_TouchUpInside(object sender, EventArgs e) { var currentTime = DateTime.Now; //lblDate.Text = currentTime.ToLongDateString(); lblDate.Text = currentTime.ToString("D", System.Globalization.CultureInfo.GetCultureInfo("es-mx")); lblTime.Text = currentTime.ToLongTimeString(); } void BtnNSDate_TouchUpInside(object sender, EventArgs e) { var currentTime2 = NSDate.Now; //lblDate.Text = currentTime2.Description; var tiempoFormato = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium, DateFormat = "HH:mm:ss a" }; var fechaFormato = new NSDateFormatter { DateStyle = NSDateFormatterStyle.Long, DateFormat = "dd 'de' MMMM 'del' yyyy" }; NSLocale f = new NSLocale(identifier: ("es_mx")); fechaFormato.Locale = f; tiempoFormato.Locale = f; lblDate.Text = fechaFormato.ToString(currentTime2); lblTime.Text = tiempoFormato.ToString(currentTime2); /* dateFormatter.locale = Locale(identifier: "en_US"); NSDateFormatter.locale = NSLocale(NSIdentifier: "en_US"); */ } #endregion } }
//Author: Nate Hales //Builds a gui Display when the player stays with in the trigger, watch for a button press, and stops drawing the Gui when the player leaves the space. using System.Collections; using System.Collections.Generic; using UnityEngine; public class PressureValve : MonoBehaviour { [SerializeField] Rect textRect; string displayText = "Press 'F'"; [SerializeField] GUIStyle displayStyle; [SerializeField] SteamPipes _steamPipe; public bool bIsNear = false; private void Start() { bIsNear = false; } private void OnTriggerStay(Collider other) { if (other.CompareTag("Player")) { bIsNear = true; } } private void OnTriggerExit(Collider other){ if (other.CompareTag("Player")){ bIsNear = false; } } private void OnGUI() { //if the player is near the valve display the text if (bIsNear) { Rect calcRect = new Rect();//placeholder //Make our calculations to be a proportion of the screen calcRect.x = textRect.x * Screen.width; calcRect.width = textRect.width * Screen.width; calcRect.y = textRect.y * Screen.height; calcRect.height = textRect.height * Screen.height; GUI.Label(calcRect, displayText, displayStyle);//Assign and draw if (Input.GetKeyDown(KeyCode.F)) { _steamPipe.bIsArmed = true; // arm the assign Steam pipe enabled = false; //Disable yourself } } } }
using gView.Framework.Data; using System; using System.Windows.Forms; namespace gView.Framework.Carto.Rendering.UI { internal partial class FormLabelExpression : Form { private IFeatureClass _fc; public FormLabelExpression(IFeatureClass fc) { InitializeComponent(); _fc = fc; MakeGUI(); } private void MakeGUI() { if (_fc == null) { return; } lstFields.Items.Clear(); foreach (IField field in _fc.Fields.ToEnumerable()) { if (field == null) { continue; } lstFields.Items.Add(field.name); } } public string Expression { get { return txtExpression.Text; } set { txtExpression.Text = value; } } private void lstFields_DoubleClick(object sender, EventArgs e) { if (lstFields.SelectedItems.Count != 1) { return; } string s1 = txtExpression.Text.Substring(0, txtExpression.SelectionStart); string s2 = txtExpression.Text.Substring(txtExpression.SelectionStart + txtExpression.SelectionLength, txtExpression.Text.Length - txtExpression.SelectionStart - txtExpression.SelectionLength); txtExpression.Text = s1 + "[" + lstFields.SelectedItems[0].Text + "]" + s2; txtExpression.SelectionStart = s1.Length + lstFields.SelectedItems[0].Text.Length + 2; } } }
using OrchardCore.ContentFields.Services; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Metadata; using YesSql; namespace DFC.ServiceTaxonomy.ContentPickerPreview.Services { public class EditLinkContentPickerResultProvider : DefaultContentPickerResultProvider, IContentPickerResultProvider { public EditLinkContentPickerResultProvider(IContentManager contentManager, IContentDefinitionManager contentDefinitionManager, ISession session) : base(contentManager, contentDefinitionManager, session) { } public new string Name => "EditLink"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201407170937)] public class AddUnitAlias : Migration { public override void Down() { Delete.ForeignKey().FromTable("PRF_UnitAlias").ForeignColumn("UnitID").ToTable("PRF_Unit").PrimaryColumn("UnitID"); Delete.Table("PRF_UnitAlias"); Delete.Table("PRF_UnitAlias_AUD"); } public override void Up() { Create.Table("PRF_UnitAlias") .WithColumn("UnitAliasID").AsInt32().PrimaryKey().Identity().NotNullable() .WithColumn("UnitID").AsInt32().NotNullable() .WithColumn("UnitName").AsString(500).NotNullable() .WithColumn("Archive").AsBoolean().WithDefaultValue(false).NotNullable() .WithColumn("Notes").AsString(int.MaxValue).Nullable(); Create.ForeignKey().FromTable("PRF_UnitAlias").ForeignColumn("UnitID").ToTable("PRF_Unit").PrimaryColumn("UnitID"); Create.Table("PRF_UnitAlias_AUD") .WithColumn("UnitAliasID").AsInt32().NotNullable() .WithColumn("REV").AsInt32() .WithColumn("REVTYPE").AsInt16() .WithColumn("UnitID").AsInt32().Nullable() .WithColumn("UnitName").AsString(500).Nullable() .WithColumn("Archive").AsBoolean().Nullable() .WithColumn("Notes").AsString(int.MaxValue).Nullable(); Create.PrimaryKey().OnTable("PRF_UnitAlias_AUD").Columns(new string[] { "UnitAliasID", "REV" }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Prism.Interactivity.InteractionRequest; namespace HabMap.SolutionHierarchyModule.Models { public class NewSolutionNotification : Confirmation, INewSolutionNotification { public string SolutionName { get; set; } public string SolutionLocation { get; set; } } }
#region MIT License /* * Copyright (c) 2009-2011 University of Jyväskylä, Department of Mathematical * Information Technology. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion /* * Authors: Tomi Karppinen, Tero Jäntti */ using System; namespace Jypeli { /// <summary> /// Ikkuna, joka sisältää käyttäjän määrittelemän viestin ja OK-painikkeen. /// Ikkunan koko määräytyy automaattisesti tekstin ja ruudun koon mukaan. /// </summary> public class MessageWindow : Window { /// <summary> /// Viesti. /// </summary> public Label Message { get; private set; } /// <summary> /// OK-painike /// </summary> public PushButton OKButton { get; private set; } ///<inheritdoc/> public override Color Color { get { return base.Color; } set { OKButton.Color = Color.Darker(value, 40); base.Color = value; } } /// <summary> /// Alustaa uuden viesti-ikkunan. /// </summary> /// <param name="message">Viesti</param> public MessageWindow(string message) { Layout = new VerticalLayout { Spacing = 20, LeftPadding = 15, RightPadding = 15, TopPadding = 15, BottomPadding = 15 }; int maxWidth = (int)Game.Screen.Width - 30; Message = new Label(Math.Min(maxWidth, Font.Default.MeasureSize(message).X), 100, message) { SizeMode = TextSizeMode.Wrapped, VerticalSizing = Sizing.Expanding }; Add(Message); #if !ANDROID OKButton = new PushButton("OK"); OKButton.Clicked += new Action(Close); Add(OKButton); #endif AddedToGame += AddListeners; } private void AddListeners() { var l1 = Game.Instance.PhoneBackButton.Listen(delegate { Close(); }, null).InContext(this); var l2 = Game.Instance.TouchPanel.Listen(ButtonState.Pressed, delegate { Close(); }, null).InContext(this); var l3 = Game.Instance.Keyboard.Listen(Key.Enter, ButtonState.Pressed, Close, null).InContext(this); var l4 = Game.Instance.Keyboard.Listen(Key.Space, ButtonState.Pressed, Close, null).InContext(this); associatedListeners.AddItems(l1, l2, l3, l4); foreach (var controller in Game.Instance.GameControllers) { l1 = controller.Listen(Button.A, ButtonState.Pressed, Close, null).InContext(this); l2 = controller.Listen(Button.B, ButtonState.Pressed, Close, null).InContext(this); associatedListeners.AddItems(l1, l2); } } } }
using System; namespace ResumeEditor.Torrents { public class Hashes { #region Constants /// <summary> /// Hash code length (in bytes) /// </summary> internal static readonly int HashCodeLength = 20; #endregion #region Private Fields private int count; private byte[] hashData; #endregion Private Fields #region Properties /// <summary> /// Number of Hashes (equivalent to number of Pieces) /// </summary> public int Count { get { return this.count; } } #endregion Properties #region Constructors internal Hashes(byte[] hashData, int count) { this.hashData = hashData; this.count = count; } #endregion Constructors #region Methods /// <summary> /// Determine whether a calculated hash is equal to our stored hash /// </summary> /// <param name="hash">Hash code to check</param> /// <param name="hashIndex">Index of hash/piece to verify against</param> /// <returns>true iff hash is equal to our stored hash, false otherwise</returns> public bool IsValid(byte[] hash, int hashIndex) { if (hash == null) throw new ArgumentNullException("hash"); if (hash.Length != HashCodeLength) throw new ArgumentException(string.Format("Hash must be {0} bytes in length", HashCodeLength), "hash"); if (hashIndex < 0 || hashIndex > count) throw new ArgumentOutOfRangeException("hashIndex", string.Format("hashIndex must be between 0 and {0}", count)); int start = hashIndex * HashCodeLength; for (int i = 0; i < HashCodeLength; i++) if (hash[i] != this.hashData[i + start]) return false; return true; } /// <summary> /// Returns the hash for a specific piece /// </summary> /// <param name="hashIndex">Piece/hash index to return</param> /// <returns>byte[] (length HashCodeLength) containing hashdata</returns> public byte[] ReadHash(int hashIndex) { if (hashIndex < 0 || hashIndex >= count) throw new ArgumentOutOfRangeException("hashIndex"); // Read out our specified piece's hash data byte[] hash = new byte[HashCodeLength]; Buffer.BlockCopy(this.hashData, hashIndex * HashCodeLength, hash, 0, HashCodeLength); return hash; } #endregion Methods } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundDetect : Singleton<SoundDetect> { private AudioClip clip; private string deviceName; private int sampleSize = 128; public float maxSum; [HideInInspector] public float currentVolume; // 当前麦克风检测到的音量,用于操纵音量条 //public SoundVisualize sv; private float sum_old = 0; // Use this for initialization void Start () { deviceName = Microphone.devices[0]; Debug.LogFormat("Number of devices: {0}", Microphone.devices.Length); clip = Microphone.Start(deviceName, true, 10, 44100); } // Update is called once per frame void Update () { int startPos = Microphone.GetPosition(deviceName) - (sampleSize + 1); float[] data = new float[sampleSize]; clip.GetData(data, Mathf.Max(0,startPos)); float sum = 0f; foreach (float sample in data) { sum += Mathf.Abs(sample); } // 平滑音量信号 sum = Mathf.Lerp(sum_old, sum, 0.2f); sum_old = sum; currentVolume = Mathf.Clamp(sum, 0, maxSum) / maxSum; } }
using ScriptableObjectFramework.Events; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScriptableObjectFramework.Conditions { public enum EqualityComparison { EqualTo, NotEqualTo } public class EqualityCondition<T, Y, Z> : Condition<T> where Y : IValue<T> where Z : IEvent<T> { public EqualityComparison Condition; public Y Argument; public Z Event; private EqualityComparison lastState; public override void Evaluate(T value) { EqualityComparison currentState = value.Equals(Argument.Value) ? EqualityComparison.EqualTo : EqualityComparison.NotEqualTo; if (currentState == Condition && (currentState != lastState || ExecutionMode != ConditionExecutionMode.OnThreshold)) { Event.Fire(value); } lastState = currentState; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item : MonoBehaviour { //接收玩家指令 public GameObject player; // Use this for initialization protected virtual void Start () { } // Update is called once per frame protected virtual void Update () { } protected virtual void OnTriggerEnter2D(Collider2D other) { } protected virtual void OnTriggerExit2D(Collider2D other){ } protected virtual void Action(){ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using c = System.Console; namespace ConsoleApplication2 { class Program { } class FirstProgram { static String St1, St2 = "Good Boys"; //public static void Main() //{ // Console.BackgroundColor = ConsoleColor.Yellow; // Console.WriteLine("\"Hello, Microsoft .Net Framework!\" \n Wonderfule Day to You"); // Console.WriteLine(St2); // c.WriteLine("Hello, Microsoft .Net Framework!"); // Console.WriteLine(FirstProgram.St2); //} } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New BattleData", menuName = "New BattleData", order = 52)] public class BattleData : ScriptableObject { [SerializeField] public Row[] rows; public Bot bot; [Serializable] public struct Row { public string[] units; } }
using AutoTests.Framework.Tests.Web.Elements; using AutoTests.Framework.Web.Binding; namespace AutoTests.Framework.Tests.Web.Pages.PreconditionTest { public class PreconditionTestPage : DemoPage { public ElementWithPrecondition Element { get; set; } public PreconditionTestPage(Application application) : base(application) { } public Binder<PreconditionTestModel> BindPreconditionTestModel(int position) { return new Binder<PreconditionTestModel>() .Bind(x => x.Value, Element, x => x.Position = position); } } }
using System; using KingNetwork.Client; using KingNetwork.Shared.Interfaces; namespace KingNetwork.HandlerExample.Client.PacketHandlers { /// <summary> /// This interface is responsible for represents the implementation of MyPacketHandlerOne from client packet handler. /// </summary> public class MyPacketHandlerOne : PacketHandler { /// <inheritdoc/> public override void HandleMessageData(IKingBufferReader reader) { Console.WriteLine("Received message in MyPacketHandlerOne"); } } }
namespace ContentPatcher.Framework.Lexing.LexTokens { /// <summary>A lexical token which represents a pipe that transfers the output of one token into the input of another.</summary> internal readonly struct LexTokenPipe : ILexToken { /********* ** Accessors *********/ /// <summary>The lexical token type.</summary> public LexTokenType Type { get; } /// <summary>A text representation of the lexical token.</summary> public string Text { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="text">A text representation of the lexical token.</param> public LexTokenPipe(string text) { this.Type = LexTokenType.TokenPipe; this.Text = text; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WPF.Interfaces { interface IRepository<T> where T : class, IEntity { ObservableCollection<T>Data {get;set;} ObservableCollection<T> GetAll(); T Get(int id); void Add(T item); void Delete(int id); void Update(T item); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.UI; public class ShowControlsAction : MenuAction { public GameObject toHide; public GameObject toShowOneHanded; public GameObject toShowTwoHanded; public Toggle toggle; public Transform earthModel; public Transform smallerModel; public Transform largerModel; public bool makeSmaller; public override void TakeAction() { if(toggle.isOn){ toShowOneHanded.SetActive(true); }else{ toShowTwoHanded.SetActive(true); } toHide.SetActive(false); if(earthModel!=null) { if(makeSmaller) { earthModel.position = smallerModel.position; earthModel.localScale = smallerModel.localScale; } else { earthModel.position = largerModel.position; earthModel.localScale = largerModel.localScale; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using System.Configuration; using BELCORP.GestorDocumental.Common.Excepcion; using BELCORP.GestorDocumental.Common.Util; using BELCORP.GestorDocumental.Common; using BELCORP.GestorDocumental.DA.Sharepoint; using BELCORP.GestorDocumental.BL.DDP; using BELCORP.GestorDocumental.BE.DDP; using BELCORP.GestorDocumental.BL; using System.IO; using BELCORP.GestorDocumental.BE.Comun; using System.Collections; namespace BELCORP.GestorDocumental.DDP.CA_ActualizarListasIntermedias { class Program { static void Main(string[] args) { SPSecurity.RunWithElevatedPrivileges(delegate() { string URL_SitioDDP = ConfigurationManager.AppSettings["URLSitio"].ToString(); int totalProcesar = Convert.ToInt32(ConfigurationManager.AppSettings["totalProcesar"].ToString()); Console.WriteLine("Inicio del recorrido de los tipos documentales"); Console.WriteLine("============================================="); Console.Write("Ingrese el codigo del tipo documental: "); string CodigoTipoDoc = Console.ReadLine(); TipoDocumentalBE oTipoDocumental = TipoDocumentalBL.Instance.ObtenerPorCodigo(URL_SitioDDP, CodigoTipoDoc); if (oTipoDocumental != null && !string.IsNullOrEmpty(oTipoDocumental.ListaDocumento)) { String TipoRelacion = null; if (oTipoDocumental.Codigo == Constantes.CodigoTipoDocumental.DescripcionProcesos || oTipoDocumental.Codigo == Constantes.CodigoTipoDocumental.PoliticasProceso) TipoRelacion = Constantes.TipoRelacionIntermedia.Proceso; if (oTipoDocumental.Codigo == Constantes.CodigoTipoDocumental.Procedimientos || oTipoDocumental.Codigo == Constantes.CodigoTipoDocumental.Intrucciones || oTipoDocumental.Codigo == Constantes.CodigoTipoDocumental.MetodoAnalisisInterno || oTipoDocumental.Codigo == Constantes.CodigoTipoDocumental.MetodoAnalisisExterno) TipoRelacion = Constantes.TipoRelacionIntermedia.Politica; int TotalFilas = 0; SPListItemCollection itemCollectio = SharePointHelper.ObtenerInformacionLista(URL_SitioDDP, oTipoDocumental.ListaDocumento); //List<ElementoBE> ListaElementos = ElementoBL.Instance.ListarFiltrado(URL_SitioDDP, null, 1, 100, ref TotalFilas, oTipoDocumental.ListaDocumento); int itemCount = 0; foreach (SPListItem itemElemento in itemCollectio) { Console.WriteLine("Actualizando: " + itemElemento.Title + " ID: " + itemElemento.ID); //if (itemCount == totalProcesar) //{ // Console.WriteLine("Seguro de continuar"); // Console.ReadLine(); //} if (!itemElemento.Web.AllowUnsafeUpdates) itemElemento.Web.AllowUnsafeUpdates = true; Dictionary<string, object> dicPropiedades = new Dictionary<string, object>(); switch (TipoRelacion) { case Constantes.TipoRelacionIntermedia.Politica: if (itemElemento["Politica"] != null) { Console.WriteLine(itemElemento["Politica"].ToString()); SPFieldLookupValue objSPFieldPolitica = new SPFieldLookupValue(itemElemento["Politica"].ToString()); itemElemento["Politica"] = objSPFieldPolitica; itemElemento.Update(); } break; case Constantes.TipoRelacionIntermedia.Proceso: if (itemElemento["Proceso"] != null) { SPFieldLookupValue objSPFieldProceso = new SPFieldLookupValue(itemElemento["Proceso"].ToString()); itemElemento["Proceso"] = objSPFieldProceso; itemElemento.Update(); } break; default: break; } itemCount++; //Actualizar(URL_SitioDDP, oTipoDocumental.ListaDocumento, itemElemento, TipoRelacion); } } }); } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace Xamarin.Android.Tasks.LLVMIR { // TODO: add cache for members and data provider info sealed class StructureInfo<T> : IStructureInfo { public string Name { get; } = String.Empty; public ulong Size { get; } public List<StructureMemberInfo<T>> Members { get; } = new List<StructureMemberInfo<T>> (); public NativeAssemblerStructContextDataProvider? DataProvider { get; } public int MaxFieldAlignment { get; private set; } = 0; public bool HasStrings { get; private set; } public bool HasPreAllocatedBuffers { get; private set; } public bool IsOpaque => Members.Count == 0; public StructureInfo (LlvmIrGenerator generator) { Type t = typeof(T); Name = t.GetShortName (); Size = GatherMembers (t, generator); DataProvider = t.GetDataProvider (); } public void RenderDeclaration (LlvmIrGenerator generator) { TextWriter output = generator.Output; generator.WriteStructureDeclarationStart (Name, forOpaqueType: IsOpaque); if (IsOpaque) { return; } for (int i = 0; i < Members.Count; i++) { StructureMemberInfo<T> info = Members[i]; string nativeType = LlvmIrGenerator.MapManagedTypeToNative (info.MemberType); if (info.Info.IsNativePointer ()) { nativeType += "*"; } // TODO: nativeType can be an array, update to indicate that (and get the size) string arraySize; if (info.IsNativeArray) { arraySize = $"[{info.ArrayElements}]"; } else { arraySize = String.Empty; } var comment = $"{nativeType} {info.Info.Name}{arraySize}"; generator.WriteStructureDeclarationField (info.IRType, comment, i == Members.Count - 1); } generator.WriteStructureDeclarationEnd (); } public string? GetCommentFromProvider (StructureMemberInfo<T> smi, StructureInstance<T> instance) { if (DataProvider == null || !smi.Info.UsesDataProvider ()) { return null; } string ret = DataProvider.GetComment (instance.Obj, smi.Info.Name); if (ret.Length == 0) { return null; } return ret; } public ulong GetBufferSizeFromProvider (StructureMemberInfo<T> smi, StructureInstance<T> instance) { if (DataProvider == null) { return 0; } return DataProvider.GetBufferSize (instance.Obj, smi.Info.Name); } ulong GatherMembers (Type type, LlvmIrGenerator generator) { ulong size = 0; foreach (MemberInfo mi in type.GetMembers ()) { if (mi.ShouldBeIgnored () || (!(mi is FieldInfo) && !(mi is PropertyInfo))) { continue; } var info = new StructureMemberInfo<T> (mi, generator); Members.Add (info); size += info.Size; if ((int)info.Size > MaxFieldAlignment) { MaxFieldAlignment = (int)info.Size; } if (!HasStrings && info.MemberType == typeof (string)) { HasStrings = true; } if (!HasPreAllocatedBuffers && info.Info.IsNativePointerToPreallocatedBuffer (out ulong _)) { HasPreAllocatedBuffers = true; } } return size; } } }
using System; using System.Collections.Generic; namespace BattleEngine.Utils { public class Factory : IDisposable { private Dictionary<Type, Stack<object>> _dictionary; public object newInstance(Type type, params object[] constructorArgs) { return Activator.CreateInstance(type, constructorArgs); } public object getInstance(Type type, params object[] constructorArgs) { _dictionary = _dictionary ?? (_dictionary = new Dictionary<Type, Stack<object>>()); Stack<object> collection; if (_dictionary.TryGetValue(type, out collection) && collection.Count != 0) { return collection.Pop(); } return Activator.CreateInstance(type, constructorArgs); } public T getInstance<T>() { return (T)getInstance(typeof(T)); } public void returnInstance(object instance) { if (instance != null && !(instance is Type)) { _dictionary = _dictionary ?? (_dictionary = new Dictionary<Type, Stack<object>>()); var type = instance.GetType(); Stack<object> collection; if (!_dictionary.TryGetValue(type, out collection)) { _dictionary[type] = collection = new Stack<object>(); } collection.Push(instance); } } /* INTERFACE common.system.IDisposable */ public void Dispose() { _dictionary = null; } } }
using System.Data.Entity; using angularRef.EntityFramework; using Entities; using Microsoft.Practices.Unity; using Shared; namespace angularRef.Service { public static class UnityConfigurator { public static IUnityContainer Configurate(LifetimeManager lifetimeManager) { var container = new UnityContainer(); // register all your components with the container here // it is NOT necessary to register your controllers container.RegisterType<DbContext, AppContext>(lifetimeManager); // Register Repositories container.RegisterType(typeof (IRepository<>), typeof (Repository<>)); container.RegisterType<IRepository<Kid>, Repository<Kid>>(); container.RegisterType<IKidService, KidService>(); container.RegisterType<IUnitOfWork, UnitOfWork>(); // e.g. container.RegisterType<ITestService, TestService>(); return container; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TempBasicAI : MonoBehaviour { public float testFloat; public virtual void StartTurn() { if (!Attack()) { StartCoroutine(Move()); } } public virtual bool Attack() { Debug.Log("base.Attack() called"); Debug.Log("testFloat = " + testFloat); return false; } public virtual IEnumerator Move() { Debug.Log("base.Move() called"); yield return true; } }
//\=========================================================================================== //\ File: Node.cs //\ Author: Morgan James //\ Brief: The maze is made up of nodes and so this class is used to save information about each node. //\=========================================================================================== using UnityEngine; using System.Collections.Generic; public class Node { public Vector3 m_v3WorldPosition;//The position of the node in world space. public int m_iWeight;//How important this node is. public List<Node> m_lAdjacentNodes;//Contains all of the node adjacent to this node. public int m_iAdjacentNodesOpened;//How many adjacent nodes have been check through. public bool m_bIsStart = false;//True if the node is the starting node. public bool m_bIsEnd = false;//True if the node is the final node. //Creates a node at the desired location and with the desired weight of importance. public Node(Vector3 a_v3WorldPosition, int a_iWeight) { m_v3WorldPosition = a_v3WorldPosition;//Sets the position of the node. m_iWeight = a_iWeight;//Sets the weight of the node. } }
using Abhs.Application.IService; using Abhs.Common.Enums; using Abhs.Data.Repository; using Abhs.Model.Access; using Abhs.Model.Common; using Abhs.Model.Model; using Abhs.Model.ViewModel; using StructureMap.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abhs.Application.Service { public class PackageLessonService : IBaseService<SysPackageLesson>, IPackageLessonService { [SetterProperty] public IRepositoryBase<SysPackageLesson> packageLessonDAL { get; set; } [SetterProperty] public IRepositoryBase<SysPackageLessonItems> lessonItemDAL { get; set; } public SysPackageLesson FindEntity(object pk) { return packageLessonDAL.FindEntity(pk); } public IQueryable<SysPackageLesson> Queryable() { return packageLessonDAL.IQueryable(); } public void PackageLessonInit() { var list = this.Queryable().Where(x => x.spl_State == 1).OrderBy(x => x.spl_Index).ToList(); list.ForEach(x => { var itemList = lessonItemDAL.IQueryable().Where(y => y.spk_splID == x.spl_ID).Select(y => y.spk_ID).ToList(); x.itemList = itemList; RedisService.Instance().SetPackageLessonCache<SysPackageLesson>(x.spl_ID, x); }); } /// <summary> /// 获取所有课时 /// </summary> /// <returns></returns> public List<SysPackageLesson> GetAllPackageLessonByCache() { return this.Queryable().Where(x => x.spl_State == 1).OrderBy(x => x.spl_Index).ToList(); var list = RedisService.Instance().GetAllPackageLessonData<SysPackageLesson>(); if (list == null || list.Count == 0) { list = this.Queryable().Where(x=>x.spl_State==1).OrderBy(x=>x.spl_Index).ToList(); list.ForEach(x => { var itemList = lessonItemDAL.IQueryable().Where(y => y.spk_splID == x.spl_ID).Select(y => y.spk_ID).ToList(); x.itemList = itemList; RedisService.Instance().SetPackageLessonCache<SysPackageLesson>(x.spl_ID, x); }); } return list; } /// <summary> /// 从缓存获取实体 /// </summary> /// <param name="id"></param> /// <returns></returns> public SysPackageLesson GetModelByCache(int id) { var model=RedisService.Instance().GetPackageLesson<SysPackageLesson>(id); if (model == null) { model = this.FindEntity(id); if(model != null) { var itemList = lessonItemDAL.IQueryable().Where(y => y.spk_splID == model.spl_ID).Select(y => y.spk_ID).ToList(); model.itemList = itemList; RedisService.Instance().SetPackageLessonCache<SysPackageLesson>(model.spl_ID, model); } } return model; } public SysPackageLesson GetModel(int id) { return this.FindEntity(id); } private IQueryable<SysPackageLesson> GetPackageLessonByPackId(int packId) { return this.Queryable().Where(x => x.spl_spID == packId&&x.spl_State==1).OrderBy(x=>x.spl_Index); } /// <summary> /// 获取课程下的课时,有缓存 /// </summary> /// <param name="packId"></param> /// <returns></returns> public List<SysPackageLesson> GetModelListByPackId(int packId) { return GetPackageLessonByPackId(packId).ToList(); //var lessonList = RedisService.Instance().GetPackageLessonByPackId<SysPackageLesson>(packId).OrderBy(x=>x.spl_Index).ToList(); //if (lessonList == null || lessonList.Count == 0) //{ // lessonList = GetPackageLessonByPackId(packId).ToList(); //} //return lessonList; } /// <summary> /// 获取课程下的课时,包含未审核的,有缓存 /// </summary> /// <param name="packId"></param> /// <returns></returns> public List<SysPackageLesson> GetListByPackId(int packId) { return this.Queryable().Where(x => x.spl_spID == packId&&x.spl_State!=-5).OrderBy(x => x.spl_Index).ToList(); } public List<SysPackageLesson> GetLessonByPackIds(List<int> packIds) { return this.Queryable().Where(x => packIds.Contains(x.spl_spID)&& x.spl_State ==1).ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MyHotel.Utils; using AjaxControlToolkit; namespace MyHotel.Business.Statistics { public partial class IncomesStatisticsForm : BaseWebFormMgmt { private static DateTime getDefaultStartDate() { return HelperCommon.GetUADateTimeNow().Date.AddDays(-HelperCommon.GetUADateTimeNow().Day + 1); } private static DateTime getDefaultEndDate() { return HelperCommon.GetUADateTimeNow().Date.AddDays(-HelperCommon.GetUADateTimeNow().Day + 1).AddDays(DateTime.DaysInMonth(HelperCommon.GetUADateTimeNow().Year, HelperCommon.GetUADateTimeNow().Month)).AddMilliseconds(-1); } protected override void OnInit(EventArgs e) { base.OnInit(e); DateRangerPeriod.DateChanged += new WebControls.DateRange.DateRangerControl.DateChangedEventHandler(DateRangerPeriod_DateChanged); } protected void Page_Load(object sender, EventArgs e) { if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated) { AddScriptManager(); if (!Page.IsPostBack) { DateRangerPeriod.SetDateRange(getDefaultStartDate(), getDefaultEndDate()); } else { IncomesViewCtrl.Refresh(DateRangerPeriod.GetStartDate(), DateRangerPeriod.GetEndDate()); } } else { Response.Redirect("/LoginForm.aspx"); } } void DateRangerPeriod_DateChanged(object sender, WebControls.DateRange.DateEventArgs e) { IncomesViewCtrl.Refresh(e.StartDate, e.EndDate); } } }
using NeuralNetLibrary.algorithms; using NeuralNetLibrary.components; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Windows; namespace DigitRecognition { /// <summary> /// Logika interakcji dla klasy LearningProgressWindow.xaml /// </summary> public partial class LearningProgressWindow : Window { public List<DataItem> DataItems { get; set; } public NeuralNetwork NeuralNet { get; set; } public double LearningRate { get; set; } public double Momentum { get; set; } public double ErrorThreshold { get; set; } public bool Multithreading { get; set; } private BackpropagationAlgorithm backpropagationAlgorithm; private Thread thread; private bool stopSignal; private bool refreshProgress; public LearningProgressWindow() { InitializeComponent(); } private void initChart() { chart.ChartAreas["chartArea"].AxisX.Title = "Epoka"; chart.ChartAreas["chartArea"].AxisY.Title = "Błąd"; chart.ChartAreas["chartArea"].AxisX.MajorGrid.LineColor = System.Drawing.Color.Silver; chart.ChartAreas["chartArea"].AxisY.MajorGrid.LineColor = System.Drawing.Color.Silver; chart.Series["series"].Points.Clear(); } private void Window_Loaded(object sender, RoutedEventArgs e) { refreshProgress = true; initChart(); startTraining(); } private void startTraining() { stopSignal = false; if (Multithreading) { backpropagationAlgorithm = new ParallelBackpropagation( NeuralNet, DataItems, LearningRate, Momentum, ErrorThreshold, Environment.ProcessorCount); } else { backpropagationAlgorithm = new Backpropagation( NeuralNet, DataItems, LearningRate, Momentum, ErrorThreshold); } thread = new Thread(new ThreadStart(trainNetwork)); thread.Start(); } private void trainNetwork() { bool trainComplete = false; int currentEpoch; double currentError; var watch = Stopwatch.StartNew(); do { trainComplete = backpropagationAlgorithm.Train(); if (refreshProgress) { Dispatcher.Invoke(() => { currentEpoch = backpropagationAlgorithm.GetCurrentEpoch(); currentError = backpropagationAlgorithm.GetCurrentError(); epochLabel.Content = currentEpoch.ToString(); errorLabel.Content = String.Format("{0:0.00000}", currentError); learningProgressBar.Value = (int)((ErrorThreshold / currentError * 100)); chart.Series["series"].Points.AddXY(currentEpoch, currentError); }); } } while (!trainComplete && !stopSignal); watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; Dispatcher.Invoke(() => { abortButton.IsEnabled = false; }); if (stopSignal) { backpropagationAlgorithm.Abort(); MessageBox.Show("Przerwano uczenie sieci (Czas: " + elapsedMs + " ms)"); } else { MessageBox.Show("Sieć została nauczona (Czas: " + elapsedMs + " ms)"); ; } } private void CheckBox_Checked(object sender, RoutedEventArgs e) { refreshProgress = false; } private void CheckBox_Unchecked(object sender, RoutedEventArgs e) { refreshProgress = true; } private void Abort_Button_Click(object sender, RoutedEventArgs e) { stopSignal = true; abortButton.IsEnabled = false; } protected override void OnClosed(EventArgs e) { base.OnClosed(e); stopSignal = true; } } }
namespace Tutorial.Tests.Introduction { using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Tutorial.Introduction; [TestClass] public class LinqTests { [TestMethod] public async Task LinqToJsonTest() { await Linq.LinqToJson("fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4"); } } }
namespace Blackjack21.Game.Model { /// <summary> /// Hand Type Enumerate /// </summary> public enum PlayerHandType { SINGLE_HAND = 1, SPLIT_HAND = 2 } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Services; using Newtonsoft.Json; public partial class _Default : Page { protected static void Page_Load(object sender, EventArgs e) { } protected void Page_LoadComplete(object sender, EventArgs e) { } }
using System; using System.Collections; 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 Ejercicios_LibroCSharp.Cap._10.Entidades; using Ejercicios_LibroCSharp.Cap._10.UI.Registro; using Ejercicios_LibroCSharp.Cap._10; namespace Ejercicios_LibroCSharp.Cap._10.UI.Registro { public partial class rInventarioT : Form { public rInventarioT() { InitializeComponent(); } ArrayList arrayList = new ArrayList(); public InventarioTienda [] productos = new InventarioTienda [30]; private bool Validar() { bool paso = true; MyErrorProvider.Clear(); if (DescripcionTextBox.Text == string.Empty) { MyErrorProvider.SetError(DescripcionTextBox, "Este campo no puede estar vacio"); DescripcionTextBox.Focus(); paso = false; } if (PrecioTextBox.Text == string.Empty) { MyErrorProvider.SetError(PrecioTextBox, "Este campo no puede estar vacio"); PrecioTextBox.Focus(); paso = false; } if (CantidadTextBox.Text == string.Empty) { MyErrorProvider.SetError(CantidadTextBox, "Este campo no puede estar vacio"); CantidadTextBox.Focus(); paso = false; } return paso; } public void Limpiar() { IdNumericUpDown.Text = string.Empty; DescripcionTextBox.Text = string.Empty; PrecioTextBox.Text = string.Empty; CantidadTextBox.Text = string.Empty; } public void Agregar() { InventarioTienda inventario = new InventarioTienda(); inventario.Precio = PrecioTextBox.Text; inventario.Nombre = DescripcionTextBox.Text; inventario.Precio = PrecioTextBox.Text; inventario.Cantidad = CantidadTextBox.Text; inventario.ProductoId = IdNumericUpDown.Text; arrayList.Add(productos); MessageBox.Show("!!Producto Guardado!!"); } public void Mostrar() { DataGridView.DataSource = null; DataGridView.DataSource = arrayList; } private void NuevoButton_Click(object sender, EventArgs e) { Limpiar(); } private void GuardarButton_Click(object sender, EventArgs e) { if (Validar()) Agregar(); Limpiar(); } private void MostrarButton_Click(object sender, EventArgs e) { Mostrar(); Limpiar(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReachCollider : MonoBehaviour { Ray cameraToCursorRay; Ray playerToCurorRay; RaycastHit cursorPos; public GameObject Ball; public GameObject Player; public float hittingForce = 20f; public bool inReach = false; public static bool playerLastTouched = false; void FixedUpdate() { cameraToCursorRay = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(cameraToCursorRay, out cursorPos, 1000)) { Debug.DrawRay(cameraToCursorRay.origin, cameraToCursorRay.direction * cursorPos.distance, Color.yellow); } playerToCurorRay = new Ray(Player.transform.position, cursorPos.point); Debug.DrawRay(playerToCurorRay.origin, playerToCurorRay.direction * cursorPos.distance, Color.green); // if(Input.GetMouseButtonDown(0) && inReach) // { // print(playerToCurorRay.direction); // // Ball.GetComponent<Rigidbody>().AddForce(playerToCurorRay.direction * hittingForce, ForceMode.Impulse); // // Ball.GetComponent<Rigidbody>().AddForce(Vector3.left * hittingForce, ForceMode.Impulse); // } } void OnTriggerEnter(Collider coll) { if (coll.gameObject.tag == "Ball") { inReach = true; playerLastTouched = true; FrontWallCollider.hitFrontWall = false; // Ball.GetComponent<Rigidbody>().AddForce(playerToCurorRay.direction * hittingForce, ForceMode.Impulse); Ball.GetComponent<Rigidbody>().AddForce((playerToCurorRay.direction * hittingForce) + Vector3.left, ForceMode.Impulse); } } void OnTriggerExit(Collider coll) { if (coll.gameObject.tag == "Ball") { inReach = false; } } }
using UnityEngine; using System.Collections; public class globo : MonoBehaviour { public static bool ready = false; void Start() { this.GetComponent<SpriteRenderer>().enabled = true; StartCoroutine(Mostrar()); } void FixedUpdate() { if(ready==false) { this.GetComponent<SpriteRenderer>().enabled = true; StartCoroutine(Mostrar()); } } IEnumerator Mostrar() { yield return new WaitForSeconds(4); this.GetComponent<SpriteRenderer>().enabled = false; ready = true; } }
using System.Collections.Generic; using System.Threading.Tasks; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; using TelegramFootballBot.Core.Models; namespace TelegramFootballBot.Core.Services { public interface IMessageService { Task<List<SendMessageResponse>> SendMessagesAsync(string text, IEnumerable<ChatId> chats, IReplyMarkup replyMarkup = null); Task<List<SendMessageResponse>> EditMessagesAsync(string text, IEnumerable<Message> messagesToRefresh); Task<Message> SendMessageToBotOwnerAsync(string text, IReplyMarkup replyMarkup = null); Task<Message> SendMessageAsync(ChatId chatId, string text, IReplyMarkup replyMarkup = null); Task DeleteMessageAsync(ChatId chatId, int messageId); Task<Message> SendErrorMessageToUserAsync(ChatId chatId, string playerName); Task ClearReplyMarkupAsync(ChatId chatId, int messageId); } }
using System; using System.Collections.Generic; namespace POSServices.Models { public partial class StoreDiscount { public int Id { get; set; } public string Description { get; set; } public bool? Active { get; set; } public double? DiscountPrecentage { get; set; } public double? Margin { get; set; } public int? StoreId { get; set; } public virtual Store Store { get; set; } } }
using System; namespace DelftTools.Utils { public static class ComparableExtensions { public static bool IsBigger(this IComparable object1, IComparable object2) { if (object1 == null) { return false; // null is not bigger than anything } return object1.CompareTo(object2) == 1; } public static bool IsSmaller(this IComparable object1, IComparable object2) { if (object1 == null) { return object2 != null; // smaller than anything but null } return object1.CompareTo(object2) == -1; } public static bool IsInRange(this IComparable value, IComparable limitOne, IComparable limitTwo) { IComparable min; IComparable max; if (limitOne.IsSmaller(limitTwo)) { min = limitOne; max = limitTwo; } else { min = limitTwo; max = limitOne; } return (min.IsSmaller(value) && max.IsBigger(value)) || min.CompareTo(value) == 0 || max.CompareTo(value) == 0; } } }
using System; using StardewValley.Menus; namespace SkillPrestige { /// <summary> /// Manages the necessary methods to handle a level up menu. /// </summary> public class LevelUpManager { /// <summary> /// The type of the level up menu. /// </summary> public Type MenuType { get; set; } /// <summary> /// Returns the skill being levelled up. /// </summary> public Func<Skill> GetSkill { get; set; } /// <summary> /// Returns the level that has been reached. /// </summary> public Func<int> GetLevel { get; set; } /// <summary> /// Returns the menu that will replace the original level up menu. /// </summary> public Func<Skill, int, IClickableMenu> CreateNewLevelUpMenu { get; set; } } }
using AppLogic.Dto; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Domain.InterfacesRepo; using AppLogic.DtoCreate; using DataAccess; using DataAccess.Repositories; using AppLogic.DtoUpdate; using AppLogic.DtoConverter; namespace AppLogic.Management { public class SalePositionManager : IManager<CreateSalePosition, ReadSalePosition, UpdateSalePosition> { public ReadSalePosition Add(CreateSalePosition item) { using (Context context = new Context()) { EfSalePositionRepository rep = new EfSalePositionRepository(context); SalePositionConvert convert = new SalePositionConvert(context); return convert.ToRead(rep.Add(convert.ToEntity(item))); } } public ReadSalePosition Get(int id) { using (Context context = new Context()) { EfSalePositionRepository rep = new EfSalePositionRepository(context); SalePositionConvert convert = new SalePositionConvert(context); return convert.ToRead(rep.Get(id)); } } public List<ReadSalePosition> GetAll() { using (Context context = new Context()) { EfSalePositionRepository rep = new EfSalePositionRepository(context); SalePositionConvert convert = new SalePositionConvert(context); return convert.ToReadList(rep.GetAll()); } } public ReadSalePosition Remove(int id) { using (Context context = new Context()) { EfSalePositionRepository rep = new EfSalePositionRepository(context); SalePositionConvert convert = new SalePositionConvert(context); return convert.ToRead(rep.Remove(id)); } } public bool Update(UpdateSalePosition item) { using (Context context = new Context()) { EfSalePositionRepository rep = new EfSalePositionRepository(context); SalePositionConvert convert = new SalePositionConvert(context); return rep.Update(convert.ToEntity(item)); } } } }
 namespace Stack_Sum { using System; using System.Collections; using System.Linq; class Program { static void Main(string[] args) { var input = Console.ReadLine(); var numbers = input .Split(" ") .Select(x => int.Parse(x)) .ToList(); string command = Console.ReadLine(); Stack stackToSum = new Stack(); foreach (var number in numbers) { stackToSum.Push(number); } while (command.ToLower() != "end") { var tokens = command.Split(); var currentCommand = tokens[0]; if (currentCommand.ToLower() == "add") { var firstNumber = int.Parse(tokens[1]); var secondNumber = int.Parse(tokens[2]); stackToSum.Push(firstNumber); stackToSum.Push(secondNumber); } else if (currentCommand.ToLower() == "remove") { var count = int.Parse(tokens[1]); if (stackToSum.Count < count) { command = Console.ReadLine(); continue; } for (int i = 0; i < count; i++) { stackToSum.Pop(); } } command = Console.ReadLine(); } var sum = 0; while (stackToSum.Count >0) { sum += (int)stackToSum.Pop(); } Console.WriteLine("Sum: " + sum); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitClassroom.DAL.Models { public class MentorReport { public int Id { get; set; } [ForeignKey ("Mentor")] public string MentorId { get; set; } public virtual ApplicationUser Mentor { get; set; } [ForeignKey("Student")] public string StudentId { get; set; } public virtual ApplicationUser Student { get; set; } [ForeignKey("Surveys")] public int SurveyId { get; set; } public virtual List<Survey> Surveys { get; set; } public virtual Survey Survey { get; set; } [NotMapped] public List<ApplicationUser> Students { get; set; } public List<QuestionResponse> Responses { get; set; } public DateTime DateSubmitted { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EasyDev.EPS.BusinessObject; using EasyDev.EPS.Portal; using EasyDev.EPS; namespace EasyDev.EPS.Security { public class UserService : AbstractService { /// <summary> /// 服务初始化 /// </summary> protected override void Initialize() { base.Initialize(); } /// <summary> /// 创建用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual Users CreateUser(Users user) { try { if (user.USERID == null || user.USERID.Length == 0) { user.USERID = GetDefaultBO<Users>().GetNextSequenceId("Users"); } user.CREATED = DateTime.Now; user.MODIFIED = DateTime.Now; user.ACTIVED = "Y"; if (GetDefaultBO<Users>().Save(user)) { return user; } else { return null; } } catch (Exception e) { throw e; } } /// <summary> /// 创建用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual Users CreateUser(string username, string userpwd) { Users user = ModelFactory.CreateModel<Users>(); user.NAME = username; user.PASSWORD = userpwd; try { return CreateUser(user); } catch (Exception e) { throw e; } } /// <summary> /// 创建用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual Users CreateUser(string username, string userpwd, string email) { Users user = ModelFactory.CreateModel<Users>(); user.NAME = username; user.PASSWORD = userpwd; user.EMAIL = email; try { return CreateUser(user); } catch (Exception e) { throw e; } } /// <summary> /// 创建用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual Users CreateUser(string username, string userpwd, string email, string question, string answer) { Users user = ModelFactory.CreateModel<Users>(); user.NAME = username; user.PASSWORD = userpwd; user.EMAIL = email; user.QUESTION = question; user.ANSWER = answer; try { return CreateUser(user); } catch (Exception e) { throw e; } } /// <summary> /// 删除用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual bool RemoveUser(Users user) { return GetDefaultBO<Users>().Delete(user); } /// <summary> /// 删除用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual bool RemoveUser(string userid) { Users user = ModelFactory.CreateModel<Users>(); user.USERID = userid; return RemoveUser(user); } /// <summary> /// 修改用户密码 /// </summary> /// <param name="user"></param> /// <param name="oldpasswd"></param> /// <param name="newpasswd"></param> public virtual bool ChangeUserPassword(Users user, string newpasswd) { try { Users toValidUser = ValidateUser(user); if (toValidUser != null) { toValidUser.PASSWORD = newpasswd; return GetDefaultBO<Users>().Update(toValidUser); } else { throw new InvalidUserException("Invalid_user"); } } catch (InvalidUserException e) { throw e; } } /// <summary> /// 修改用户密码,调用此方法的前提是数据库中的用户表的用户名字段应该有唯一约束 /// </summary> /// <param name="username">用户名(唯一约束)</param> /// <param name="oldpasswd"></param> /// <param name="newpasswd"></param> public virtual bool ChangeUserPassword(string username, string oldpasswd, string newpasswd) { try { Users user = ValidateUser(username, oldpasswd); if (user != null) { user.PASSWORD = newpasswd; return GetDefaultBO<Users>().Update(user); } else { throw new InvalidUserException("Invalid_user"); } } catch (InvalidUserException e) { throw e; } } /// <summary> /// 修改用户密码 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual bool ChangeUserPassword(string username, string email, string oldpasswd, string newpasswd) { try { Users user = ValidateUser(username,oldpasswd, email); if (user != null) { user.PASSWORD = newpasswd; return GetDefaultBO<Users>().Update(user); } else { throw new InvalidUserException("Invalid_user"); } } catch (InvalidUserException e) { throw e; } } /// <summary> /// 验证用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual Users ValidateUser(Users user) { return GetBO<UserBO>().FindByInstance(user) as Users; } /// <summary> /// 验证用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual Users ValidateUser(string username, string passwd) { Users user = ModelFactory.CreateModel<Users>(); user.NAME = username; user.PASSWORD = passwd; return ValidateUser(user); } /// <summary> /// 验证用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual Users ValidateUser(string username, string passwd, string email) { Users user = ModelFactory.CreateModel<Users>(); user.EMAIL = email; user.NAME = username; user.PASSWORD = passwd; return ValidateUser(user); } /// <summary> /// 用户所在的组 /// </summary> /// <param name="user"></param> /// <returns></returns> public virtual IList<Roles> RolesOfUser(string userid) { return GetBO<RoleBO>().GetRolesByUserID(userid); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using MovementManager = UnityStandardAssets.Characters.ThirdPerson.MovementManager; public class FiniteStateMachine : MonoBehaviour { /// <summary> /// Variables to hold states of FSM, used to swap a Coroutine (state) with another. /// </summary> IEnumerator _currState; IEnumerator _nextState; /// <summary> /// A List of transform of all the closest enemies /// </summary> [SerializeField]private List <Transform> _neighbors = new List <Transform>(); /// <summary> /// The transform of the leader to be followed when flocking /// </summary> [SerializeField]private Transform _leader; /// <summary> /// Maximum number of a single flock /// </summary> private int max__flock = 5; /// <summary> /// A bool to check if the leader has already been found /// </summary> private bool _leader_locked = false; /// <summary> /// The point to evade when a bullet has been shot near the agent /// </summary> private Vector3 _hitpoint; /// <summary> /// Variable to tell if a leader is attacking /// </summary> private bool _attacking; /// <summary> /// The message to alert the user an enemy leader is chasing him /// </summary> public Text AlertText; /// <summary> /// Getters /// </summary> public Vector3 hitPoint{ get { return _hitpoint; } } public bool attacking{ get { return _attacking; } } public List <Transform> neighbors{ get { return _neighbors; } } public Transform leader{ get { return _leader; } } void Start () { ///First coroutine will always be the move state _currState = Moving (); StartCoroutine(StateMachine()); } /// <summary> /// The function for showing the alert message on screen /// </summary> IEnumerator ShowMessage (string message, float delay) { AlertText.text = message; AlertText.enabled = true; yield return new WaitForSeconds(delay); AlertText.enabled = false; } /// <summary> /// Moving state will have Avoid Input and Wander Input /// </summary> IEnumerator Moving(){ GetComponent<MovementManager> ().ClearSteerings (); GetComponent<MovementManager> ().AddSteering(GetComponent<AvoidInput>()); GetComponent<MovementManager> ().AddSteering(GetComponent<WanderInput>()); while (_nextState == null) { if (Input.GetKeyDown(KeyCode.Tab)) { _nextState = Idling (); } yield return null; } } /// <summary> /// Alert State will be entered when a bullet has been shot nearby /// </summary> IEnumerator Alert(){ GetComponent<MovementManager> ().ClearSteerings (); GetComponent<MovementManager> ().AddSteering(GetComponent<AvoidInput>()); GetComponent<MovementManager> ().AddSteering(GetComponent<EvadeInput>()); while (_nextState == null) { if (GetComponent<EvadeInput>().Steering == Vector3.zero) { _nextState = Moving (); } yield return null; } } /// <summary> /// Flock state will have avoid input, follow to follow the leader and separation to keep distance from other members of the flock /// </summary> IEnumerator Flock(){ GetComponent<MovementManager> ().ClearSteerings (); GetComponent<MovementManager> ().AddSteering(GetComponent<AvoidInput>()); GetComponent<MovementManager> ().AddSteering(GetComponent<FollowInput>()); GetComponent<MovementManager> ().AddSteering(GetComponent<SeparationInput>()); while (_nextState == null) { if (_neighbors.Count > max__flock || leader == null) { _leader = null; _leader_locked = false; _neighbors.Clear(); _nextState = Idling (); //change state } yield return null; } } /// <summary> /// Attack will only be entered from leaders and will seek at full speed the player /// </summary> IEnumerator Attack(){ StartCoroutine(ShowMessage ("...KILL THE LEADERS BEFORE THEY REACH YOU...", 3)); GetComponent<MovementManager> ().ClearSteerings (); GetComponent<MovementManager> ().AddSteering(GetComponent<AvoidInput>()); GetComponent<MovementManager> ().AddSteering(GetComponent<SeekInput>()); _attacking = true; gameObject.GetComponentInChildren<Renderer> ().material.color = Color.red; while (_nextState == null) { yield return null; } } /// <summary> /// Idling is actually just a standby for 1.5 seconds, then the agent will go back to moving /// </summary> IEnumerator Idling(){ GetComponent<MovementManager> ().ClearSteerings (); GetComponent<MovementManager> ().AddSteering(GetComponent<AvoidInput>()); while (_nextState == null) { yield return new WaitForSeconds (1.5f); _nextState = Moving (); yield return null; } } /// <summary> /// The actual StateMachine will handle the state swap and loop /// </summary> IEnumerator StateMachine(){ while (_currState != null) { yield return StartCoroutine (_currState); _currState = _nextState; _nextState = null; } } /// <summary> /// All the collision is checked in here and states are swapped accordingly /// </summary> private void OnTriggerEnter(Collider coll){ if (coll.tag != null) { if (!_leader_locked && coll.CompareTag("Leader") && gameObject.tag != "Leader" //If a leader has already been picked and the agent nearby is a leader then start flocking and following it && !coll.GetComponent<FiniteStateMachine>().attacking) { _leader = coll.transform; //get the leader transform once so doesnt get confused with other leader's _leader_locked = true; _nextState = Flock (); //change state } if (coll.CompareTag("Enemy") && _leader_locked && !_neighbors.Contains(coll.transform)) { _neighbors.Add (coll.transform); } if (coll.CompareTag("Bullet") && _currState != Alert() ) { //if a bullet has been detected if (gameObject.CompareTag ("Leader") ) {//if the agent is a leader will chase the player if (_currState != Attack ()) { _nextState = Attack (); //change state } } else { //if is an enemy will stop flocking and Evade (Alert state) the point where the bullet has been shot _leader = null; _leader_locked = false; _neighbors.Clear(); if (_hitpoint == Vector3.zero) { //set the closest point of the shot _hitpoint = coll.transform.position; } _nextState = Alert (); } } } } /// <summary> /// If an enemy is near the agent but is not flocking, then dont add it to the neighbors count /// Otherwise do add it. /// </summary> private void OnTriggerStay(Collider coll){ if (gameObject.CompareTag("Enemy")) { if (coll.CompareTag("Enemy")) { if (coll.GetComponent<FiniteStateMachine>().leader == null) { if (_neighbors.Contains(coll.transform)) { _neighbors.Remove (coll.transform); } } } } } /// <summary> /// If the leader has left, top flocking and start Moving around /// </summary> private void OnTriggerExit(Collider coll){ if (coll.tag != null) { if (coll.transform == _leader) { _leader = null; _leader_locked = false; _neighbors.Clear (); _nextState = Moving (); } else if (coll.CompareTag ("Enemy")) { if (_neighbors.Contains(coll.transform)) { _neighbors.Remove (coll.transform); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccesLayer.Repositorys { public class AdminsRepository { ContentManagementEntities db; Admin admin; public AdminsRepository() { db = new ContentManagementEntities(); } public List<Admin> List() { var adminList = db.Admin.ToList(); return adminList; } public void Add(Admin entity) { admin = db.Admin.Add(entity); db.SaveChanges(); } public void Update(Admin entity) { admin = db.Admin.Where(c => c.Id == entity.Id).FirstOrDefault(); admin.Password = entity.Password; admin.Username = entity.Username; db.SaveChanges(); } public void Delete(int id) { admin = db.Admin.Where(c => c.Id == id).FirstOrDefault(); db.Admin.Remove(admin); db.SaveChanges(); } public bool isAdmin(string u , string p) { bool isfound = false; var adminList = db.Admin.Where(c => c.Username == u && c.Password == p).ToList(); if (adminList.Count >0) { isfound = true; } return isfound; } public Admin search(string u, string p) { admin = db.Admin.Where(c => c.Username == u && c.Password == p).FirstOrDefault(); return admin; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShowAndHide : MonoBehaviour { private SpriteRenderer[] renderers; private bool m_IsShowing = false; private void Awake() { renderers = transform.GetComponentsInChildren<SpriteRenderer>(); } //showTime时间内渐入 public void Show(float showTime = 1f, System.Action action = null) { //初始化alpha为0 renderers = transform.GetComponentsInChildren<SpriteRenderer>(); for (int i = 0; i < renderers.Length; i++) { renderers[i].color = new Color(renderers[i].color.r, renderers[i].color.g, renderers[i].color.b, 0f); } m_IsShowing = true; gameObject.SetActive(m_IsShowing); StartCoroutine(IE_Show(showTime, action)); } IEnumerator IE_Show(float showTime, System.Action action = null) { float delta = Time.deltaTime / showTime; //showTime时间内渐入/淡出 bool finish = false; while (!finish) { finish = true; for(int i = 0; i < renderers.Length; i++) { renderers[i].color = new Color(renderers[i].color.r, renderers[i].color.g, renderers[i].color.b, (renderers[i].color.a + delta) <= 1f ? (renderers[i].color.a + delta) : 1f); if (renderers[i].color.a != 1f) finish = false; } yield return 0; } if (action != null) { action.Invoke(); } } //showTime时间内淡出 public void Hide(float hideTime = 1f, System.Action action = null) { m_IsShowing = false; StartCoroutine(IE_Hide(hideTime,action)); } IEnumerator IE_Hide(float hideTime, System.Action action) { float delta = Time.deltaTime / hideTime; //showTime时间内渐入/淡出 bool finish = false; while (!finish) { finish = true; for (int i = 0; i < renderers.Length; i++) { renderers[i].color = new Color(renderers[i].color.r, renderers[i].color.g, renderers[i].color.b, (renderers[i].color.a - delta) >= 0f ? (renderers[i].color.a - delta) : 0f); if (renderers[i].color.a != 0f) finish = false; } yield return 0; } gameObject.SetActive(m_IsShowing); if (action != null) { action.Invoke(); } } }
using System; using System.Collections.Generic; using System.Text; using Hayaa.DataAccess; using Hayaa.BaseModel; using Hayaa.Security.Service.Config; /// <summary> ///代码效率工具生成,此文件不要修改 /// </summary> namespace Hayaa.Security.Service.Dao{ internal partial class LoginInfoDal : CommonDal { private static String con = ConfigHelper.Instance.GetConnection(DefineTable.DatabaseName); internal static int Add(LoginInfo info, bool isReturn = true) { string sql = null; if (isReturn) { sql = "insert into LoginInfo(LoginKey,UserId,Status) values(@LoginKey,@UserId,@Status);select @@IDENTITY;"; return InsertWithReturnID<LoginInfo,int>(con, sql, info); } else { sql = "insert into LoginInfo(LoginKey,UserId,Status) values(@LoginKey,@UserId,@Status);"; return Insert<LoginInfo>(con, sql, info); } } internal static int Update(LoginInfo info) { string sql = "update LoginInfo set LoginKey=@LoginKey,UserId=@UserId,Status=@Status where LoginInfoId=@LoginInfoId"; return Update<LoginInfo>(con, sql, info); } internal static bool Delete(List<int> IDs) { string sql = "delete from LoginInfo where LoginInfoId in @ids"; return Excute(con, sql, new { ids = IDs.ToArray() }) > 0; } internal static LoginInfo Get(int Id) { string sql = "select * from LoginInfo where LoginInfoId=@LoginInfoId"; return Get<LoginInfo>(con, sql, new { LoginInfoId = Id }); } internal static List<LoginInfo> GetList(LoginInfoSearchPamater pamater) { string sql = "select * from LoginInfo " + pamater.CreateWhereSql(); return GetList<LoginInfo>(con, sql, pamater); } internal static GridPager<LoginInfo> GetGridPager(GridPagerPamater<LoginInfoSearchPamater> pamater) { string sql = "select SQL_CALC_FOUND_ROWS * from LoginInfo " + pamater.SearchPamater.CreateWhereSql() + " limit @Start,@PageSize;select FOUND_ROWS();"; pamater.SearchPamater.Start = (pamater.Current - 1) * pamater.PageSize; pamater.SearchPamater.PageSize = pamater.PageSize; return GetGridPager<LoginInfo>(con, sql, pamater.PageSize, pamater.Current, pamater.SearchPamater); } }}
/**************************************************************************** *Copyright (c) 2018 Microsoft All Rights Reserved. *CLR版本: 4.0.30319.42000 *公司名称:Microsoft *命名空间:HPYL.DAL.DoctorAdvice *文件名: DoctorAdviceDAL *版本号: V1.0.0.0 *当前的用户域:QH-20160830FLFX *创建人:丁新亮 *创建时间:2018/7/17 14:12:41 *描述: * *===================================================================== *修改标记 *修改时间:2018/7/17 14:12:41 *修改人: *版本号: V1.0.0.0 *描述: * *****************************************************************************/ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using HPYL.Model; using Maticsoft.DBUtility; using MySql.Data.MySqlClient; namespace HPYL.DAL { public class DoctorAdviceDAL { /// <summary> /// 获取内容类表 /// </summary> /// <param name="hFT_ID"></param> /// <returns></returns> public List<AdviceArticle> GetAdviceArticleList(long hFT_ID) { string strSql = "select HAA_ID,HFT_ID,HAA_Title,HAA_PicUrl,HAA_Content,HAA_State from hpyl_advicearticle where HFT_ID=" + hFT_ID + " and HAA_State=1"; return new Repository<AdviceArticle>().FindList(strSql).ToList(); } /// <summary> /// 关联后写入随访计划 /// </summary> /// <param name="model"></param> /// <returns></returns> public bool InFollowPlan(BaseDoctorFollowPlan model) { //根据模板获取随访内容 int errorcount = 0; List<DoctorFollowContent> PlanContent = FollowList(model.HAA_ID); foreach (DoctorFollowContent item in PlanContent) { DoctorFollowPlan pmodel = new DoctorFollowPlan(); pmodel.HDP_Content = item.HDC_Content; pmodel.HDP_CreateTime = item.HDC_StratTime; pmodel.HDP_DoctorId = model.HDP_DoctorId; pmodel.HDP_PatientId = model.HDP_PatientId; pmodel.HDP_Remind = model.HDP_Remind; pmodel.HDP_State = 0; pmodel.HDP_UserId = model.HDP_UserId; pmodel.HAA_ID = model.HAA_ID; if (!AddPlan(pmodel)) { errorcount++; } } if (errorcount > 0) { return false; } else { return true; } } /// <summary> /// 新增随访计划 /// </summary> /// <param name="model"></param> /// <returns></returns> private bool AddPlan(DoctorFollowPlan model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into hpyl_doctorfollowplan("); strSql.Append("HAA_ID,HDP_CreateTime,HDP_UserId,HDP_Remind,HDP_Content,HDP_DoctorId,HDP_PatientId,HDP_State)"); strSql.Append(" values ("); strSql.Append("@HAA_ID,@HDP_CreateTime,@HDP_UserId,@HDP_Remind,@HDP_Content,@HDP_DoctorId,@HDP_PatientId,@HDP_State)"); MySqlParameter[] parameters = { new MySqlParameter("@HAA_ID", model.HAA_ID), new MySqlParameter("@HDP_CreateTime", model.HDP_CreateTime), new MySqlParameter("@HDP_UserId", model.HDP_UserId), new MySqlParameter("@HDP_Remind", model.HDP_Remind), new MySqlParameter("@HDP_Content", model.HDP_Content), new MySqlParameter("@HDP_DoctorId", model.HDP_DoctorId), new MySqlParameter("@HDP_PatientId", model.HDP_PatientId), new MySqlParameter("@HDP_State",model.HDP_State)}; int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 获取内容随访计划列表 /// </summary> /// <param name="hAA_ID"></param> /// <returns></returns> public List<DoctorFollowContent> FollowList(long hAA_ID) { string strSql = "select HDC_ID,HAA_ID,HDC_Days,HDC_Content,date_format(date_add(now(), interval HDC_Days day), '%Y-%m-%d %H:%i:%s' )HDC_StratTime from hpyl_doctorfollowcontent where HAA_ID=" + hAA_ID + ""; return new Repository<DoctorFollowContent>().FindList(strSql).ToList(); } #region 获取实体 /// <summary> /// 得到一个对象实体 /// </summary> public AdviceArticle GetModel(long HAA_ID) { StringBuilder strSql = new StringBuilder(); strSql.Append("select HAA_ID,HFT_ID,HAA_Title,HAA_PicUrl,HAA_Content,HAA_State from hpyl_advicearticle "); strSql.Append(" where HAA_ID=@HAA_ID"); MySqlParameter[] parameters = { new MySqlParameter("@HAA_ID", HAA_ID) }; parameters[0].Value = HAA_ID; AdviceArticle model = new AdviceArticle(); DataSet ds = DbHelperMySQL.Query(strSql.ToString(), parameters); if (ds.Tables[0].Rows.Count > 0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// 得到一个对象实体 /// </summary> public AdviceArticle DataRowToModel(DataRow row) { AdviceArticle model = new AdviceArticle(); if (row != null) { if (row["HAA_ID"] != null && row["HAA_ID"].ToString() != "") { model.HAA_ID = long.Parse(row["HAA_ID"].ToString()); } if (row["HFT_ID"] != null && row["HFT_ID"].ToString() != "") { model.HFT_ID = long.Parse(row["HFT_ID"].ToString()); } if (row["HAA_Title"] != null) { model.HAA_Title = row["HAA_Title"].ToString(); } if (row["HAA_PicUrl"] != null) { model.HAA_PicUrl = row["HAA_PicUrl"].ToString(); } if (row["HAA_Content"] != null) { model.HAA_Content = row["HAA_Content"].ToString(); } if (row["HAA_State"] != null && row["HAA_State"].ToString() != "") { model.HAA_State = int.Parse(row["HAA_State"].ToString()); } } return model; } #endregion } }
using System; namespace RabbitMQ.Client.Service.Interfaces { public interface IAMQPChannelProvider : IDisposable { IModel GetAMQPChannel(); } }
namespace S3.AutoBatcher { public enum BatchStatus { /// <summary> /// it admits requests /// </summary> Opened = 1, /// <summary> /// It is being executed /// </summary> /// <remarks>it does not admit requests</remarks> Executing, } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using WebSocketSharp; // for web server connection using Newtonsoft.Json; public class LandmarksServer : MonoBehaviour { WebSocket socket; public MoveCoordinate[] nodes; // Start is called before the first frame update void getNodes() { nodes = GetComponents<MoveCoordinate>(); } void Start() { getNodes(); socket = new WebSocket("ws://localhost:3030"); socket.OnOpen += (sender, e) => { Debug.Log("Connection established"); socket.Send("Connection established in Unity"); }; socket.OnMessage += (sender, e) => { //Debug.Log("Message received from " + ((WebSocket)sender).Url + ", Data: " + e.Data); // Using Newtonsoft.Json var landmarks = JsonConvert.DeserializeObject<Dictionary<string, float>[]>(e.Data); foreach (MoveCoordinate n in nodes) { n.UpdateLandmark(landmarks); } }; socket.OnClose += (sender, e) => { Debug.Log("Connection closed with " + e.Reason); }; socket.Connect(); } void OnApplicationQuit() { if (socket != null) { socket.Close(1001, "Game Quit"); } } }
using UnityEngine; public class Play : MonoBehaviour { GameObject mainMenuCanvas; GameObject playUICanvas; GameObject carObject; void Start() { mainMenuCanvas = GameObject.Find("MainMenu"); playUICanvas = GameObject.Find("PlayUI"); playUICanvas.gameObject.SetActive(false); carObject = GameObject.Find("Car"); carObject.GetComponent<Drive>().enabled = false; //idle script already enabled } public void PlayMode() { mainMenuCanvas.gameObject.SetActive(false); playUICanvas.gameObject.SetActive(true); carObject.GetComponent<Drive>().enabled = true; } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; namespace NetEscapades.AspNetCore.SecurityHeaders.Headers { /// <summary> /// The header value to use for Feature-Policy. /// </summary> public class FeaturePolicyHeader : DocumentHeaderPolicyBase { private readonly string _value; /// <summary> /// Initializes a new instance of the <see cref="FeaturePolicyHeader"/> class. /// </summary> /// <param name="value">The value to apply for the header</param> public FeaturePolicyHeader(string value) { _value = value; } /// <inheritdoc /> public override string Header => "Feature-Policy"; /// <inheritdoc /> protected override string GetValue(HttpContext context) => _value; /// <summary> /// Configure a feature policy. /// </summary> /// <param name="configure">Configure the Feature-Policy header</param> /// <returns>The complete Feature-Policy header</returns> public static FeaturePolicyHeader Build(Action<FeaturePolicyBuilder> configure) { var builder = new FeaturePolicyBuilder(); configure(builder); return new FeaturePolicyHeader(builder.Build()); } } }
/** Vincent Casamayou RIES GROUP SMAP Animation System 29/05/2020 **/ using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using Data; namespace Display { public class AnimateObject : MonoBehaviour { public bool isRectTransform = false; CloudData data; public float indexkey = 0.0f; public float keyframeTimestep = 5.0f; // Time the object takes to move from one frame to the next public float timestep = 5f; public float animationTime; public float AnimationDuration = 30; //in seconds RectTransform UItransform; Animation anim; public Keyframe keyRotationW = new Keyframe(); public Keyframe keyRotationX = new Keyframe(); public Keyframe keyRotationY = new Keyframe(); public Keyframe keyRotationZ = new Keyframe(); public Keyframe keyScaleX = new Keyframe(); public Keyframe keyScaleY = new Keyframe(); public Keyframe keyScaleZ = new Keyframe(); public Keyframe keyPositionX = new Keyframe(); public Keyframe keyPositionY = new Keyframe(); public Keyframe keyPositionZ = new Keyframe(); //Only for RectTransform (ClippingPlane) public Keyframe keyHeight = new Keyframe(); public Keyframe keyWidth = new Keyframe(); public AnimationClip clip; AnimationCurve curveRotationW; AnimationCurve curveRotationX; AnimationCurve curveRotationY; AnimationCurve curveRotationZ; AnimationCurve curveScaleX; AnimationCurve curveScaleY; AnimationCurve curveScaleZ; public AnimationCurve curvePositionX; public AnimationCurve curvePositionY; public AnimationCurve curvePositionZ; //Only for RectTransform (ClippingPlane) AnimationCurve curveHeight; AnimationCurve curveWidth; //CloudStatus Variables private Dictionary<int, VR_Interaction.CloudStateInTime> CloudStatesDict; void Awake() { CloudStatesDict = new Dictionary<int, VR_Interaction.CloudStateInTime>(); anim = gameObject.AddComponent(typeof(Animation)) as Animation; anim.playAutomatically = false; clip = new AnimationClip(); clip.legacy = true; curveRotationW = new AnimationCurve(keyRotationW); curveRotationX = new AnimationCurve(keyRotationX); curveRotationY = new AnimationCurve(keyRotationY); curveRotationZ = new AnimationCurve(keyRotationZ); curveScaleX = new AnimationCurve(keyScaleX); curveScaleY = new AnimationCurve(keyScaleY); curveScaleZ = new AnimationCurve(keyScaleZ); curvePositionX = new AnimationCurve(keyPositionX); curvePositionY = new AnimationCurve(keyPositionY); curvePositionZ = new AnimationCurve(keyPositionZ); //ClearAnimation(); /** if (isRectTransform) { UItransform = this.gameObject.GetComponent<RectTransform>(); curveHeight = new AnimationCurve(keyHeight); curveWidth = new AnimationCurve(keyWidth); //Initialize UI Size curveHeight.MoveKey(0, new Keyframe(0, UItransform.rect.height)); curveWidth.MoveKey(0, new Keyframe(0, UItransform.rect.width)); } else { //Initialize Object Position curveRotationW.MoveKey(0, new Keyframe(0, this.gameObject.transform.localRotation.w)); curveRotationX.MoveKey(0, new Keyframe(0, this.gameObject.transform.localRotation.x)); curveRotationY.MoveKey(0, new Keyframe(0, this.gameObject.transform.localRotation.y)); curveRotationZ.MoveKey(0, new Keyframe(0, this.gameObject.transform.localRotation.z)); curveScaleX.MoveKey(0, new Keyframe(0, this.gameObject.transform.localScale.x)); curveScaleY.MoveKey(0, new Keyframe(0, this.gameObject.transform.localScale.y)); curveScaleZ.MoveKey(0, new Keyframe(0, this.gameObject.transform.localScale.z)); curvePositionX.MoveKey(0, new Keyframe(0, this.gameObject.transform.localPosition.x)); curvePositionY.MoveKey(0, new Keyframe(0, this.gameObject.transform.localPosition.y)); curvePositionZ.MoveKey(0, new Keyframe(0, this.gameObject.transform.localPosition.z)); } UpdateAnimation(); **/ } public void ClearAnimation() { clip.ClearCurves(); curveRotationW = new AnimationCurve(keyRotationW); curveRotationX = new AnimationCurve(keyRotationX); curveRotationY = new AnimationCurve(keyRotationY); curveRotationZ = new AnimationCurve(keyRotationZ); curveScaleX = new AnimationCurve(keyScaleX); curveScaleY = new AnimationCurve(keyScaleY); curveScaleZ = new AnimationCurve(keyScaleZ); curvePositionX = new AnimationCurve(keyPositionX); curvePositionY = new AnimationCurve(keyPositionY); curvePositionZ = new AnimationCurve(keyPositionZ); } //DONE public void InitializeFirstKeyframe(Transform TransformToAdd) { //Initialize Object Position curveRotationW.MoveKey(0, new Keyframe(0, TransformToAdd.localRotation.w)); curveRotationX.MoveKey(0, new Keyframe(0, TransformToAdd.localRotation.x)); curveRotationY.MoveKey(0, new Keyframe(0, TransformToAdd.localRotation.y)); curveRotationZ.MoveKey(0, new Keyframe(0, TransformToAdd.localRotation.z)); curveScaleX.MoveKey(0, new Keyframe(0, TransformToAdd.localScale.x)); curveScaleY.MoveKey(0, new Keyframe(0, TransformToAdd.localScale.y)); curveScaleZ.MoveKey(0, new Keyframe(0, TransformToAdd.localScale.z)); curvePositionX.MoveKey(0, new Keyframe(0, TransformToAdd.localPosition.x)); curvePositionY.MoveKey(0, new Keyframe(0, TransformToAdd.localPosition.y)); curvePositionZ.MoveKey(0, new Keyframe(0, TransformToAdd.localPosition.z)); } //DONE public int AddKeyframe(Transform TransformToAdd, float time) { indexkey++; int indexKeyReturn = 0; //animationTime = keyframeTimestep * indexkey; Debug.Log(TransformToAdd); Debug.Log(curveRotationW); //FOR UI ELEMENTS if (isRectTransform) { indexKeyReturn = curveWidth.AddKey(time, UItransform.rect.width); curveHeight.AddKey(time, UItransform.rect.height); curvePositionX.AddKey(time, UItransform.anchoredPosition.x); curvePositionY.AddKey(time, UItransform.anchoredPosition.y); } //FOR GAMEOBJECTS else { curveRotationW.AddKey(time, TransformToAdd.localRotation.w); curveRotationX.AddKey(time, TransformToAdd.localRotation.x); curveRotationY.AddKey(time, TransformToAdd.localRotation.y); curveRotationZ.AddKey(time, TransformToAdd.localRotation.z); curveScaleX.AddKey(time, TransformToAdd.localScale.x); curveScaleY.AddKey(time, TransformToAdd.localScale.y); curveScaleZ.AddKey(time, TransformToAdd.localScale.z); curvePositionX.AddKey(time, TransformToAdd.localPosition.x); curvePositionY.AddKey(time, TransformToAdd.localPosition.y); indexKeyReturn = curvePositionZ.AddKey(time, TransformToAdd.localPosition.z); } //indexkey++; UpdateAnimation(); return indexKeyReturn; } public Vector3 GetPositionatTime(float Time) { Vector3 result = Vector3.zero; result.x = curvePositionX.Evaluate(Time); result.y = curvePositionY.Evaluate(Time); result.z = curvePositionZ.Evaluate(Time); return result; } //Used to trigger specific event, for now only change colormap public void AddAnimationEvent(VR_Interaction.CloudStateInTime state) { if (!CloudStatesDict.ContainsKey(state.ID)) { CloudStatesDict.Add(state.ID, state); } else { Debug.Log("Tried to add event at id " + state.ID + " but an event already had this id !"); } AnimationEvent evt = new AnimationEvent(); evt.time = state.Time; evt.intParameter = state.ID; evt.functionName = "UpdateCloudStatus"; clip.AddEvent(evt); } public void ClearEvents() { AnimationEvent[] allEvents = clip.events; if (allEvents.Length != 0) { var eventsList = allEvents.ToList(); for (int j = 0; j < eventsList.Count; j++) { eventsList.RemoveAt(j); } clip.events = eventsList.ToArray(); } CloudStatesDict.Clear(); UpdateAnimation(); } public void UpdateColorMap(string ColorMapName) { CloudUpdater.instance.ChangeCurrentColorMap(ColorMapName); } public void UpdateCloudStatus(int CloudStateID) { //Call cloudupdater update mesh CloudUpdater.instance.OverrideBoxScale(CloudStatesDict[CloudStateID].BoxScale); CloudUpdater.instance.OverrideMesh(CloudStatesDict[CloudStateID].Mesh); CloudUpdater.instance.ChangePointSize(CloudStatesDict[CloudStateID].PointSize); CloudUpdater.instance.ChangeCloudScale(CloudStatesDict[CloudStateID].Scale); UpdateColorMap(CloudStatesDict[CloudStateID].ColorMap); } //DONE public int UpdateKeyframe(int indexKey, int newTime, Transform objectTransform) { //animationTime = keyframeTimestep * (float)index; int indexKeyReturn = 0; //For UI ELEMENTS if (isRectTransform) { Keyframe TMPkeyHeight = new Keyframe(newTime, UItransform.rect.height); curveHeight.MoveKey(indexKey, TMPkeyHeight); Keyframe TMPkeyWidth = new Keyframe(newTime, UItransform.rect.width); curveWidth.MoveKey(indexKey, TMPkeyWidth); Keyframe TMPkeyPositionX = new Keyframe(newTime, UItransform.anchoredPosition.x); curvePositionX.MoveKey(indexKey, TMPkeyPositionX); Keyframe TMPkeyPositionY = new Keyframe(newTime, UItransform.anchoredPosition.y); indexKeyReturn = curvePositionY.MoveKey(indexKey, TMPkeyPositionY); } //FOR GAMEOBJECTS else { Keyframe TMPkeyRotationW = new Keyframe(newTime, objectTransform.localRotation.w); curveRotationW.MoveKey(indexKey, TMPkeyRotationW); Keyframe TMPkeyRotationX = new Keyframe(newTime, objectTransform.localRotation.x); curveRotationX.MoveKey(indexKey, TMPkeyRotationX); Keyframe TMPkeyRotationY = new Keyframe(newTime, objectTransform.localRotation.y); curveRotationY.MoveKey(indexKey, TMPkeyRotationY); Keyframe TMPkeyRotationZ = new Keyframe(newTime, objectTransform.localRotation.z); curveRotationZ.MoveKey(indexKey, TMPkeyRotationZ); Keyframe TMPkeyScaleX = new Keyframe(newTime, objectTransform.localScale.x); curveScaleX.MoveKey(indexKey, TMPkeyScaleX); Keyframe TMPkeyScaleY = new Keyframe(newTime, objectTransform.localScale.y); curveScaleY.MoveKey(indexKey, TMPkeyScaleY); Keyframe TMPkeyScaleZ = new Keyframe(newTime, objectTransform.localScale.z); curveScaleZ.MoveKey(indexKey, TMPkeyScaleZ); Keyframe TMPkeyPositionX = new Keyframe(newTime, objectTransform.localPosition.x); curvePositionX.MoveKey(indexKey, TMPkeyPositionX); Keyframe TMPkeyPositionY = new Keyframe(newTime, objectTransform.localPosition.y); curvePositionY.MoveKey(indexKey, TMPkeyPositionY); Keyframe TMPkeyPositionZ = new Keyframe(newTime, objectTransform.localPosition.z); indexKeyReturn = curvePositionZ.MoveKey(indexKey, TMPkeyPositionZ); } UpdateAnimation(); return indexKeyReturn; } public void UpdateAnimation() { //FOR UI ELEMENTS if (isRectTransform) { clip.SetCurve("", typeof(RectTransform), "m_SizeDelta.x", curveWidth); clip.SetCurve("", typeof(RectTransform), "m_SizeDelta.y", curveHeight); clip.SetCurve("", typeof(RectTransform), "m_AnchoredPosition.x", curvePositionX); clip.SetCurve("", typeof(RectTransform), "m_AnchoredPosition.y", curvePositionY); } //FOR GAMEOBJECTS else { clip.SetCurve("", typeof(Transform), "localRotation.w", curveRotationW); clip.SetCurve("", typeof(Transform), "localRotation.x", curveRotationX); clip.SetCurve("", typeof(Transform), "localRotation.y", curveRotationY); clip.SetCurve("", typeof(Transform), "localRotation.z", curveRotationZ); clip.SetCurve("", typeof(Transform), "localScale.x", curveScaleX); clip.SetCurve("", typeof(Transform), "localScale.y", curveScaleY); clip.SetCurve("", typeof(Transform), "localScale.z", curveScaleZ); clip.SetCurve("", typeof(Transform), "localPosition.x", curvePositionX); clip.SetCurve("", typeof(Transform), "localPosition.y", curvePositionY); clip.SetCurve("", typeof(Transform), "localPosition.z", curvePositionZ); } anim.AddClip(clip, clip.name); anim.clip = clip; } public void PlayAnimation() { Debug.Log("PlayAnimation Called"); if (!anim.isPlaying) { Debug.Log("Animation playing"); anim.Play(); } else { Debug.Log("Animation stop"); anim.Stop(); } } public void SetAnimationSpeed(float animSpeed) { keyframeTimestep = timestep / animSpeed; Debug.Log("Timestep is " + keyframeTimestep); } //HERE IF YOU WANT TO REMOVE NEW VARIABLES public void RemoveCurves(int i) { //FOR UI ELEMENTS if (isRectTransform) { curveHeight.RemoveKey(i); curveWidth.RemoveKey(i); curvePositionX.RemoveKey(i); curvePositionY.RemoveKey(i); } //FOR GAMEOBJECTS else { curveRotationW.RemoveKey(i); curveRotationX.RemoveKey(i); curveRotationY.RemoveKey(i); curveRotationZ.RemoveKey(i); curveScaleX.RemoveKey(i); curveScaleY.RemoveKey(i); curveScaleZ.RemoveKey(i); curvePositionX.RemoveKey(i); curvePositionY.RemoveKey(i); curvePositionZ.RemoveKey(i); } } public void ShiftCurves(int index, int shift = 0) { int key_to_shift = index - shift; if (key_to_shift >= curveRotationW.keys.Length) { key_to_shift = curveRotationW.keys.Length - 1; } else if (key_to_shift <= 0) { key_to_shift = 1; } //FOR UI ELEMENTS if (isRectTransform) { curveHeight.MoveKey(index, curveHeight.keys[key_to_shift]); curveWidth.MoveKey(index, curveWidth.keys[key_to_shift]); curvePositionX.MoveKey(index, curvePositionX.keys[key_to_shift]); curvePositionY.MoveKey(index, curvePositionY.keys[key_to_shift]); } //FOR GAMEOBJECTS else { curveRotationW.MoveKey(index, curveRotationW.keys[key_to_shift]); curveRotationX.MoveKey(index, curveRotationX.keys[key_to_shift]); curveRotationY.MoveKey(index, curveRotationY.keys[key_to_shift]); curveRotationZ.MoveKey(index, curveRotationZ.keys[key_to_shift]); curveScaleX.MoveKey(index, curveScaleX.keys[key_to_shift]); curveScaleY.MoveKey(index, curveScaleY.keys[key_to_shift]); curveScaleZ.MoveKey(index, curveScaleZ.keys[key_to_shift]); curvePositionX.MoveKey(index, curvePositionX.keys[key_to_shift]); curvePositionY.MoveKey(index, curvePositionY.keys[key_to_shift]); curvePositionZ.MoveKey(index, curvePositionZ.keys[key_to_shift]); } } public void RemoveAnimation() { for (int i = 0; i < curvePositionX.keys.Length; i++) { RemoveCurves(i); } indexkey = 0; clip.ClearCurves(); anim.RemoveClip(clip); } public void RemoveKeyframe(int index) { float timestamp = curvePositionX.keys[index].time; animationTime = animationTime - keyframeTimestep; for (int i = index; i < curvePositionX.keys.Length; i++) { Debug.Log("Shift Keyframe " + i); if (i == curvePositionX.keys.Length - 1) { Debug.Log("Last Curve removed"); RemoveCurves(i); break; } else { ShiftCurves(i, -1); } } //Remove Event AnimationEvent[] allEvents = clip.events; if (allEvents.Length != 0) { var eventsList = allEvents.ToList(); for (int j = 0; j < eventsList.Count; j++) { if (eventsList[j].time == timestamp) { eventsList.RemoveAt(j); } } clip.events = eventsList.ToArray(); } UpdateAnimation(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { public double speed; public bool jumping; private double i = 0.0; public float jumpspeed = 0.1f; public Vector3 initialvelocity; Rigidbody rb ; public float distToGround = 0.5f; // Use this for initialization void Start () { rb = GetComponent<Rigidbody>(); } // Update is called once per frame void Update () { if (i >= 1.0) { Vector3 initial = new Vector3(0, jumpspeed, 0); rb.velocity = rb.velocity - initial; } if (Input.GetKey(KeyCode.Space) & IsGrounded()){ // rb.AddForce(Vector3.up * 3); Vector3 jumpVelocity = new Vector3(0, jumpspeed, 0); rb.velocity = rb.velocity + jumpVelocity; jumping = true; } if (Input.GetKey("space") & IsGrounded()) { print("dfa"); } transform.Translate(0, 0, Time.deltaTime +0.03f); } bool IsGrounded() { return Physics.Raycast(transform.position, Vector3.down, distToGround); } }
namespace Models.Towers { public class LargeTowerModel : ITower { public ItemType Type { get { return ItemType.LargeTower; } } public string Name { get { return "Large Tower"; } } public decimal BuyPrice { get { return 200; } } public decimal SellPrice { get { return 100; } } public IWeapon Weapon { get { return WeaponsLibrary.Canon; } } } }
using System.Collections.Generic; // ReSharper disable once CheckNamespace - must be in same namespace as the other professions classes. namespace SkillPrestige.Professions { public partial class Profession { /// <summary> /// Professions created by the Luck Skill Mod. /// </summary> public static IEnumerable<Profession> LuckProfessions => new List<Profession> { Lucky, Quester, SpecialCharm, LuckA2, NightOwl, LuckB2 }; protected static TierOneProfession Lucky { get; set; } protected static TierOneProfession Quester { get; set; } protected static TierTwoProfession SpecialCharm { get; set; } /// <summary> /// Profession has not been given a function by the Luck Skill mod. /// </summary> protected static TierTwoProfession LuckA2 { get; set; } protected static TierTwoProfession NightOwl { get; set; } /// <summary> /// Profession has not been given a function by the Luck Skill mod. /// </summary> protected static TierTwoProfession LuckB2 { get; set; } } }
using UnityEngine; using System.Collections; public class DebugGUI : MonoBehaviour { private int screenButtonHeight = 100; private string logLine = string.Empty; void OnGUI() { if(GUI.Button(new Rect(0, 0, 200, screenButtonHeight), "Load Set")) { SoundCloudPlayer.Instance.LoadSet(false); } // GUI.TextArea(new Rect(0, Screen.height - 300, Screen.width, 300), logLine); } private void OnResolveCallback(SCServiceResponse response) { if(response.isSuccess) { Debug.Log(string.Format("DebugGUI.OnResolveCallback() - SUCCESS! {0}, streamable:{1}, from url:{2}", response.trackInfo.title, response.trackInfo.streamable, response.trackInfo.stream_url) ); } else { Debug.Log("DebugGUI.OnResolveCallback(): " + response.errorMsg); } } private void OnLogCallback(string logMsg) { logLine = logMsg + "\n" + logLine; } }
using AutoMapper; using CarRental.API.BL.Models; using CarRental.API.BL.Models.Car; using CarRental.API.DAL.DataServices.Car; using CarRental.API.DAL.Entities; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace CarRental.API.BL.Services { public class CarService : ICarService { private readonly IMapper _mapper; private readonly ICarDataService _carDataService; public CarService(IMapper mapper, ICarDataService carDataService) { _mapper = mapper; _carDataService = carDataService; } public async Task<IEnumerable<CarModel>> GetAllAsync() { var cars = await _carDataService.GetAllAsync(); return _mapper.Map<IEnumerable<CarModel>>(cars); } public async Task<CarModel> GetAsync(Guid id) { var car = await _carDataService.GetAsync(id); return _mapper.Map<CarModel>(car); } public async Task<CarItem> CreateAsync(CreateCarModel item) { var car = _mapper.Map<CarItem>(item); return await _carDataService.CreateAsync(car); } public async Task<IEnumerable<CarItem>> UpsertAsync(CarModel item) { var car = _mapper.Map<CarItem>(item); return await _carDataService.UpsertAsync(car); } public async Task<CarItem> DeleteAsync(Guid id) { return await _carDataService.DeleteAsync(id); } public async Task<IEnumerable<CarItem>> MarkCarAsAvailable(CarAvailabilityModel item) { var car = _mapper.Map<CarItem>(item); return await _carDataService.MarkCarAsAvailable(car); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace badanie_ksiag_wieczystych { public class Firefox { public string pathFirefox { get; } public string pageUri { get; } public Firefox() { this.pathFirefox = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; this.pageUri = @"https://przegladarka-ekw.ms.gov.pl/eukw_prz/KsiegiWieczyste/wyszukiwanieKW?komunikaty=true&kontakt=true&okienkoSerwisowe=false"; } public Firefox(string path_firefox,string page_uri) { this.pathFirefox = path_firefox; this.pageUri = page_uri; } public void startFirefox() { Process process = new Process(); process.StartInfo.FileName = this.pathFirefox; process.StartInfo.Arguments = this.pageUri; process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; process.Start(); } public void startFirefox(string uri) { Process process = new Process(); process.StartInfo.FileName = this.pathFirefox; process.StartInfo.Arguments = uri; process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; process.Start(); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace PlayFab.Internal { /// <summary> /// This is a base-class for all Api-request objects. /// It is currently unfinished, but we will add result-specific properties, /// and add template where-conditions to make some code easier to follow /// </summary> public class PlayFabRequestCommon { } /// <summary> /// This is a base-class for all Api-result objects. /// It is currently unfinished, but we will add result-specific properties, /// and add template where-conditions to make some code easier to follow /// </summary> public class PlayFabResultCommon { } public class PlayFabJsonError { public int code; public string status; public string error; public int errorCode; public string errorMessage; public Dictionary<string, string[]> errorDetails = null; } public class PlayFabJsonSuccess<TResult> where TResult : PlayFabResultCommon { public int code; public string status; public TResult data; } public static class PlayFabHttp { private static IPlayFabHttp _http; static PlayFabHttp() { var httpInterfaceType = typeof(IPlayFabHttp); var types = typeof(PlayFabHttp).GetAssembly().GetTypes(); foreach (var eachType in types) { if (httpInterfaceType.IsAssignableFrom(eachType) && !eachType.IsAbstract) { _http = (IPlayFabHttp)Activator.CreateInstance(eachType.AsType()); return; } } throw new Exception("Cannot find a valid IPlayFabHttp type"); } public static async Task<object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey) { if (PlayFabSettings.TitleId == null) throw new Exception("You must set your titleId before making an api call"); return await _http.DoPost(urlPath, request, authType, authKey); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Exceptions; namespace ProjectManagerDAL { public class ProjectRepository : IRepository<Project> { ProjectManagerModel objContext; public ProjectRepository() { objContext = new ProjectManagerModel(); } public bool Add(Project obj) { try { if (obj != null) { objContext.Projects.Add(obj); return objContext.SaveChanges() > 0; } else { throw new ProjectManagerException("No Project to add"); } } catch (ProjectManagerException e) { throw e; } } //public List<Employee> projectmanagerlist() //{ // ProjectManagerModel context = new ProjectManagerModel(); // var Query = from item in context.Projects // select item.EmployeeId; // var q = from Employee in context.Employees // where Employee.EmployeeDesignation == "ProjectManager" && !Query.Contains(Employee.EmployeeId) // select Employee; // return q.ToList(); //} public Project Find(int id) { try { return objContext.Projects.Find(id); } catch (ProjectManagerException e) { throw e; } throw new ProjectManagerException("Error finding Project"); } public List<Project> Display() { try { if (objContext.Projects.Count() > 0) { return objContext.Projects.ToList(); } else { throw new ProjectManagerException("No Data To Display"); } } catch (ProjectManagerException e) { throw e; } } public void Dispose() { objContext.Dispose(); } } }
using System; using System.Collections.Generic; using System.Text; namespace RPG_Game { public class Batman : Character { public Batman(int level) { MaxAttackValue = CalculateMaxMoveValue(level); MaxDefenseValue = CalculateMaxMoveValue(level); CharName = "Batman"; AttackSkills = new string[2] { "Summon Bats", "Batarang" }; DefenseSkills = new string[2] { "Heal", "Roll Escape" }; } // ======================================== // METHODS // // ======================================== // ------------- ATTACK ----------------// public int SummonBats(int curAttackValue) { int newAttackValue = (int)Math.Round(curAttackValue * 1.8, 0); return newAttackValue; } public int Batarang(int curAttackValue) { int newAttackValue = curAttackValue + RandomNumberGenerator.GenerateRandomNumber(MaxAttackValue); return newAttackValue; } public override int Attack(int option) { int attackValue = RandomNumberGenerator.GenerateRandomNumber(MaxAttackValue); int finalAttackValue = 0; switch (option) { case (0): finalAttackValue = SummonBats(attackValue); break; case (1): finalAttackValue = Batarang(attackValue); break; default: break; } return finalAttackValue; } // ------------- DEFENSE----------------// /* * Disarms the opponent, meaning the opponent can not inflict any damage */ public int Heal(int curAttackValue) { int random = RandomNumberGenerator.GenerateRandomNumber(curAttackValue); int heal = (random / 2); return heal; //return 0; } public int RollEscape(int curAttackValue) { int defenseVal = RandomNumberGenerator.GenerateRandomNumber(curAttackValue / 2); return defenseVal; } public override int Defend(int enemyAttackValue) { int finalDefenseValue = 0; int option = RandomNumberGenerator.GenerateRandomNumber(2); switch (option) { case (0): finalDefenseValue = Heal(enemyAttackValue); break; case (1): finalDefenseValue = RollEscape(enemyAttackValue); break; default: break; } return finalDefenseValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using DSInterfaces; namespace Queues { /*Note to self When you want to implement other Queues create classes for them just like you did here under the Queues namespace */ public class LinkedQueue<T> : IQueue<T> { //Set up a Node class public class Node { private T _data; private Node _next; //Getters and setters for both data and next node public T Data { get { return this._data; } set { this._data = value; } } public Node Next { get { return this._next; } set { this._next = value; } } //Constructor public Node(T value, Node next = null) { this._data = value; this._next = next; } } //Queue class starts here private Node front; private Node rear; private int size; public LinkedQueue() { this.front = this.rear = null; this.size = 0; } public int GetSize() { return this.size; } public void Clear() { this.front = this.rear = null; this.size = 0; } public bool IsEmpty() { return this.size == 0; } public T Peek() { if (!this.IsEmpty()) return this.front.Data; else { Debug.WriteLine("Nothing to peek."); return default(T); } } public void Enqueue(T data) { //Create a Node for the data Node temp = new Node(data); if (this.IsEmpty()) this.front = this.rear = temp; else { this.rear.Next = temp; this.rear = this.rear.Next; } this.size++; } public T Dequeue() { T value = default(T); if (!this.IsEmpty()) { value = this.front.Data; this.front = this.front.Next; this.size--; } else Debug.WriteLine("Nothing to Dequeue."); return value; } } }
using lesson6.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace lesson6.Services { public interface IWeatherService { Task<IWeather> GetWeatherAsync(string region = null); } }
using System; using System.Windows.Controls; using System.Windows; namespace Storage_Helper_SAS_Tool { /// <summary> /// --------------------------------------------------------------------------------------------------------- /// Constructing the Account SAS URI /// https://docs.microsoft.com/pt-pt/rest/api/storageservices/create-account-sas?redirectedfrom=MSDN#constructing-the-account-sas-uri /// Delegate access to: /// service-level operations that are not currently available with a service-specific SAS, such as the Get/Set Service Properties and Get Service Stats operations. /// more than one service in a storage account at a time. For example, you can delegate access to resources in both the Blob and File services with an account SAS. /// write and delete operations for containers, queues, tables, and file shares, which are not available with an object-specific SAS. /// Specify an IP address or range of IP addresses from which to accept requests. /// Specify the HTTP protocol from which to accept requests (either HTTPS or HTTP/HTTPS). /// --------------------------------------------------------------------------------------------------------- /// Create a service SAS /// https://docs.microsoft.com/pt-pt/rest/api/storageservices/create-service-sas /// Delegates access to a resource in just one of the storage services: the Blob, Queue, Table, or File service. /// A SAS may also specify the supported IP address or address range from which requests can originate /// the supported protocol with which a request can be made /// an optional access policy identifier associated with the request. /// --------------------------------------------------------------------------------------------------------- /// </summary> class SAS_Utils { //---------------------------------------------------------------------------- /// <summary> /// Valid Storage Service Versions for Account SAS >= 2015-04-05 (if using srt) /// </summary> public static string[] validSV_AccountSAS_ARR = { "2019-02-02", "2018-11-09", "2018-03-28", "2017-11-09", "2017-07-29", "2017-04-17", "2016-05-31", "2015-12-11", "2015-07-08", "2015-04-05" }; /// <summary> /// Valid Storage Service Versions for Service SAS >= 2012-02-12 /// /// In Service Versions before 2012-02-12, the duration between signedstart and signedexpiry cannot exceed one hour /// </summary> public static string[] validSV_ServiceSas_ARR_addon = { "2015-02-21", "2014-02-14", "2013-08-15", "2012-02-12" }; //---------------------------------------------------------------------------- /// <summary> /// Struct to save one individual value from analized SAS, and the state valid/error found /// </summary> public struct StrParameter { public string v; // Value public bool s; // State } public static byte[] fromIP = { 0, 0, 0, 0 }; // Signed IP - used on v12.0.0.0_preview public static byte[] toIP = { 0, 0, 0, 0 }; /// <summary> /// Struct to save all individual values from analized SAS, used to regenerate new SAS /// The struct easly allow access all the SAS parameters from any class /// </summary> public struct SasParameters { public StrParameter sharedAccessSignature; // complete SAS without the endpoints public string blobEndpoint; public string fileEndpoint; public string tableEndpoint; public string queueEndpoint; public StrParameter storageAccountName; // storage Account Name, if provided on any Endpoint public StrParameter storageAccountKey; // storage Account Key public StrParameter containerName; // Container name, if provided on blobEndpoint public StrParameter blobName; // Blob name, if provided on blobEndpoint public StrParameter shareName; // Share name, if provided on fileEndpoint public StrParameter fileName; // File name, if provided on fileEndpoint public StrParameter queueName; // Queue name, if provided on queueEndpoint //public StrParameter tableName; // Table name, if provided on tableEndpoint, and if is an account SAS public bool onlySASprovided; // true if the endpoints not provided public StrParameter sv; // Service Version public StrParameter ss; // Signed Services public StrParameter srt; // Signed Resource Types (account SAS) public StrParameter sp; // Signed Permission public StrParameter se; // Signed Expiry DateTime public StrParameter st; // Signed Start DateTime public StrParameter sip; // Signed IP public StrParameter spr; // Signed Protocol public string sig; // Encripted signature public StrParameter sr; // public StrParameter tn; // Table Name, if is Service SAS public StrParameter blobSnapshotName; // Blob Snapshot Name if is Service SAS and using public StrParameter blobSnapshotTime; // Blob Snapshot Time - Service SAS only public string spk; // startpk; public string epk; // endpk; public string srk; // startrk; public string erk; // endrk; public StrParameter si; // Policy Name // query parameters to override response headers (Blob and File services only) public string rscc; // Cache-Control public string rscd; // Content-Disposition public string rsce; // Content-Encoding public string rscl; // Content-Language public string rsct; // Content-Type public DateTime stDateTime; // used to test the valid Date format public DateTime seDateTime; public string DebugInfo; }; public static SasParameters SAS; /// <summary> /// Contruct generic parameter on URI Escaped format, if exists /// ex: &si=sco /// </summary> /// <param name="param"></param> /// <param name="value"></param> /// <returns></returns> public static string Get_Parameter(string param, string value) { if (String.IsNullOrEmpty(value)) return ""; return "&" + param + "=" + Uri.EscapeDataString(value); } /// <summary> /// Ordering permissions - racwudpl /// </summary> /// <param name="permissions"></param> /// <returns></returns> public static string Order_permissions(string permissions) { string aux = ""; if (permissions.IndexOf("r") != -1) aux += "r"; if (permissions.IndexOf("a") != -1) aux += "a"; if (permissions.IndexOf("c") != -1) aux += "c"; if (permissions.IndexOf("w") != -1) aux += "w"; if (permissions.IndexOf("u") != -1) aux += "u"; if (permissions.IndexOf("d") != -1) aux += "d"; if (permissions.IndexOf("p") != -1) aux += "p"; if (permissions.IndexOf("l") != -1) aux += "l"; return aux; } /// <summary> /// Validate and save SAS parameter values on SAS struct /// Show SAS parameters results on BoxAuthResults /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SAS_Validate(string InputBoxSASvalue, TextBox BoxAuthResults) { // clear the left "BoxAuthResults" BoxAuthResults.Text = ""; // initialization of SAS Struct init_SASstruct(); // Validate and save SAS parameter values on SAS struct // return false if SAS String is invalid, and not show any results on left "BoxAuthResults" if (!SAS_GetParameters(InputBoxSASvalue)) return; // Show SAS parameters results on "BoxAuthResults" SAS_ShowResults(BoxAuthResults); } /// <summary> /// Test parameters on provided Account/Service SAS /// https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-an-Account-SAS?redirectedfrom=MSDN#constructing-the-account-sas-uri /// /// return false if SAS String is invalid, and not show any results on left TextBox /// </summary> /// <param name="InputBoxSAS"></param> private bool SAS_GetParameters(string InputBoxSASvalue) { // testing other parameters: (SharedAccessSignature, ;SharedAccessSignature?, BlobEndpoint=, FileEndpoint=, TableEndpoint=, QueueEndpoint= ) // return if SAS String is invalid if (!Check_SASString(InputBoxSASvalue)) return false; //--------------------------------------------------------------------- // Retrieving values from Service endpoints //--------------------------------------------------------------------- SAS.blobEndpoint = Get_SASValue(InputBoxSASvalue, "BlobEndpoint=", ";"); SAS.fileEndpoint = Get_SASValue(InputBoxSASvalue, "FileEndpoint=", ";"); SAS.tableEndpoint = Get_SASValue(InputBoxSASvalue, "TableEndpoint=", ";"); SAS.queueEndpoint = Get_SASValue(InputBoxSASvalue, "QueueEndpoint=", ";"); // If Endpoints not found, check if only URI (starting with http(s)://) was provided on InputBoxSAS // This is the case of the Service SAS Get_Endpoint_FromServiceSASURI(InputBoxSASvalue); // If endpoint Found // Search on endpoints strings, for values to SAS struct: // containerName, blobName, shareName, fileName, queueName, tableName Get_ResourceNames_FromEndpoints(); // Try to Get the Storage Account Name from any Endpoint, if provided Get_StorageAccountName_FromEndpoint(); //--------------------------------------------------------------------- // Retrieving Shared Access Signature //--------------------------------------------------------------------- // Connection string was provided SAS.onlySASprovided = false; SAS.sharedAccessSignature.v = Get_SASValue(InputBoxSASvalue, "SharedAccessSignature=", ";"); // only SAS token was provided if (SAS.sharedAccessSignature.v == "not found") { SAS.sharedAccessSignature.v = Get_SASValue(InputBoxSASvalue, "?"); if (Found(SAS.sharedAccessSignature.v, "not found=")) { SAS.sharedAccessSignature.s = false; return Utils.WithMessage("Missing the '?' at the begin of SAS token, or the term 'SharedAccessSignature=' on a Connection String", "Invalid SAS"); } else SAS.onlySASprovided = true; } //--------------------------------------------------------------------- //--------------------------------------------------------------------- // Retrieving the SAS parameters // Account SAS: https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-an-Account-SAS // Service SAS: https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas //--------------------------------------------------------------------- //--------------------------------------------------------------------- SAS.sv.v = Get_SASValue(SAS.sharedAccessSignature.v, "sv=", "&"); // Required (>=2015-04-05) SAS.ss.v = Get_SASValue(SAS.sharedAccessSignature.v, "ss=", "&"); SAS.srt.v = Get_SASValue(SAS.sharedAccessSignature.v, "srt=", "&"); SAS.sp.v = Get_SASValue(SAS.sharedAccessSignature.v, "sp=", "&"); SAS.se.v = Get_SASValue(SAS.sharedAccessSignature.v, "se=", "&"); SAS.st.v = Get_SASValue(SAS.sharedAccessSignature.v, "st=", "&"); SAS.sip.v = Get_SASValue(SAS.sharedAccessSignature.v, "sip=", "&"); SAS.spr.v = Get_SASValue(SAS.sharedAccessSignature.v, "spr=", "&"); SAS.sig = Get_SASValue(SAS.sharedAccessSignature.v, "sig=", "&"); //--------------------------------------------------------------------- //--------------------------------------------------------------------- // Retrieving the SAS parameters // Specific for Service SAS // Service SAS: https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas //--------------------------------------------------------------------- //--------------------------------------------------------------------- // sr: signedresource - Required { b,c } // blob, container - for blobs // { s,f } // share, file - for files //--------------------------------------------------------------------- SAS.sr.v = Get_SASValue(SAS.sharedAccessSignature.v, "sr=", "&"); //--------------------------------------------------------------------- // tn: tablename - Required. // The name of the table to share. //--------------------------------------------------------------------- SAS.tn.v = Get_SASValue(SAS.sharedAccessSignature.v, "tn=", "&"); //--------------------------------------------------------------------- // The startpk, startrk, endpk, and endrk fields define a range of table entities associated with a shared access signature. // Table queries will only return results that are within the range, and attempts to use the shared access signature to add, update, or delete entities outside this range will fail. // If startpk equals endpk, the shared access signature only authorizes access to entities in one partition in the table. // If startpk equals endpk and startrk equals endrk, the shared access signature can only access one entity in one partition. // Use the following table to understand how these fields constrain access to entities in a table. // startpk partitionKey >= startpk // endpk partitionKey <= endpk // startpk, startrk(partitionKey > startpk) || (partitionKey == startpk && rowKey >= startrk) // endpk, endrk(partitionKey < endpk) || (partitionKey == endpk && rowKey <= endrk) // https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-a-Service-SAS?redirectedfrom=MSDN#specifying-table-access-ranges //--------------------------------------------------------------------- // spk: startpk - Table service only. // srk: startrk - Optional, but startpk must accompany startrk. The minimum partition and row keys accessible with this shared access signature. // Key values are inclusive. If omitted, there is no lower bound on the table entities that can be accessed. // epk: endpk - Table service only. // erk: endrk - Optional, but endpk must accompany endrk. The maximum partition and row keys accessible with this shared access signature. // Key values are inclusive. If omitted, there is no upper bound on the table entities that can be accessed. //--------------------------------------------------------------------- SAS.spk = Get_SASValue(SAS.sharedAccessSignature.v, "spk=", "&"); SAS.epk = Get_SASValue(SAS.sharedAccessSignature.v, "epk=", "&"); SAS.srk = Get_SASValue(SAS.sharedAccessSignature.v, "srk=", "&"); SAS.erk = Get_SASValue(SAS.sharedAccessSignature.v, "erk=", "&"); //--------------------------------------------------------------------- // override response headers // Service SAS only - (Blob and File services only) // https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas#specifying-query-parameters-to-override-response-headers-blob-and-file-services-only //--------------------------------------------------------------------- SAS.rscc = Get_SASValue(SAS.sharedAccessSignature.v, "rscc=", "&"); SAS.rscd = Get_SASValue(SAS.sharedAccessSignature.v, "rscd=", "&"); SAS.rsce = Get_SASValue(SAS.sharedAccessSignature.v, "rsce=", "&"); SAS.rscl = Get_SASValue(SAS.sharedAccessSignature.v, "rscl=", "&"); SAS.rsct = Get_SASValue(SAS.sharedAccessSignature.v, "rsct=", "&"); //--------------------------------------------------------------------- // si: signedidentifier - Optional. // A unique value up to 64 characters in length that correlates to an access policy specified for the container, queue, or table. //--------------------------------------------------------------------- SAS.si.v = Get_SASValue(SAS.sharedAccessSignature.v, "si=", "&"); return true; } /// <summary> /// Show SAS parameters results on BoxAuthResults /// </summary> /// <param name="BoxAuthResults"></param> private static void SAS_ShowResults(TextBox BoxAuthResults) { //--------------------------------------------------------------------- //--------------------------------------------------------------------- // Showing the results //--------------------------------------------------------------------- //--------------------------------------------------------------------- BoxAuthResults.Text += Show_SASType(); BoxAuthResults.Text += "SAS Token (Unescaped): \n?" + SAS.sharedAccessSignature.v + "\n"; BoxAuthResults.Text += "\n"; // Verify if Services on URI are the same as on Service SAS permissions (Service SAS) BoxAuthResults.Text += Show_Services(); // ss: {bqtf} - Required // Service endpoints: (optional) BoxAuthResults.Text += Show_ss(SAS.ss.v, SAS.blobEndpoint, SAS.fileEndpoint, SAS.tableEndpoint, SAS.queueEndpoint, SAS.spr.v, SAS.onlySASprovided, SAS.srt.v); // spr: {https,http} - Optional (default both) BoxAuthResults.Text += Show_spr(SAS.spr.v, SAS.sr.v, SAS.tn.v, SAS.sv.v); // sv: Service Versions - Required (>=2015-04-05) - TODO more recent versions BoxAuthResults.Text += Show_sv(SAS.sv.v, SAS.sr.v, SAS.srt.v, SAS.tn.v); //--------------------------------------------------------------------- // srt: Signed Resource Types {s,c,o} {Service, Container, Object} - Required // Specific for Service SAS: https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas // sr: signedresource - Required { b,c } // blob, container - for blobs // { s,f } // share, file - for files, version 2015-02-21 and later // {bs} // blob snapshot, version 2018-11-09 and later // tn: tablename - Required - The name of the table to share. // No sr, srt or tn provided means queue service //--------------------------------------------------------------------- string s = SAS_ValidateParam.Sr_srt_tn(SAS.sr.v, SAS.srt.v, SAS.tn.v); switch (s) { // No srt, sr or tn provided - Service Queue SAS //--------------------------------------------------------------------- case "": BoxAuthResults.Text += Show_Queue(SAS.queueName.v); break; // More than one srt, sr or tn provided - Only one Required //--------------------------------------------------------------------- case "all": BoxAuthResults.Text += Show_All_srt_sr_tn("all"); break; //---------------- Account SAS ---------------------------------------- // srt: Signed Resource Types {s,c,o} {Service, Container, Object} - Required //--------------------------------------------------------------------- case "srt": BoxAuthResults.Text += Show_srt(SAS.srt.v); break; //---------------- Service SAS ---------------------------------------- // sr: signedresource - Required { b,c } // blob, container - for blobs // { s,f } // share, file - for files, version 2015-02-21 and later // {bs} // blob snapshot, version 2018-11-09 and later //--------------------------------------------------------------------- case "sr": BoxAuthResults.Text += Show_sr(SAS.sr.v, SAS.sv.v); break; //---------------- Service SAS ---------------------------------------- // tn: tablename - Required - The name of the table to share. //--------------------------------------------------------------------- case "tn": BoxAuthResults.Text += Show_tn(SAS.tn.v); break; } //--------------------------------------------------------------------- // 'si' Policy may define Permissions and Start and Expiry datetime // If Policy provided, no validate Permissions and Start and Expiry datetime if (String.IsNullOrEmpty(SAS.si.v)) { // sp: SignedPermissions {r,w,d,l,a,c,u,p} - Required // This field must be omitted if it has been specified in an associated stored access policy. - TODO (Service SAS) BoxAuthResults.Text += Show_sp(SAS.sp.v, SAS.srt.v, SAS.sr.v, SAS.tn.v, SAS.sv.v); // st (SignedStart) - optional // se (SignedExpiry) - Required BoxAuthResults.Text += Show_st_se(SAS.st.v, SAS.se.v); } // sip: Allowed IP's (optional) BoxAuthResults.Text += Show_sip(SAS.sip.v); // sig: Enchripted Signature - Required BoxAuthResults.Text += Show_sig(SAS.sig); //--------------------------------------------------------------------- // The startpk, startrk, endpk, and endrk fields define a range of table entities associated with a shared access signature. // Table queries will only return results that are within the range, and attempts to use the shared access signature to add, update, or delete entities outside this range will fail. // If startpk equals endpk, the shared access signature only authorizes access to entities in one partition in the table. // If startpk equals endpk and startrk equals endrk, the shared access signature can only access one entity in one partition. // Use the following table to understand how these fields constrain access to entities in a table. // startpk partitionKey >= startpk // endpk partitionKey <= endpk // startpk, startrk(partitionKey > startpk) || (partitionKey == startpk && rowKey >= startrk) // endpk, endrk(partitionKey < endpk) || (partitionKey == endpk && rowKey <= endrk) // https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-a-Service-SAS?redirectedfrom=MSDN#specifying-table-access-ranges //--------------------------------------------------------------------- // spk: startpk - Table service only. // srk: startrk - Optional, but startpk must accompany startrk. The minimum partition and row keys accessible with this shared access signature. // Key values are inclusive. If omitted, there is no lower bound on the table entities that can be accessed. // epk: endpk - Table service only. // erk: endrk - Optional, but endpk must accompany endrk. The maximum partition and row keys accessible with this shared access signature. // Key values are inclusive. If omitted, there is no upper bound on the table entities that can be accessed. //--------------------------------------------------------------------- BoxAuthResults.Text += Show_pk_rk(SAS.tn.v, SAS.spk, SAS.epk, SAS.srk, SAS.erk); //--------------------------------------------------------------------- // override response headers (Blob and File services only) // Service SAS only - (Blob and File services only) // https://docs.microsoft.com/en-us/rest/api/storageservices/create-service-sas#specifying-query-parameters-to-override-response-headers-blob-and-file-services-only //--------------------------------------------------------------------- BoxAuthResults.Text += Show_rscX(SAS.rscc, SAS.rscd, SAS.rsce, SAS.rscl, SAS.rsct); //--------------------------------------------------------------------- // si: signedidentifier - Optional. // A unique value up to 64 characters in length that correlates to an access policy specified for the container, queue, or table. //--------------------------------------------------------------------- BoxAuthResults.Text += Show_si(SAS.si.v, SAS.srt.v); } /// <summary> /// testing other parameters: /// SharedAccessSignature /// ;SharedAccessSignature? /// BlobEndpoint= /// FileEndpoint= /// TableEndpoint= /// QueueEndpoint= /// </summary> /// <param name="InputBoxSAS"></param> /// <returns></returns> private bool Check_SASString(string InputBoxSASvalue) { // Assuming some error will be found SAS.sharedAccessSignature.s = false; // Check for empty string if (InputBoxSASvalue == "") return Utils.WithMessage("Empty SAS or Connection String", "Invalid SAS"); // Check for some spaces or newlines on the string string space = Get_SpaceNL(InputBoxSASvalue.Trim()); if (space != "") return Utils.WithMessage("Invalid string - " + space + " found on SAS", "Invalid SAS"); // test 'SharedAccessSignature' (connection string) or '?' SAS if (InputBoxSASvalue.IndexOf("?") != -1 && Found(InputBoxSASvalue, "SharedAccessSignature")) return Utils.WithMessage("Only one 'SharedAccessSignature' or '?' should be provided on SAS", "Invalid SAS"); // test '??' found on SAS if (InputBoxSASvalue.IndexOf("??") != -1) return Utils.WithMessage("Only one '?' should be provided on SAS", "Invalid SAS"); // no 'SharedAccessSignature=' or '?' found if (!Found(InputBoxSASvalue, "SharedAccessSignature=") && InputBoxSASvalue.IndexOf("?") == -1) return Utils.WithMessage("Missing 'SharedAccessSignature=' (for connection strings)\n or '?' (for SAS token), on the provided SAS", "Invalid SAS"); // SharedAccessSignature?= found if (Found(InputBoxSASvalue, "SharedAccessSignature?=") || Found(InputBoxSASvalue, "SharedAccessSignature=?")) return Utils.WithMessage("Invalid characters found after 'SharedAccessSignature',\n on the provided SAS", "Invalid SAS"); // Connection string found, but no Endpoints found if (Found(InputBoxSASvalue, "SharedAccessSignature=") && !EndpointsExists(InputBoxSASvalue)) return Utils.WithMessage("Connection string found, but no Endpoints found.\nWithout endpoints, the SAS token should start with '?' instead of using 'SharedAccessSignature'", "Invalid SAS"); // if (InputBoxSASvalue.IndexOf("srt") == -1 && (InputBoxSASvalue.IndexOf("sr") != -1 || InputBoxSASvalue.IndexOf("tn") != -1)) // sr or tn (Service SAS) found { // Endpoints found if (!EndpointFound(InputBoxSASvalue, "BlobEndpoint")) return false; if (!EndpointFound(InputBoxSASvalue, "FileEndpoint")) return false; if (!EndpointFound(InputBoxSASvalue, "TableEndpoint")) return false; if (!EndpointFound(InputBoxSASvalue, "QueueEndpoint")) return false; } // if (InputBoxSASvalue.IndexOf("?") != -1 && EndpointsExists(InputBoxSASvalue)) return Utils.WithMessage("Endpoints should be removed from the SAS token.\nOnly allowed on Connection string", "Invalid SAS"); // No error found - restoring the .s value to true, before return SAS.sharedAccessSignature.s = true; return true; } /// <summary> /// return true if any Endpoint exists in string s; otherwise return false /// </summary> /// <param name="s"></param> /// <returns></returns> private static bool EndpointsExists(string s) { if (Found(s, "BlobEndpoint=")) return true; if (Found(s, "FileEndpoint=")) return true; if (Found(s, "QueueEndpoint=")) return true; if (Found(s, "TableEndpoint=")) return true; return false; } /// <summary> /// /// </summary> /// <param name="endpointStr"></param> /// <returns></returns> private bool EndpointFound(string InputBoxSASvalue, string endpointStr) { if (InputBoxSASvalue.IndexOf(endpointStr) != -1) { MessageBox.Show("Term '" + endpointStr + "' should be removed from the Service SAS URI", "Invalid SAS", MessageBoxButton.OK, MessageBoxImage.Exclamation); return false; } else return true; } /// <summary> /// If none Endpoint found, check if only URI (starting with http(s)://) was provided on InputBoxSAS /// This is the case of the Service SAS /// </summary> private void Get_Endpoint_FromServiceSASURI(string inputBoxSAS) { if (SAS.blobEndpoint == "not found" && SAS.fileEndpoint == "not found" && SAS.tableEndpoint == "not found" && SAS.queueEndpoint == "not found") { string newEndpoint = ""; string service = ""; int i = inputBoxSAS.IndexOf("?"); if (i != -1) newEndpoint = inputBoxSAS.Substring(0, i); service = Get_SASValue(newEndpoint, ".", ".core"); switch (service) { case "blob": SAS.blobEndpoint = newEndpoint; break; case "file": SAS.fileEndpoint = newEndpoint; break; case "queue": SAS.queueEndpoint = newEndpoint; break; case "table": SAS.tableEndpoint = newEndpoint; break; } } } /// <summary> /// Search on endpoints strings, for values to: /// SAS.containerName /// SAS.blobName /// SAS.shareName /// SAS.fileName /// SAS.queueName /// SAS.tableName /// /// Some of endpoints (Blob, File, Table, Queue) can be "not found" /// </summary> private void Get_ResourceNames_FromEndpoints() { if (SAS.blobEndpoint != "not found") { // Format, if exists: https://<storage>.blob.core.windows.net/container string s1 = Get_SASValue(SAS.blobEndpoint, ".blob.core.windows.net/", "/"); if (s1 != "not found") SAS.containerName.v = s1.TrimStart().Replace("/", String.Empty); // remove '/' at the end, if exists // Format, if exists: https://<storage>.blob.core.windows.net/container/blob if (SAS.containerName.v != "") { string s2 = Get_SASValue(SAS.blobEndpoint, ".blob.core.windows.net/" + SAS.containerName.v + "/"); if (s2 != "not found") { // remove subfolders int i = s2.LastIndexOf('/'); if (i == s2.Length - 1 && s2 != "") // blob name ends with '/' { SAS.blobName.v = "<invalid blob on endpoint>"; SAS.blobName.s = false; } else if (i > 0) // sub folders exist - removing subfolders SAS.blobName.v = s2.Substring(i + 1); else // only blob name found after the container name SAS.blobName.v = s2; } } } if (SAS.fileEndpoint != "not found") { // Format, if exists: https://<storage>.file.core.windows.net/share string s1 = Get_SASValue(SAS.fileEndpoint, ".file.core.windows.net/", "/"); if (s1 != "not found") SAS.shareName.v = s1.TrimStart().Replace("/", String.Empty); // remove '/' at the end, if exists // Format, if exists: https://<storage>.file.core.windows.net/share/file if (SAS.shareName.v != "") { string s2 = Get_SASValue(SAS.fileEndpoint, ".file.core.windows.net/" + SAS.shareName.v + "/"); if (s2 != "not found") { // remove subfolders int i = s2.LastIndexOf('/'); if (i == s2.Length - 1 && s2 != "") // file name ends with '/' { SAS.fileName.v = "<invalid file on endpoint>"; SAS.fileName.s = false; } else if (i > 0) // sub folders exist - removing subfolders SAS.fileName.v = s2.Substring(i + 1); else // only file name found after the share name SAS.fileName.v = s2; } } } // Table name if provided on tn paramenter and not on the URL /* if (SAS.tableEndpoint != "not found") { // Format, if exists: https://<storage>.table.core.windows.net/ string s = Get_SASValue(SAS.tableEndpoint, ".table.core.windows.net/"); int start = s.LastIndexOf("/") + 1; // start of the table name //if (s != "not found" && start > 0) // SAS.tn.v = s.Substring(start, s.Length - start); SAS.tn.v = s.TrimStart().Replace("/", String.Empty); // remove '/' at the end, if exists } */ if (SAS.queueEndpoint != "not found") { // Format, if exists: https://<storage>.queue.core.windows.net/queue string s = Get_SASValue(SAS.queueEndpoint, ".queue.core.windows.net/"); int start = s.LastIndexOf("/") + 1; // start of the Queue name SAS.queueName.v = s.TrimStart().Replace("/", String.Empty); // remove '/' at the end, if exists //if(SAS.queueName.v == "") // SAS.queueName.s = false; } } /// <summary> /// Return the type of the SAS detected /// </summary> private static string Show_SASType() { if (SAS.srt.v != "not found") return "Account SAS detected\n-----------------------------\n"; else if (SAS.sr.v != "not found" || SAS.tn.v != "not found") // Blob, Container, Share, File, Table { string service = ""; if (SAS.tn.v != "not found") service = "Table"; else switch (SAS.sr.v) { case "b": service = "Blob"; break; case "c": service = "Container"; break; case "s": service = "Share"; break; case "f": service = "File"; break; case "bs": service = "Blob Snapshot"; break; } return service + " Service SAS detected\n---------------------------- -\n"; } else return "Queue Service SAS detected\n-----------------------------\n"; // Queue } //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- /// <summary> /// Verify if Services on URI are the same as on Service SAS permissions /// </summary> public static string Show_Services() { // Table Service if (SAS.tn.v != "not found") { if (SAS.tableEndpoint == "not found") return " --> Table name 'tn' provided on SAS parameter, but a different or no URI was provided to the service.\n\n"; //if (!(SAS.tableEndpoint.EndsWith(".net") || SAS.tableEndpoint.EndsWith(".net/"))) // return " --> Incorrect Table Endpoint format.\nTable Endpoint should not mention the table name on URI.\n\n"; } // Blob Service if (SAS.sr.v == "b") { if (SAS.blobEndpoint == "not found") return " --> Blob was provided on 'sr' SAS parameter, but a different or no URI was provided to the service.\n\n"; if (SAS.blobName.v == "") return " --> Blob was provided on 'sr' SAS parameter, but no Blob name was provided on URI.\n\n"; } if (SAS.sr.v == "c") { if (SAS.blobEndpoint == "not found") return " --> Container was provided on 'sr' SAS parameter, but a different or no URI was provided to the service.\n\n"; if (SAS.containerName.v == "") return " --> Container was provided on 'sr' SAS parameter, but no Container name was provided on URI.\n\n"; if (SAS.blobName.v != "") return " --> Container was provided on 'sr' SAS parameter, but the Blob name should be removed from URI.\n\n"; } if (SAS.sr.v == "bs") { if (SAS.blobEndpoint == "not found") return " --> Blob Snapshot was provided on 'sr' SAS parameter, but a different or no URI was provided to the service.\n\n"; if (SAS.blobName.v == "") return " --> Blob Snapshot was provided on 'sr' SAS parameter, but no Snapshot name was provided on URI.\n\n"; } // File Service if (SAS.sr.v == "f") { if (SAS.fileEndpoint == "not found") return " --> File was provided on 'sr' SAS parameter, but a different or no URI was provided to the service.\n\n"; if (SAS.fileName.v == "") return " --> File was provided on 'sr' SAS parameter, but no File name was provided on URI.\n\n"; } if (SAS.sr.v == "s") { if (SAS.fileEndpoint == "not found") return " --> Share was provided on 'sr' SAS parameter, but a different or no URI was provided to the service.\n\n"; if (SAS.shareName.v == "") return " --> Share was provided on 'sr' SAS parameter, but no Share name was provided on URI.\n\n"; if (SAS.fileName.v != "") return " --> Share was provided on 'sr' SAS parameter, but the File name should be removed from URI.\n\n"; } // Queue Service if ((SAS.sr.v == "???") && SAS.queueEndpoint == "not found") return " --> Queue was provided on 'sr' SAS parameter, but a different service was provided on URI.\n\n"; return ""; } /// <summary> /// Format the output string for ss parameter and Endpoints provided on connection string /// b,f,t,q /// </summary> public static string Show_ss(string ss, string blobEndpoint, string fileEndpoint, string tableEndpoint, string queueEndpoint, string spr, bool onlySASprovided, string srt) { string s = "'ss' parameter (Signed Services):\n"; string res = SAS_ValidateParam.Ss(ss, spr, srt); if (SAS.ss.s == false) // error on value return s + " --> " + res + "\n\n"; if (res == "noSrt") return ""; // silent return ("not found") // value validated - add the endpoint //------------------------------------------------------------------ if (onlySASprovided) // only SAS token was provided { s += " Blob Service " + (ss.IndexOf("b") == -1 ? "NOT " : "") + "allowed " + (blobEndpoint != "not found" ? SAS_ValidateParam.EndpointFormat(blobEndpoint, "Blob", spr) : "") + "\n"; s += " File Service " + (ss.IndexOf("f") == -1 ? "NOT " : "") + "allowed " + (fileEndpoint != "not found" ? SAS_ValidateParam.EndpointFormat(fileEndpoint, "File", spr) : "") + "\n"; s += " Table Service " + (ss.IndexOf("t") == -1 ? "NOT " : "") + "allowed " + (tableEndpoint != "not found" ? SAS_ValidateParam.EndpointFormat(tableEndpoint, "Table", spr) : "") + "\n"; s += " Queue Service " + (ss.IndexOf("q") == -1 ? "NOT " : "") + "allowed " + (queueEndpoint != "not found" ? SAS_ValidateParam.EndpointFormat(queueEndpoint, "Queue", spr) : "") + "\n"; } else // Connection string was provided { s += " Blob Service " + (ss.IndexOf("b") == -1 ? "NOT allowed" : "allowed " + (blobEndpoint == "not found" ? "--> but Blob Endpoint NOT provided." : SAS_ValidateParam.EndpointFormat(blobEndpoint, "Blob", spr))) + "\n"; s += " File Service " + (ss.IndexOf("f") == -1 ? "NOT allowed" : "allowed " + (fileEndpoint == "not found" ? "--> but File Endpoint NOT provided." : SAS_ValidateParam.EndpointFormat(fileEndpoint, "File", spr))) + "\n"; s += " Table Service " + (ss.IndexOf("t") == -1 ? "NOT allowed" : "allowed " + (tableEndpoint == "not found" ? "--> but Table Endpoint NOT provided." : SAS_ValidateParam.EndpointFormat(tableEndpoint, "Table", spr))) + "\n"; s += " Queue Service " + (ss.IndexOf("q") == -1 ? "NOT allowed" : "allowed " + (queueEndpoint == "not found" ? "--> but Queue Endpoint NOT provided." : SAS_ValidateParam.EndpointFormat(queueEndpoint, "Queue", spr))) + "\n"; } return andSetState("ss", true, s + "\n"); } /// <summary> /// Format the output string for spr parameter and Endpoints provided on connection string /// Note that HTTP only is not a permitted value. /// https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas#constructing-the-account-sas-uri /// </summary> public static string Show_spr(string spr, string sr, string tn, string sv) { string s = "'spr' parameter (Allowed Protocols):\n"; string res = SAS_ValidateParam.Spr(spr, sr, tn, sv); if (SAS.spr.s == true) // value validated return s + " " + res + "\n\n"; else // error on value return s + " --> " + res + "\n\n"; } /// <summary> /// Format the output string for sv parameter /// /// You can specify two versioning options on a shared access signature. /// If specified, the optional api-version header indicates which service version to use to execute the API operation. /// The SignedVersion (sv) parameter specifies the service version to use to authorize and authenticate the request made with the SAS. /// If the api-version header is not specified, then the value of the SignedVersion (sv) parameter also indicates the version to /// use to execute the API operation. /// https://docs.microsoft.com/en-us/rest/api/storageservices/versioning-for-the-azure-storage-services#specifying-service-versions-in-requests /// ---------------------------------------------------------------------- /// Valid Storage Service Versions - Account SAS - Required (>=2015-04-05) - TODO more recent versions /// https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas#constructing-the-account-sas-uri /// /// Valid Storage Service Versions - Service SAS - Required (>=2012-02-12) - TODO more recent versions /// https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-a-Service-SAS?redirectedfrom=MSDN#specifying-the-signed-version-field /// 2015-02-21 /// 2014-02-14 /// 2013-08-15 /// 2012-02-12 /// /// Before version 2012-02-12, a shared access signature not associated with a stored access policy could not have an active period that exceeded one hour. /// Before version 2012-02-12 is supported ??? - TODO /// /// Available Versions: /// https://docs.microsoft.com/en-us/rest/api/storageservices/previous-azure-storage-service-versions /// -------------------------------------------------------------------------- /// </summary> public static string Show_sv(string sv, string sr, string srt, string tn) { string s = "'sv' parameter (Storage Service Version):\n"; string res = SAS_ValidateParam.Sv(sv, sr, srt, tn); if (SAS.sv.s == true) // value validated return s + " " + res + "\n\n"; else // error on value return s + " --> " + res + "\n\n"; } /// <summary> /// Format the output string in case of more than one provided /// </summary> /// <param name="s"></param> /// <returns></returns> public static string Show_All_srt_sr_tn(string str) { string s = "'srt', 'sr', 'tn' parameters (Account / Service SAS):\n"; string res = SAS_ValidateParam.Srt_sr_tn(str); if (SAS.srt.s == true && SAS.sr.s == true && SAS.tn.s == true) // value validated return s + " " + res + "\n\n"; else // error on value return s + " --> " + res + "\n\n"; } /// <summary> /// Format the output string for srt parameter /// SignedResourceTypes {s,c,o} Service, Container, Object} - Required /// </summary> /// <param name="srt"></param> /// <returns></returns> public static string Show_srt(string srt) { string s = "'srt' parameter (Signed Resource Type):\n"; // no (required) srt provided if (srt == "not found") return andSetState("srt", false, s + " --> 'srt' Required but not provided\n\n"); // srt empty if (srt.Length == 0) return andSetState("srt", false, s + " --> Empty Signed Resource Type value (srt=" + srt + ")\n\n"); // found chars not supported by srt paramenter if (!Utils.ValidateString(srt, "sco")) return andSetState("srt", false, s + " --> Invalid Signed Resource Types (srt=" + srt + ")\n\n"); // srt OK if (srt.Length <= 3) { if (srt.IndexOf("s") != -1) s += " Access to Service-level APIs (Get/Set Service Properties, Get Service Stats, List Containers/Queues/Tables/Shares)\n"; if (srt.IndexOf("c") != -1) s += " Access to Container-level APIs (Create/Delete Container, Create/Delete Queue, Create/Delete Table, Create/Delete Share, List Blobs/Files and Directories)\n"; if (srt.IndexOf("o") != -1) s += " Access to Object-level APIs (Put Blob, Query Entity, Get Messages, Create File, etc.)\n"; } else return andSetState("srt", false, s + " --> Invalid Signed Resource Types (srt=" + srt + ")\n\n"); return andSetState("srt", true, s + "\n"); } /// <summary> /// Format the output string for sr parameter /// SignedResource sr: Required { b,c } // blob, container - for blobs /// { s,f } // share, file - for files, version 2015-02-21 and later /// {bs} // blob snapshot, version 2018-11-09 and later /// </summary> /// <param name="sr"></param> /// <param name="sv"></param> /// <returns></returns> public static string Show_sr(string sr, string sv) { string s = "'sr' parameter (Signed Resource):\n"; string res = SAS_ValidateParam.Sr(sr, sv); if (SAS.sr.s == true) // value validated return s + " " + res + "\n\n"; else // error on value return s + " --> " + res + "\n\n"; } /// <summary> /// Format the output string for tr parameter /// TableResource {TableName} The name of the table to share - Required /// </summary> /// <param name="tn"></param> /// <returns></returns> public static string Show_tn(string tn) { string s = "'tn' parameter (Table Name):\n"; string res = SAS_ValidateParam.Tn(tn); if (SAS.tn.s == true) // value validated return s + " " + res + "\n\n"; else // error on value return s + " --> " + res + "\n\n"; } /// <summary> /// Format the output string in case of none queue parameter provided on URI, - Service Queue /// </summary> /// <param name="queue"></param> /// <returns></returns> public static string Show_Queue(string queue) { string s = "Queue Service SAS (no 'srt', 'sr', 'tn'):\n"; string res = SAS_ValidateParam.Queue(queue); if (SAS.tn.s == true) // value validated return s + " " + res + "\n\n"; else // error on value return s + " --> " + res + "\n\n"; } /// <summary> /// Format the output string for startpk, startrk, endpk, and endrk parameter /// TableResource {TableName} The name of the table to share - Required /// /// Specifying table access ranges /// The startpk, startrk, endpk, and endrk fields define a range of table entities associated with a shared access signature. /// </summary> /// <param name="tn"></param> /// <param name="startpk"></param> /// <param name="endpk"></param> /// <param name="startrk"></param> /// <param name="endrk"></param> /// <returns></returns> public static string Show_pk_rk(string tn, string startpk, string endpk, string startrk, string endrk) { // no table access ranges provided if (startpk == "not found" && endpk == "not found" && startrk == "not found" && endrk == "not found") return ""; // No table access ranges specified (optional) string s = "'startpk', 'endpk', 'startrk', 'endrk' parameters - Table access range - Partition and Row Keys:\n"; // no tn provided to apply partition and row ranges if (tn == "not found") return s += " --> 'tn' Required but not provided, when specifying 'startpk', 'endpk', 'startrk', 'endrk' parameters (tn=" + tn + ")\n\n"; // one partition key provided -> need provide both ??? - TODO if ((startpk == "not found" && endpk != "not found") || (startpk != "not found" && endpk == "not found")) return s += " --> Missing Table Partition Key on specifying allowed Partitions (startpk=" + startpk + ", endpk=" + endpk + ")\n\n"; // one row key provided -> need provide both ??? - TODO if ((startrk == "not found" && endrk != "not found") || (startrk != "not found" && endrk == "not found")) return s += " --> Missing Table Row Key on specifying allowed Rows (startrk=" + startrk + ", endrk=" + endrk + ")\n\n"; if (startpk != "not found" && endpk != "not found") { if (startpk.Length == 0) return s += " --> Empty Start Partition Key value (startpk=" + startpk + ")\n\n"; if (endpk.Length == 0) return s += " --> Empty End Partition Key value (endpk=" + endpk + ")\n\n"; s += " Allowing Table access from Partition '" + startpk + "' to '" + endpk + "'\n"; } if (startrk != "not found" && endrk != "not found") { if (startrk.Length == 0) return s += " --> Empty Start Row Key value (startrk=" + startrk + ")\n\n"; if (endrk.Length == 0) return s += " --> Empty End Row Key value (endrk=" + endrk + ")\n\n"; s += " Allowing Table access from Row '" + startrk + "' to '" + endrk + "'\n"; } return s + "\n"; } public static string Show_rscX(string rscc, string rscd, string rsce, string rscl, string rsct) { string s = ""; if (rscc != "not found") s += " Cache-Control: " + rscc; if (rscd != "not found") s += " Content-Disposition: " + rscd; if (rsce != "not found") s += " Content-Encoding: " + rsce; if (rscl != "not found") s += " Content-Language: " + rscl; if (rsct != "not found") s += " Content-Type: " + rsct; if (s != "") s += "'rscc', 'rscd', 'rsce', 'rscl', 'rsct' parameters - Override response headers (Blob and File services only):\n" + s; return s + "\n"; } /// <summary> /// Format the output string for si parameter /// si: signedidentifier - Optional. /// A unique value up to 64 characters in length that correlates to an access policy specified for the container, queue, or table. /// </summary> /// <param name="si"></param> /// <returns></returns> public static string Show_si(string si, string srt) { string s = "'si' parameter (Signed Identifier - Policy):\n"; string res = SAS_ValidateParam.Si(si, srt); if (SAS.si.s == false) // error on value return s + " --> " + res + "\n\n"; if (res == "") return ""; // silent return ("not found") // value validated return s + " " + res + "\n\n"; } /// <summary> /// Format the output string for sp parameter - SignedPermissions {r,w,d,l,a,c,u,p} - Required /// </summary> /// <param name="sp"></param> /// <param name="srt"></param> /// <param name="sr"></param> /// <param name="tn"></param> /// <param name="sv"></param> /// <returns></returns> public static string Show_sp(string sp, string srt, string sr, string tn, string sv) { string s = "'sp' parameter (Signed Permissions):\n"; string res = SAS_ValidateParam.Sp(sp, srt, sr, tn, sv); if (SAS.sp.s == false) // error on value return s + " --> " + res + "\n\n"; // value validated return s + " " + res + "\n"; } /// <summary> /// Format the output string for st and se parameters /// st (SignedStart) - optional /// se (SignedExpiry) - Required /// --------------------------------------------- /// TODO Service SAS - Before version 2012-02-12, a shared access signature not associated with a stored access policy could not have an active period that exceeded one hour. /// --------------------------------------------- /// Supported ISO 8601 formats include the following: /// YYYY-MM-DD /// YYYY-MM-DDThh:mmZ /// YYYY-MM-DDThh:mm:ssZ /// https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-an-Account-SAS?redirectedfrom=MSDN#specifying-the-signature-validity-interval /// </summary> /// <param name="st"></param> /// <param name="se"></param> /// <returns></returns> public static string Show_st_se(string st, string se) { string s = "'st','se' parameters (Signed Start & Signed End Date/Time):\n"; string res = SAS_ValidateParam.St_se(st, se); if (SAS.st.s == false || SAS.se.s == false) // error on value return s + " --> " + res + "\n\n"; // value validated return s + " " + res + "\n\n"; } /// <summary> /// sip: Allowed IP's (optional) /// sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 /// Multiple IPs not supported /// </summary> /// <param name="sip"></param> /// <returns></returns> public static string Show_sip(string sip) { string s = "'sip' parameter (Signed IP):\n"; string res = SAS_ValidateParam.Sip(sip); if (SAS.sip.s == false) // error on value return s + " --> " + res + "\n\n"; // value validated return s + " " + res + "\n\n"; } /// <summary> /// Format the output string for sig parameter /// Encripted signature - Required /// https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-a-Service-SAS?redirectedfrom=MSDN#specifying-the-signature /// </summary> /// <param name="sig"></param> /// <returns></returns> public static string Show_sig(string sig) { string s = "'sig' parameter (Signature):\n"; // no (required) sig provided if (sig == "not found") return s += " --> 'sig' required but not provided\n\n"; // sig empty if (sig.Length == 0) return s += " --> Empty required Signature value (sig=" + sig + ")\n\n"; // TODO - some other sig checks here return s += " Encripted Signature sig=" + sig + "\n\n"; } /// <summary> /// Try to Get the Storage Account Name from any Endpoint, if provided /// </summary> private void Get_StorageAccountName_FromEndpoint() { SAS.storageAccountName.v = Get_SASValue(SAS.blobEndpoint, "://", "."); if (SAS.storageAccountName.v == "" || SAS.storageAccountName.v == "not found") SAS.storageAccountName.v = Get_SASValue(SAS.fileEndpoint, "://", "."); if (SAS.storageAccountName.v == "" || SAS.storageAccountName.v == "not found") SAS.storageAccountName.v = Get_SASValue(SAS.tableEndpoint, "://", "."); if (SAS.storageAccountName.v == "" || SAS.storageAccountName.v == "not found") SAS.storageAccountName.v = Get_SASValue(SAS.queueEndpoint, "://", "."); } /// <summary> /// Search on source and returns the string value between SASHeader and delimiter, or the end of the string if delimiter not found /// debug=true : adds additional information /// </summary> public static string Get_SASValue(string source, string SASHeader, string delimiter, bool debug = false) { string s2 = "not found"; int i = source.IndexOf(SASHeader); int lenght = 0; if (i >= 0) { i += SASHeader.Length; lenght = source.IndexOf(delimiter, i) - i; if (lenght >= 0) s2 = source.Substring(i, lenght); if (lenght < 0) // delimeter not found - end of the string s2 = source.Substring(i); } if (debug) return "SASHeader:" + SASHeader + " i:" + i.ToString() + " lenght:" + lenght.ToString() + " s2:" + s2; return s2; } /// <summary> /// Search on source and returns the string value between SASHeader and the end on the source. /// debug=true : adds additional information /// </summary> public static string Get_SASValue(string source, string SASHeader, bool debug = false) { string s2 = "not found"; int i = source.IndexOf(SASHeader); if (i >= 0) s2 = source.Substring(i + SASHeader.Length); if (debug) return "SASHeader:" + SASHeader + " i:" + i.ToString() + " s2:" + s2; return s2; } /// <summary> /// Search on source to seach any space or new line in the source. /// return "" if ok /// </summary> public static string Get_SpaceNL(string source) { int i = -1; i = source.IndexOf(" "); // space if (i != -1) return "Space"; else i = source.IndexOf("\r\n"); if (i == -1) i = source.IndexOf("\r"); if (i == -1) i = source.IndexOf("\n"); if (i != -1) return "New Line"; return ""; } /// <summary> /// Return true if the str is found on ComboBox items list /// </summary> /// <param name="str"></param> /// <returns></returns> private static bool ComboItemFound(ComboBox comboBox, string str) { for (int i = 0; i < comboBox.Items.Count; i++) if (str == comboBox.Items[i].ToString()) return true; return false; } /// <summary> /// Fill the sv ComboBox and the API_Version with the values of the array passed /// </summary> /// <param name="comboBox1"></param> public static void PopulateComboBox_sv(ComboBox comboBox1, string comboBox_sr_txt, string TextBox_tn_txt) { string s = comboBox1.Text; comboBox1.Items.Clear(); // Check Account SAS PopulateComboBox(comboBox1, comboBox_sr_txt, validSV_AccountSAS_ARR); // Check Service SAS if (comboBox_sr_txt != "" || TextBox_tn_txt != "") PopulateComboBox(comboBox1, comboBox_sr_txt, validSV_ServiceSas_ARR_addon); // Validate the old value of the combo box are in the new list, otherwise clean the value if (ComboItemFound(comboBox1, s)) comboBox1.Text = s; else comboBox1.Text = ""; } /// <summary> /// Fill an genetic ComboBox with the values of the array passed /// Control Service Versions supported on each type of SAS /// </summary> /// <param name="comboBox1"></param> public static void PopulateComboBox(ComboBox comboBox1, string sr, string[] arr) { for (int i = 0; i < arr.Length; i++) { if (sr == "bs") { if (arr[i].CompareTo("2018-11-09") >= 0) // Service SAS bs suported on Service version 2018-11-09 and later comboBox1.Items.Add(arr[i]); } else if (sr == "f" || sr == "s") { if (arr[i].CompareTo("2015-02-21") > 0) // Service SAS File and Share suported on Service version 2015-02-21 and later comboBox1.Items.Add(arr[i]); // (from Storage Explorer, seems 2015-02-21 not suported - removing the '=') } else comboBox1.Items.Add(arr[i]); } } /// <summary> /// true / false ig the 'findStr' found on 'source' /// </summary> /// <param name="source"></param> /// <param name="find"></param> /// <returns></returns> private static bool Found(string source, string findStr) { if (source.IndexOf(findStr) != -1) return true; return false; } /// <summary> /// Set the state on StrParameter param, and return the string /// States: true - no error on parameter; false - Error found on paramenter /// Used on Show_XXX functions /// </summary> public static string andSetState(string param, bool state, string s) { Set_StateParameter(param, state); return s; } /// <summary> /// /// </summary> /// <param name="param"></param> /// <param name="state"></param> public static void Set_StateParameter(string param, bool state) { switch (param) { case "sv": SAS.sv.s = state; break; case "ss": SAS.ss.s = state; break; case "srt": SAS.srt.s = state; break; case "sp": SAS.sp.s = state; break; case "st": SAS.st.s = state; break; case "se": SAS.se.s = state; break; case "sip": SAS.sip.s = state; break; case "spr": SAS.spr.s = state; break; case "sr": SAS.sr.s = state; break; case "tn": SAS.tn.s = state; break; case "si": SAS.si.s = state; break; case "queue": SAS.queueName.s = state; break; } } //-------------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------- public static void init_SASstruct() { SAS.sharedAccessSignature.v = ""; SAS.sharedAccessSignature.s = true; SAS.blobEndpoint = ""; SAS.fileEndpoint = ""; SAS.tableEndpoint = ""; SAS.queueEndpoint = ""; SAS.storageAccountName.v = ""; SAS.storageAccountName.s = true; SAS.storageAccountKey.v = ""; SAS.storageAccountKey.s = true; SAS.containerName.v = ""; SAS.containerName.s = true; SAS.blobName.v = ""; SAS.blobName.s = true; SAS.shareName.v = ""; SAS.shareName.s = true; SAS.fileName.v = ""; SAS.fileName.s = true; SAS.queueName.v = ""; SAS.queueName.s = true; // table name in SAS.tn,v //SAS.onlySASprovided = true; SAS.sv.v = ""; SAS.sv.s = true; SAS.ss.v = ""; SAS.ss.s = true; SAS.srt.v = ""; SAS.srt.s = true; SAS.sp.v = ""; SAS.sp.s = true; SAS.se.v = ""; SAS.se.s = true; SAS.st.v = ""; SAS.st.s = true; SAS.sip.v = ""; SAS.sip.s = true; SAS.spr.v = ""; SAS.spr.s = true; SAS.sig = ""; SAS.sr.v = ""; SAS.sr.s = true; SAS.tn.v = ""; SAS.tn.s = true; SAS.blobSnapshotName.v = ""; SAS.blobSnapshotName.s = true; SAS.blobSnapshotTime.v = ""; SAS.blobSnapshotTime.s = true; // Service SAS only SAS.spk = ""; // The bellow are disable by default on UI SAS.epk = ""; SAS.srk = ""; SAS.erk = ""; SAS.si.v = ""; SAS.si.s = true; SAS.rscc = ""; SAS.rscd = ""; SAS.rsce = ""; SAS.rscl = ""; SAS.rsct = ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; public class PointCloudDiffTool : MonoBehaviour { public TextAsset PointCloud1; public TextAsset PointCloud2; public Material Material1; public Material Material2; void Start() { ConstructPointCloud(PointCloud1, Material1); ConstructPointCloud(PointCloud2, Material2); } void ConstructPointCloud(TextAsset file, Material mat) { var p = AssetDatabase.GetAssetPath(file); string[] lines = File.ReadAllLines(p); print($"file has {lines.Length} points"); var vertices = new Vector3[lines.Length]; var indices = new int[vertices.Length]; for (var i = 0; i < vertices.Length; ++i) { indices[i] = i; } var mesh = new Mesh(); for (int i = 0; i < lines.Length; i++) { var split = lines[i].Split('/'); var pos = new Vector3(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2])); vertices[i] = pos; if (i == 0) { print(pos); } } print($"mesh has {vertices.Length} points"); mesh.SetVertices(vertices); mesh.SetIndices(indices, MeshTopology.Points, 0); var go = new GameObject(file.name, typeof(MeshFilter), typeof(MeshRenderer)); var mf = go.GetComponent<MeshFilter>(); var mr = go.GetComponent<MeshRenderer>(); mr.material = mat; mf.mesh = mesh; } }
#region copyright // ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** #endregion using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Inventory.Models { public class CustomerModel : BaseModel { static public CustomerModel CreateEmpty() => new CustomerModel { Id = -1, IsEmpty = true }; public DateTimeOffset CreatedOn { get; set; } public DateTimeOffset? LastModifiedOn { get; set; } public Guid RowGuid { get; set; } [Required] public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public DateTimeOffset? BirthDate { get; set; } [DefaultValue(true)] public bool SignOfConsent { get; set; } public int? SourceId { get; set; } public SourceModel Source { get; set; } public bool IsBlockList { get; set; } public byte[] Picture { get; set; } public object PictureSource { get; set; } public byte[] Thumbnail { get; set; } public object ThumbnailSource { get; set; } public string FullName => $"{LastName} {FirstName} {MiddleName}".Trim(); public string Initials => String.Format("{0}{1}", $"{FirstName} "[0], $"{LastName} "[0]).Trim().ToUpper(); public override void Merge(ObservableObject source) { if (source is CustomerModel model) { Merge(model); } } public void Merge(CustomerModel source) { if (source != null) { Id = source.Id; CreatedOn = source.CreatedOn; LastModifiedOn = source.LastModifiedOn; RowGuid = source.RowGuid; FirstName = source.FirstName; MiddleName = source.MiddleName; LastName = source.LastName; BirthDate = source.BirthDate; SignOfConsent = source.SignOfConsent; SourceId = source.SourceId; Source = source.Source; IsBlockList = source.IsBlockList; Thumbnail = source.Thumbnail; ThumbnailSource = source.ThumbnailSource; Picture = source.Picture; PictureSource = source.PictureSource; } } public override string ToString() { return IsEmpty ? "Empty" : FullName; } } }
using Basic.Message; namespace Arm { public abstract class ArmActionFactory { protected readonly IMessage _message; protected bool _connected = false; public bool Connected => _connected; public ArmActionFactory(IMessage message) { _message = message; } public abstract IConnect Connect(); public abstract IDisconnect Disconnect(); public abstract IAbsoluteMotion AbsoluteMotion(double[] position); public abstract IAbsoluteMotion AbsoluteMotion(double xJ1, double yJ2, double zJ3, double aJ4, double bJ5, double cJ6); public abstract IRelativeMotion RelativeMotion(double[] position); public abstract IRelativeMotion RelativeMotion(double xJ1, double yJ2, double zJ3, double aJ4, double bJ5, double cJ6); } }
namespace TripDestination.Web.MVC.Controllers.ChildActionControllers { using System.Web.Mvc; using Services.Data.Contracts; using ViewModels.Shared; using Common.Infrastructure.Constants; public class StatisticsChildActionController : Controller { public StatisticsChildActionController(IStatisticsServices statisticsServices) { this.StatisticsServices = statisticsServices; } public IStatisticsServices StatisticsServices { get; set; } [ChildActionOnly] [OutputCache(Duration = CacheTimeConstants.StatisticsTodaysTrips, VaryByParam = "itemsPerRow")] public ActionResult TodaysStats(int? itemsPerRow) { var colMdValue = 6; if (itemsPerRow != null) { switch (itemsPerRow) { case 1: colMdValue = 12; break; case 2: colMdValue = 6; break; case 3: colMdValue = 4; break; case 4: colMdValue = 3; break; default: colMdValue = 6; break; } } var viewModel = new TodaysStatisticsViewModel() { ColMdValue = colMdValue, TodayCreatedTrips = this.StatisticsServices.TripsGetTodayCreatedCount(), TodayInProgressTrips = this.StatisticsServices.TripsGetTodayInProgressCount(), TodayFinishedTrips = this.StatisticsServices.TripsGetTodayFinishedCount(), TodayTopDestinationTown = this.StatisticsServices.TripsGetTodayTopDestination() }; return this.PartialView("~/Views/Shared/_TodaysStatisticsPartial.cshtml", viewModel); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GeneralResources.XUnitExample.CollectionTests { #region Run sequencially public class TestClass1 { [Fact] public void Test1() { Thread.Sleep(3000); } [Fact] public void Test2() { Thread.Sleep(5000); } } #endregion #region Run parallel public class TestClass2 { [Fact] public void Test1() { Thread.Sleep(3000); } } public class TestClass3 { [Fact] public void Test2() { Thread.Sleep(5000); } } #endregion #region Run Sequencially even in different classes [Collection("These test collection takes part of #1")] public class TestClass4 { [Fact] public void Test1() { Thread.Sleep(3000); } } [Collection("These test collection takes part of #1")] public class TestClass5 { [Fact] public void Test2() { Thread.Sleep(5000); } } #endregion }
using UnityEngine; public class DoubleJumpTrigger : MonoBehaviour { private void OnTriggerEnter2D(Collider2D collision) { var playerController = GameManager.instance.player.GetComponent<PlayerController>(); playerController.allowedJumps = 2; } }
using System; using System.Collections.Generic; using System.Linq; namespace BorderControl { public class StartUp { static void Main(string[] args) { var buyers = new List<IBuyer>(); var numberOfLines = int.Parse(Console.ReadLine()); for (int i = 0; i < numberOfLines; i++) { var tokens = Console.ReadLine().Split(); if (tokens.Length > 3) { var citizen = new Citizen(tokens[0], int.Parse(tokens[1]), tokens[2], tokens[3]); buyers.Add(citizen); } else { var rebel = new Rebel(tokens[0], int.Parse(tokens[1]), tokens[2]); buyers.Add(rebel); } } var command = Console.ReadLine(); while (command!="End") { var name = command; if (buyers .Where(x => x.Name == name) .ToList().Count == 1) { buyers .Where(x => x.Name == name) .ToList()[0] .BuyFood(); } command = Console.ReadLine(); } Console.WriteLine(buyers.Sum(x => x.Food)); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; using CaseManagement.DataObjects; using CaseManagement.Models.SQL; using System.IO; namespace CaseManagement.Controllers { [Authorize] public class ClientDocumentsController : ApiController { private SQLDatabase db = new SQLDatabase(); // GET: api/ClientDocuments/5 public List<ClientDocument> GetClientDocument(int id) { return db.ClientDocuments.Where(x => x.clientId == id).ToList(); } // DELETE: api/ClientDocuments/5 [ResponseType(typeof(ClientDocument))] public void DeleteClientDocument(int id) { var doc = db.ClientDocuments.Where(x => x.clientDocumentId == id).Single(); var file = new FileInfo(doc.filePath); file.Delete(); db.ClientDocuments.Remove(doc); db.SaveChanges(); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }