public IObservable<Unit> InsertAll(IList<Session> sessions)
        {
            return blob.GetOrCreateObject<IList<Session>>(KEY_SESSIONS, () => new List<Session>())
                .Select(source =>
                    {
                        var checkedSessions = sessions.Where(session => session.IsChecked).ToDictionary(session => session.id);
                        var merged = sessions.Union(source);

                        return merged.Select(session =>
                            {
                                session.IsChecked = checkedSessions.ContainsKey(session.id);
                                return session;
                            });
                    })
                .SelectMany(merged =>
                    {
                        return Observable.Merge(
                            merged.ToObservable()
                                .Select(session => session.category)
                                .ToList().Distinct()
                                .SelectMany(categoryDao.InsertAll),
                            merged.ToObservable()
                                .Select(session => session.place)
                                .ToList().Distinct()
                                .SelectMany(placeDao.InsertAll),
                            blob.InsertObject(KEY_SESSIONS, merged)
                        );
                    });
        }
Example #2
1
 /// <summary>
 /// Initialises the list of profiles
 /// </summary>
 private void InitialiseProfiles()
 {
     _existingProfiles = _authService.GetProfiles();
     foreach (var i in _existingProfiles.Union(new[] { NewProfileItem }))
     {
         cbbProfiles.Items.Add(i);
     }
     cbbProfiles.SelectedIndex = 0;
 }
 public IObservable<Unit> InsertAll(IList<Category> categories)
 {
     return blob.GetOrCreateObject<IList<Category>>(KEY_CATEGORIES, () => new List<Category>())
         .Select(source =>
             {
                 return categories.Union(source);
             })
         .SelectMany(merged => blob.InsertObject(KEY_CATEGORIES, merged));
 }
        public void Subscribe(string client, IList<string> messageTypes)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                var existingSubscription = session.AsQueryable<Subscription>().SingleOrDefault(x => x.SubscriberEndpoint == client) 
                    ?? new Subscription { SubscriberEndpoint = client, MessageTypes = new List<string>() };

                var messageTypesToSubscribe = messageTypes.Union(existingSubscription.MessageTypes).ToList();

                existingSubscription.MessageTypes = messageTypesToSubscribe;
                session.Store(existingSubscription);
                session.Commit();
            }
        }
 public byte[] Serialize(IList<HeaderInfo> headers)
 {
   if (CurrentSagaIds.OutgoingIds != null && CurrentSagaIds.OutgoingIds.Length > 0)
   {
     var value = String.Join(",", CurrentSagaIds.OutgoingIds.Select(x => x.ToString()).ToArray());
     var header = new HeaderInfo()
     {
       Key = "machine.sagas",
       Value = value
     };
     _log.Debug("Serializing: " + value);
     return _serializer.Serialize(headers.Union(new[] { header }).ToList());
   }
   return _serializer.Serialize(headers);
 }
    protected void Page_Init(object sender, EventArgs e)
    {
        #region 設定搜尋控制項目

        plSearch.Controls.Add(new LiteralControl("<br />"));

        Search_Date sd = new Search_Date(this.ViewState, plSearch, "日期範圍", "selectDate", "sCreatetime", "tbStartDate", "tbEndDate");
        SearchItems = SearchItems.Union(sd.SearchItems).ToList();
        Search_Checkbox sc = new Search_Checkbox(this.ViewState, plSearch, "僅列出有效資料", "chksFBUID", "sFBUID");
        SearchItems = SearchItems.Union(sc.SearchItems).ToList();
        st = new Search_Textfield(this.ViewState, plSearch, "sFBUID:", "tbsFBUID", "sFBUID", "sFBUID");
        SearchItems = SearchItems.Union(st.SearchItems).ToList();
        st = new Search_Textfield(this.ViewState, plSearch, "sFBDisplayName:", "tbsFBDisplayName", "sFBDisplayName", "sFBDisplayName");
        SearchItems = SearchItems.Union(st.SearchItems).ToList();
        st = new Search_Textfield(this.ViewState, plSearch, "sName:", "tbsName", "sName", "sName");
        SearchItems = SearchItems.Union(st.SearchItems).ToList();

        #endregion
    }
Example #7
1
        /// <summary>
        /// This method determins if straight flush of clubs combination is available 
        /// </summary>
        /// <param name="charactersCardsCollection">
        /// Player's cards
        /// </param>
        /// <param name="tableCardsCollection">
        /// All cards visible on the table
        /// </param>
        /// <param name="character">
        /// current player
        /// </param>
        /// <returns></returns>
        private bool CheckForStraightFlushOfClubs(IList<ICard> charactersCardsCollection,
            IList<ICard> tableCardsCollection, ICharacter character)
        {
            bool hasStraightFlush = false;

            List<ICard> joinedCardCollection = charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            List<ICard> straightFlushCardsCollection = joinedCardCollection.Where(c => c.Suit == CardSuit.Clubs).ToList();

            straightFlushCardsCollection = new List<ICard>(straightFlushCardsCollection.OrderByDescending(c => c.Rank));

            if (straightFlushCardsCollection.Count < 5)
            {
                return false;
            }
            else
            {
                straightFlushCardsCollection = straightFlushCardsCollection.Take(5).ToList();

                double power = 0;
                for (int i = 0; i < straightFlushCardsCollection.Count - 1; i++)
                {
                    if ((int)straightFlushCardsCollection[i].Rank - 1 != (int)straightFlushCardsCollection[i + 1].Rank)
                    {
                        return false;
                    }
                }

                if (straightFlushCardsCollection[0].Rank == CardRank.Ace)
                {
                    power = (int)straightFlushCardsCollection[0].Rank + BigStraightFlushBehaviourPower * 100;
                }

                else
                {
                    power = (int)straightFlushCardsCollection[0].Rank + LittleStraightFlushBehaviourPower * 100;
                }

                IList<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination = joinedCardCollection.Where(x => !straightFlushCardsCollection.Contains(x)).ToList();

                if (character.CardsCombination == null || character.CardsCombination.Type < CombinationType.StraightFlush)
                {
                    character.CardsCombination = new Combination(
                        power,
                        CombinationType.StraightFlush,
                        LittleStraightFlushBehaviourPower,
                        straightFlushCardsCollection,
                        theOtherCardsFromTheHandNotIncludedInTheCombination);
                }

                hasStraightFlush = true;
            }

            return hasStraightFlush;
        }
