Esempio n. 1
1
        public Junction MapXmlToDomain(XmlJunction xmlJunction, IList<SplitTrack> subTracks)
        {
            SplitTrack defaultTrack = subTracks.First(subTrack => xmlJunction.BranchDefaultId.Equals(subTrack.Id));
            SplitTrack altTrack = subTracks.First(subTrack => xmlJunction.BranchAlternateId.Equals(subTrack.Id));

            return new Junction(xmlJunction.Id, defaultTrack, altTrack, xmlJunction.Direction);
        }
Esempio n. 2
1
 //exactly same as x.browser
 private static void UpdateManifest(IList<Services.Data.ExtensionManifestDataModel> found, IExtensionManifest ext)
 {
     if (found != null && found.Count() > 0)
     {
         ext.IsExtEnabled = found.First().IsExtEnabled;
         ext.LaunchInDockPositions = (ExtensionInToolbarPositions)found.First().LaunchInDockPositions;
         ext.FoundInToolbarPositions = (ExtensionInToolbarPositions)found.First().FoundInToolbarPositions;
     }
 }
        public CurrencyRateViewMode(IList<CurrencyRate> rates)
        {
            var dollarSellingRate = rates.First(r => r.Type == TradeType.Selling && r.CurrencyName == "Dollar");
            var euroSellingRate = rates.First(r => r.Type == TradeType.Selling && r.CurrencyName == "Euro");
            var dollarBuyingRate = rates.First(r => r.Type == TradeType.Buying && r.CurrencyName == "Dollar");
            var euroBuyingRate = rates.First(r => r.Type == TradeType.Buying && r.CurrencyName == "Euro");

            SellingUsDollar = new RateKeyPair(dollarSellingRate.RateId){ExchangePrice =  dollarSellingRate.ExchangePrice};
            SellingEuro = new RateKeyPair(euroSellingRate.RateId) { ExchangePrice = euroSellingRate.ExchangePrice};
            BuyingUsDollar = new RateKeyPair(dollarBuyingRate.RateId) {ExchangePrice = dollarBuyingRate.ExchangePrice};
            BuyingEuro = new RateKeyPair(euroBuyingRate.RateId) { ExchangePrice = euroBuyingRate.ExchangePrice };
        }
 private Section CreateSection(IList<string> lines, int level)
 {
     string title = null;
     var headingMarker = new String('#', level) + " ";
     if (lines.First().StartsWith(headingMarker))
     {
         title = lines.First().TrimStart('#').Trim();
         lines.RemoveAt(0);
     }
     var furtherLevelMarkers = new String('#', level + 1);
     return lines.Any(x => x.StartsWith(furtherLevelMarkers))
         ? new Section(level, title, BreakDownSection(lines, level + 1).ToList())
         : new Section(level, title, string.Join(Environment.NewLine, lines));
 }
Esempio n. 5
1
 public Measure GetHourlyEnergyMeasure(IList<Measure> sourceMeasures, string hourMeasureSource, string hourDataVariable)
 {
     var dataVariable = hourDataVariable;
     var measurePercentage = 1;
     var plant = sourceMeasures.First().Plant;
     var reliability = 0;
     var resolution = getHourResolution();
     var source = hourMeasureSource;
     var utcDate = sourceMeasures.First().UtcDate;
     var utcHour = sourceMeasures.First().UtcHour;
     var utcMinute = 00;
     var utcSecond = 00;
     var value = getValue(sourceMeasures);
     return new Measure(plant, source, dataVariable, utcDate, utcHour, utcMinute, utcSecond, value, measurePercentage, reliability, resolution);
 }
Esempio n. 6
1
        public Statistics(IList<IVehicle> vehicles, bool removeOutliers = true)
        {
            if (vehicles == null || !vehicles.Any())
                throw new ArgumentException("Vehicles is null or count is 0. Must be greater than 0");

            _vehicles = vehicles;
            _outlierVehicles = new List<OutlierVehicle>();
            Make = _vehicles.First().Make;
            Model = _vehicles.First().Model;

            if (removeOutliers)
            {
                RemoveOutliers();
            }
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (IsHtmlFile && completionSets.Any())
            {
                var bottomSpan = completionSets.First().ApplicableTo;
                if (!JScriptEditorUtil.IsInJScriptLanguageBlock(_lbm, bottomSpan.GetStartPoint(bottomSpan.TextBuffer.CurrentSnapshot)))
                {
                    // This is an HTML statement completion session, so do nothing
                    return;
                }
            }

            // TODO: Reflect over the ShimCompletionSet to see where the Description value comes from
            //       as setting the property does not actually change the value.
            var newCompletionSets = completionSets
                .Select(cs => cs == null ? cs : new ScriptCompletionSet(
                    cs.Moniker,
                    cs.DisplayName,
                    cs.ApplicableTo,
                    cs.Completions
                        .Select(c => c == null ? c : new Completion(
                            c.DisplayText,
                            c.InsertionText,
                            DocCommentHelper.ProcessParaTags(c.Description),
                            c.IconSource,
                            c.IconAutomationText))
                        .ToList(),
                    cs.CompletionBuilders))
                .ToList();
            
            completionSets.Clear();

            newCompletionSets.ForEach(cs => completionSets.Add(cs));
        }
        /// <summary>
        /// Sort the items by their priority and their index they currently exist in the collection
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public static IList<IClientDependencyFile> SortItems(IList<IClientDependencyFile> files)
        {
            //first check if each item's order is the same, if this is the case we'll make sure that we order them 
            //by the way they were defined
            if (!files.Any()) return files;

            var firstPriority = files.First().Priority;

            if (files.Any(x => x.Priority != firstPriority))
            {
                var sortedOutput = new List<IClientDependencyFile>();
                //ok they are not the same so we'll need to sort them by priority and by how they've been entered
                var groups = files.GroupBy(x => x.Priority).OrderBy(x => x.Key);
                foreach (var currentPriority in groups)
                {
                    //for this priority group, we'll need to prioritize them by how they are found in the files array
                    sortedOutput.AddRange(currentPriority.OrderBy(files.IndexOf));
                }
                return sortedOutput;
            }

            //they are all the same so we can really just return the original list since it will already be in the 
            //order that they were added.
            return files;
        } 
        private FeedResult FeedResult(IList<SyndicationItem> items)
        {
            var settings = Settings.GetSettings<FunnelWebSettings>();

            Debug.Assert(Request.GetOriginalUrl() != null, "Request.GetOriginalUrl() != null");

            var baseUri = Request.GetOriginalUrl();
            var feedUrl = new Uri(baseUri, Url.Action("Recent", "Wiki"));
            return new FeedResult(
                new Atom10FeedFormatter(
                    new SyndicationFeed(settings.SiteTitle, settings.SearchDescription, feedUrl, items)
                    {
                        Id = baseUri.ToString(),
                        Links =
                        {
                            new SyndicationLink(baseUri)
                            {
                                RelationshipType = "self"
                            }
                        },
                        LastUpdatedTime = items.Count() == 0 ? DateTime.Now : items.First().LastUpdatedTime
                    }), items.Max(i => i.LastUpdatedTime.LocalDateTime))
            {
                ContentType = "application/atom+xml"
            };
        }
Esempio n. 10
1
        public static MapRepresentation Create(HttpRequestMessage req, IList<ContextSurface> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) {
            OptionalProperty[] memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToArray();
            INakedObjectSurface target = contexts.First().Target;
            MapRepresentation mapRepresentation;

            if (format == Format.Full) {
                var tempProperties = new List<OptionalProperty>();

                if (flags.SimpleDomainModel) {
                    var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName());
                    tempProperties.Add(dt);
                }

                if (flags.FormalDomainModel) {
                    var links = new OptionalProperty(JsonPropertyNames.Links, new[] {
                        Create(new OptionalProperty(JsonPropertyNames.Rel, RelValues.DescribedBy),
                               new OptionalProperty(JsonPropertyNames.Href, new UriMtHelper(req, target.Specification).GetDomainTypeUri()))
                    });
                    tempProperties.Add(links);
                }

                var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues));
                tempProperties.Add(members);
                mapRepresentation = Create(tempProperties.ToArray());
            }
            else {
                mapRepresentation = Create(memberValues);
            }

            mapRepresentation.SetContentType(mt);

            return mapRepresentation;
        }
Esempio n. 11
1
        public MultilayerPerceptron(int numInputs, int numOutputs, IList<int> hiddenLayerSizes)
        {
            if (numInputs <= 0)
                throw new NeuralNetworkException($"Argument {nameof(numInputs)} must be positive; was {numInputs}.");

            if (numOutputs <= 0)
                throw new NeuralNetworkException($"Argument {nameof(numOutputs)} must be positive; was {numOutputs}.");

            if (hiddenLayerSizes == null || !hiddenLayerSizes.Any())
                throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} cannot be null or empty.");

            if (hiddenLayerSizes.Any(h => h <= 0))
            {
                var badSize = hiddenLayerSizes.First(h => h <= 0);
                var index = hiddenLayerSizes.IndexOf(badSize);
                throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} must contain only positive " +
                                                $"values; was {badSize} at index {index}.");
            }

            NumInputs = numInputs;
            NumOutputs = numOutputs;
            HiddenLayerSizes = hiddenLayerSizes.ToArray();

            Weights = new double[hiddenLayerSizes.Count + 1][];

            for (var i = 0; i < hiddenLayerSizes.Count + 1; i++)
            {
                if (i == 0)
                    Weights[i] = new double[(numInputs + 1) * hiddenLayerSizes[0]];
                else if (i < hiddenLayerSizes.Count)
                    Weights[i] = new double[(hiddenLayerSizes[i-1] + 1) * hiddenLayerSizes[i]];
                else
                    Weights[i] = new double[(hiddenLayerSizes[hiddenLayerSizes.Count - 1] + 1) * numOutputs];
            }
        }
 private void CheckFirstAndLastPoint(IList<DepthPointEx> points)
 {
     if (PointsAreClose(points.Last(), points.First()))
     {
         points.RemoveAt(points.Count - 1);
     }
 }
