Example #1
1
        static bool Files(IList<string> unparsed)
        {
            if (unparsed.Count > 2)
            {
                Console.Error.WriteLine("Too many arguments for [files]: {0}", String.Join(", ", unparsed.Select(s => String.Format("'{0}'", s))));
                Console.Error.WriteLine("Usage: vmc files <appname> <path>");
                return false;
            }
            if (unparsed.Count < 1)
            {
                Console.Error.WriteLine("Not enough arguments for [files]: {0}", String.Join(", ", unparsed.Select(s => String.Format("'{0}'", s))));
                Console.Error.WriteLine("Usage: vmc files <appname> <path (optional)>");
                return false;
            }

            string appname = unparsed[0];
            string path = string.Empty;
            if (unparsed.Count == 2)
                path = unparsed[1];

            IVcapClient vc = new VcapClient();
            byte[] output = vc.FilesSimple(appname, path, 0);
            if (false == output.IsNullOrEmpty())
            {
                Stream stdout = Console.OpenStandardOutput();
                stdout.Write(output, 0, output.Length);
                stdout.Flush();
            }
            return true;
        }
        public OperationResult CopyOrMoveContentFromSelf(IList<FarFile> files, string destination, bool isMove)
        {
            OnDeviceOperation doc = null;

            if (_fs.CurrentLevel == EFileSystemLevel.OnDevice)
            {
                var playLists = files.Select(p => (Playlist)p.Data);

                if (IsSilentOperation() ||
                    CommonDialog.ForCopyPlayListsToPath(playLists, ref destination, isMove) == 0)
                {
                    doc = new CopyContentFromSelfOperation(
                        _fs.CurrentDevice, playLists, destination, isMove);

                }
            }
            else if (_fs.CurrentLevel == EFileSystemLevel.OnPlayList)
            {
                var tracks = files.Select(p => (Track)p.Data);

                if (IsSilentOperation() ||
                    CommonDialog.ForCopyTracksToPath(tracks, ref destination, isMove) == 0)
                {
                    doc = new CopyContentFromSelfOperation(
                         _fs.CurrentDevice, tracks, destination, isMove, IsInternalOperation() || IsSilentOperation());
                }
            }

            return execOperation(doc, files);
        }
Example #3
1
        /// <summary>
        /// Converts a timestamp  specified in seconds/nanoseconds to a string.
        /// </summary>
        /// <remarks>
        /// If the value is a normalized duration in the range described in <c>field_mask.proto</c>,
        /// <paramref name="diagnosticOnly"/> is ignored. Otherwise, if the parameter is <c>true</c>,
        /// a JSON object with a warning is returned; if it is <c>false</c>, an <see cref="InvalidOperationException"/> is thrown.
        /// </remarks>
        /// <param name="paths">Paths in the field mask</param>
        /// <param name="diagnosticOnly">Determines the handling of non-normalized values</param>
        /// <exception cref="InvalidOperationException">The represented field mask is invalid, and <paramref name="diagnosticOnly"/> is <c>false</c>.</exception>
        internal static string ToJson(IList<string> paths, bool diagnosticOnly)
        {
            var firstInvalid = paths.FirstOrDefault(p => !ValidatePath(p));
            if (firstInvalid == null)
            {
                var writer = new StringWriter();
#if DOTNET35
                var query = paths.Select(JsonFormatter.ToJsonName);
                JsonFormatter.WriteString(writer, string.Join(",", query.ToArray()));
#else
                JsonFormatter.WriteString(writer, string.Join(",", paths.Select(JsonFormatter.ToJsonName)));
#endif
                return writer.ToString();
            }
            else
            {
                if (diagnosticOnly)
                {
                    var writer = new StringWriter();
                    writer.Write("{ \"@warning\": \"Invalid FieldMask\", \"paths\": ");
                    JsonFormatter.Default.WriteList(writer, (IList)paths);
                    writer.Write(" }");
                    return writer.ToString();
                }
                else
                {
                    throw new InvalidOperationException($"Invalid field mask to be converted to JSON: {firstInvalid}");
                }
            }
        }
Example #4
1
        /// <summary>
        /// Create a styles.xml file
        /// </summary>
        /// <param name="styles"></param>
        /// <returns></returns>
        internal static XmlFile CreateStyleXml(IList<XlsxCellStyle> styles)
        {
            var uniqueBorders = styles.Select(s => s.Border).Where(s => s != CellBorder.None).Distinct().ToList();
            uniqueBorders.Insert(0, CellBorder.None);

            var numberFormats = styles.Select(s => s.Format).Distinct().ToList();
            var uniqueFonts = styles.Select(s => s.Font).Distinct().ToList();
            uniqueFonts.Insert(0, new XlsxFont());

            var file = new XmlFile
            {
                ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
                Path = "xl/styles.xml"
            };

            var doc = new XDocument(new XElement(Namespaces.workbook + "styleSheet", new XAttribute("xmlns", Namespaces.workbook)));

            StyleAddNumFmtsElement(doc, numberFormats);
            StyleAddFontsElement(doc, uniqueFonts);
            StyleAddFillsElement(doc);
            StyleAddBordersElement(doc, uniqueBorders);
            StyleAddCellStyleXfsElement(doc);
            StyleAddCellXfsElement(doc, styles, uniqueBorders, numberFormats, uniqueFonts);

            file.Content = doc;

            return file;
        }
      public async Task<IssuesCollectionStatistics> Calculate(IList<JiraIssue> issues)
      {
         if(issues == null || issues.Any() == false)
            return null;

         return await Task.Factory.StartNew(() =>
         {
            return new IssuesCollectionStatistics
            {
               IssuesCount = issues.Count(),
               ResolvedIssuesCount = issues.Where(i => i.Resolved.HasValue).Count(),
               UnresolvedIssuesCount = issues.Where(i => i.Resolved.HasValue == false).Count(),

               AverageResolutionTimeHours = issues
                                               .Where(i => i.Resolved.HasValue)
                                               .Select(i => (i.Resolved.Value - i.Created).TotalHours).Average(),
               MaxResolutionTimeHours = issues
                                               .Where(i => i.Resolved.HasValue)
                                               .Select(i => (i.Resolved.Value - i.Created).TotalHours).Max(),

               TotalStorypoints = issues.Sum(i => i.StoryPoints),
               AverageStorypointsPerTask = issues.Average(i => i.StoryPoints),

               AverageSubtasksCount = issues.Average(i => i.Subtasks),

               EpicsInvolved = issues.Select(i => i.EpicLink).Distinct().Count(),

               DistinctReporters = issues.Select(i => i.Reporter).Distinct().Count()
            };
         });
      }