Example #8
1
        /// <summary>
        /// Checks if the character has two pairs.
        /// </summary>
        /// <param name="charactersCardsCollection"></param>
        /// <param name="tableCardsCollection"></param>
        /// <param name="character"></param>
        /// <returns></returns>
        private bool CheckForTwoPairs(IList<ICard> charactersCardsCollection,
        IList<ICard> tableCardsCollection, ICharacter character)
        {
            bool hasOnePair = CheckForOnePair(charactersCardsCollection, tableCardsCollection, character, false);

            bool hasASecondPair = false;

            if (hasOnePair)
            {
                IList<ICard> nonCombinationCards = charactersCardsCollection.Union(tableCardsCollection).Where(x => !character.CardsCombination.CombinationCardsCollection.Contains(x) && x.IsVisible).ToList();

                IList<ICard> emptyCollection = new List<ICard>();

                hasASecondPair = CheckForOnePair(nonCombinationCards, emptyCollection, character, true);
            }
            return hasASecondPair;
        }
Example #9
0
        /// <summary>
        /// Checks if the two character's cards make a "Pair" or if one of the character's cards makes a "Pair" with one card from the table.
        /// </summary>
        /// <param name="charactersCardsCollection"></param>
        /// <param name="tableCardsCollection"></param>
        /// <param name="character"></param>
        /// <returns></returns>
        private bool CheckForOnePair(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection, ICharacter character, bool isCheckingForASecondPair)
        {
            IList<ICombination> combinationsCollection = new List<ICombination>();

            bool foundOnePair = false;
            bool foundASecondPair = false;

            IList<ICard> joinedCardCollection = charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            FindAllOnePairCombinations(joinedCardCollection, combinationsCollection);

            combinationsCollection = combinationsCollection.OrderByDescending(x => x.Power).ToList();

            if (isCheckingForASecondPair)
            {
                if (combinationsCollection.Count >= 1)
                {
                    foundASecondPair = true;
                }

                if (foundASecondPair)
                {
                    RegisterTwoPairs(character, combinationsCollection);
                }
            }
            else
            {
                if (combinationsCollection.Count >= 1)
                {
                    foundOnePair = true;
                    RegisterOnePair(character, combinationsCollection);
                }
            }

            bool foundAPairOrPairs = foundOnePair || foundASecondPair;

            return foundAPairOrPairs;
        }
Example #10
0
        /// <summary>
        /// Checks for a "High card" combination
        /// </summary>
        /// <param name="charactersCardsCollection"></param>
        /// <param name="tableCardsCollection"></param>
        /// <param name="character"></param>
        /// <returns></returns>
        private bool CheckForHighCard(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection, ICharacter character)
        {
            double power = Math.Max((double)charactersCardsCollection[0].Rank, (double)charactersCardsCollection[1].Rank);

            IList<ICard> joinedCardCollection = charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).OrderByDescending(x => x.Rank).ToList();

            IList<ICard> combinationCardsCollection = new List<ICard>();
            combinationCardsCollection.Add(joinedCardCollection[0]);

            IList<ICard> nonCombinationCards = joinedCardCollection.Where(x => !combinationCardsCollection.Contains(x)).ToList();

            RegisterCombination(character, power, combinationCardsCollection, nonCombinationCards, CombinationType.HighCard, Constants.HighCardBehaviourPower);

            return true;
        }
Example #11
0
        //This method gets the rank (number) of the cards that make up a three-of-a-kind
        private int GetThreeOfAKindCardRank(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection)
        {
            int cardRank = -1;

            IList<ICard> joinedCardCollection =
                charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            foreach (var element in joinedCardCollection)
            {
                IList<ICard> sameRankCardsCollection = joinedCardCollection.Where(x => x.Rank == element.Rank).ToList();

                if (sameRankCardsCollection.Count == 3)
                {
                    cardRank = (int)element.Rank;
                }
            }

            return cardRank;
        }