Esempio n. 13
1
        public int Update(AdoAdapter adapter, string tableName, IList<IDictionary<string, object>> data, IDbTransaction transaction, IList<string> keyFields)
        {
            int count = 0;
            if (data == null) throw new ArgumentNullException("data");
            if (data.Count < 2) throw new ArgumentException("UpdateMany requires more than one record.");

            if (keyFields.Count == 0) throw new NotSupportedException("Adapter does not support key-based update for this object.");
            if (!AllRowsHaveSameKeys(data)) throw new SimpleDataException("Records have different structures. Bulk updates are only valid on consistent records.");
            var table = adapter.GetSchema().FindTable(tableName);

            var exampleRow = new Dictionary<string, object>(data.First(), HomogenizedEqualityComparer.DefaultInstance);

            var commandBuilder = new UpdateHelper(adapter.GetSchema()).GetUpdateCommand(tableName, exampleRow,
                                                                    ExpressionHelper.CriteriaDictionaryToExpression(
                                                                        tableName, GetCriteria(keyFields, exampleRow)));

            using (var connectionScope = ConnectionScope.Create(transaction, adapter.CreateConnection))
            using (var command = commandBuilder.GetRepeatableCommand(connectionScope.Connection))
            {
                var propertyToParameterMap = CreatePropertyToParameterMap(data, table, command);

                foreach (var row in data)
                {
                    foreach (var kvp in row)
                    {
                        propertyToParameterMap[kvp.Key].Value = kvp.Value ?? DBNull.Value;
                    }
                    count += command.ExecuteNonQuery();
                }
            }

            return count;
        }
        public IList<DepthPointEx> Filter(IList<DepthPointEx> points)
        {
            IList<DepthPointEx> result = new List<DepthPointEx>();

            if (points.Count > 0)
            {
                var point = new DepthPointEx(points.First());
                result.Add(point);

                foreach (var currentSourcePoint in points.Skip(1))
                {
                    if (!PointsAreClose(currentSourcePoint, point))
                    {
                        point = new DepthPointEx(currentSourcePoint);
                        result.Add(point);
                    }
                }

                if (result.Count > 1)
                {
                    CheckFirstAndLastPoint(result);
                }
            }

            return result;
        }
Esempio n. 15
1
        public MainWindow()
        {
            InitializeComponent();
            Loaded += (sender, e) => ClearValue(SizeToContentProperty);

            _allControllerViewModels =
                (from type in GetType().Assembly.GetTypes()
                 where !type.IsInterface && typeof(IController).IsAssignableFrom(type)
                 let viewModel = new ControllerViewModel((IController)Activator.CreateInstance(type))
                 orderby viewModel.SortIndex, viewModel.Library, viewModel.Description
                 select viewModel).ToList();
            _allControllerViewModels.First().IsChecked = true;
            ControllerGroups.ItemsSource = _allControllerViewModels.GroupBy(viewModel => viewModel.Library);

            _allResolutionViewModels = new[] {
                new ResolutionViewModel(800, 600, 50, 42),
                new ResolutionViewModel(1024, 768, 64, 54),
                new ResolutionViewModel(1280, 1024, 80, 73),
                new ResolutionViewModel(1440, 900, 90, 64),
            };
            _allResolutionViewModels.Last(
                res => res.Width <= SystemParameters.PrimaryScreenWidth &&
                res.Height <= SystemParameters.PrimaryScreenHeight).IsChecked = true;
            Resolutions.ItemsSource = _allResolutionViewModels;

            RunResults.ItemsSource = _runResults;
        }
Esempio n. 16
1
        public IList<Point> Filter(IList<Point> points)
        {
            IList<Point> result = new List<Point>();
            if (points.Count == 0)
            {
                return result;
            }

            var point = new Point(points.First());
            result.Add(point);

            foreach (var currentSourcePoint in points.Skip(1))
            {
                if (!this.DistanceIsTooSmall(currentSourcePoint, point))
                {
                    point = new Point(currentSourcePoint);
                    result.Add(point);
                }
            }

            if (this.checkBoundary && result.Count > 1)
            {
                CheckFirstAndLastPoint(result);
            }

            return result;
        }
Esempio n. 17
1
 private void CheckFirstAndLastPoint(IList<Point> points)
 {
     if (this.DistanceIsTooSmall(points.Last(), points.First()))
     {
         points.RemoveAt(points.Count - 1);
     }
 }
        public static MapRepresentation Create(IOidStrategy oidStrategy, HttpRequestMessage req, ContextFacade contextFacade, IList<ContextFacade> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) {
            var memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, req, c, flags))).ToList();
            IObjectFacade target = contexts.First().Target;
            MapRepresentation mapRepresentation;

            if (format == Format.Full) {
                var tempProperties = new List<OptionalProperty>();

                if (!string.IsNullOrEmpty(contextFacade?.Reason)) {
                    tempProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, contextFacade.Reason));
                }

                var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName(oidStrategy));
                tempProperties.Add(dt);

                var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues.ToArray()));
                tempProperties.Add(members);
                mapRepresentation = Create(tempProperties.ToArray());
            }
            else {
                mapRepresentation = Create(memberValues.ToArray());
            }

            mapRepresentation.SetContentType(mt);

            return mapRepresentation;
        }
Esempio n. 19
0
    public void SignIn_ResultHasCorrectValues(AuthenticationProperties properties, IList <string> authenticationSchemes)
    {
        // Arrange
        var principal = new ClaimsPrincipal();

        // Act
        var result = TypedResults.SignIn(principal, properties, authenticationSchemes?.First());

        // Assert
        Assert.Equal(principal, result.Principal);
        Assert.Equal(properties, result.Properties);
        Assert.Equal(authenticationSchemes?.First(), result.AuthenticationScheme);
    }
Esempio n. 20
0
        public static RatioValue Calculate(IList<double> numerators, IList<double> denominators)
        {
            if (numerators.Count != denominators.Count)
            {
                throw new ArgumentException();
            }
            if (numerators.Count == 0)
            {
                return null;
            }
            if (numerators.Count == 1)
            {
                return new RatioValue(numerators.First()/denominators.First());
            }
            var statsNumerators = new Statistics(numerators);
            var statsDenominators = new Statistics(denominators);
            var ratios = new Statistics(numerators.Select((value, index) => value/denominators[index]));

            // The mean ratio is the average of "ratios" weighted by "statsDenominators".
            // It's also equal to the sum of the numerators divided by the sum of the denominators.
            var meanRatio = statsNumerators.Sum()/statsDenominators.Sum();

            // Helpers.Assume(Math.Abs(mean - stats.Mean(statsW)) < 0.0001);
            // Make sure the value does not exceed the bounds of a float.
            float meanRatioFloat = (float)Math.Min(float.MaxValue, Math.Max(float.MinValue, meanRatio));

            return new RatioValue
            {
                Ratio = meanRatioFloat,
                StdDev = (float) ratios.StdDev(statsDenominators),
                DotProduct = (float) statsNumerators.Angle(statsDenominators),
            };
        }
Esempio n. 21
0
        public string pequenoResumoTodasPartidas(IList <IPartida> partidas)
        {
            this.valorTotalGanho   = 0;
            this.valorTotalPerdido = 0;

            StringBuilder stringBuilder = new StringBuilder("#\t\tGanhador\tValorGanho\tTotalPote" + Environment.NewLine);

            foreach (IPartida p in partidas)
            {
                stringBuilder.AppendLine(this.pequenoResumo(p));
            }

            IJogadorStack jogStack = partidas?.First().Jogador?.JogadorStack;

            if (jogStack == null)
            {
                return("");
            }

            stringBuilder.AppendLine();
            stringBuilder.AppendLine();
            stringBuilder.AppendFormat("Ganhos: {0}", this.valorTotalGanho);
            stringBuilder.AppendFormat("\tPerdas: {0}" + Environment.NewLine, this.valorTotalPerdido);

            return(stringBuilder.ToString());
        }
        private void InternalSubmitData(IList<MongodbItem> items)
        {
            if (items == null || items.Count == 0)
                return;

            var databaseName = items.First().DatabaseName;

            try
            {
                if (CachedMongoServer == null)
                    return;

                var database = CachedMongoServer.GetDatabase(databaseName);

                foreach (var item in items)
                {
                    var collection = database.GetCollection(item.TableName);

                    collection.Insert(item.Data);
                }
            }
            catch (Exception ex)
            {
                LocalLoggingService.Exception("MongodbInsertService.InternalSubmitData<{0}> error: {1}", databaseName, ex.Message);
            }
        }