Example #6
1
        /// <summary>
        ///     获取百度地图静态图片
        /// </summary>
        /// <param name="lng">中心点经度</param>
        /// <param name="lat">中心点维度</param>
        /// <param name="scale">
        ///     返回图片大小会根据此标志调整。取值范围为1或2:
        ///     1表示返回的图片大小为size= width * height;
        ///     2表示返回图片为(width*2)*(height *2),且zoom加1
        ///     注:如果zoom为最大级别,则返回图片为(width*2)*(height*2),zoom不变。
        /// </param>
        /// <param name="zoom">地图级别。高清图范围[3, 18];低清图范围[3,19]</param>
        /// <param name="markersList">标记列表,如果为null则不输出标记</param>
        /// <param name="width">图片宽度。取值范围:(0, 1024]。</param>
        /// <param name="height">图片高度。取值范围:(0, 1024]。</param>
        /// <returns></returns>
        public static string GetBaiduStaticMap(double lng, double lat, int scale, int zoom,
            IList<BaiduMarkers> markersList, int width = 400, int height = 300)
        {
            var url = new StringBuilder();
            url.Append("http://api.map.baidu.com/staticimage?");

            url.AppendFormat("center={0},{1}", lng, lat);
            url.AppendFormat("&width={0}", width);
            url.AppendFormat("&height={0}", height);
            url.AppendFormat("&scale={0}", scale);
            url.AppendFormat("&zoom={0}", zoom);

            if (markersList != null && markersList.Count > 0)
            {
                url.AppendFormat("&markers={0}",
                    string.Join("|",
                        markersList.Select(z => string.Format("{0},{1}", z.Longitude, z.Latitude)).ToArray()));
                url.AppendFormat("&markerStyles={0}",
                    string.Join("|",
                        markersList.Select(z => string.Format("{0},{1},{2}", z.Size.ToString(), z.Label, z.Color))
                            .ToArray()));
            }

            return url.ToString();
        }
        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));
        }
 public DesignTimeCompilationException(IList<DiagnosticMessage> compileResponseErrors)
     : base(string.Join(Environment.NewLine, compileResponseErrors.Select(e => e.FormattedMessage)))
 {
     CompilationFailures = compileResponseErrors.GroupBy(g => g.SourceFilePath, StringComparer.OrdinalIgnoreCase)
                                                .Select(g => new CompilationFailure(g.Key, g))
                                                .ToArray();
 }
Example #9
1
 public static void GetLocationSelectedListItem(IList<Location> locations, out MultiSelectList allLocation, out List<SelectListItem> selectListItems)
 {
     var multiSelectList = new MultiSelectList(locations, "LocationId", "Province", locations);
     allLocation = multiSelectList;
     selectListItems =
         locations.Select(o => new SelectListItem { Text = o.Province, Value = o.Province }).ToList();
 }
Example #10
0
        public static void TestConstructorArgumentsNullCombinations(Type testedType, Type[] typeArguments, IList<Func<object>> arguments)
        {
            if (testedType.IsGenericType)
            {
                testedType = testedType.MakeGenericType(typeArguments);
            }

            var argumentTypes = arguments.Select(argument => argument.Method.ReturnType).ToArray();
            var constructor = testedType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, argumentTypes, null);

            if (constructor == null)
            {
                throw new ArgumentException("Constructor could not be found");
            }

            for (int i = 0; i < arguments.Count; i++)
            {
                object[] args = arguments.Select(a => a()).ToArray();
                args[i] = null;

                Assert.That(() =>
                {
                    try
                    {
                        constructor.Invoke(args);
                    }
                    catch (TargetInvocationException exception)
                    {
                        throw exception.InnerException;
                    }
                }, Throws.TypeOf<ArgumentNullException>());
            }
        }
        /// <summary>
        ///     Extracts the specified number of evaluation unit samples from each navigator/maze species for subsuquent clustering
        ///     analysis.
        /// </summary>
        /// <param name="experimentId">The experiment that was executed.</param>
        /// <param name="run">The run number of the given experiment.</param>
        /// <param name="batch">The batch number of the given run.</param>
        /// <param name="allEvaluationUnits">All evaluation during the given experiment/run/batch.</param>
        /// <param name="sampleSize">The sample size to extract from each navigator/maze species.</param>
        /// <returns>The specified number of evaluation unit samples from each navigator/maze species.</returns>
        public static IList<MazeNavigatorEvaluationUnit> ExtractEvaluationUnitSamplesFromSpecies(int experimentId,
            int run,
            int batch, IList<MazeNavigatorEvaluationUnit> allEvaluationUnits, int sampleSize)
        {
            List<MazeNavigatorEvaluationUnit> evalUnitSamples = new List<MazeNavigatorEvaluationUnit>();

            // Extract all maze and navigator genome IDs
            var allMazeGenomeIds = allEvaluationUnits.Select(eu => eu.MazeId).Distinct().ToList();
            var allNavigatorGenomeIds = allEvaluationUnits.Select(eu => eu.AgentId).Distinct().ToList();

            // Get the species to which the mazes and navigators are assigned
            var mazeSpecieGenomesGroups = ExperimentDataHandler.GetSpecieAssignmentsForMazeGenomeIds(experimentId, run,
                batch, allMazeGenomeIds);
            var navigatorSpecieGenomesGroups =
                ExperimentDataHandler.GetSpecieAssignmentsForNavigatorGenomeIds(experimentId, run, batch,
                    RunPhase.Primary, allNavigatorGenomeIds);

            // Extract a sample of mazes and navigators for each of their respective species
            var sampleMazeIds = ExtractGenomeIdSample(mazeSpecieGenomesGroups, sampleSize);
            var sampleNavigatorIds = ExtractGenomeIdSample(navigatorSpecieGenomesGroups, sampleSize);

            // Collect maze and navigator samples
            CollectEvaluationSamples(sampleMazeIds, allEvaluationUnits, evalUnitSamples, true);
            CollectEvaluationSamples(sampleNavigatorIds, allEvaluationUnits, evalUnitSamples, true);

            return evalUnitSamples;
        }
 public TaskMessages(RemoteTask task, string taskMatchStyle, IList<TaskMessage> taskMessages)
 {
     this.task = task;
     this.taskMatchStyle = taskMatchStyle;
     messages = taskMessages.Select(tm => tm.Message).ToList();
     serverActions = taskMessages.Select(tm => tm.ServerAction).ToList();
 }
        public IList<string> GetDayActivity(IList<string> zoo, string killer)
        {
            if (!zoo.Contains(killer))
            {
                return new List<string>();
            }

            var herring = new List<string>(GameResources.Herrings);
            var goodTraits = new List<string>(GameResources.GoodTraits);
            var badTraits = new List<string>(GameResources.BadTraits);
            herring.Shuffle();
            goodTraits.Shuffle();
            badTraits.Shuffle();

            // good and bad traits
            int badIndex = 0;
            int goodIndex = 0;
            var clues = zoo.Select(x =>
                                {
                                    double chance = x == killer ? ChanceBadKillerTrait : ChanceBadFodderTrait;
                                    string trait = Extensions.RandomGenerator.Next(0, 999)/1000.0 < chance
                                        ? badTraits[badIndex++]
                                        : goodTraits[goodIndex++];
                                    return String.Format(trait, x);
                                }).ToList();

            // herrings
            int herringIndex = 0;
            clues.AddRange(zoo.Select(x => String.Format(herring[herringIndex++], x)));

            clues.Shuffle();

            return clues;
        }