Example #12
0
        /// <summary>
        /// This method checks if the character has card combination "Full House"
        /// </summary>
        /// <param name="charactersCardsCollection">The collection of cards in the characters hand.</param>
        /// <param name="tableCardsCollection">The collection of cards on the table.</param>
        /// <param name="character">The character that holds the cards.</param>
        /// <returns><c>true</c> if the character has a Full House, <c>false</c> if they don't.</returns>
        private bool CheckForFullHouse(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection,
            ICharacter character)
        {
            bool hasFullHouse = false;

            IList<ICard> joinedCardCollection = charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            bool characterHasThreeOfAKind = CheckForThreeOfAKind(charactersCardsCollection, tableCardsCollection,
                character);

            IList<ICard> threeOfAKindCards = new List<ICard>();

            int threeOfAKindRank = -1;

            if (characterHasThreeOfAKind)
            {
                threeOfAKindRank = GetThreeOfAKindCardRank(charactersCardsCollection, tableCardsCollection);

                //removes the three-of-a-kind cards from the joinedCardCollection (hand+table cards)
                // and adds them to the threeOfAKindCards list
                for (int i = 0; i < joinedCardCollection.Count; i++)
                {
                    if ((int)joinedCardCollection[i].Rank == threeOfAKindRank)
                    {
                        threeOfAKindCards.Add(joinedCardCollection[i]);
                        joinedCardCollection.RemoveAt(i);
                        i--;
                    }
                }

                //checks if there is a pair in the remaining collection
                //if yes -> the player has a full house combination
                int maxPairRank = -1;
                foreach (ICard card in joinedCardCollection)
                {
                    IList<ICard> remainingEqualRankCards =
                        joinedCardCollection.Where(x => x.Rank == card.Rank).ToList();

                    if (remainingEqualRankCards.Count == 2)
                    {
                        hasFullHouse = true;

                        //This is a check for multiple pairs in the remaining cards
                        //If there is more than one pair, the highest one is taken
                        maxPairRank = Math.Max(maxPairRank, (int)card.Rank); //  take the one with the higher rank

                        IList<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination =
                            joinedCardCollection.Where(x => x != remainingEqualRankCards[0]).ToList();

                        IList<ICard> fullHouseCards = threeOfAKindCards;
                        fullHouseCards = fullHouseCards.Union(remainingEqualRankCards).ToList();


                        double power = maxPairRank * 2 + FullHouseBehaviourPower * 100;

                        if (character.CardsCombination == null ||
                            character.CardsCombination.Type < CombinationType.FullHouse)
                        {
                            character.CardsCombination = new Combination(power, CombinationType.FullHouse, Constants.FullHouseBehaviourPower, fullHouseCards, theOtherCardsFromTheHandNotIncludedInTheCombination);
                        }

                    }
                }
            }

            return hasFullHouse;
        }
 public IObservable<Unit> UpdateAll(IList<Session> sessions)
 {
     return blob.GetOrCreateObject<IList<Session>>(KEY_SESSIONS, () => new List<Session>())
         .Select(source =>
             {
                 return sessions.Union(source);
             })
         .SelectMany(merged => blob.InsertObject(KEY_SESSIONS, merged));
 }
Example #14
0
        IList<IType> FindTypesInBounds(IList<IType> lowerBounds, IList<IType> upperBounds)
        {
            // If there's only a single type; return that single type.
            // If both inputs are empty, return the empty list.
            if (lowerBounds.Count == 0 && upperBounds.Count <= 1)
                return upperBounds;
            if (upperBounds.Count == 0 && lowerBounds.Count <= 1)
                return lowerBounds;
            if (nestingLevel > maxNestingLevel)
                return EmptyList<IType>.Instance;

            // Finds a type X so that "LB <: X <: UB"
            Log.WriteCollection("FindTypesInBound, LowerBounds=", lowerBounds);
            Log.WriteCollection("FindTypesInBound, UpperBounds=", upperBounds);

            // First try the Fixing algorithm from the C# spec (§7.5.2.11)
            List<IType> candidateTypes = lowerBounds.Union(upperBounds)
                .Where(c => lowerBounds.All(b => conversions.ImplicitConversion(b, c).IsValid))
                .Where(c => upperBounds.All(b => conversions.ImplicitConversion(c, b).IsValid))
                .ToList(); // evaluate the query only once

            Log.WriteCollection("FindTypesInBound, Candidates=", candidateTypes);

            // According to the C# specification, we need to pick the most specific
            // of the candidate types. (the type which has conversions to all others)
            // However, csc actually seems to choose the least specific.
            candidateTypes = candidateTypes.Where(
                c => candidateTypes.All(o => conversions.ImplicitConversion(o, c).IsValid)
            ).ToList();

            // If the specified algorithm produces a single candidate, we return
            // that candidate.
            // We also return the whole candidate list if we're not using the improved
            // algorithm.
            if (candidateTypes.Count == 1 || !(algorithm == TypeInferenceAlgorithm.Improved || algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults))
            {
                return candidateTypes;
            }
            candidateTypes.Clear();

            // Now try the improved algorithm
            Log.Indent();
            List<ITypeDefinition> candidateTypeDefinitions;
            if (lowerBounds.Count > 0) {
                // Find candidates by using the lower bounds:
                var hashSet = new HashSet<ITypeDefinition>(lowerBounds[0].GetAllBaseTypeDefinitions());
                for (int i = 1; i < lowerBounds.Count; i++) {
                    hashSet.IntersectWith(lowerBounds[i].GetAllBaseTypeDefinitions());
                }
                candidateTypeDefinitions = hashSet.ToList();
            } else {
                // Find candidates by looking at all classes in the project:
                candidateTypeDefinitions = compilation.GetAllTypeDefinitions().ToList();
            }

            // Now filter out candidates that violate the upper bounds:
            foreach (IType ub in upperBounds) {
                ITypeDefinition ubDef = ub.GetDefinition();
                if (ubDef != null) {
                    candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef));
                }
            }

            foreach (ITypeDefinition candidateDef in candidateTypeDefinitions) {
                // determine the type parameters for the candidate:
                IType candidate;
                if (candidateDef.TypeParameterCount == 0) {
                    candidate = candidateDef;
                } else {
                    Log.WriteLine("Inferring arguments for candidate type definition: " + candidateDef);
                    bool success;
                    IType[] result = InferTypeArgumentsFromBounds(
                        candidateDef.TypeParameters,
                        new ParameterizedType(candidateDef, candidateDef.TypeParameters),
                        lowerBounds, upperBounds,
                        out success);
                    if (success) {
                        candidate = new ParameterizedType(candidateDef, result);
                    } else {
                        Log.WriteLine("Inference failed; ignoring candidate");
                        continue;
                    }
                }
                Log.WriteLine("Candidate type: " + candidate);

                if (upperBounds.Count == 0) {
                    // if there were only lower bounds, we aim for the most specific candidate:

                    // if this candidate isn't made redundant by an existing, more specific candidate:
                    if (!candidateTypes.Any(c => c.GetDefinition().IsDerivedFrom(candidateDef))) {
                        // remove all existing candidates made redundant by this candidate:
                        candidateTypes.RemoveAll(c => candidateDef.IsDerivedFrom(c.GetDefinition()));
                        // add new candidate
                        candidateTypes.Add(candidate);
                    }
                } else {
                    // if there were upper bounds, we aim for the least specific candidate:

                    // if this candidate isn't made redundant by an existing, less specific candidate:
                    if (!candidateTypes.Any(c => candidateDef.IsDerivedFrom(c.GetDefinition()))) {
                        // remove all existing candidates made redundant by this candidate:
                        candidateTypes.RemoveAll(c => c.GetDefinition().IsDerivedFrom(candidateDef));
                        // add new candidate
                        candidateTypes.Add(candidate);
                    }
                }
            }
            Log.Unindent();
            return candidateTypes;
        }