Esempio n. 23
0
        public static List<PlayEvent> Create(IList<Event> events, string homeTeam)
        {
            var penalties = new List<PlayEvent>();

            var penaltyEvents = events.Where(e => e.Class == "Penalty");

            foreach (var penaltyEvent in penaltyEvents)
            {
                var penaltyStartTime = GameTimeCalculator.Calculate(penaltyEvent.Period, penaltyEvent.TimePeriod);
                var penaltyEndTime = CalculatePenaltyEndTime(penaltyEvent.Description, penaltyEvent.Period, penaltyEvent.TimePeriod);

                Logger.Debug(string.Format("Game {0} S {1} E {2} ET {3}", events.First().GameId, penaltyStartTime.ToClockTime(), penaltyEndTime.ToClockTime(), penaltyEvent.Description));

                penalties.Add(new PlayEvent
                {
                    StartTime = penaltyStartTime,
                    EndTime = penaltyEndTime,
                    Class = penaltyEvent.Class,
                    Description = penaltyEvent.Description,
                    HomeTeam = penaltyEvent.Team == homeTeam,
                });
            }

            return penalties;
        }
Esempio n. 24
0
 public AnimatedSprite(Texture2D texture, EntityType entityType, IList<AnimationSequence> animations, AnimationActions initialAnimationAction,
     Rectangle worldPosition, Vector2 speed = new Vector2(), Vector2 direction = new Vector2(), bool isCollidable = false, int collisionOffset = 0)
     : base(texture, entityType, worldPosition, speed: speed, direction: direction, isCollidable: isCollidable, collisionOffset: collisionOffset)
 {
     Animations = animations;
     CurrentAnimation = Animations.First(a => a.AnimationAction == initialAnimationAction);
 }