Example #14
0
        public Volume(IList<Point> points)
        {
            var rangeX = new Range(points.Select(p => p.X));
            var rangeY = new Range(points.Select(p => p.Y));
            var rangeZ = new Range(points.Select(p => p.Z));

            this.location = new Point(rangeX.Min, rangeY.Min, rangeZ.Min);
            this.width = rangeX.Interval;
            this.height = rangeY.Interval;
            this.depth = rangeZ.Interval;
        }
 private IList<RoomState> GetRoomsStates(IList<Room> rooms, DateTime date)
 {
     var roomsIds = rooms.Select(r => r.Id).ToList();
     var furnitureItems = furnitureReader.Get(roomsIds, date);
     return rooms.Select(room => new RoomState
     {
         RoomId = room.Id,
         Date = room.CreateDate,
         RoomName = room.Name,
         FurnitureItems = furnitureItems.Where(f => f.RoomId == room.Id).ToList()
     }).ToList();
 }
        public List<TaskExecutionResult> ExecuteTasks(IList<IExecutableTask> list)
        {
            _taskStatusUpdater.BeginExecution(list);
            List<LuceneAction> luceneActions =
                list.Select(task => task as ILuceneIndexTask)
                    .SelectMany(task => task.GetActions())
                    .Distinct(LuceneActionComparison.Comparer)
                    .ToList();

            LuceneActionExecutor.PerformActions(_indexService, luceneActions);
            List<TaskExecutionResult> results = list.Select(TaskExecutionResult.Successful).ToList();
            _taskStatusUpdater.CompleteExecution(results);
            return results;
        }
        public List<TaskExecutionResult> ExecuteTasks(IList<IExecutableTask> list)
        {
            _taskStatusUpdater.BeginExecution(list);
            List<UniversalSearchIndexData> data =
                list.Select(task => task as IUniversalSearchIndexTask)
                    .Select(task => task.UniversalSearchIndexData)
                    .Distinct(UniversalSearchIndexData.Comparer)
                    .ToList();

            UniversalSearchActionExecutor.PerformActions(_universalSearchIndexManager, _searchConverter, data);
            List<TaskExecutionResult> results = list.Select(TaskExecutionResult.Successful).ToList();
            _taskStatusUpdater.CompleteExecution(results);
            return results;
        }
Example #18
0
        public IEnumerable<StudentIdName> GetStudents(IList<Student> students)
        {
            var result = students.Select(s => new StudentIdName
            {
                Id = s.Id,
                Name = s.Name
            });

            return result;

            var result1 = students.Select(s => new { Id = s.Id, Name = s.Name});
            var result2 = students.Select(s => new { Id = s.Id, Age = s.Age });
            var result3 = students.Select(s => new { Id = s.Id, Class = GetClass(s.Id) });
            // ......
        }
Example #19
0
 public static CalibrationCurve LinearFit(IList<WeightedPoint> points)
 {
     CalibrationCurve calibrationCurve = new CalibrationCurve().ChangePointCount(points.Count);
     try
     {
         double[] values = WeightedRegression.Weighted(points.Select(p => new Tuple<double[], double>(new[] {p.X}, p.Y)),
             points.Select(p => p.Weight).ToArray(), true);
         calibrationCurve = calibrationCurve.ChangeSlope(values[1]).ChangeIntercept(values[0]);
     }
     catch (Exception ex)
     {
         calibrationCurve = calibrationCurve.ChangeErrorMessage(ex.Message);
     }
     return calibrationCurve;
 }
        private double CalculateNormalisedMean(IList<double> scores)
        {
            if(scores.Count == 0)
            {
                return 0;
            }

            //http://en.wikipedia.org/wiki/Weighted_mean
            return
                scores.Select(
                    (s, i) => (s * CalculateScoreWeight(i, _predictorParameters.PreviousGameMultiplier))).Sum()
                              /
                              scores.Select(
                                  (_, i) => CalculateScoreWeight(i, _predictorParameters.PreviousGameMultiplier)).Sum();
        }