Example #15
0
        public void SaveToCache(IList<ITweetable> viewport)
        {
            if (!Cached)
                return;

            var toSave = viewport
                .Union(Source.OrderByDescending(x => x.Id).Take(CacheSize))
                .OfType<TwitterStatus>()
                .OrderByDescending(x => x.Id);

            try
            {
                Cacher.SaveToCache(Resource, toSave);
            }
            catch (Exception)
            {
            }
        }
 private void activatePackages(IList<IPackageInfo> packages, IList<IActivator> discoveredActivators)
 {
     _diagnostics.LogExecutionOnEach(discoveredActivators.Union(_activators),
                                     a => { a.Activate(packages, _diagnostics.LogFor(a)); });
 }
        //: BaseService, IContentAdminService {
        // **************************************
        //  Update
        // **************************************
        public static void Update(Content contentModel, 
			IList<int> tagsModel,
			IDictionary<TagType, string> newTagsModel,
			IList<ContentRepresentationUpdateModel> representationModel)
        {
            using (var ctx = new SongSearchContext()) {
                    //UpdateModelWith Content
                    var content = ctx.Contents
                            .Include("Tags")
                            .Include("Catalog")
                            .Include("ContentRepresentations")
                            .Include("ContentRepresentations.Territories")
                        .Where(c => c.ContentId == contentModel.ContentId).SingleOrDefault();// && user.UserCatalogRoles.Any(x => x.CatalogId == c.CatalogId)).SingleOrDefault();

                    if (content == null) {
                        throw new ArgumentOutOfRangeException("Content does not exist");
                    }

                    content.UpdateModelWith(contentModel);

                    //UpdateModelWith Tags
                    tagsModel = tagsModel.Where(t => t > 0).ToList();
                    // create new tags
                    var newTags = ctx.CreateTags(newTagsModel);
                    tagsModel = tagsModel.Union(newTags).ToList();

                    // add to tagsModel
                    content = ctx.UpdateTags(content, tagsModel);

                    //UpdateModelWith Representation
                    content = ctx.UpdateRepresentation(content, representationModel);

                    content.LastUpdatedByUserId = Account.User().UserId;
                    content.LastUpdatedOn = DateTime.Now;

                    ctx.SaveChanges();

                    CacheService.InitializeApp(true);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.Content);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.Rights);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.TopTags);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.Tags);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.Territories);
                }
        }