Esempio n. 25
0
        public string pequenoResumo(IList <IPartida> partidas)
        {
            StringBuilder stringBuilder = new StringBuilder();

            IJogadorStack jogStack = partidas?.First().Jogador?.JogadorStack;

            if (jogStack == null)
            {
                return("");
            }

            int vitorias = 0, derrotas = 0, empates = 0;

            vitorias = partidas.Where(p => p.JogadorGanhador == VencedorPartida.Jogador).Count();
            derrotas = partidas.Where(p => p.JogadorGanhador == VencedorPartida.Banca).Count();
            empates  = partidas.Where(p => p.JogadorGanhador == VencedorPartida.Empate).Count();

            stringBuilder.AppendFormat("Resumo dos jogos" + Environment.NewLine);
            stringBuilder.AppendFormat("V\tD\tE" + Environment.NewLine);
            stringBuilder.AppendFormat("{0}\t{1}\t{2}" + Environment.NewLine + Environment.NewLine, vitorias, derrotas, empates);

            stringBuilder.AppendFormat("Resumo do stack " + Environment.NewLine);
            stringBuilder.AppendFormat("Inicial: {0}" + Environment.NewLine, jogStack.StackInicial);
            stringBuilder.AppendFormat("Final: {0}" + Environment.NewLine, jogStack.Stack);

            return(stringBuilder.ToString());
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 public SubmissionCandidatesViewModel(
     User user,
     IList<Commit> commits,
     Func<Commit, string> commitUrlBuilder,
     Checkpoint checkpoint,
     Model.Projects.Submission latestSubmission,
     ITimeZoneProvider timeZoneProvider)
 {
     User = user;
     Checkpoint = checkpoint;
     Candidates = commits
         .OrderByDescending(commit => commit.PushDate)
         .ThenByDescending(commit => commit.CommitDate)
         .Select
         (
             commit => new SubmissionCandidateViewModel
             (
                 commit,
                 commitUrlBuilder(commit),
                 latestSubmission?.CommitId == commit.Id,
                 commit == commits.First(),
                 timeZoneProvider
             )
         ).ToList();
 }
Esempio n. 27
0
		public bool CanExecute(IList<string> documentIds)
		{
			if (documentIds == null || documentIds.Count == 0)
				return false;

			return string.IsNullOrEmpty(documentIds.First()) == false;
		}
 private static string tryGetInstanceName(MethodInfo methodInfo, IList<object> arguments)
 {
     return methodInfo.Name.StartsWith("GetNamed", StringComparison.InvariantCultureIgnoreCase)
            && arguments.Any()
         ? Convert.ToString(arguments.First())
         : null;
 }
Esempio n. 29
0
        public virtual Span Handle(IList<Token> tokens, Options options)
        {
            var now = options.Clock();
            var span = new Span(now, now.AddSeconds(1));

            var grabberTokens = tokens
                .SkipWhile(token => token.IsNotTaggedAs<Grabber>())
                .ToList();
            if (grabberTokens.Any())
            {
                span = grabberTokens.GetAnchor(options);
            }

            var scalarRepeaters = tokens
                .TakeWhile(token => token.IsNotTaggedAs<Pointer>())
                .Where(token => token.IsNotTaggedAs<SeparatorComma>())
                .ToList();

            var pointer = tokens.First(token => token.IsTaggedAs<Pointer>());

            for (var index = 0; index < scalarRepeaters.Count - 1; index++)
            {
                var scalar = scalarRepeaters[index];
                var repeater = scalarRepeaters[++index];
                span = Handle(new List<Token>{ scalar, repeater, pointer}, span, options);
            }

            return span;
        }
 public static QueryExpressionSyntax WithAllClauses(
     this QueryExpressionSyntax query,
     IList<SyntaxNode> allClauses)
 {
     var fromClause = (FromClauseSyntax)allClauses.First();
     return query.WithFromClause(fromClause).WithBody(query.Body.WithAllClauses(allClauses.Skip(1)));
 }
 public ActionResult AprobarOrden(int id, IList<DetalleOrdenRecargaPrepago> detalleOrden, decimal MontoTotalRecargas, string indicadorGuardar, string DocumentoReferencia, string Observaciones)
 {
     ViewModel viewmodel = new ViewModel();
     detalleOrden.First().documentoOrden = DocumentoReferencia;
     detalleOrden.First().observacionesOrden = Observaciones;
     if (indicadorGuardar == "Aprobar")
     {
         if (repOrden.AprobarOrden(detalleOrden.ToList(), MontoTotalRecargas))
         {
             viewmodel.Title = "Prepago / Ordenes de Recarga / Detalle de la Orden";
             viewmodel.Message = "Orden Aprobada.";
             viewmodel.ControllerName = "OrdenRecargaPrepago";
             viewmodel.ActionName = "FilterReview";
             return RedirectToAction("GenericView", viewmodel);
             //return RedirectToAction("DetalleOrden", new { id = id, idOrden = idOrden });
         }
         else
         {
             viewmodel.Title = "Prepago / Ordenes de Recarga / Detalle de la Orden";
             viewmodel.Message = "Falló el proceso de aprobación de la Orden.";
             viewmodel.ControllerName = "OrdenRecargaPrepago";
             viewmodel.ActionName = "FilterReview";
             return RedirectToAction("GenericView", viewmodel);
         }
     }
     else
     {
         if (repOrden.GuardarOrden(detalleOrden.ToList(), MontoTotalRecargas))
         {
             viewmodel.Title = "Prepago / Ordenes de Recarga / Detalle de la Orden";
             viewmodel.Message = "Datos de la Orden actualizados.";
             viewmodel.ControllerName = "OrdenRecargaPrepago";
             viewmodel.ActionName = "FilterReview";
             return RedirectToAction("GenericView", viewmodel);
             //return RedirectToAction("DetalleOrden", new { id = id, idOrden = idOrden });
         }
         else
         {
             viewmodel.Title = "Prepago / Ordenes de Recarga / Detalle de la Orden";
             viewmodel.Message = "Falló el proceso de guardado de la Orden.";
             viewmodel.ControllerName = "OrdenRecargaPrepago";
             viewmodel.ActionName = "FilterReview";
             return RedirectToAction("GenericView", viewmodel);
         }
     }
 }
Esempio n. 32
0
 public DataProviderViewModel(ExperimentViewModel experimentViewModel, IServiceLocator serviceLocator)
 {
     this.serviceLocator = serviceLocator;
     _experimentViewModel = experimentViewModel;
     ViewModel = experimentViewModel;
     dataProviders = serviceLocator.GetAllInstances<IDataProvider>().ToList();
     selectedDataProvider = dataProviders.First();
 }
Esempio n. 33
0
		public bool CanExecute(IList<DocumentViewModel> documents)
		{
			if (documents == null || documents.Count == 0)
				return false;

			var document = documents.First();
			return document != null && document.CollectionType != BuiltinCollectionName.Projection;
		}
        public void Convert_OneElement_ReturnsCorrespondingList()
        {
            //Arrange
            var converter         = new CultureInfoCollectionStringConverter();
            var language          = new CultureInfo("en-US");
            var expectedConverted = language.DisplayName + " (" + language.Name + ")";
            IEnumerable <CultureInfo> languages = new List <CultureInfo> {
                language
            };

            //Act
            var converted = converter.Convert(
                languages, typeof(IEnumerable <string>), null, CultureInfo.InvariantCulture);
            IList <string> convertedAsTargetType = (converted as IEnumerable <string>)?.ToList();

            //Assert
            Assert.IsInstanceOfType(converted, typeof(IEnumerable <string>));
            Assert.AreEqual(1, convertedAsTargetType?.Count);
            Assert.AreEqual(expectedConverted, convertedAsTargetType?.First());
        }
Esempio n. 35
0
        public static string SectorOf(IList <string> input)
        {
            var result = input.First(x => x.Contains("north") && x.Contains("pole"));

            return(Regex.Match(result, @"[0-9]+").Value);
        }
Esempio n. 36
0
 public LanguageSettings(IList <LanguageDefintion> languageDefintions)
 {
     CurrentLanguage     = languageDefintions.First();
     LanguageDefinitions = new ReadOnlyCollection <LanguageDefintion>(languageDefintions);
 }
Esempio n. 37
0
        public virtual async Task DefaultEnumTypesProviderShouldReturnEnumTypes()
        {
            const string sourceCodes = @"

public interface IDto {
}

public class DtoController<TDto>
    where TDto : IDto
{

}

public class DtoWithEnum : IDto
{
    public virtual int Id { get; set; }

    public virtual TestGender? Gender { get; set; }

    public virtual string Test { get; set; }
}

public enum TestGender
{
    Man = 3, Woman = 12, Other
}

public enum TestGender2
{
    Man = 3, Woman = 12, Other
}

public sealed class ParameterAttribute : System.Attribute
{
    public ParameterAttribute(string name, System.Type type, bool isOptional = false)
    {
    }
}

public class DtoWithEnumController : DtoController<DtoWithEnum>
{
    [ActionAttribute]
    [ParameterAttribute(""gender"", typeof(TestGender))]
    public virtual int GetDtoWithEnumsByGender()
    {
        return 1;
    }

    [ActionAttribute]
    [ParameterAttribute(""gender"", typeof(TestGender2))]
    public virtual int GetDtoWithEnumsByGender2()
    {
        return 1;
    }
}

";

            IProjectDtoControllersProvider projectDtoControllersProvider = new DefaultProjectDtoControllersProvider();

            IProjectEnumTypesProvider projectEnumTypesProvider = new DefaultProjectEnumTypesProvider(projectDtoControllersProvider, new DefaultProjectDtosProvider(projectDtoControllersProvider));

            Project proj = CreateProjectFromSourceCodes(sourceCodes);

            IList <EnumType> result = projectEnumTypesProvider.GetProjectEnumTypes(proj, new[] { proj });

            Assert.IsTrue(result.Select(enumType => enumType.EnumTypeSymbol.Name).SequenceEqual(new[] { "TestGender", "TestGender2" }));

            Assert.IsTrue(result.First().Members.SequenceEqual(new[]
            {
                new EnumMember {
                    Name = "Man", Value = 3, Index = 0
                },
                new EnumMember {
                    Name = "Woman", Value = 12, Index = 1
                },
                new EnumMember {
                    Name = "Other", Value = 13, Index = 2
                }
            }, new EnumMemberEqualityComparer()));
        }
Esempio n. 38
0
 public object Build(Type typeToBuild)
 {
     return(funcs.First(f => f.Item1 == typeToBuild).Item2());
 }
Esempio n. 39
0
        /// <summary>
        /// Uses pre-defined list of animals to put in wagons.
        /// </summary>
        /// <returns></returns>
        public IList <Bandwagon> SortAnimalsInWagons()
        {
            List <Animal> AvailableAnimals = new List <Animal>
            {
                new Elephant(),
                new Elephant(),
                new Elephant(),
                new Elephant(),
                new Elephant(),
                new Elephant(),
                new Elephant(),
                new Elephant(),
                new Elephant(),
                new Elephant(),
                new Camel(),
                new Camel(),
                new Camel(),
                new Monkey(),
                new Monkey(),
                new Monkey(),
                new Monkey(),
                new Monkey(),
                new Monkey()
            };
            IList <Bandwagon> OrderWagons = new List <Bandwagon>();

            IList <Animal> meatEaters = AvailableAnimals.FindAll(x => x.IsMeatLover).OrderByDescending(x => x.Size).ToList();
            IList <Animal> vegans     = AvailableAnimals.FindAll(x => !x.IsMeatLover).OrderByDescending(x => x.Size).ToList();

            while (AvailableAnimals.Any())
            {
                Bandwagon newBandwagon      = new Bandwagon(new List <Animal>());
                Animal    meatEaterSelected = new Animal();
                if (meatEaters.Count > 0)
                {
                    meatEaterSelected = meatEaters.First();
                    newBandwagon.animals.Add(meatEaterSelected);
                    newBandwagon.bandWagonSpace += meatEaterSelected.Size;
                    meatEaters.Remove(meatEaterSelected);
                }

                foreach (Animal vegan in vegans)
                {
                    if (meatEaterSelected.Size < vegan.Size)
                    {
                        if (vegan.Size + newBandwagon.bandWagonSpace <= 10)
                        {
                            newBandwagon.animals.Add(vegan);
                            newBandwagon.bandWagonSpace += vegan.Size;
                        }
                    }
                }

                OrderWagons.Add(newBandwagon);
                foreach (Animal newBandwagonAnimal in newBandwagon.animals)
                {
                    AvailableAnimals.RemoveAt(AvailableAnimals.IndexOf(newBandwagonAnimal));
                    vegans.Remove(newBandwagonAnimal);
                }
            }

            return(OrderWagons);
        }
Esempio n. 40
0
 public LotteryPlan GetLotteryPlan(int planId)
 {
     return(_lotteryPlans.First(p => p.PlanId == planId));
 }
Esempio n. 41
0
 public IActionResult WhoIsTheBestOwner()
 {
     return(Ok(owners.First().Name));
 }
Esempio n. 42
0
        protected override void SelectionChanged(IList <int> selectedIds)
        {
            SettingsProvider selectedProvider = GetFirstValidProvider(selectedIds.Count > 0 ? selectedIds.First() : -1);

            currentProviderChanged?.Invoke(currentProvider, selectedProvider);
            currentProvider = selectedProvider;
        }
        public TqRegistrationProfile SeedRegistrationDataByStatus(long uln, RegistrationPathwayStatus status = RegistrationPathwayStatus.Active, TqProvider tqProvider = null)
        {
            var profile = new TqRegistrationProfileBuilder().BuildList().FirstOrDefault(p => p.UniqueLearnerNumber == uln);
            var tqRegistrationProfile = RegistrationsDataProvider.CreateTqRegistrationProfile(DbContext, profile);
            var tqRegistrationPathway = RegistrationsDataProvider.CreateTqRegistrationPathway(DbContext, tqRegistrationProfile, tqProvider ?? TqProviders.First());

            tqRegistrationPathway.Status = status;

            if (status == RegistrationPathwayStatus.Withdrawn)
            {
                tqRegistrationPathway.EndDate = DateTime.UtcNow.AddDays(-1);
            }

            DbContext.SaveChanges();
            return(profile);
        }
        private ModificationFunctionMapping GenerateFunctionMapping(
            ModificationOperator modificationOperator,
            EntitySetBase entitySetBase,
            EntityTypeBase entityTypeBase,
            DbDatabaseMapping databaseMapping,
            IEnumerable <EdmProperty> parameterProperties,
            IEnumerable <Tuple <ModificationFunctionMemberPath, EdmProperty> > iaFkProperties,
            IList <ColumnMappingBuilder> columnMappings,
            IEnumerable <EdmProperty> resultProperties = null,
            string functionNamePrefix = null)
        {
            DebugCheck.NotNull(entitySetBase);
            DebugCheck.NotNull(entityTypeBase);
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(parameterProperties);
            DebugCheck.NotNull(iaFkProperties);
            DebugCheck.NotNull(columnMappings);

            var useOriginalValues = modificationOperator == ModificationOperator.Delete;

            var parameterMappingGenerator
                = new FunctionParameterMappingGenerator(_providerManifest);

            var parameterBindings
                = parameterMappingGenerator
                  .Generate(
                      modificationOperator,
                      parameterProperties,
                      columnMappings,
                      new List <EdmProperty>(),
                      useOriginalValues)
                  .Concat(
                      parameterMappingGenerator
                      .Generate(iaFkProperties, useOriginalValues))
                  .ToList();

            var parameters
                = parameterBindings.Select(b => b.Parameter).ToList();

            UniquifyParameterNames(parameters);

            var functionPayload
                = new EdmFunctionPayload
                {
                ReturnParameters = new FunctionParameter[0],
                Parameters       = parameters.ToArray(),
                IsComposable     = false
                };

            var function
                = databaseMapping.Database
                  .AddFunction(
                      (functionNamePrefix ?? entityTypeBase.Name) + "_" + modificationOperator.ToString(),
                      functionPayload);

            var functionMapping
                = new ModificationFunctionMapping(
                      entitySetBase,
                      entityTypeBase,
                      function,
                      parameterBindings,
                      null,
                      resultProperties != null
                        ? resultProperties.Select(
                          p => new ModificationFunctionResultBinding(
                              columnMappings.First(cm => cm.PropertyPath.SequenceEqual(new[] { p })).ColumnProperty.Name,
                              p))
                        : null);

            return(functionMapping);
        }
Esempio n. 45
0
        /// <summary>
        /// Streams the channel data.
        /// </summary>
        /// <param name="contextList">The context list.</param>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        protected virtual async Task StreamChannelData(IList <ChannelStreamingContext> contextList, CancellationToken token)
        {
            _channelStreamingContextLists.Add(contextList);

            // These values can be set outside of our processing loop as the won't chnage
            //... as context is processed and completed.
            var firstContext         = contextList.First();
            var channelStreamingType = firstContext.ChannelStreamingType;
            var parentUri            = firstContext.ParentUri;
            var indexes             = firstContext.ChannelMetadata.Indexes.Cast <IIndexMetadataRecord>().ToList();
            var primaryIndex        = indexes[0];
            var isTimeIndex         = indexes.Select(i => i.IndexKind == (int)ChannelIndexKinds.Time).ToArray();
            var requestLatestValues =
                channelStreamingType == ChannelStreamingTypes.IndexCount
                    ? firstContext.IndexCount
                    : channelStreamingType == ChannelStreamingTypes.LatestValue
                        ? 1
                        : (int?)null;
            var  increasing = primaryIndex.Direction == (int)IndexDirections.Increasing;
            bool?firstStart = null;

            // Loop until there is a cancellation or all channals have been removed
            while (!IsStreamingStopped(contextList, ref token))
            {
                firstStart = !firstStart.HasValue;

                var channelIds = contextList.Select(i => i.ChannelId).Distinct().ToArray();
                Logger.Debug($"Streaming data for parentUri {parentUri.Uri} and channelIds {string.Join(",", channelIds)}");

                // We only need a start index value for IndexValue and RangeRequest or if we're streaming
                //... IndexCount or LatestValue and requestLatestValues is no longer set.
                var minStart =
                    (channelStreamingType == ChannelStreamingTypes.IndexValue || channelStreamingType == ChannelStreamingTypes.RangeRequest) ||
                    ((channelStreamingType == ChannelStreamingTypes.IndexCount || channelStreamingType == ChannelStreamingTypes.LatestValue) &&
                     !requestLatestValues.HasValue)
                        ? contextList.Min(x => Convert.ToInt64(x.StartIndex))
                        : (long?)null;

                // Only need and end index value for range request
                var maxEnd = channelStreamingType == ChannelStreamingTypes.RangeRequest
                    ? contextList.Max(x => Convert.ToInt64(x.EndIndex))
                    : (long?)null;

                //var isTimeIndex = primaryIndex.IndexType == ChannelIndexTypes.Time;
                var rangeSize = WitsmlSettings.GetRangeSize(isTimeIndex[0]);

                // Convert indexes from scaled values
                var minStartIndex = minStart?.IndexFromScale(primaryIndex.Scale, isTimeIndex[0]);
                var maxEndIndex   = channelStreamingType == ChannelStreamingTypes.IndexValue
                    ? (increasing ? minStartIndex + rangeSize : minStartIndex - rangeSize)
                    : maxEnd?.IndexFromScale(primaryIndex.Scale, isTimeIndex[0]);

                // Get channel data
                var mnemonics     = contextList.Select(c => c.ChannelMetadata.ChannelName).ToList();
                var dataProvider  = GetDataProvider(parentUri);
                var optimiseStart = channelStreamingType == ChannelStreamingTypes.IndexValue;
                var channelData   = dataProvider.GetChannelData(parentUri, new Range <double?>(minStartIndex, maxEndIndex), mnemonics, requestLatestValues, optimiseStart);

                // Stream the channel data
                await StreamChannelData(contextList, channelData, mnemonics.ToArray(), increasing, isTimeIndex, primaryIndex.Scale, firstStart.Value, token);

                // If we have processed an IndexCount or LatestValue query clear requestLatestValues so we can
                //... keep streaming new data as long as the channel is active.
                if (channelStreamingType == ChannelStreamingTypes.IndexCount ||
                    channelStreamingType == ChannelStreamingTypes.LatestValue)
                {
                    requestLatestValues = null;
                }

                // Check each context to see of all the data has streamed.
                var completedContexts = contextList
                                        .Where(
                    c =>
                    (c.ChannelStreamingType != ChannelStreamingTypes.RangeRequest &&
                     c.ChannelMetadata.Status != (int)ChannelStatuses.Active && c.ChannelMetadata.EndIndex.HasValue &&
                     c.StartIndex >= c.ChannelMetadata.EndIndex.Value) ||

                    (c.ChannelStreamingType == ChannelStreamingTypes.RangeRequest &&
                     c.StartIndex >= c.EndIndex))
                                        .ToArray();

                // Remove any contexts from the list that have completed returning all data
                completedContexts.ForEach(c =>
                {
                    // Notify consumer if the ReceiveChangeNotification field is true
                    if (c.ChannelMetadata.Status != (int)ChannelStatuses.Active && c.ReceiveChangeNotification)
                    {
                        // TODO: Decide which message shoud be sent...
                        // ChannelStatusChange(c.ChannelId, c.ChannelMetadata.Status);
                        // ChannelRemove(c.ChannelId);
                    }

                    contextList.Remove(c);
                });

                // Delay to prevent CPU overhead
                await Task.Delay(WitsmlSettings.StreamChannelDataDelayMilliseconds, token);
            }
        }
        /// <summary>
        /// Among the given filtered (invalid have been removed) candidate grid points find the optimum
        /// </summary>
        /// <param name="routeGridPoints">the current route grid points</param>
        /// <param name="candidateGridPointsFiltered">the filtered candidated grid points</param>
        /// <param name="middleGridPoint">middle grid point</param>
        /// <param name="closest">
        /// true: find the point that is closest to middle and to current grid point
        /// false: find the point that is farthest from middle point and farthest from current grid point</param>
        /// <param name="nextPointFound">out bool: true = a next point was find</param>
        /// <param name="gridPoint">the found next point</param>
        internal static void GetNextGridPoint_CountGreater1_FindOptimum(IList <Point> routeGridPoints, IList <Point> candidateGridPointsFiltered,
                                                                        Point middleGridPoint, bool closest, out bool nextPointFound, out Point gridPoint)
        {
            // find that point which is
            // - closest to last point
            // - closest to the inner curve, i.e. closest to the middle grid point.
            // - does not go in the opposite direction of current quadrant
            nextPointFound = false;
            while (nextPointFound == false)
            {
                // 1. last point distance
                IList <Point> points2CurrentPoint;
                if (closest)
                {
                    points2CurrentPoint = VectorMath.FindPointsInTheListClosest2FixPoint(routeGridPoints.Last(), candidateGridPointsFiltered);
                }
                else
                {
                    points2CurrentPoint = VectorMath.FindPointsInTheListFarthest2FixPoint(routeGridPoints.Last(), candidateGridPointsFiltered);
                }

                if (points2CurrentPoint.Count == 0)
                {
                    return;
                }

                // remove them from the candidateGridPoints list, so that they are not in the list in case we need to have another go in this loop
                candidateGridPointsFiltered = candidateGridPointsFiltered.Except(points2CurrentPoint).ToList();

                bool secondFoundFlag = false;
                while (secondFoundFlag == false)
                {
                    // 2. distance to the inner curve, i.e. distance to the middle grid point.
                    IList <Point> points2MiddleGridPoint;
                    if (closest)
                    {
                        points2MiddleGridPoint = VectorMath.FindPointsInTheListClosest2FixPoint(middleGridPoint, points2CurrentPoint);
                    }
                    else
                    {
                        points2MiddleGridPoint = VectorMath.FindPointsInTheListFarthest2FixPoint(middleGridPoint, points2CurrentPoint);
                    }

                    if ((points2MiddleGridPoint == null) || (points2MiddleGridPoint.Count == 0))
                    {
                        // leave this inner loop to continue searching with the remaining points in candidateGridPoints
                        break;
                    }

                    // remove them from the points2CurrentPoint list,
                    // so that they are not in the list in case we need to have another go in this loop
                    points2CurrentPoint = points2CurrentPoint.Except(points2MiddleGridPoint).ToList();

                    if (routeGridPoints.Count >= 3)
                    {
                        // filter candidates with a unfavorable direction (opposite direction for the current quadrant)
                        IList <Point> filterResult = FilterCandidatePoints_RemoveUnfavorableDir
                                                         (points2MiddleGridPoint, routeGridPoints, middleGridPoint);
                        if (filterResult.Count > 0)
                        {
                            // now take the first that does not go into the quadrant opposite direction
                            secondFoundFlag = true;
                            nextPointFound  = true;
                            gridPoint       = filterResult.First();
                        }
                    }
                    else
                    {
                        // only 2 grid points so far, we do not need to do the pre-pre-vector check because there is no pre-pre-vector
                        // just take the first in closestPoints2MiddleGridPoint
                        secondFoundFlag = true;
                        nextPointFound  = true;
                        gridPoint       = points2MiddleGridPoint[0];
                    }
                }
            }
        }
Esempio n. 47
0
        public async Task <DialogTurnResult> AfterUpdateStartTime(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                var events = new List <EventModel>();

                var calendarService  = ServiceManager.InitCalendarService(state.APIToken, state.EventSource);
                var searchByEntities = state.OriginalStartDate.Any() || state.OriginalStartTime.Any() || state.Title != null;

                if (state.Events.Count < 1)
                {
                    if (state.OriginalStartDate.Any() || state.OriginalStartTime.Any())
                    {
                        events = await GetEventsByTime(state.OriginalStartDate, state.OriginalStartTime, state.OriginalEndDate, state.OriginalEndTime, state.GetUserTimeZone(), calendarService);

                        state.OriginalStartDate = new List <DateTime>();
                        state.OriginalStartTime = new List <DateTime>();
                        state.OriginalEndDate   = new List <DateTime>();
                        state.OriginalStartTime = new List <DateTime>();
                    }
                    else if (state.Title != null)
                    {
                        events = await calendarService.GetEventsByTitle(state.Title);

                        state.Title = null;
                    }
                    else
                    {
                        sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
                        var userInput = content != null?content.ToString() : sc.Context.Activity.Text;

                        try
                        {
                            IList <DateTimeResolution> dateTimeResolutions = sc.Result as List <DateTimeResolution>;
                            if (dateTimeResolutions.Count > 0)
                            {
                                foreach (var resolution in dateTimeResolutions)
                                {
                                    if (resolution.Value == null)
                                    {
                                        continue;
                                    }

                                    var startTimeValue = DateTime.Parse(resolution.Value);
                                    if (startTimeValue == null)
                                    {
                                        continue;
                                    }

                                    var  dateTimeConvertType = resolution.Timex;
                                    bool isRelativeTime      = IsRelativeTime(sc.Context.Activity.Text, dateTimeResolutions.First().Value, dateTimeResolutions.First().Timex);
                                    startTimeValue = isRelativeTime ? TimeZoneInfo.ConvertTime(startTimeValue, TimeZoneInfo.Local, state.GetUserTimeZone()) : startTimeValue;

                                    startTimeValue = TimeConverter.ConvertLuisLocalToUtc(startTimeValue, state.GetUserTimeZone());
                                    events         = await calendarService.GetEventsByStartTime(startTimeValue);

                                    if (events != null && events.Count > 0)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }

                        if (events == null || events.Count <= 0)
                        {
                            state.Title = userInput;
                            events      = await calendarService.GetEventsByTitle(userInput);
                        }
                    }

                    state.Events = events;
                }

                if (state.Events.Count <= 0)
                {
                    if (searchByEntities)
                    {
                        await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(UpdateEventResponses.EventWithStartTimeNotFound));

                        state.Clear();
                        return(await sc.CancelAllDialogsAsync());
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NoEvent)));
                    }
                }
                else if (state.Events.Count > 1)
                {
                    var options = new PromptOptions()
                    {
                        Choices = new List <Choice>(),
                    };

                    for (var i = 0; i < state.Events.Count; i++)
                    {
                        var item   = state.Events[i];
                        var choice = new Choice()
                        {
                            Value    = string.Empty,
                            Synonyms = new List <string> {
                                (i + 1).ToString(), item.Title
                            },
                        };
                        options.Choices.Add(choice);
                    }

                    var replyToConversation = sc.Context.Activity.CreateReply(UpdateEventResponses.MultipleEventsStartAtSameTime);
                    replyToConversation.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    replyToConversation.Attachments      = new List <Microsoft.Bot.Schema.Attachment>();

                    var cardsData = new List <CalendarCardData>();
                    foreach (var item in state.Events)
                    {
                        var meetingCard = item.ToAdaptiveCardData(state.GetUserTimeZone());
                        var replyTemp   = sc.Context.Activity.CreateAdaptiveCardReply(CalendarMainResponses.GreetingMessage, item.OnlineMeetingUrl == null ? "Dialogs/Shared/Resources/Cards/CalendarCardNoJoinButton.json" : "Dialogs/Shared/Resources/Cards/CalendarCard.json", meetingCard);
                        replyToConversation.Attachments.Add(replyTemp.Attachments[0]);
                    }

                    options.Prompt = replyToConversation;

                    return(await sc.PromptAsync(Actions.EventChoice, options));
                }
                else
                {
                    return(await sc.EndDialogAsync(true));
                }
            }
            catch (SkillException ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Esempio n. 48
0
 public HttpResponseMessage submitDetail(IList <QM_DISCIPLINE_DETAILS> list)
 {
     try
     {
         //using (TransactionScope ts = new TransactionScope()) {
         Boolean flag = true;
         foreach (QM_DISCIPLINE_DETAILS q in list)
         {
             if (q.ItemResult == "NG")
             {
                 flag = false;
             }
             if (q.ItemResult != "")
             {
                 q.InspectTime = SSGlobalConfig.Now;
             }
             if (q.Improvement == "已改善")
             {
                 q.ImproveTime = SSGlobalConfig.Now;
             }
             _QM_DISCIPLINE_DETAILSBO.UpdateSome(q);
         }
         QM_DISCIPLINE_TOP qM_DISCIPLINE_TOP = _IQM_DISCIPLINE_TOPBO.GetEntity((int)(list.First().KID));
         if (qM_DISCIPLINE_TOP.SequenceStatus == "检测中")
         {
             qM_DISCIPLINE_TOP.SequenceStatus = "已检";
         }
         if (qM_DISCIPLINE_TOP.SequenceStatus == "待改善")
         {
             Boolean flagStatus = true;
             foreach (QM_DISCIPLINE_DETAILS detail in list)
             {
                 if ((detail.ItemResult == "NG" && detail.Improvement == "未改善") || (detail.ItemResult == "NG" && detail.Improvement == ""))
                 {
                     flagStatus = false;
                 }
             }
             if (flagStatus)
             {
                 qM_DISCIPLINE_TOP.SequenceStatus = "已改善";
             }
         }
         qM_DISCIPLINE_TOP.Inspector      = list[0].Attribute10;
         qM_DISCIPLINE_TOP.EndTime        = SSGlobalConfig.Now;
         qM_DISCIPLINE_TOP.SequenceResult = flag ? "OK" : "NG";
         _IQM_DISCIPLINE_TOPBO.UpdateSome(qM_DISCIPLINE_TOP);
         //ts.Complete();
         return(Request.CreateResponse(HttpStatusCode.OK, "提交成功"));
         //}
     }
     catch {
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, "提交失败"));
     }
 }