Example #21
0
        public History fit(Array x = null, Array y = null, int batch_size = 32, int epochs = 1, int verbose = 1,
                           CallbackList callbacks = null, double validation_split            = 0, IList <Array> validation_data = null, Shuffle shuffle = Shuffle.True,
                           Dictionary <int, double> class_weight = null, Array sample_weight = null, int initial_epoch          = 0, object kwargs      = null, int?nb_epoch = null)
        {
            // Legacy support
            if (nb_epoch != null)
            {
                Trace.TraceWarning("The 'nb_epoch' argument in 'fit' has been renamed 'epochs'.");
                epochs = nb_epoch.Value;
            }

            return(this.fit(
                       x.dict_from_single(),
                       y.dict_from_single(),
                       batch_size,
                       epochs,
                       verbose,
                       callbacks,
                       validation_split,
                       validation_data?.Select(a => a.dict_from_single()).ToList(),
                       shuffle,
                       class_weight?.Select(p => (p.Key.ToString(), p.Value)).ToDictionary(a => a.Item1, b => b.Item2).dict_from_single(),
                       sample_weight.dict_from_single(),
                       initial_epoch,
                       kwargs));
        }
        public async Task HandleAsync(PublishJokeCommand command, CancellationToken cancellationToken = default)
        {
            IList <Flag> flags = command.Flags != null && command.Flags.Any() ? await _getFlagsByNamesQuery.HandleAsync(new GetFlagsByNamesQuery(command.Flags), cancellationToken) : null;

            IList <Category> categories = await _getCategoriesByNamesQuery.HandleAsync(new GetCategoriesByNamesQuery(new List <string> {
                command.Category
            }), cancellationToken);

            Joke joke = new Joke
            {
                CategoryId = categories.First().Id,
                CreateDate = DateTime.Now,
                JokeFlags  = flags?.Select(f => new JokeFlag()
                {
                    FlagId = f.Id,
                }).ToList(),
                Parts = command.Parts.Select((p, i) => new Part()
                {
                    JokePart = p,
                    Order    = i + 1
                }).ToList()
            };

            await _context.Jokes.AddAsync(joke, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);
        }
Example #23
0
            public static AllTranslationsResponseModel SendTranslations(IList <WordTranslationsEntity> translations)
            {
                var translationDtos = translations?
                                      .Select(t =>
                {
                    var translation = new TranslationsDto(
                        t.English,
                        t.German,
                        t.Description,
                        t.GroupId
                        );

                    return(translation);
                }).ToList() ?? new List <TranslationsDto>();

                AllTranslationsResponseModel response = new AllTranslationsResponseModel()
                {
                    Messages     = new string[] { "Translation returned" },
                    StatusCode   = System.Net.HttpStatusCode.OK,
                    Success      = true,
                    translations = translationDtos
                };

                return(response);
            }
Example #24
0
        /// <summary>
        /// Map events
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IEnumerable <GetEventViewModel> Map(IList <CalendarEvent> source)
        {
            Arg.NotNull(source, nameof(Map));
            var mapped = source?.Select(Map);

            return(mapped);
        }
Example #25
0
        public async Task <long> Delete(Expression <Func <BlobEntity, bool> > expression)
        {
            IList <BlobEntity> entities = null;

            using (var transaction = await _repository.BeginTransactionAsync())
            {
                entities = await _repository.QueryAsync(q =>
                {
                    return(q.Where(expression).Select(x => new BlobEntity()
                    {
                        Id = x.Id,
                        BlobId = x.BlobId,
                        ChunkIndex = x.ChunkIndex
                    }).ToListAsyncTestable());
                });

                if (entities.Count > 0)
                {
                    _repository.RemoveRange(entities);
                    await _repository.SaveChangesAsync();

                    transaction.Commit();
                }
            }
            return(entities?.Select(x => x.BlobId).Distinct().LongCount() ?? 0);
        }
        public IDictionary <QuestionModel, object> GetAnswers()
        {
            var answers = _entryViews?.Select(ev => ev?.GetAnswer())
                          .ToDictionary(k => k?.Item1, v => v?.Item2);

            return(answers);
        }
Example #27
0
 public static IList <PlacementKeyValuePairs> ToPlacementKeyValuePairs(this IList <PSKeyValuePairs> psKeysValuePair)
 {
     return(psKeysValuePair?.Select(e => new PlacementKeyValuePairs()
     {
         Key = e.Key, Value = e.Value
     }).ToList());
 }
Example #28
0
        private static IList <IMetricsBaseSegmentInfo> GetSegmentInfo(IList <MetricsSegmentInfo> segments)
        {
            return(segments?.Select(seg =>
            {
                IMetricsBaseSegmentInfo result;
                if (seg.Segments != null && seg.Segments.Count != 0)
                {
                    result = new MetricsNestedSegment()
                    {
                        SegmentId = seg.SegmentId,
                        SegmentValue = seg.SegmentValue,
                        Segments = GetSegmentInfo(seg.Segments),
                    };
                }
                else
                {
                    result = new MetricsSegmentedData
                    {
                        SegmentId = seg.SegmentId,
                        SegmentValue = seg.SegmentValue,
                        Sum = seg.GetSum(),
                        Average = seg.GetAverage(),
                        Min = seg.GetMin(),
                        Max = seg.GetMax(),
                        Count = seg.GetCount()
                    };
                }

                return result;
            }).ToList());
        }