Example #18
0
        private IPagedList<MovimientoDTO> BusquedaYPaginado_Movimiento(IList<MovimientoDTO> lista, string sortOrder, string currentFilter, string searchString, int? page)
        {
            if (!String.IsNullOrEmpty(searchString))
            { searchString = searchString.ToLower(); }
            ViewBag.CurrentSort = sortOrder;

            ViewBag.vbFecha = sortOrder == "Fecha" ? "Fecha_desc" : "Fecha";
            ViewBag.vbTipo = sortOrder == "Tipo" ? "Tipo_desc" : "Tipo";
            ViewBag.vbDetalle = sortOrder == "Detalle" ? "Detalle_desc" : "Detalle";
            ViewBag.vbMonto = sortOrder == "Monto" ? "Monto_desc" : "Monto";
            ViewBag.vbCategoria = sortOrder == "Categoria" ? "Categoria_desc" : "Categoria";
            ViewBag.vbEntidad = sortOrder == "Entidad" ? "Entidad_desc" : "Entidad";
            ViewBag.vbDocumento = sortOrder == "Documento" ? "Documento_desc" : "Documento";
            ViewBag.vbUsuario = sortOrder == "Usuario" ? "Usuario_desc" : "Usuario";
            ViewBag.vbEstado = sortOrder == "Estado" ? "Estado_desc" : "Estado";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            string tipoDato = "cadena";
            DateTime pTiempo;
            if (DateTime.TryParse(searchString, out pTiempo))
            {
                tipoDato = "tiempo";
                pTiempo = Convert.ToDateTime(searchString);
            }

            Decimal pDecimal;
            if (Decimal.TryParse(searchString, out pDecimal))
            {
                tipoDato = "numerico";
                pDecimal = Convert.ToDecimal(searchString);
            }

            if (!String.IsNullOrEmpty(searchString))
            {
                IList<MovimientoDTO> listaP;
                listaP = lista.Where(s => (s.NroOperacion.ToLower() ?? "").Contains(searchString)
                        || (s.NombreCategoria.ToLower() ?? "").Contains(searchString)
                        || (s.NombreEntidadR.ToLower() ?? "").Contains(searchString)
                        || (s.NumeroDocumento.ToLower() ?? "").Contains(searchString)
                        || (s.NombreUsuario.ToLower() ?? "").Contains(searchString)
                        ).ToList();

                switch (tipoDato)
                {
                    case "tiempo":
                        lista = lista.Where(s => DateTime.Compare(s.Fecha, pTiempo) <= 0).ToList();
                        lista = lista.Union(listaP).ToList();
                        break;
                    case "numerico":
                        lista = lista.Where(s => s.Monto.ToString().Contains(pDecimal.ToString())).ToList();
                        lista = lista.Union(listaP).ToList();
                        break;
                    default:
                        lista = listaP;
                        break;
                }
            }

            switch (sortOrder)
            {
                case "Fecha":
                    lista = lista.OrderBy(s => s.Fecha).ToList();
                    break;
                case "Tipo":
                    lista = lista.OrderBy(s => s.IdTipoMovimiento).ToList();
                    break;
                case "Detalle":
                    lista = lista.OrderBy(s => s.NroOperacion).ToList();
                    break;
                case "Monto":
                    lista = lista.OrderBy(s => s.Monto).ToList();
                    break;
                case "Categoria":
                    lista = lista.OrderBy(s => s.NombreCategoria).ToList();
                    break;
                case "Entidad":
                    lista = lista.OrderBy(s => s.NombreEntidadR).ToList();
                    break;
                case "Documento":
                    lista = lista.OrderBy(s => s.NumeroDocumento).ToList();
                    break;
                case "Usuario":
                    lista = lista.OrderBy(s => s.NombreUsuario).ToList();
                    break;
                case "Estado":
                    lista = lista.OrderBy(s => s.IdEstadoMovimiento).ToList();
                    break;
                case "Fecha_desc":
                    lista = lista.OrderByDescending(s => s.Fecha).ToList();
                    break;
                case "Tipo_desc":
                    lista = lista.OrderByDescending(s => s.IdTipoMovimiento).ToList();
                    break;
                case "Detalle_desc":
                    lista = lista.OrderByDescending(s => s.NroOperacion).ToList();
                    break;
                case "Monto_desc":
                    lista = lista.OrderByDescending(s => s.Monto).ToList();
                    break;
                case "Categoria_desc":
                    lista = lista.OrderByDescending(s => s.NombreCategoria).ToList();
                    break;
                case "Entidad_desc":
                    lista = lista.OrderByDescending(s => s.NombreEntidadR).ToList();
                    break;
                case "Documento_desc":
                    lista = lista.OrderByDescending(s => s.NumeroDocumento).ToList();
                    break;
                case "Usuario_desc":
                    lista = lista.OrderByDescending(s => s.NombreUsuario).ToList();
                    break;
                case "Estado_desc":
                    lista = lista.OrderByDescending(s => s.IdEstadoMovimiento).ToList();
                    break;
            }

            int pageSize = 50;
            int pageNumber = (page ?? 1);

            return lista.ToPagedList(pageNumber, pageSize);
        }