Esempio n. 49
0
        private void UpdateJournalsInChunk(IList <Journal> existingJournalsChunk, IList <Country> countries, IList <Publisher> publishers, IList <Language> languages, IList <Subject> subjects, IList <Journal> allJournals, ISet <JournalUpdateProperty> journalUpdateProperties)
        {
            foreach (var journal in existingJournalsChunk)
            {
                var currentJournal = allJournals.First(j => string.Equals(j.ISSN, journal.ISSN, StringComparison.InvariantCultureIgnoreCase));

                if (journalUpdateProperties.Contains(JournalUpdateProperty.DoajSeal))
                {
                    currentJournal.DoajSeal = journal.DoajSeal;
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.Title))
                {
                    currentJournal.Title = journal.Title;
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.Link))
                {
                    currentJournal.Link = journal.Link;
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.OpenAccess))
                {
                    currentJournal.OpenAccess = journal.OpenAccess;
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.DataSource))
                {
                    currentJournal.DataSource = journal.DataSource;
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.Country))
                {
                    currentJournal.Country = countries.First(p => string.Equals(p.Name, journal.Country.Name.Trim().ToLowerInvariant(), StringComparison.InvariantCultureIgnoreCase));
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.Publisher))
                {
                    currentJournal.Publisher = publishers.First(p => string.Equals(p.Name, journal.Publisher.Name.Trim().ToLowerInvariant(), StringComparison.InvariantCultureIgnoreCase));
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.Languages))
                {
                    currentJournal.Languages.Clear();

                    foreach (var language in journal.Languages.Select(l => languages.First(a => string.Equals(a.Name, l.Name.Trim().ToLowerInvariant(), StringComparison.InvariantCultureIgnoreCase))))
                    {
                        currentJournal.Languages.Add(language);
                    }
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.Subjects))
                {
                    currentJournal.Subjects.Clear();

                    foreach (var subject in journal.Subjects.Select(s => subjects.First(u => string.Equals(u.Name, s.Name.Trim().ToLowerInvariant(), StringComparison.InvariantCultureIgnoreCase))))
                    {
                        currentJournal.Subjects.Add(subject);
                    }
                }

                if (journalUpdateProperties.Contains(JournalUpdateProperty.PISSN))
                {
                    currentJournal.PISSN = journal.PISSN;
                }

                currentJournal.LastUpdatedOn = DateTime.Now;
                this.journalRepository.InsertOrUpdate(currentJournal);
            }

            this.journalRepository.Save();
        }