Example #29
0
        public async Task <ApiResponse> GetMatchPlayers([FromRoute] short competitionID, [FromRoute] short matchID)
        {
            var match = await this._matchRepository.Get(matchID);

            IList <Com.BinaryBracket.BowlsResults.Common.Domain.Entities.Player> homePlayers = null;
            IList <Com.BinaryBracket.BowlsResults.Common.Domain.Entities.Player> awayPlayers = null;

            if (match is PlayerMatch playerMatch)
            {
                homePlayers = playerMatch.Home.GetPlayers();
                awayPlayers = playerMatch.Away.GetPlayers();
            }

            if (match is TeamMatch teamMatch)
            {
                var response = await this._matchService.GetTeamMatchPlayers(competitionID, teamMatch);

                homePlayers = response.Item1;
                awayPlayers = response.Item2;
            }

            return(ApiResponse.CreateSuccess(new
            {
                homePlayers = homePlayers?.Select(x => x.AssembleDto()),
                awayPlayers = awayPlayers?.Select(x => x.AssembleDto())
            }));
        }
        private bool ThresholdDetailsEquals(IList <ThresholdDetail> other)
        {
            var currentIds = this.ThresholdDetails?.Select(x => x.Id).ToArray() ?? new int[] { };
            var newIds     = other?.Select(x => x.Id).ToArray() ?? new int[] { };

            var firstNotSecond = currentIds.Except(newIds).ToList();
            var secondNotFirst = newIds.Except(currentIds).ToList();

            if (firstNotSecond.Any() || secondNotFirst.Any())
            {
                return(false);
            }

            if (this.ThresholdDetails != null && other != null)
            {
                foreach (var thresholdDetail in this.ThresholdDetails)
                {
                    var otherThreshold = other.FirstOrDefault(i => i.Id == thresholdDetail.Id);

                    if (otherThreshold == null || !otherThreshold.Equals(thresholdDetail))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Example #31
0
        /// <summary>
        /// Converts this contract into its <see cref="AuthenticationPrompt"/> model.
        /// </summary>
        /// <returns>The <see cref="AuthenticationPrompt"/> model.</returns>
        public AuthenticationPrompt ToAuthenticationPrompt()
        {
            AuthenticationPrompt authPrompt = new AuthenticationPrompt();

            authPrompt.AuthType = new AuthType(this.Type);
            JArray mfaArray = this.Prompt as JArray;

            if (authPrompt.AuthType == AuthType.Device)
            {
                JObject jobj    = this.Prompt as JObject;
                string  message = jobj["message"].Value <string>();
                authPrompt.DeviceMessage = message;
            }
            else if (authPrompt.AuthType == AuthType.Code)
            {
                IList <MfaCodeResponse> codeList = mfaArray?.ToObject <IList <MfaCodeResponse> >();
                authPrompt.CodeDeliveryOptions = codeList?.Select(c => c.ToCodeOption()).ToList();
            }
            else if (authPrompt.AuthType == AuthType.Questions)
            {
                IList <MfaQuestionResponse> questionList = mfaArray?.ToObject <IList <MfaQuestionResponse> >();
                authPrompt.Questions = questionList?.Select(c => c.Question).ToList();
            }
            else if (authPrompt.AuthType == AuthType.Selection)
            {
                IList <MfaSelectionResponse> selectionList = mfaArray?.ToObject <IList <MfaSelectionResponse> >();
                authPrompt.MultipleChoiceQuestions = selectionList?.Select(c => c.ToSelectionItem()).ToList();
            }

            return(authPrompt);
        }
Example #32
0
        public AppCheckModel CheckAppId(string appId)
        {
            AppCheckModel        rtnModel = new AppCheckModel();
            IList <AppItemModel> appList  = null;

            try
            {
                appList = ((SimCaptchaOptions)Options).AppList;
            }
            catch (Exception ex)
            {
                throw new Exception("DefaultAppChecker 必需使用 SimCaptchaOptions(因为这里面有AppList), 如果你需要使用AppChecker, 请自行实现 IAppChecker");
            }
            bool isExist = appList?.Select(m => m.AppId).Contains(appId) ?? false;

            if (!isExist)
            {
                rtnModel.Pass    = false;
                rtnModel.Message = "appId 不存在";
                return(rtnModel);
            }
            rtnModel.Pass    = true;
            rtnModel.Message = "appId 效验通过";
            return(rtnModel);
        }
Example #33
0
        public async Task <(IList <BlogUser> users, int totalUsers)> GetUsers(UsersFilter filter)
        {
            var query = _context.Users
                        .AsNoTracking();

            query = QueryUsersBySearchText(query, filter.Search);

            List <User> users = null;

            var count = await query.CountAsync();

            if (count != 0)
            {
                var skip = (filter.Page - 1) * filter.PageSize;
                users = await query
                        .OrderBy(x => x.Id)
                        .Skip(skip)
                        .Take(filter.PageSize)
                        .ToListAsync();
            }

            var dtoUsers = users?.Select(x => Mapper.ConvertToModel(x))?.ToList();

            return(dtoUsers, count);
        }
        /// <summary>
        /// Adds and activates new set of fees
        /// </summary>
        /// <param name="classTermFees">A list of fees (i.e jss - sss)</param>
        /// <param name="username">The user performing this action, for audit trail.</param>
        /// <returns>A list of ids of the newly added fees and the ones deactivated </returns>
        public ActivatedAndDeactivatedId AddClassTermFees(IList<ClassTermFee> classTermFees, string username)
        {
            var currentFees = GetCurrentFees();

            var deActivatedIds = DeactivateFeesAndGetIds(currentFees);

            // Add fees and return ids
            try
            {
                var activatedIds = classTermFees.Select(x => _classTermFees.Add(x).Id).ToList();

                var activatedAndDeactivatedId = new ActivatedAndDeactivatedId
                {
                    DeActivatedIds = deActivatedIds,
                    ActivatedIds = activatedIds
                };

                // Update School
                UpdateSchool(classTermFees);

                _auditTrailRepository.Log($"School fees created by {username}", AuditActionEnum.Created);

                _log.Info("Fees added");

                return activatedAndDeactivatedId;

            }
            catch (Exception ex)
            {
                _log.Error("Error", ex);
                return null;
            }
        }
Example #35
0
        public static void Do(string strToFindInCommandLine, string strToFindInCommandLine2, IList<string> filename, bool giveFocus = true)
        {
            int procID = 0;

            string wmiQuery = "select ProcessId, CommandLine from Win32_Process";
            ManagementObjectSearcher search = new ManagementObjectSearcher(wmiQuery);
            ManagementObjectCollection processList = search.Get();

            foreach (ManagementObject process in processList) {
                if (process["CommandLine"] != null) {
                    var cmdLine = process["CommandLine"].ToString();
                    if (cmdLine.Contains(strToFindInCommandLine) && cmdLine.Contains(strToFindInCommandLine2)) {
                        procID = Convert.ToInt32(process["ProcessId"]);
                    }
                }
            }

            if (procID != 0) {
                IntPtr winHandle = FindWindow.GetProcessWindow(procID);
                MmdDrop.DropFile(winHandle, filename.Select(x => new MmdDropFile(x)).ToList());

                if (giveFocus)
                    SetForegroundWindow(winHandle);
            }
        }
Example #36
0
        private void AssertInputs(string ruleSetPath, IList <string> expectedInputs)
        {
            ProjectRootElement projectRootElement = ProjectRootElement.Create(Path.Combine(_rootDir, "project.proj"));

            if (ruleSetPath != null)
            {
                ProjectPropertyGroupElement propertyGroup = projectRootElement.AddPropertyGroup();
                projectRootElement.AddProperty(CodeAnalysisRuleSetPredictor.CodeAnalysisRuleSetPropertyName, ruleSetPath);
            }

            var projectInstance = TestHelpers.CreateProjectInstanceFromRootElement(projectRootElement);

            var expectedInputFiles = expectedInputs?
                                     .Select(input => new PredictedItem(input, nameof(CodeAnalysisRuleSetPredictor)))
                                     .ToArray();

            _predictor
            .GetProjectPredictions(projectInstance)
            .AssertPredictions(
                projectInstance,
                expectedInputFiles,
                null,
                null,
                null);
        }
        public async Task <StandardTableDataCM> Query(SalesforceObjectType type, IList <FieldDTO> propertiesToRetrieve, string filter, AuthorizationToken authToken)
        {
            var whatToSelect = propertiesToRetrieve?.Select(p => p.Name).ToArray() ?? new string[0];
            var selectQuery  = $"SELECT {(whatToSelect.Length == 0 ? "*" : string.Join(", ", whatToSelect))} FROM {type}";

            if (!string.IsNullOrEmpty(filter))
            {
                selectQuery += " WHERE " + NormalizeFilterByFiedType(propertiesToRetrieve, filter);
            }
            try
            {
                var result = await ExecuteClientOperationWithTokenRefresh(CreateForceClient, x => x.QueryAsync <object>(selectQuery), authToken);

                var table = ParseQueryResult(result);
                table.FirstRowHeaders = true;
                var headerRow = whatToSelect.Length > 0
                    ? whatToSelect.Select(x => new TableCellDTO {
                    Cell = new KeyValueDTO(x, x)
                }).ToList()
                    : (await GetProperties(type, authToken)).Select(x => new TableCellDTO {
                    Cell = new KeyValueDTO(x.Name, x.Label)
                }).ToList();
                table.Table.Insert(0, new TableRowDTO {
                    Row = headerRow
                });
                return(table);
            }
            catch (ForceException ex)
            {
                _logger.Error($"Failed to execute Salesforce query for object type {type} and filter {filter}", ex);
                throw;
            }
        }
        public void OnTestingOfMutantStarting(string mutantDestination, IList<string> mutantFilePaths)
        {
            string src = _projectPath.Join("chromedriver.exe").Path;

            string dest = Path.Combine(mutantDestination, "chromedriver.exe");
            if (!File.Exists(dest))
            {
                File.Copy(src, dest, true);
            }

            foreach (var p in mutantFilePaths.Select(path=>new FilePathAbsolute(path)))
            {
                var mutdest = _projectPath.Join("bin");//.Join(p.FileName).Path;
             /*   if(File.Exists(mutdest.Join(p.FileName).Path))
                {
                    File.Move(mutdest.Join(p.FileName).Path, mutdest.Join(p.FileNameWithoutExtension).Join(".dlltmp").Path);
                }*/

                File.Copy(p.Path, mutdest.Join(p.FileName).Path, true);
            }


            Process.Start(cmdPath);

        }
Example #39
0
        public static void BindInterfacesAsSingleton(
            this IBindingRoot bindingRoot,
            IList <Type> conventionIgnore,
            IList <Type> bindInterfacesInAssemblies,
            params Type[] assemblies)
        {
            var list = new List <Type>
            {
                typeof(IConfigObject),
                typeof(IEvent),
                typeof(IEnvironment),
                typeof(HttpServiceListener),
                typeof(GigyaSiloHost)
            };

            if (conventionIgnore != null)
            {
                list.AddRange(conventionIgnore);
            }

            bindingRoot.Bind(x =>
            {
                x.FromAssemblyContaining(assemblies)
                .SelectAllClasses()
                .Where(t => list.All(nonSingletonType => nonSingletonType.IsAssignableFrom(t) == false))
                // Bind interfaces to the implementation from assemblies ( by types )
                // The interfaces are from the specific assemblies ( by types as well)
                // The last is to avoid bind types arbitrary and isolate it to same assembly or abstraction assembly.
                .BindSelection((type, types) =>
                               types.Where(i => assemblies.Select(a => a.Assembly).Contains(i.Assembly) ||
                                           bindInterfacesInAssemblies?.Select(a => a.Assembly).Contains(i.Assembly) == true))
                .Configure(c => c.InSingletonScope());
            });
        }
Example #40
0
        public ClassAnalyzer(IList<IExtractor> extractors)
        {
            Ensure.NotNullOrEmpty(extractors);

            _extractors = extractors;
            _heuristics = _extractors.Select(x => x.Heuristic).ToList();
        }
			public static StringBuilder SetComplexTypes(List<string> strlist, IList<int> intlist, Dictionary<string, int> map,
				string[] strarray, int[] intarray)
			{
				StringBuilder sb = new StringBuilder();

				sb.Append(string.Join(",", strlist.ToArray()));

				sb.Append("|");

				sb.Append(string.Join(",", intlist.Select(i => i.ToString()).ToArray()));

				sb.Append("|");

				sb.Append(string.Join(",", map.Keys.OrderBy(x => x).Select(i => i.ToString()).ToArray()));

				sb.Append("|");

				sb.Append(string.Join(",", map.Values.OrderBy(x => x).Select(i => i.ToString()).ToArray()));

				sb.Append("|");

				sb.Append(string.Join(",", strarray));

				sb.Append("|");

				sb.Append(string.Join(",", intarray.Select(i => i.ToString()).ToArray()));

				return sb;
			}
Example #42
0
        public async Task <(IList <BlogPost> posts, int totalPosts)> GetPosts(PostsFilter filter)
        {
            // there are no posts w/o status
            if (!filter.Drafted && !filter.Published && !filter.Removed)
            {
                return(null, 0);
            }

            var query = _context.Posts
                        .AsNoTracking();

            query = QueryPostsByStatus(query, filter.Drafted, filter.Published, filter.Removed);
            query = QueryPostsByAuthorId(query, filter.AuthorId);
            query = QueryPostsBySearchText(query, filter.Search);

            List <Post> posts = null;

            var count = await query.CountAsync();

            if (count != 0)
            {
                var skip = (filter.Page - 1) * filter.PageSize;
                posts = await query
                        .Include(x => x.Author)
                        .OrderBy(x => x.Id)
                        .Skip(skip)
                        .Take(filter.PageSize)
                        .ToListAsync();
            }

            var dtoPosts = posts?.Select(x => Mapper.ConvertToModel(x))?.ToList();

            return(dtoPosts, count);
        }
Example #43
0
        /////// Export sample ///////
        private async Task <string> PostExportRequest(
            PowerBIClient client,
            Guid reportId,
            Guid groupId,
            FileFormat format,
            IList <string> pageNames = null /* Get the page names from the GetPages API */)
        {
            var powerBIReportExportConfiguration = new PowerBIReportExportConfiguration
            {
                Settings = new ExportReportSettings
                {
                    Locale = "en-us",
                },
                // Note that page names differ from the page display names.
                // To get the page names use the GetPages API.
                Pages = pageNames?.Select(pn => new ExportReportPage(pageName: pn)).ToList(),
            };
            var exportRequest = new ExportReportRequest
            {
                Format = format,
                PowerBIReportConfiguration = powerBIReportExportConfiguration,
            };
            var export = await client.Reports.ExportToFileInGroupAsync(groupId, reportId, exportRequest);

            // Save the export ID, you'll need it for polling and getting the exported file
            return(export.Id);
        }
        private void SendCreateActorResponse(CreateActor originalMessage, IList <Actor> actors = null, string failureMessage = null, Action onCompleteCallback = null)
        {
            Trace trace = new Trace()
            {
                Severity = (actors != null) ? TraceSeverity.Info : TraceSeverity.Error,
                Message  = (actors != null) ?
                           $"Successfully created {actors?.Count ?? 0} objects." :
                           failureMessage
            };

            Protocol.Send(new ObjectSpawned()
            {
                Result = new OperationResult()
                {
                    ResultCode = (actors != null) ? OperationResultCode.Success : OperationResultCode.Error,
                    Message    = trace.Message
                },

                Traces = new List <Trace>()
                {
                    trace
                },
                Actors = actors?.Select((actor) => actor.GenerateInitialPatch()) ?? new ActorPatch[] { }
            },
                          originalMessage.MessageId);

            onCompleteCallback?.Invoke();
        }
        private static IEnumerable<FileInfo> FindPatches(IList<string> inputPaths)
        {
            if (inputPaths.Count == 0)
                inputPaths.Add(".");

            // make all path's rooted
            IEnumerable<string> rootedPaths = inputPaths.Select(p =>
                                                                Path.IsPathRooted(p) ? p : Path.Combine(_baseDir, p)
                );

            foreach (string path in rootedPaths)
            {
                bool isDir = Directory.Exists(path);
                bool isFile = File.Exists(path);

                if (!(isDir || isFile))
                    throw new Exception("Could not find file or directory: " + path);

                if (isDir)
                {
                    var dir = new DirectoryInfo(path);
                    foreach (FileInfo file in dir.GetFiles("*.patch"))
                    {
                        if (!file.Name.StartsWith("svn-"))
                            yield return file;
                    }
                }
                else
                {
                    yield return new FileInfo(path);
                }
            }

            yield break;
        }
		public static IMethodOrProperty FindOverload(IList<IMethodOrProperty> list,
		                                             IReturnType[] arguments,
		                                             bool allowAdditionalArguments,
		                                             bool substituteInferredTypes,
		                                             out bool acceptableMatch)
		{
			OverloadResolution or = new OverloadResolution();
			or.candidates = list.Select(m => new Candidate(m)).ToList();
			or.arguments = arguments;
			or.allowAdditionalArguments = allowAdditionalArguments;
			
			if (or.candidates.Count == 0)
				throw new ArgumentException("at least one candidate is required");
			
			MemberLookupHelper.Log("OverloadResolution");
			MemberLookupHelper.Log("  arguments = ", arguments);
			
			or.ConstructExpandedForms();
			or.InferTypeArguments();
			or.CheckApplicability();
			
			Candidate result = or.FindBestCandidate();
			MemberLookupHelper.Log("Overload resolution finished. Winning candidate = " + result);
			acceptableMatch = result.Status == CandidateStatus.Success;
			if (substituteInferredTypes)
				return result.Method;
			else
				return result.OriginalMethod;
		}
Example #47
0
        public IList<Order> StoreAll(Customer customer, IList<Order> orders)
        {
            foreach (var order in orders)
            {
                if (order.Id == default(Guid))
                {
                    order.Id = Guid.NewGuid();
                }
                order.UserId = customer.Id;
                if (!customer.Orders.Contains(order.Id))
                {
                    customer.Orders.Add(order.Id);
                }

                foreach (var x in order.Lines)
                    _redisClient
                        .IncrementItemInSortedSet(RedisKeys.BestSellingItems,
                            (string) x.Item, (long) x.Quantity);

            }
            var orderIds = orders.Select(o => o.Id.ToString()).ToList();
            using (var transaction = _redisClient.CreateTransaction())
            {
                transaction.QueueCommand(c => c.Store(customer));
                transaction.QueueCommand(c => c.StoreAll(orders));
                transaction.QueueCommand(c => c.AddRangeToSet(RedisKeys
                    .GetCustomerOrdersReferenceKey(customer.Id),
                    orderIds));
                transaction.Commit();
            }

            return orders;
        }
        public override string Select(
            IClassMapper map,
            IPredicate predicate,
            IList <ISort> sort,
            Parameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            var dialect = this.GetDialect(map.EntityType);
            var query   = new SqlBuilder(dialect);

            var table = this.GetTableName(map);

            var sortingColumns = sort?.Select(column =>
                                              this.GetColumnName(map, column.PropertyName, false) +
                                              (column.Ascending ? " ASC" : " DESC"));

            query
            .Select(BuildSelectColumns(map))
            .From(table)
            .Where(predicate?.GetSql(this, parameters))
            .OrderBy(sortingColumns?.AppendStrings());

            return(query.Build());
        }
Example #49
0
		internal static IList<ITypeReference> ToTypeReference(IList<IType> typeArguments)
		{
			if (typeArguments == null)
				return null;
			else
				return typeArguments.Select(t => t.ToTypeReference()).ToArray();
		}
Example #50
0
        private static IDictionary<string, int> PrefillAuthors(IList<boeken> books, AuthorRepository authorsRepo, UnitOfWork unitOfWork)
        {
            var allAuthorsInOldDb = books.Select(_ => _.auteurs.Trim()).Distinct().ToList();
            var newAuthors = authorsRepo.All.ToList();
            var result =  new Dictionary<string, int>();
            Console.WriteLine("Found {0} authors in old db", allAuthorsInOldDb.Count());
            foreach(var a in allAuthorsInOldDb)
            {
                var candidate = newAuthors.FirstOrDefault(_ => _.Name.ToLower() == a.ToLower());

                if (candidate == null)
                {
                    candidate = new Author()
                    {
                        State = State.Added,
                        Name = a
                    };

                    authorsRepo.InsertOrUpdate(candidate);                    
                    unitOfWork.Save();
                    newAuthors.Add(candidate);
                }
                result[a.ToLower()] = candidate.Id;                
            }
            

            return result;
        }
Example #51
0
        public override void Execute(object parameter)
        {
            var maxCount = _inventory?.Select(x => x.CarId).DefaultIfEmpty().Max() ?? 0;

            _inventory?.Add(new Car {
                CarId = ++maxCount, Color = "Yellow", Make = "VW", CarNickName = "Birdie", IsChanged = false
            });
        }
Example #52
0
 public HandRepresentation(IList <Card> cardList, IDictionary <Card, ICommand> commandDictionary)
 {
     CardList = cardList;
     CardCommandDictionary  = commandDictionary;
     CardRepresentationList = CardList
                              ?.Select(c => new CardRepresentation(c, (CardCommandDictionary?.ContainsKey(c) ?? false) ? CardCommandDictionary[c] : null))
                              .ToList();
 }
        private FunctionSignatureWithReturnType[] GetCustomFunctionSignaturesOrNull(string customFunctionName)
        {
            IList <KeyValuePair <string, FunctionSignatureWithReturnType> > resultFunctionSignaturesWithReturnType = null;

            CustomUriFunctions.TryGetCustomFunction(customFunctionName, out resultFunctionSignaturesWithReturnType);

            return(resultFunctionSignaturesWithReturnType?.Select(_ => _.Value).ToArray());
        }
Example #54
0
 public static ClassSummaryViewData Create(ClassDetails classDetails, Room currentRoom, IList <Period> periods, IList <DayType> dayTypes)
 {
     return(new ClassSummaryViewData(classDetails)
     {
         Room = currentRoom != null?RoomViewData.Create(currentRoom) : null,
                    Periods = periods?.Select(x => x.Name).ToList(),
                    DayTypes = dayTypes?.Select(x => x.Name).ToList()
     });
 }
Example #55
0
 public static List <ReportWithPaymentDate> MapReportWithPaymentDate(IList <IList <string> > analyticsReportWithPaymentDate)
 {
     return(analyticsReportWithPaymentDate?.Select(gaEntity => new ReportWithPaymentDate
     {
         SessionId = gaEntity[0],
         PaymentDate = ParseDate(gaEntity[1]),
         Sessions = int.Parse(gaEntity[2])
     }).ToList());
 }
Example #56
0
 public static List <ReportWithSessionType> MapReportWithSessionType(IList <IList <string> > analyticsReportWithSessionType)
 {
     return(analyticsReportWithSessionType?.Select(gaEntity => new ReportWithSessionType
     {
         SessionId = gaEntity[0],
         SessionType = gaEntity[1],
         Sessions = int.Parse(gaEntity[2])
     }).ToList());
 }
Example #57
0
 public static List <ReportWithProduct> MapReportWithProduct(IList <IList <string> > analyticsReportWithProduct)
 {
     return(analyticsReportWithProduct?.Select(gaEntity => new ReportWithProduct
     {
         SessionId = gaEntity[0],
         Product = gaEntity[1],
         Sessions = int.Parse(gaEntity[2])
     }).ToList());
 }
Example #58
0
 public static List <ReportWithEmployees> MapReportWithEmployees(IList <IList <string> > analyticsReportWithEmployees)
 {
     return(analyticsReportWithEmployees?.Select(gaEntity => new ReportWithEmployees
     {
         SessionId = gaEntity[0],
         Employyes = TryParseInt(gaEntity[1]),
         Sessions = int.Parse(gaEntity[2])
     }).ToList());
 }
Example #59
0
 public static List <ReportWithTariff> MapReportWithTariff(IList <IList <string> > analyticsReportWithTariff)
 {
     return(analyticsReportWithTariff?.Select(gaEntity => new ReportWithTariff
     {
         SessionId = gaEntity[0],
         TariffId = TryParseInt(gaEntity[1]),
         Sessions = int.Parse(gaEntity[2])
     }).ToList());
 }
Example #60
0
 public static List <ReportWithCompanyId> MapReportWithCompaynyId(IList <IList <string> > analyticsReportWithCompaynyId)
 {
     return(analyticsReportWithCompaynyId?.Select(gaEntity => new ReportWithCompanyId
     {
         SessionId = gaEntity[0],
         CompanyId = TryParseInt(gaEntity[1]),
         Sessions = int.Parse(gaEntity[2])
     }).ToList());
 }