Example #19
0
        private IPagedList<ComprobanteDTO> BusquedaYPaginado_Comprobantes(IList<ComprobanteDTO> lista, string sortOrder, string currentFilter, string searchString, int? page)
        {
            if (!String.IsNullOrEmpty(searchString))
            { searchString = searchString.ToLower(); }
            ViewBag.CurrentSort = sortOrder;

            ViewBag.vbFecha = sortOrder == "Fecha" ? "Fecha_desc" : "Fecha";
            ViewBag.vbDocumento = sortOrder == "Documento" ? "Documento_desc" : "Documento";
            ViewBag.vbNumero = sortOrder == "Numero" ? "Numero_desc" : "Numero";
            ViewBag.vbEntidad = sortOrder == "Entidad" ? "Entidad_desc" : "Entidad";
            ViewBag.vbProyecto = sortOrder == "Proyecto" ? "Proyecto_desc" : "Proyecto";
            ViewBag.vbMontoSinIGV = sortOrder == "MontoSinIGV" ? "MontoSinIGV_desc" : "MontoSinIGV";
            ViewBag.vbCategoria = sortOrder == "Categoria" ? "Categoria_desc" : "Categoria";
            ViewBag.vbFechaFin = sortOrder == "FechaFin" ? "FechaFin_desc" : "FechaFin";
            ViewBag.vbUsuario = sortOrder == "Usuario" ? "Usuario_desc" : "Usuario";
            ViewBag.vbEstado = sortOrder == "Estado" ? "Estado_desc" : "Estado";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            string tipoDato = "cadena";
            DateTime pTiempo;
            if (DateTime.TryParse(searchString, out pTiempo))
            {
                tipoDato = "tiempo";
                pTiempo = Convert.ToDateTime(searchString);
            }

            Decimal pDecimal;
            if (Decimal.TryParse(searchString, out pDecimal))
            {
                tipoDato = "numerico";
                pDecimal = Convert.ToDecimal(searchString);
            }

            if (!String.IsNullOrEmpty(searchString))
            {
                IList<ComprobanteDTO> listaP;
                listaP = lista.Where(s => (s.NombreTipoDocumento.ToLower() ?? "").Contains(searchString)
                        || (s.NombreCategoria.ToLower() ?? "").Contains(searchString)
                        || (s.NroDocumento.ToLower() ?? "").Contains(searchString)
                        || (s.NombreEntidad.ToLower() ?? "").Contains(searchString)
                        || (s.NombreUsuario.ToLower() ?? "").Contains(searchString)
                        || (s.NombreProyecto.ToLower() ?? "").Contains(searchString)
                        ).ToList();

                switch (tipoDato)
                {
                    case "tiempo":
                        lista = lista.Where(s => DateTime.Compare(s.FechaEmision, pTiempo) <= 0 || DateTime.Compare(s.FechaConclusion.GetValueOrDefault(), pTiempo) <= 0).ToList();
                        lista = lista.Union(listaP).ToList();
                        break;
                    case "numerico":
                        lista = lista.Where(s => s.MontoSinIGV.ToString().Contains(pDecimal.ToString())).ToList();
                        lista = lista.Union(listaP).ToList();
                        break;
                    default:
                        lista = listaP;
                        break;
                }
            }

            switch (sortOrder)
            {
                case "Documento":
                    lista = lista.OrderBy(s => s.NombreTipoDocumento).ToList();
                    break;
                case "Numero":
                    lista = lista.OrderBy(s => s.NroDocumento).ToList();
                    break;
                case "Categoria":
                    lista = lista.OrderBy(s => s.NombreCategoria).ToList();
                    break;
                case "Entidad":
                    lista = lista.OrderBy(s => s.NombreEntidad).ToList();
                    break;
                case "MontoSinIGV":
                    lista = lista.OrderBy(s => s.MontoSinIGV).ToList();
                    break;
                case "Usuario":
                    lista = lista.OrderBy(s => s.NombreUsuario).ToList();
                    break;
                case "Fecha":
                    lista = lista.OrderBy(s => s.FechaEmision).ToList();
                    break;
                case "FechaFin":
                    lista = lista.OrderBy(s => s.FechaConclusion).ToList();
                    break;
                case "Estado":
                    lista = lista.OrderBy(s => s.Ejecutado).ToList();
                    break;
                case "Documento_desc":
                    lista = lista.OrderByDescending(s => s.NombreTipoDocumento).ToList();
                    break;
                case "Numero_desc":
                    lista = lista.OrderByDescending(s => s.NroDocumento).ToList();
                    break;
                case "Categoria_desc":
                    lista = lista.OrderByDescending(s => s.NombreCategoria).ToList();
                    break;
                case "Entidad_desc":
                    lista = lista.OrderByDescending(s => s.NombreEntidad).ToList();
                    break;
                case "MontoSinIGV_desc":
                    lista = lista.OrderByDescending(s => s.MontoSinIGV).ToList();
                    break;
                case "Usuario_desc":
                    lista = lista.OrderByDescending(s => s.NombreUsuario).ToList();
                    break;
                case "Fecha_desc":
                    lista = lista.OrderByDescending(s => s.FechaEmision).ToList();
                    break;
                case "FechaFin_desc":
                    lista = lista.OrderByDescending(s => s.FechaConclusion).ToList();
                    break;
                case "Estado_desc":
                    lista = lista.OrderByDescending(s => s.Ejecutado).ToList();
                    break;
                default:
                    lista = lista.OrderByDescending(s => s.FechaEmision).ToList();
                    break;
            }

            int pageSize = 50;
            int pageNumber = (page ?? 1);

            return lista.ToPagedList(pageNumber, pageSize);
        }
        void DeleteHandler(IList<string> pathStack, string user, string pass,string privateKeyFile)
        {
            if(pathStack.Count > 0)
            {
                string path = pathStack[0];
                pathStack.RemoveAt(0);

                bool addBack = true;

                IList<IActivityIOPath> allFiles = ListFilesInDirectory(ActivityIOFactory.CreatePathFromString(path, user, pass, privateKeyFile)).GroupBy(a => a.Path).Select(g => g.First()).ToList();
                IList<IActivityIOPath> allDirs = ListFoldersInDirectory(ActivityIOFactory.CreatePathFromString(path, user, pass, privateKeyFile));

                if(allDirs.Count == 0)
                {
                    // delete path ;)
                    foreach(var file in allFiles)
                    {
                        DeleteOp(file);
                    }
                    IActivityIOPath tmpPath = ActivityIOFactory.CreatePathFromString(path, user, pass, privateKeyFile);
                    DeleteOp(tmpPath);
                    addBack = false;
                }
                else
                {
                    // more dirs to process 
                    pathStack = pathStack.Union(allDirs.Select(ioPath => ioPath.Path)).ToList();
                }

                DeleteHandler(pathStack, user, pass, privateKeyFile);

                if(addBack)
                {
                    // remove the dir now all its sub-dirs are gone ;)
                    DeleteHandler(new List<string> { path }, user, pass, privateKeyFile);
                }
            }
        }
        public void RetriveData()
        {
            //该用户所属角色
            SysRole sysRole = bizSysRole.ListSysRoleByUserID(UserId.Value);

            //该用户可以访问的所有菜单
            IList<SysMenu> userTypeVisitMenu = bizSysMenu.ListSysMenuByUserTypeID(sysRole == null ? Guid.Empty : sysRole.UserTypeID.Value);

            //该用户角色可以访问的所有菜单
            IList<SysMenu> userRoleMenu = bizSysMenu.ListSysMenuBySysRoleID(sysRole == null ? Guid.Empty : sysRole.ID).Where(x=>userTypeVisitMenu.Select(y=>y.ID).Contains(x.ID)).ToList();

            //该用户可以访问的菜单
            UserMenu = bizSysMenu.ListSysMenuByUserId(UserId.Value).Distinct().ToList().Where(x=>userTypeVisitMenu.Select(y=>y.ID).Contains(x.ID)).ToList();

            //用户已分配权限菜单
            AssignedRoleMenu = UserMenu.Union(userRoleMenu).ToList();

            //用户未分配权限菜单
            NonAssignedRoleMenu = userTypeVisitMenu.Where(x => !AssignedRoleMenu.Select(s => s.ID).Contains(x.ID)).ToList();

            //所有菜单

            IList<SysMenu> MenuList = bizSysMenu.ListBy(ReflectionTools.SerializeExpression<SysMenu>(x => x.Level.Value == 1 || x.Level.Value == 2));

            // 未分配权限父节点
            NonAssignedRoleMenuParent = GetSysMenuParentID(MenuList, NonAssignedRoleMenu);

            //已分配权限父节点
            AssignedRoleMenuParent = GetSysMenuParentID(MenuList, AssignedRoleMenu);
        }
        public async Task<IList<JiraIssue>> UpdateCache(IList<JiraIssue> updatedIssues)
        {
            if (_jiraUrl == "demo")
                return updatedIssues;

            try
            {
                if (IsAvailable == false)
                    InitializeCacheDirectory();

                var cachedItems = await LoadIssuesFromCache();

                var updatedCache = (await Task.Factory.StartNew(() => updatedIssues.Union(cachedItems))).ToList();

                await DumpCache(updatedCache);
                await StoreMetafile();

                return updatedCache;
            }
            catch (Exception e)
            {
                _logger.Warn(e, "Cache update failed");
                throw new CacheCorruptedException();
            }
        }
        protected virtual Expression AnalyzeCall(MethodCallExpression expression, IList<Expression> parameters, TranslationContext context)
        {
            var operands = expression.GetOperands().ToList();
            var operarandsToSkip = expression.Method.IsStatic ? 1 : 0;
            var originalParameters = operands.Skip(parameters.Count + operarandsToSkip);
            var newParameters = parameters.Union(originalParameters).ToList();

            var dt = expression.Method.DeclaringType;
            if(dt == typeof(Queryable) || dt == typeof(Enumerable))
              return AnalyzeQueryableCall(expression.Method, newParameters, context);
            if(dt == typeof(Vita.Entities.EntityQueryExtensions))
              return AnalyzeQueryExtensionsCall(expression.Method, newParameters, context);
            if(dt == typeof(string))
              return AnalyzeStringCall(expression.Method, newParameters, context);
            if(dt == typeof(Math))
              return AnalyzeMathCall(expression.Method, newParameters, context);
            return AnalyzeUnknownCall(expression, newParameters, context);
        }
        public void PrepareForUpdateChildrenMasterPages(PageProperties page, Guid? masterPageId, out IList<Guid> newMasterIds, out IList<Guid> oldMasterIds, out IList<Guid> childrenPageIds, out IList<MasterPage>  existingChildrenMasterPages)
        {
            if ((page.MasterPage != null && page.MasterPage.Id != masterPageId) || (page.MasterPage == null && masterPageId.HasValue))
            {
                newMasterIds = masterPageId.HasValue ? GetPageMasterPageIds(masterPageId.Value) : new List<Guid>(0);

                oldMasterIds = page.MasterPage != null && page.MasterPages != null ? page.MasterPages.Select(mp => mp.Master.Id).Distinct().ToList() : new List<Guid>(0);

                var intersectingIds = newMasterIds.Intersect(oldMasterIds).ToArray();
                foreach (var id in intersectingIds)
                {
                    oldMasterIds.Remove(id);
                    newMasterIds.Remove(id);
                }

                var updatingIds = newMasterIds.Union(oldMasterIds).Distinct().ToList();
                existingChildrenMasterPages = GetChildrenMasterPagesToUpdate(page, updatingIds, out childrenPageIds);
            }
            else
            {
                newMasterIds = null;
                oldMasterIds = null;
                childrenPageIds = null;
                existingChildrenMasterPages = null;
            }
        }