Esempio n. 50
0
 public NumberInfo GetNumberInfo(int key)
 {
     return(NumberInfos.First(p => p.KeyNumber == key));
 }
Esempio n. 51
0
 public override IFlowDefinition GetApplicableFlowDefinitionOverride(IList <IFlowDefinition> overrides, IFlowStepRequest request)
 {
     return(overrides?.First());
 }
Esempio n. 52
0
        public IShape Build(string[] args)
        {
            IShape result = factories?.First().MakeShape(args);

            return(result);
        }
Esempio n. 53
0
 public IActionResult WhoIsTheBestCat()
 {
     return(Ok(cats.First().Name));
 }
 public async Task <Transaction> FindById(int id)
 {
     return(await Task.Run(() => _transactions.First(t => t.Id == id)));
 }
Esempio n. 55
0
 public IActionResult WhoIsTheBestDog()
 {
     return(Ok(dogs.First().Name));
 }
 public ListMailPage SendMail()
 {
     sendButtons.First().Click();
     Browser.Driver.WaitForAjax();
     return(new ListMailPage());
 }
Esempio n. 57
0
        public static void Run()
        {
            var config = Application.ReadConfig("config.json");
            var client = Application.CreateClient(config);

            if (!(client is ProxyCertClient))
            {
                throw new ApplicationException("This test supports only proxy cert client");
            }

            var randomNum      = Application.GetRandomNumber(1000);
            var simulationName = "TestGetSimError_" + randomNum;
            var experimentName = "TestGetSimError_exp_" + randomNum;

            var simDir       = "test_scenario_error_executor";
            var executorPath = string.Format("{0}{1}{2}", simDir, Path.DirectorySeparatorChar, "executor.sh");
            var binPath      = string.Format("{0}{1}{2}", simDir, Path.DirectorySeparatorChar, "hello.zip");

            var simulationParameters = new List <Scalarm.ExperimentInput.Parameter>()
            {
                new Scalarm.ExperimentInput.Parameter("a", "A")
                {
                    ParametrizationType = Scalarm.ExperimentInput.ParametrizationType.RANGE,
                    Type = Scalarm.ExperimentInput.Type.FLOAT,
                    Min  = 0.1f, Max = 10
                },
            };

            SimulationScenario simScenario = client.RegisterSimulationScenario(
                simulationName, binPath, simulationParameters, executorPath);

            List <Scalarm.ValuesMap> points = new List <ValuesMap>();

            Random rnd = new Random();

            for (int i = 0; i < 1000; ++i)
            {
                points.Add(new ValuesMap {
                    { "a", rnd.NextDouble() }
                });
            }

            Dictionary <string, object> experimentParams = new Dictionary <string, object>()
            {
                { "experiment_name", experimentName },
                { "execution_time_constraint", 5 }
            };

            var experiment = simScenario.CreateExperimentWithPoints(points, experimentParams);

            experiment.ScheduleZeusJobs(1);

            try {
                experiment.WaitForDone(5 * 60 * 1000, 10);
            } catch (NoActiveSimulationManagersException) {
                IList <SimulationManager> workers = experiment.GetSimulationManagers();
                if (workers.Count != 1)
                {
                    throw new ApplicationException("Invalid workers count: " + workers.Count);
                }
                var sim = workers.First();
                Console.WriteLine("Simulation Manager failed with error/log:");
                Console.WriteLine(sim.Error);
                Console.WriteLine(sim.ErrorDetails);
            }
        }