Example #25
0
        /// <summary>
        /// This method checks if the character has card combination "Straight"
        /// </summary>
        /// <param name="charactersCardsCollection">The collection of cards in the characters hand.</param>
        /// <param name="tableCardsCollection">The collection of cards on the table.</param>
        /// <param name="character">The character that holds the cards.</param>
        /// <returns><c>true</c> if the character has a Straight, <c>false</c> if they don't.</returns>     
        private bool CheckForStraight(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection,
            ICharacter character)
        {
            List<ICard> joinedCardCollection =
                charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();
            joinedCardCollection = new List<ICard>(joinedCardCollection.OrderByDescending(x => x.Rank));
            List<int> distinctCardRanks = joinedCardCollection.Select(x => (int)x.Rank).Distinct().OrderByDescending(x => x).ToList();

            int endBorderOfStraight = 4; // if a number is the beginning of a straight, then the end is '4' numbers later (straight must be 5 cards))
            bool hasStraight = false;
            double power = 0;

            for (int currentCardIndex = 0; currentCardIndex < distinctCardRanks.Count - endBorderOfStraight; currentCardIndex++)
            {
                if (distinctCardRanks[currentCardIndex] - endBorderOfStraight == distinctCardRanks[currentCardIndex + endBorderOfStraight])
                {
                    hasStraight = true;
                    int highestCardInStraight = distinctCardRanks[currentCardIndex];
                    power = highestCardInStraight + Constants.StraightBehaviourPower * 100;
                    break;
                }
            }

            if (hasStraight)
            {
                List<ICard> straightCombinationCards = new List<ICard>();

                foreach (int distinctRank in distinctCardRanks)
                {
                    ICard cardToBeAdded = joinedCardCollection.Find(card => (int)card.Rank == distinctRank);
                    straightCombinationCards.Add(cardToBeAdded);
                }
                IList<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination =
                    joinedCardCollection.Where(x => !straightCombinationCards.Contains(x)).ToList();

                RegisterCombination(character, power, straightCombinationCards,
                    theOtherCardsFromTheHandNotIncludedInTheCombination, CombinationType.Straight,
                    Constants.StraightBehaviourPower);
            }

            return hasStraight;
        }
Example #26
0
        private DelegateDefinition GetExistingDelegate(IList<string> libraries, string delegateString)
        {
            if (libraries.Count == 0)
                return Context.Delegates.Values.FirstOrDefault(t => t.Signature == delegateString);

            DelegateDefinition @delegate = null;
            if (libraries.Union(
                Context.Symbols.Libraries.Where(l => libraries.Contains(l.FileName)).SelectMany(
                    l => l.Dependencies)).Any(l => libsDelegates.ContainsKey(l) &&
                        libsDelegates[l].TryGetValue(delegateString, out @delegate)))
                return @delegate;

            return null;
        }
Example #27
0
        /// <summary>
        /// This method checks if the character has card combination "Flush"
        /// </summary>
        /// <param name="charactersCardsCollection">The collection of cards in the characters hand.</param>
        /// <param name="tableCardsCollection">The collection of cards on the table.</param>
        /// <param name="character">The character that holds the cards.</param>
        /// <returns><c>true</c> if the character has a Flush, <c>false</c> if they don't.</returns>
        private bool CheckForFlush(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection,
            ICharacter character)
        {
            List<ICard> joinedCardCollection =
                charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            bool hasFlush = false;
            int requiredCardsForFlush = 5;

            List<ICard> cardsThatMakeUpFlush = new List<ICard>();

            foreach (ICard card in joinedCardCollection)
            {
                List<ICard> sameSuitCardsCollection = joinedCardCollection.Where(x => x.Suit == card.Suit).ToList();

                if (sameSuitCardsCollection.Count >= requiredCardsForFlush)
                {
                    hasFlush = true;
                    cardsThatMakeUpFlush = sameSuitCardsCollection;
                    break;
                }
            }
            if (hasFlush)
            {
                List<ICard> tableCardsThatMakeUpFlush = cardsThatMakeUpFlush;

                tableCardsThatMakeUpFlush.RemoveAll(x => charactersCardsCollection.Contains(x));

                if (tableCardsThatMakeUpFlush.Count == requiredCardsForFlush)
                {
                    return CheckForFlushIfTableCardsMakeFlush(charactersCardsCollection, tableCardsThatMakeUpFlush, joinedCardCollection,
                        character);
                }
                else
                {
                    if (cardsThatMakeUpFlush.Count > requiredCardsForFlush)
                    {
                        int lowestCardInFlush = (int)cardsThatMakeUpFlush.Min(x => x.Rank);
                        cardsThatMakeUpFlush.RemoveAll(x => (int)x.Rank == lowestCardInFlush);
                    }

                    int highestCardInFlush = (int)cardsThatMakeUpFlush.Max(x => x.Rank);
                    double currentFlushBehaviourPower = Constants.LittleFlushBehaviourPower;

                    //Check if character has Ace in his hand that is part of the flush
                    //If they do -> the behaviour power is different (greater)
                    foreach (ICard card in charactersCardsCollection)
                    {
                        if (card.Suit == cardsThatMakeUpFlush[0].Suit && card.Rank == CardRank.Ace)
                        {
                            currentFlushBehaviourPower = Constants.BigFlushBehaviourPower;
                        }
                    }

                    double power = highestCardInFlush + currentFlushBehaviourPower * 100;
                    List<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination =
                        joinedCardCollection.Where(x => !cardsThatMakeUpFlush.Contains(x)).ToList();

                    RegisterCombination(character, power, cardsThatMakeUpFlush, theOtherCardsFromTheHandNotIncludedInTheCombination, CombinationType.Flush, currentFlushBehaviourPower);
                }
            }
            return hasFlush;
        }
 private void activatePackages(IList<IPackageInfo> packages, IList<IActivator> discoveredActivators)
 {
     var discoveredPlusRegisteredActivators = discoveredActivators.Union(_activators);
     _diagnostics.LogExecutionOnEach(discoveredPlusRegisteredActivators,
                                     activator => activator.Activate(packages, _diagnostics.LogFor(activator)));
 }
Example #29
0
        /// <summary>
        /// This method cheks for forur of a kind combination
        /// </summary>
        /// <param name="charactersCardsCollection">
        /// Cards in player's hand
        /// </param>
        /// <param name="tableCardsCollection">
        /// Cards on table
        /// </param>
        /// <param name="character">
        /// player whose cards are checked
        /// </param>
        /// <returns></returns>
        private bool CheckForFourOfAKind(
            IList<ICard> charactersCardsCollection,
            IList<ICard> tableCardsCollection,
            ICharacter character)
        {
            IList<ICard> joinedCardCollection =
                charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            foreach (var element in joinedCardCollection)
            {
                IList<ICard> sameRankCardsCollection = joinedCardCollection.Where(x => x.Rank == element.Rank).ToList();

                if (sameRankCardsCollection.Count == 4)
                {
                    double power = (int)sameRankCardsCollection[0].Rank * 4 + FourOfAKindBehaviourPower * 100;

                    IList<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination =
                        joinedCardCollection.Where(x => !sameRankCardsCollection.Contains(x)).ToList();

                    RegisterCombination(character, power, sameRankCardsCollection, theOtherCardsFromTheHandNotIncludedInTheCombination, CombinationType.FourOfAKind, Constants.FourOfAKindBehavourPower);

                    return true;
                }
            }
            return false;
        }