Esempio n. 58
0
        public virtual IList <StockBalanceDTO> StockBalances(
            IUnitOfWork uow,
            Warehouse warehouse,
            IList <Nomenclature> nomenclatures,
            DateTime onTime,
            IEnumerable <WarehouseOperation> excludeOperations = null)
        {
            StockBalanceDTO    resultAlias = null;
            WarehouseOperation warehouseExpenseOperationAlias = null;
            WarehouseOperation warehouseIncomeOperationAlias  = null;
            WarehouseOperation warehouseOperationAlias        = null;
            Nomenclature       nomenclatureAlias = null;
            Size sizeAlias   = null;
            Size heightAlias = null;

            var excludeIds = excludeOperations?.Select(x => x.Id).ToList();

            // null == null => null              null <=> null => true
            var expenseQuery = QueryOver.Of(() => warehouseExpenseOperationAlias)
                               .Where(() => warehouseExpenseOperationAlias.Nomenclature.Id == nomenclatureAlias.Id &&
                                      (warehouseExpenseOperationAlias.WearSize.Id == sizeAlias.Id ||
                                       warehouseOperationAlias.WearSize == null && sizeAlias == null) &&
                                      (warehouseExpenseOperationAlias.Height.Id == heightAlias.Id ||
                                       warehouseOperationAlias.Height == null && heightAlias == null) &&
                                      warehouseExpenseOperationAlias.WearPercent == warehouseOperationAlias.WearPercent)
                               .Where(e => e.OperationTime <= onTime);

            if (warehouse == null)
            {
                expenseQuery.Where(x => x.ExpenseWarehouse != null);
            }
            else
            {
                expenseQuery.Where(x => x.ExpenseWarehouse == warehouse);
            }

            if (excludeIds != null && excludeIds.Count > 0)
            {
                expenseQuery.WhereNot(x => x.Id.IsIn(excludeIds));
            }

            expenseQuery.Select(Projections
                                .Sum(Projections
                                     .Property(() => warehouseExpenseOperationAlias.Amount)));

            var incomeSubQuery = QueryOver.Of(() => warehouseIncomeOperationAlias)
                                 .Where(() => warehouseIncomeOperationAlias.Nomenclature.Id == nomenclatureAlias.Id &&
                                        (warehouseIncomeOperationAlias.WearSize.Id == sizeAlias.Id ||
                                         warehouseOperationAlias.WearSize == null && sizeAlias == null) &&
                                        (warehouseIncomeOperationAlias.Height.Id == heightAlias.Id ||
                                         warehouseOperationAlias.Height == null && heightAlias == null) &&
                                        warehouseIncomeOperationAlias.WearPercent == warehouseOperationAlias.WearPercent)
                                 .Where(e => e.OperationTime < onTime);

            if (warehouse == null)
            {
                incomeSubQuery.Where(x => x.ReceiptWarehouse != null);
            }
            else
            {
                incomeSubQuery.Where(x => x.ReceiptWarehouse == warehouse);
            }

            if (excludeIds != null && excludeIds.Count > 0)
            {
                incomeSubQuery.WhereNot(x => x.Id.IsIn(excludeIds));
            }

            incomeSubQuery.Select(Projections
                                  .Sum(Projections
                                       .Property(() => warehouseIncomeOperationAlias.Amount)));

            var projection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.Int32, "( IFNULL(?1, 0) - IFNULL(?2, 0) )"),
                NHibernateUtil.Int32,
                Projections.SubQuery(incomeSubQuery),
                Projections.SubQuery(expenseQuery)
                );

            var queryStock = uow.Session.QueryOver(() => warehouseOperationAlias);

            queryStock.Where(Restrictions.Not(Restrictions.Eq(projection, 0)));
            queryStock.Where(() => warehouseOperationAlias.Nomenclature.IsIn(nomenclatures.ToArray()));

            var result = queryStock
                         .JoinAlias(() => warehouseOperationAlias.Nomenclature, () => nomenclatureAlias)
                         .JoinAlias(() => warehouseOperationAlias.WearSize, () => sizeAlias, JoinType.LeftOuterJoin)
                         .JoinAlias(() => warehouseOperationAlias.Height, () => heightAlias, JoinType.LeftOuterJoin)
                         .SelectList(list => list
                                     .SelectGroup(() => nomenclatureAlias.Id).WithAlias(() => resultAlias.NomenclatureId)
                                     .SelectGroup(() => warehouseOperationAlias.WearSize).WithAlias(() => resultAlias.WearSize)
                                     .SelectGroup(() => warehouseOperationAlias.Height).WithAlias(() => resultAlias.Height)
                                     .SelectGroup(() => warehouseOperationAlias.WearPercent).WithAlias(() => resultAlias.WearPercent)
                                     .Select(projection).WithAlias(() => resultAlias.Amount)
                                     )
                         .TransformUsing(Transformers.AliasToBean <StockBalanceDTO>())
                         .List <StockBalanceDTO>();

            //Проставляем номенклатуру.
            result.ToList().ForEach(item =>
                                    item.Nomenclature = nomenclatures.First(n => n.Id == item.NomenclatureId));
            return(result);
        }
Esempio n. 59
0
            // Occurs whenever database has been successfully connected - become operational.
            private void OnOperational(object sender, TaskEventArgs e)
            {
                // Enable control appropriate when application is connected with database, and user is logged out.
                this._controlsEnabler.OnConnect_Operational(sender, e);

                // Set all the consoles according database becoming operational.
                this._consolesServices.OnConnect_Operational(sender, e);

                // Continue on any connection fault.
                e.Task.ContinueWith((t) =>
                {
                    // Get flatten collection of exceptions which caused task to fail.
                    IList <Exception> connectTaskExceptions = t.Exception.Flatten().InnerExceptions;


                    // If established connection failed..
                    if (connectTaskExceptions.Any((ex) => { return(ex.GetType() == typeof(DBConnectionFailureException)); }))
                    {
                        DBConnectionFailureException connectionFailureEx = connectTaskExceptions.First((ex) => { return(ex.GetType() == typeof(DBConnectionFailureException)); }) as DBConnectionFailureException;
                        this.OnConnectionFailed(sender, new ExceptionEventArgs <DBConnectionFailureException>(connectionFailureEx));
                    }

                    // If forced to  disconnect..
                    else if (connectTaskExceptions.Any((ex) => { return(ex.GetType() == typeof(DBForcedToBeTakenOverException)); }))
                    {
                        this.OnForcedToDisconnect(sender, e);
                    }

                    // If disconnected willingly..
                    else if (connectTaskExceptions.Any((ex) => { return(ex.GetType() == typeof(DBDisconnectedException)); }))
                    {
                        ; // Do Nothing - should not occur anyway // this.OnConnectionFailed(sender, e);
                    }
                    // Any other exception...
                    else
                    {
                        this.OnConnectionFailed(sender, new ExceptionsEventArgs(connectTaskExceptions));
                    }
                }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

                // Attempt to fetch all data from database...
                Task fetchDataTask = this._app.FetchDataAsync(new CancellationTokenSource());

                fetchDataTask.ContinueWith((t) =>
                {
                    switch (t.Status)
                    {
                    case TaskStatus.RanToCompletion:
                        // If successfully fetch data from database.
                        this.OnDataFetchCompleted(sender, e);
                        break;

                    case TaskStatus.Faulted:
                        // If failed to fetch data from database.
                        this.OnDataFetchFailed(sender, e);
                        break;

                    case TaskStatus.Canceled:
                        // If canceled to fetch data from database.
                        this.OnDataFetchCanceled(sender, e);
                        break;
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
        public ActionResult Index(MailChimpListViewModel model)
        {
            int countryId = 0;
            int cultureId = 0;
            IList <CountryRecord> countries;
            IList <CultureRecord> cultures = null;
            string culture = "en-MY";

            countries = _countryService.GetAllCountry().ToList();
            if (model.CountryId > 0)
            {
                cultures  = _countryService.GetCultureByCountry(model.CountryId).ToList();
                countryId = model.CountryId;
                cultureId = model.CultureId;
            }
            else
            {
                if (countries.Count > 0)
                {
                    cultures  = _countryService.GetCultureByCountry(countries.First().Id).ToList();
                    countryId = countries.First().Id;
                    if (cultures.Count > 0)
                    {
                        cultureId = cultures.First().Id;
                    }
                }
            }
            var cultureRecord = _cultureRepository.Get(model.CultureId == 0 ? cultureId : model.CultureId);

            if (cultureRecord != null)
            {
                culture = cultureRecord.Culture;
            }


            MailChimpListViewModel setting;
            var pathToTemplates = Server.MapPath("/Modules/Teeyoot.Module/Content/message-templates/" + culture + "/");
            var settings        = _settingsService.GetSettingByCulture(culture).List().Select(s => new MailChimpListViewModel
            {
                Id              = s.Id,
                ApiKey          = s.ApiKey,
                SellerTemplate  = System.IO.File.Exists(pathToTemplates + "seller-template.html") ? "seller-template.html" : "No file!",
                WelcomeTemplate = System.IO.File.Exists(pathToTemplates + "welcome-template.html") ? "welcome-template.html" : "No file!",
                RelaunchApprovedSellerTemplate = System.IO.File.Exists(pathToTemplates + "relaunch.html") ? "relaunch.html" : "No file!",
                RelaunchApprovedBuyerTemplate  = System.IO.File.Exists(pathToTemplates + "relaunch-buyer.html") ? "relaunch-buyer.html" : "No file!",
                RelaunchAdminSellerTemplate    = System.IO.File.Exists(pathToTemplates + "relaunch-to-admin-seller.html") ? "relaunch-to-admin-seller.html" : "No file!",
                LaunchTemplate                     = System.IO.File.Exists(pathToTemplates + "launch-template.html") ? "launch-template.html" : "No file!",
                WithdrawTemplate                   = System.IO.File.Exists(pathToTemplates + "withdraw-template.html") ? "withdraw-template.html" : "No file!",
                PlaceOrderTemplate                 = System.IO.File.Exists(pathToTemplates + "place-order-template.html") ? "place-order-template.html" : "No file!",
                NewOrderTemplate                   = System.IO.File.Exists(pathToTemplates + "new-order-template.html") ? "new-order-template.html" : "No file!",
                ShippedOrderTemplate               = System.IO.File.Exists(pathToTemplates + "shipped-order-template.html") ? "shipped-order-template.html" : "No file!",
                DeliveredOrderTemplate             = System.IO.File.Exists(pathToTemplates + "delivered-order-template.html") ? "delivered-order-template.html" : "No file!",
                CancelledOrderTemplate             = System.IO.File.Exists(pathToTemplates + "cancelled-order-template.html") ? "cancelled-order-template.html" : "No file!",
                OrderIsPrintingBuyerTemplate       = System.IO.File.Exists(pathToTemplates + "order-is-printing-buyer-template.html") ? "order-is-printing-buyer-template" + culture + ".html" : "No file!",
                CampaignIsPrintingSellerTemplate   = System.IO.File.Exists(pathToTemplates + "campaign-is-printing-seller-template.html") ? "campaign-is-printing-seller-template.html" : "No file!",
                PaidCampaignTemplate               = System.IO.File.Exists(pathToTemplates + "paid-campaign-template.html") ? "paid-campaign-template.html" : "No file!",
                UnpaidCampaignTemplate             = System.IO.File.Exists(pathToTemplates + "unpaid-campaign-template.html") ? "unpaid-campaign-template.html" : "No file!",
                CampaignNotReachGoalBuyerTemplate  = System.IO.File.Exists(pathToTemplates + "not-reach-goal-buyer-template.html") ? "not-reach-goal-seller-template.html" : "No file!",
                CampaignNotReachGoalSellerTemplate = System.IO.File.Exists(pathToTemplates + "not-reach-goal-seller-template.html") ? "not-reach-goal-buyer-template.html" : "No file!",
                //PartiallyPaidCampaignTemplate = System.IO.File.Exists(pathToTemplates + "partially-paid-campaign-template.html") ? "partially-paid-campaign-template.html" : "No file!",
                CampaignPromoTemplate     = System.IO.File.Exists(pathToTemplates + "campaign-promo-template.html") ? "campaign-promo-template.html" : "No file!",
                AllOrderDeliveredTemplate = System.IO.File.Exists(pathToTemplates + "all-orders-delivered-seller-template.html") ? "all-orders-delivered-seller-template.html" : "No file!",
                //CampaignIsFinishedTemplate = System.IO.File.Exists(pathToTemplates + "campaign-is-finished-template.html") ? "campaign-is-finished-template.html" : "No file!",
                DefinitelyGoSellerTemplate    = System.IO.File.Exists(pathToTemplates + "definitely-go-to-print-seller-template.html") ? "definitely-go-to-print-seller-template.html" : "No file!",
                DefinitelyGoBuyerTemplate     = System.IO.File.Exists(pathToTemplates + "definitely-go-to-print-buyer-template.html") ? "definitely-go-to-print-buyer-template.html" : "No file!",
                EditedCampaignTemplate        = System.IO.File.Exists(pathToTemplates + "edited-campaign-template.html") ? "edited-campaign-template.html" : "No file!",
                ExpiredMetMinimumTemplate     = System.IO.File.Exists(pathToTemplates + "expired-campaign-met-minimum-admin-template.html") ? "expired-campaign-met-minimum-admin-template.html" : "No file!",
                ExpiredNotSuccessfullTemplate = System.IO.File.Exists(pathToTemplates + "expired-campaign-notSuccessfull-admin-template.html") ? "expired-campaign-notSuccessfull-admin-template.html" : "No file!",
                ExpiredSuccessfullTemplate    = System.IO.File.Exists(pathToTemplates + "expired-campaign-successfull-admin-template.html") ? "expired-campaign-successfull-admin-template.html" : "No file!",
                MakeTheCampaignTemplate       = System.IO.File.Exists(pathToTemplates + "make_the_campaign_seller.html") ? "make_the_campaign_seller.html" : "No file!",
                NewCampaignAdminTemplate      = System.IO.File.Exists(pathToTemplates + "new-campaign-admin-template.html") ? "new-campaign-admin-template.html" : "No file!",
                //NewOrderBuyerTemplate = System.IO.File.Exists(pathToTemplates + "new-order-buyer-template.html") ? "new-order-buyer-template.html" : "No file!",
                NotReachGoalMetMinimumTemplate = System.IO.File.Exists(pathToTemplates + "not-reach-goal-met-minimum-seller-template.html") ? "not-reach-goal-met-minimum-seller-template.html" : "No file!",
                RecoverOrdersTemplate          = System.IO.File.Exists(pathToTemplates + "recover_orders_for_buyer.html") ? "recover_orders_for_buyer.html" : "No file!",
                RejectTemplate            = System.IO.File.Exists(pathToTemplates + "reject-template.html") ? "reject-template.html" : "No file!",
                Shipped3DayAfterTemplate  = System.IO.File.Exists(pathToTemplates + "shipped-order-3day-after-template.html") ? "shipped-order-3day-after-template.html" : "No file!",
                TermsConditionsTemplate   = System.IO.File.Exists(pathToTemplates + "terms-conditions-template.html") ? "terms-conditions-template.html" : "No file!",
                WithdrawCompletedTemplate = System.IO.File.Exists(pathToTemplates + "withdraw-completed-template.html") ? "withdraw-completed-template.html" : "No file!",
                WithdrawSellerTemplate    = System.IO.File.Exists(pathToTemplates + "withdraw-seller-template.html") ? "withdraw-seller-template.html" : "No file!"
            });

            if (settings.FirstOrDefault() == null)
            {
                setting = new MailChimpListViewModel();
            }
            else
            {
                setting = settings.FirstOrDefault();
            }

            setting.Countries = countries;
            setting.Cultures  = cultures;
            setting.CountryId = countryId;
            setting.CultureId = cultureId;
            setting.Culture   = culture;

            return(View(setting));
        }