コード例 #1
0
        /// <summary>
        /// Get all factors that match search criteria.
        /// </summary>
        /// <param name="factorIds">Factors to filter on.</param>
        /// <param name="factorNameSearchString">String to match factor names with.</param>
        /// <param name="nameSearchMethod">How search should be performed.</param>
        /// <param name="restrictSearchToScope">Indicates scope of factor search.</param>
        /// <param name="restrictReturnToScope">Indicates scope for returned factors.</param>
        /// <returns>Filtered factors.</returns>
        public DataReader GetFactorsBySearchCriteria(List <Int32> factorIds,
                                                     String factorNameSearchString,
                                                     String nameSearchMethod,
                                                     String restrictSearchToScope,
                                                     String restrictReturnToScope)
        {
            SqlCommandBuilder commandBuilder;

            commandBuilder = new SqlCommandBuilder("GetFactorsByIdsAndSearchCriteria", true);
            if (factorIds.IsNotEmpty())
            {
                commandBuilder.AddParameter(FactorData.FACTOR_IDS, factorIds);
            }

            if (factorNameSearchString.IsNotEmpty())
            {
                commandBuilder.AddParameter(FactorData.FACTOR_NAME_SEARCH_STRING, factorNameSearchString);
            }

            commandBuilder.AddParameter(FactorData.FACTOR_NAME_SEARCH_METHOD, nameSearchMethod);
            commandBuilder.AddParameter(FactorData.IS_FACTOR_IDS_SPECIFIED, factorIds.IsNotEmpty());
            commandBuilder.AddParameter(FactorData.RESTRICT_SEARCH_TO_SCOPE, restrictSearchToScope);
            commandBuilder.AddParameter(FactorData.RESTRICT_RETURN_TO_SCOPE, restrictReturnToScope);
            return(GetReader(commandBuilder));
        }
コード例 #2
0
        /// <summary>
        /// This method updates child views and clears the batch of events. We cancel and
        /// old callback and schedule a new callback at this time if there were events in
        /// the batch.
        /// </summary>
        /// <param name="isFromSchedule">true if invoked from a schedule, false if not</param>
        protected void SendBatch(bool isFromSchedule)
        {
            // No more callbacks scheduled if called from a schedule
            if (isFromSchedule)
            {
                _callbackScheduledTime = null;
            }
            else
            {
                // Remove schedule if called from on overflow due to number of events
                if (_callbackScheduledTime != null)
                {
                    _agentInstanceContext.StatementContext.SchedulingService.Remove(_handle, _scheduleSlot);
                    _callbackScheduledTime = null;
                }
            }

            // If there are child views and the batch was filled, fireStatementStopped Update method
            if (HasViews)
            {
                // Convert to object arrays
                EventBean[] newData = null;
                EventBean[] oldData = null;
                if (_currentBatch.IsNotEmpty())
                {
                    newData = _currentBatch.ToArray();
                }
                if ((_lastBatch != null) && (_lastBatch.IsNotEmpty()))
                {
                    oldData = _lastBatch.ToArray();
                }

                // Post new data (current batch) and old data (prior batch)
                if (_viewUpdatedCollection != null)
                {
                    _viewUpdatedCollection.Update(newData, oldData);
                }
                if ((newData != null) || (oldData != null) || (_isForceOutput))
                {
                    using (Instrument.With(
                               i => i.QViewIndicate(this, _timeLengthBatchViewFactory.ViewName, newData, oldData),
                               i => i.AViewIndicate()))
                    {
                        UpdateChildren(newData, oldData);
                    }
                }
            }

            // Only if there have been any events in this or the last interval do we schedule a callback,
            // such as to not waste resources when no events arrive.
            if (((_currentBatch.IsNotEmpty()) || ((_lastBatch != null) && (_lastBatch.IsNotEmpty()))) || (_isForceOutput))
            {
                ScheduleCallback(0);
            }

            // Flush and roll
            _lastBatch    = _currentBatch;
            _currentBatch = new List <EventBean>();
        }
コード例 #3
0
        public void IsNotEmpty()
        {
            var @this = new List <string>();

            var value1 = @this.IsNotEmpty();

            @this.Add("Fizz");
            var value2 = @this.IsNotEmpty();

            Assert.IsFalse(value1);
            Assert.IsTrue(value2);
        }
コード例 #4
0
        public JsonResult Save(List <Reservation> reservations, string date, int?dealerId)
        {
            try
            {
                var reservationsInDataBase = _reservationService.Filter(new ReservationFilter {
                    Date = date, DealerId = dealerId.GetValue(), WithoutDealer = dealerId.GetValue().IsEqualToZero()
                }).Reservations;
                var reservationsByCreate = new List <Reservation>();
                var reservationsByUpdate = new List <Reservation>();
                var reservationsByDelete = new List <Reservation>();

                if (reservations.IsNotEmpty() && reservationsInDataBase.IsNotEmpty())
                {
                    reservationsByCreate.AddRange(reservations.Where(x => !reservationsInDataBase.Any(y => y.SaucerId == x.SaucerId && y.MealType == x.MealType)));
                    reservationsByUpdate.AddRange(reservations.Where(x => reservationsInDataBase.Any(y => y.SaucerId == x.SaucerId && y.MealType == x.MealType)));
                    reservationsByDelete.AddRange(reservationsInDataBase.Where(x => !reservations.Any(y => y.SaucerId == x.SaucerId && y.MealType == x.MealType)));
                }

                if (reservations.IsNotEmpty() && reservationsInDataBase.IsEmpty())
                {
                    reservationsByCreate.AddRange(reservations);
                }

                if (reservations.IsEmpty() && reservationsInDataBase.IsNotEmpty())
                {
                    reservationsByDelete.AddRange(reservationsInDataBase);
                }

                foreach (var reservationByCreate in reservationsByCreate)
                {
                    _reservationService.Create(reservationByCreate);
                }

                foreach (var reservationByUpdate in reservationsByUpdate)
                {
                    reservationByUpdate.Id = reservationsInDataBase.First(x => x.SaucerId.IsEqualTo(reservationByUpdate.SaucerId) && x.MealType.IsEquals(reservationByUpdate.MealType)).Id;
                    _reservationService.Update(reservationByUpdate);
                }

                foreach (var reservationByDelete in reservationsByDelete)
                {
                    _reservationService.Delete(reservationByDelete.Id);
                }


                return(new JsonFactory().Success(MessageConstants.Save));
            }
            catch (Exception e)
            {
                return(new JsonFactory().Failure(e.GetType(), e.Message));
            }
        }
コード例 #5
0
        /// <summary>
        /// Get all factor tree nodes that match search criteria.
        /// </summary>
        /// <param name="factorIds">Factors to filter on.</param>
        /// <returns>Factor tree nodes.</returns>
        public DataReader GetFactorTreesBySearchCriteria(List <Int32> factorIds)
        {
            SqlCommandBuilder commandBuilder;

            commandBuilder = new SqlCommandBuilder("GetFactorTreesByIdsAndSearchCriteria", true);
            if (factorIds.IsNotEmpty())
            {
                commandBuilder.AddParameter(FactorTreeData.FACTOR_IDS, factorIds);
            }

            commandBuilder.AddParameter(FactorTreeData.IS_FACTOR_IDS_SPECIFIED, factorIds.IsNotEmpty());
            return(GetReader(commandBuilder, CommandBehavior.Default));
        }
コード例 #6
0
ファイル: StackSlim.cs プロジェクト: nagyist/datavault
        public T Pop()
        {
            _impl.IsNotEmpty().AssertTrue();
            var popt = _impl.Last();

            _impl.RemoveAt(_impl.Count - 1);

            if (ItemPopped != null)
            {
                ItemPopped.Invoke(this, new StackItemEventArgs <T>(popt));
            }
            return(popt);
        }
コード例 #7
0
        public void TestIsEmptyAndIsNotEmpty()
        {
            List <int> enumerable = null;

            Assert.IsTrue(enumerable.IsEmpty());
            Assert.IsFalse(enumerable.IsNotEmpty());
            enumerable = new List <int>();
            Assert.IsTrue(enumerable.IsEmpty());
            Assert.IsFalse(enumerable.IsNotEmpty());
            enumerable.Add(0);
            Assert.IsFalse(enumerable.IsEmpty());
            Assert.IsTrue(enumerable.IsNotEmpty());
        }
コード例 #8
0
        public void IsNotEmpty()
        {
            // Type
            var @this = new List <string>();

            // Examples
            bool value1 = @this.IsNotEmpty(); // return false;

            @this.Add("Fizz");
            bool value2 = @this.IsNotEmpty(); // return true;

            // Unit Test
            Assert.IsFalse(value1);
            Assert.IsTrue(value2);
        }
コード例 #9
0
        public void Test_Emptiness_Of_An_Empty_IReadOnlyCollection()
        {
            ICollection <char> collection = new List <char>();

            collection.IsEmpty().Should().BeTrue();
            collection.IsNotEmpty().Should().BeFalse();
        }
        /// <summary>
        /// Get max species observation access rights.
        /// </summary>
        /// <param name="roles">Current roles.</param>
        /// <returns>Max species observation access rights.</returns>
        public static Int32 GetMaxProtectionLevelSimpleSpeciesObservationAccessRights(this List <WebRole> roles)
        {
            Int32 maxProtectionLevel;

            maxProtectionLevel = 1;
            if (roles.IsNotEmpty())
            {
                foreach (WebRole role in roles)
                {
                    if (role.Authorities.IsNotEmpty())
                    {
                        foreach (WebAuthority authority in role.Authorities)
                        {
                            if ((authority.Identifier == AuthorityIdentifier.Sighting.ToString()) &&
                                IsSimpleSpeciesObservationAccessRights(authority))
                            {
                                maxProtectionLevel = Math.Max(maxProtectionLevel,
                                                              authority.MaxProtectionLevel);
                            }
                        }
                    }
                }
            }

            return(maxProtectionLevel);
        }
        /// <summary>
        /// Convert points from one coordinate system to
        /// another coordinate system.
        /// </summary>
        /// <param name="points">Points that should be converted.</param>
        /// <param name="fromCoordinateSystem">From coordinate system.</param>
        /// <param name="toCoordinateSystem">To coordinate system.</param>
        /// <returns>Points with coordinates according to toCoordinateSystem</returns>
        public virtual List <IPoint> GetConvertedPoints(List <IPoint> points,
                                                        ICoordinateSystem fromCoordinateSystem,
                                                        ICoordinateSystem toCoordinateSystem)
        {
            Int32 pointIndex;
            ICoordinateTransformation transformator;
            List <double[]>           fromPointsValues, toPointsValues;
            List <IPoint>             toPoints;

            toPoints = new List <IPoint>();
            if (points.IsNotEmpty())
            {
                fromPointsValues = new List <double[]>();
                for (pointIndex = 0; pointIndex < points.Count; pointIndex++)
                {
                    fromPointsValues.Add(new double[] { points[pointIndex].X, points[pointIndex].Y });
                }

                transformator  = GetTransformator(fromCoordinateSystem, toCoordinateSystem);
                toPointsValues = transformator.MathTransform.TransformList(fromPointsValues);
                toPoints       = new List <IPoint>();
                for (pointIndex = 0; pointIndex < points.Count; pointIndex++)
                {
                    toPoints.Add(new Point(toPointsValues[pointIndex][0], toPointsValues[pointIndex][1]));
                }
            }

            return(toPoints);
        }
コード例 #12
0
        /// <summary>
        /// Get child taxon ids.
        /// Parent taxon ids are included in the result.
        /// Only valid taxon relations and child taxa are included.
        /// This method only works in web services that
        /// handles species observations.
        /// </summary>
        /// <param name="context">Web service request context.</param>
        /// <param name="parentTaxonIds">Parent taxon ids.</param>
        /// <returns>Child taxon ids.</returns>
        public virtual List <Int32> GetChildTaxonIds(WebServiceContext context,
                                                     List <Int32> parentTaxonIds)
        {
            DataIdInt32List childTaxonIds;
            Dictionary <Int32, DataIdInt32List> taxonTreeRelations;

            childTaxonIds = new DataIdInt32List();
            if (parentTaxonIds.IsNotEmpty())
            {
                taxonTreeRelations = GetTaxonTreeRelations(context);
                foreach (Int32 taxonId in parentTaxonIds)
                {
                    if (taxonTreeRelations.ContainsKey(taxonId))
                    {
                        childTaxonIds.Merge(taxonTreeRelations[taxonId]);
                    }
                    else
                    {
                        childTaxonIds.Merge(taxonId);
                    }
                }
            }

            return(childTaxonIds.GetInt32List());
        }
コード例 #13
0
        /// <summary>
        /// Get all child taxa.
        /// Parent taxa are also included in the result.
        /// </summary>
        /// <param name="context">Web service request context.</param>
        /// <param name="parentTaxonGuids">GUIDs for parent taxa.</param>
        /// <returns>All child taxa.</returns>
        private List <WebTaxon> GetChildTaxaByGuids(WebServiceContext context,
                                                    List <String> parentTaxonGuids)
        {
            List <Int32>           parentTaxonIds;
            WebTaxonSearchCriteria searchCriteria;

            // Convert taxon GUIDs to taxon ids.
            parentTaxonIds = new List <Int32>();
            if (parentTaxonGuids.IsNotEmpty())
            {
                foreach (String parentTaxonGuid in parentTaxonGuids)
                {
                    // TODO: This assumption about taxon GUIDs may
                    // change in the future.
                    parentTaxonIds.Add(parentTaxonGuid.WebParseInt32());
                }
            }

            // Create search criteria.
            searchCriteria = new WebTaxonSearchCriteria();
            searchCriteria.IsIsValidTaxonSpecified = true;
            searchCriteria.IsValidTaxon            = true;
            searchCriteria.Scope    = TaxonSearchScope.AllChildTaxa;
            searchCriteria.TaxonIds = parentTaxonIds;

            // Get child taxa.
            return(GetTaxaBySearchCriteria(context, searchCriteria));
        }
コード例 #14
0
        /// <summary>
        /// Delete species facts.
        /// </summary>
        /// <param name="context">Web service request context.</param>
        /// <param name="deleteSpeciesFacts">Existing species facts to delete.</param>
        public static void DeleteSpeciesFacts(WebServiceContext context,
                                              List <WebSpeciesFact> deleteSpeciesFacts)
        {
            DataTable    speciesFactTable;
            List <Int32> speciesFactIds;

            // Check transaction.
            context.CheckTransaction();

            // Check authorization.
            WebServiceData.AuthorizationManager.CheckAuthorization(context, AuthorityIdentifier.EditSpeciesFacts);

            // Check arguments.
            deleteSpeciesFacts.CheckData();

            if (deleteSpeciesFacts.IsNotEmpty())
            {
                // Update species facts.
                speciesFactTable = GetSpeciesFactUpdateTable(context, deleteSpeciesFacts);
                context.GetTaxonAttributeDatabase().UpdateSpeciesFacts(speciesFactTable);

                // Delete species facts.
                speciesFactIds = deleteSpeciesFacts.GetIds();
                context.GetTaxonAttributeDatabase().DeleteSpeciesFactsByIds(speciesFactIds);
            }
        }
コード例 #15
0
    // Borrowed http://answers.unity.com/answers/1133912/view.html with some changes.
    private bool IsTouchingUICalculate()
    {
        if (AlreadyTouchingUICalcualted)
        {
            return(IsTouchingUICalcualted);
        }

        if (EventSystem.current == null)
        {
            Debug.LogWarning("IsTouchingUI: EventSystem MISSING! Cannot calculate if touching UI.");
            return(false);
        }

        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);

        eventDataCurrentPosition.position = ScreenPosition;

        var results = new List <RaycastResult>();

        EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
        IsTouchingUICalcualted      = results.IsNotEmpty();
        AlreadyTouchingUICalcualted = true;

        return(IsTouchingUICalcualted);
    }
コード例 #16
0
        public void Test_IsNotEmpty_ForEmptyLit()
        {
            var input  = new List <int>();
            var actual = input.IsNotEmpty();

            Assert.False(actual);
        }
コード例 #17
0
        public Uri Build()
        {
            var builder = new StringBuilder(_baseUrl);

            if (_sections.IsNotEmpty())
            {
                var sections = string.Join("/", _sections);

                if (!_baseUrl.EndsWith("/"))
                {
                    builder.Append("/");
                }

                builder.Append(sections);
            }

            if (_parameters.IsNotEmpty())
            {
                var parameters = _parameters.Select(CreateParameter);

                builder
                .Append("?")
                .Append(string.Join("&", parameters));
            }

            if (Uri.TryCreate(builder.ToString(), UriKind.Absolute, out var uri))
            {
                return(uri);
            }

            throw new InvalidOperationException("Не удалось создать Url.");
        }
コード例 #18
0
        /// <summary>
        /// Get regions that matches the search criteria.
        /// </summary>
        /// <param name="nameSearchString">Name search string.</param>
        /// <param name="typeId">Id of type to search for.</param>
        /// <param name="categoryIds">Category ids.</param>
        /// <param name="countryIsoCodes">The country iso codes.</param>
        /// <returns>
        /// Returns an open DataReader. Remember to close the
        /// DataReader after reading has been finished.
        /// </returns>
        public DataReader GetRegionsBySearchCriteria(String nameSearchString,
                                                     Int32?typeId,
                                                     List <Int32> categoryIds,
                                                     List <Int32> countryIsoCodes)
        {
            SqlCommandBuilder commandBuilder;

            // Use SqlCommandBuilder with SqlParameter
            commandBuilder = new SqlCommandBuilder("GetRegionsBySearchCriteria", true);
            if (nameSearchString.IsNotEmpty())
            {
                commandBuilder.AddParameter(RegionData.NAME, nameSearchString, 1);
            }
            if (typeId.HasValue)
            {
                commandBuilder.AddParameter(RegionData.TYPE_ID, typeId.Value);
            }
            if (categoryIds.IsNotEmpty())
            {
                commandBuilder.AddParameter(RegionData.CATEGORY_IDS, categoryIds);
            }
            if (countryIsoCodes.IsNotEmpty())
            {
                commandBuilder.AddParameter(RegionData.COUNTRY_ISO_CODES, countryIsoCodes);
            }
            return(GetReader(commandBuilder));
        }
コード例 #19
0
        /// <summary>
        /// Update species observations.
        /// </summary>
        /// <param name="context">Web service request context.</param>
        /// <param name="speciesObservations">Updated species observations.</param>
        /// <param name="dataProvider">The dataProvider.</param>
        /// <param name="connectorServer">The connector server.</param>
        /// <param name="mappings">The mappings.</param>
        /// <param name="noOfUpdated">No of updated species observations.</param>
        /// <param name="noOfUpdatedErrors">No of updating errors.</param>
        public void UpdateSpeciesObservations(WebServiceContext context,
                                              List <WebData> speciesObservations,
                                              WebSpeciesObservationDataProvider dataProvider,
                                              IConnectorServer connectorServer,
                                              List <HarvestMapping> mappings,
                                              out int noOfUpdated,
                                              out int noOfUpdatedErrors)
        {
            noOfUpdated       = 0;
            noOfUpdatedErrors = 0;
            ArtportalenProcess artportalenProcess = new ArtportalenProcess();

            if (speciesObservations.IsNotEmpty())
            {
                List <HarvestSpeciesObservation> updatedSpeciesObservations = new List <HarvestSpeciesObservation>();
                for (Int32 index = speciesObservations.Count - 1; index >= 0; index--)
                {
                    HarvestSpeciesObservation harvestSpeciesObservation = artportalenProcess.ProcessObservation(speciesObservations[index], mappings, context);
                    updatedSpeciesObservations.Add(harvestSpeciesObservation);
                    speciesObservations.RemoveAt(index);
                    if (updatedSpeciesObservations.Count >= 10000)
                    {
                        break;
                    }
                }

                connectorServer.UpdateSpeciesObservations(context,
                                                          updatedSpeciesObservations,
                                                          dataProvider,
                                                          out noOfUpdated,
                                                          out noOfUpdatedErrors);
            }
        }
コード例 #20
0
        /// <summary>
        /// Convert a WebTaxonName array to a TaxonNameList.
        /// </summary>
        /// <param name="webTaxonNames">Web taxon names.</param>
        /// <returns>Taxon names.</returns>
        private static TaxonNameList GetTaxonNames(List <WebTaxonName> webTaxonNames)
        {
            DataFieldList dataFields;
            TaxonName     taxonName;
            TaxonNameList taxonNames = null;

            if (webTaxonNames.IsNotEmpty())
            {
                taxonNames = new TaxonNameList();
                foreach (WebTaxonName webTaxonName in webTaxonNames)
                {
                    dataFields = new DataFieldList(webTaxonName.Taxon.DataFields);
                    taxonName  = new TaxonName(webTaxonName.Id,
                                               webTaxonName.Taxon.Id,
                                               webTaxonName.TaxonNameTypeId,
                                               webTaxonName.TaxonNameUseTypeId,
                                               webTaxonName.Name,
                                               webTaxonName.Author,
                                               webTaxonName.IsRecommended);
                    taxonName.Taxon = new TaxonPrintObs(webTaxonName.Taxon.Id,
                                                        webTaxonName.Taxon.TaxonTypeId,
                                                        webTaxonName.Taxon.SortOrder,
                                                        webTaxonName.Taxon.TaxonInformationType,
                                                        webTaxonName.Taxon.ScientificName,
                                                        webTaxonName.Taxon.Author,
                                                        webTaxonName.Taxon.CommonName,
                                                        dataFields.GetString(TaxonPrintObs.PHYLUM_DATA_FIELD),
                                                        dataFields.GetString(TaxonPrintObs.CLASS_DATA_FIELD),
                                                        dataFields.GetString(TaxonPrintObs.ORDER_DATA_FIELD),
                                                        dataFields.GetString(TaxonPrintObs.FAMILY_DATA_FIELD));
                    taxonNames.Add(taxonName);
                }
            }
            return(taxonNames);
        }
コード例 #21
0
        /// <summary>
        /// Creates a new DataRow and adds it
        /// to the source DataTable for the supplied
        /// object.
        /// </summary>
        /// <typeparam name="T">Typed DataRow</typeparam>
        /// <param name="source">Object to add to the DataTable.</param>
        /// <param name="table">DataTable to add the row to.</param>
        /// <returns></returns>
        public static T AsDataRow <T>(
            this object source,
            DataTable table)
            where T : DataRow
        {
            source.AssertParameterNotNull(
                "Cannot convert a null source to a DataRow.",
                "source");

            table.AssertParameterNotNull(
                "Cannot add a DataRow to a null DataTable.",
                "table");

            T result = null;

            List <DataColumn> columns =
                MakeDataColumns(source);

            if (columns.IsNotEmpty())
            {
                table.AddColumnsToDataTable(columns);
                result = (T)table.NewRow();
                result.PopulateDataRow(source, columns);
                table.Rows.Add(result);
            }

            return(result);
        }
コード例 #22
0
        /// <summary>
        /// Pop <paramref name="count"/> items off of <paramref name="src"/>
        /// and add them to <paramref name="dest"/>.
        /// </summary>
        /// <param name="src">List to remove items from.</param>
        /// <param name="dest">List to add items to.</param>
        /// <param name="count">Number of items to drain. &lt;0 implies 'drain all'.</param>
        /// <returns>Actual number of items added to <paramref name="dest"/>.</returns>
        public static int DrainInto <T>(this List <T> src, List <T> dest, int count)
        {
            //validate
            if (src == null)
            {
                throw new ArgumentNullException(nameof(src));
            }
            if (dest == null)
            {
                throw new ArgumentNullException(nameof(dest));
            }

            //flag to drain all
            if (count < 0)
            {
                count = src.Count;
            }

            //ensure capacity
            if (dest.Capacity < Math.Min(count, src.Count))
            {
                dest.Capacity = count;
            }

            //work
            int i = 0;

            for (; i < count && src.IsNotEmpty(); ++i)
            {
                dest.Add(src.GetRemoveLast());
            }
            return(i);
        }
コード例 #23
0
        /// <summary>
        /// Get information about organizations.
        /// If organizationCategoryId is specified all organizations of that category are returned.
        /// If no organizationCategoryId is specified all organizations are returned.
        /// <param name="context">Web service request context.</param>
        /// <param name="organizationCategoryId">Organization category id.</param>
        /// </summary>
        /// <returns>
        /// Returns list of organizations or null if specified category
        /// has no organizations.
        /// </returns>
        private static List <WebOrganization> GetOrganizations(WebServiceContext context, Int32?organizationCategoryId)
        {
            WebOrganization        organization;
            List <WebOrganization> organizationList;

            // Get information from database.
            using (DataReader dataReader = context.GetUserDatabase().GetOrganizations(organizationCategoryId, context.Locale.Id))
            {
                organizationList = new List <WebOrganization>();
                while (dataReader.Read())
                {
                    organization          = new WebOrganization();
                    organization.Category = new WebOrganizationCategory();
                    organization.LoadData(dataReader);
                    organizationList.Add(organization);
                }
            }
            if (organizationList.IsNotEmpty())
            {
                foreach (WebOrganization tempOrganization in organizationList)
                {
                    // Get organizationCategory for this organization
                    tempOrganization.Category = GetOrganizationCategory(context, tempOrganization.CategoryId);
                    // Set WebAddress + WebPhone
                    tempOrganization.Addresses    = UserManager.GetAddresses(context, 0, tempOrganization.Id);
                    tempOrganization.PhoneNumbers = UserManager.GetPhoneNumbers(context, 0, tempOrganization.Id);
                }
            }
            return(organizationList);
        }
コード例 #24
0
        protected virtual void AssertValidName(string name)
        {
            var invalidChar = new List <string>();

            if (name.Contains(","))
            {
                invalidChar.Add("','");
            }
            //if (name.Contains(" "))
            //    invalidChar.Add("' '");
            if (name.Contains("*"))
            {
                invalidChar.Add("'*'");
            }
            if (name.Contains("?"))
            {
                invalidChar.Add("'?'");
            }
            if (invalidChar.IsNotEmpty())
            {
                throw new Exception(String.Format("{0} name cannot contain {1}.", this.GetType().Name, String.Join(",", invalidChar.ToArray())));
            }
            if (name.IsNullOrEmpty())
            {
                throw new Exception(String.Format("{0} name cannot empty.", this.GetType().Name));
            }
        }
コード例 #25
0
        public void IsEmptyTest()
        {
            // string
            string text = null;

            Assert.IsTrue(text.IsEmpty());
            text = "";
            Assert.IsTrue(text.IsEmpty());
            text = "aa";
            Assert.IsTrue(text.IsNotEmpty());

            // list
            List <string> arr = null;

            Assert.IsTrue(arr.IsEmpty());
            arr = new List <string> {
            };
            Assert.IsTrue(arr.IsEmpty());
            arr = new List <string> {
                "aa"
            };
            Assert.IsTrue(arr.IsNotEmpty());

            // object
            Person p = null;

            Assert.IsTrue(p.IsEmpty());
            p = new Person();
            Assert.IsTrue(p.IsNotEmpty());
        }
コード例 #26
0
        /// <summary>
        /// Get taxon ids for red listed taxa.
        /// </summary>
        /// <param name="context">Web service request context.</param>
        /// <param name="includeRedlistedTaxa">If true all red listed taxa should be returned.</param>
        /// <param name="redlistCategories">Taxa belonging to specified red list categories should be returned.</param>
        /// <returns>Requested red listed taxa.</returns>
        public List <Int32> GetRedlistedTaxonIds(WebServiceContext context,
                                                 Boolean includeRedlistedTaxa,
                                                 List <RedListCategory> redlistCategories)
        {
            Hashtable    redlistedTaxaInformation;
            List <Int32> redlistedTaxonIds;

            // Get cached information.
            redlistedTaxaInformation = GetRedlistedTaxa(context);

            if (includeRedlistedTaxa)
            {
                redlistedTaxonIds = (List <Int32>)(redlistedTaxaInformation[GetRedlistedTaxaCacheKey()]);
            }
            else
            {
                redlistedTaxonIds = new List <Int32>();
                if (redlistCategories.IsNotEmpty())
                {
                    foreach (RedListCategory redListCategory in redlistCategories)
                    {
                        redlistedTaxonIds.AddRange((List <Int32>)(redlistedTaxaInformation[GetRedlistedTaxaCacheKey(redListCategory)]));
                    }
                }
            }

            return(redlistedTaxonIds);
        }
コード例 #27
0
ファイル: Gamepad.cs プロジェクト: Vheos777/OutwardMods
        static private void SwitchToStash(Players.Data player)
        {
            if (EventSystem.current.GetCurrentSelectedGameObject(player.ID).TryGetComponent(out ItemDisplay currentItem) &&
                currentItem.m_refItem == null)
            {
                return;
            }

            // Cache
            ContainerDisplay   chest      = GetChestStashInventoryPanel(GetStashPanel(player.UI)).GetComponent <ContainerDisplay>();
            List <ItemDisplay> chestItems = chest.m_assignedDisplays;
            int currentID = chestItems.IndexOf(currentItem);

            // Execute
            if (currentID >= chestItems.Count - 1)
            {
                chestItems.First().OnSelect();
            }
            else if (currentID >= 0)
            {
                int nextID = currentID + chestItems.Count / 2;
                if (chestItems.IsIndexValid(nextID))
                {
                    chestItems[nextID].OnSelect();
                }
                else
                {
                    chestItems.Last().OnSelect();
                }
            }
            else if (chestItems.IsNotEmpty())
            {
                chestItems.First().OnSelect();
            }
        }
コード例 #28
0
        /// <summary>
        /// Get multi polygon list as string.
        /// </summary>
        /// <param name="polygons">Polygons that should be converted.</param>
        /// <returns>Multi polygon list as string.</returns>
        public static String WebToString(this List <WebMultiPolygon> multiPolygons)
        {
            Boolean       firstPolygon;
            StringBuilder stringBuilder;

            stringBuilder = new StringBuilder();
            if (multiPolygons.IsNotEmpty())
            {
                firstPolygon = true;
                stringBuilder.Append("[");
                foreach (WebMultiPolygon multiPolygon in multiPolygons)
                {
                    if (firstPolygon)
                    {
                        firstPolygon = false;
                    }
                    else
                    {
                        stringBuilder.Append(", ");
                    }

                    stringBuilder.Append(multiPolygon.WebToString());
                }

                stringBuilder.Append("]");
            }

            return(stringBuilder.ToString());
        }
コード例 #29
0
        /// <summary>
        /// Get a DataField with the specified name.
        /// </summary>
        /// <param name='dataFields'>The WebDataField list.</param>
        /// <param name='fieldName'>Name of field to get.</param>
        /// <param name='create'>If true, DataField is created if it was not found.</param>
        /// <param name='dataType'>Data type of the field. This parameter is only used if a field is created.</param>
        /// <exception cref="ArgumentException">Thrown if no field was found.</exception>
        private static WebDataField GetDataField(this List <WebDataField> dataFields,
                                                 String fieldName,
                                                 Boolean create,
                                                 WebDataType dataType)
        {
            if (dataFields.IsNotEmpty())
            {
                foreach (WebDataField dataField in dataFields)
                {
                    if (dataField.Name == fieldName)
                    {
                        return(dataField);
                    }
                }
            }

            if (create)
            {
                WebDataField dataField;

                dataField      = new WebDataField();
                dataField.Name = fieldName;
                dataField.Type = dataType;
                dataFields.Add(dataField);
                return(dataField);
            }
            else
            {
                // No field with specified name.
                throw new ArgumentException("No data field with name " + fieldName + "!");
            }
        }
コード例 #30
0
        static public IEnumerable <IEnumerable <T> > Chunk <T>(this IEnumerable <T> item, int chunk_size, bool is_strict)
        {
            if (item != null)
            {
                using (IEnumerator <T> iter = item.GetEnumerator())
                {
                    while (true)
                    {
                        List <T> chunk = new List <T>();
                        for (int i = 0; i < chunk_size; i++)
                        {
                            if (iter.MoveNext() == false)
                            {
                                if (is_strict == false)
                                {
                                    if (chunk.IsNotEmpty())
                                    {
                                        yield return(chunk);
                                    }
                                }

                                yield break;
                            }

                            chunk.Add(iter.Current);
                        }

                        yield return(chunk);
                    }
                }
            }
        }
コード例 #31
0
        public ViewModelFormAddSalon(List<Abonnement> abonnements = null)
        {
            Genre = new List<SelectListItem>
            {
               new SelectListItem { Value = "1", Text = "Homme" },
               new SelectListItem { Value = "2", Text = "Femme" }
            };

            Abonnement = new List<SelectListItem>();
            if (abonnements.IsNotEmpty())
            {
                CreateListeAbonnements(abonnements);
            }
        }
コード例 #32
0
 public ViewModelRegisterFranchise(List<Abonnement> abonnements = null)
 {
     Abonnement = new List<SelectListItem>();
     if (abonnements.IsNotEmpty())
     {
         CreateListeAbonnements(abonnements);
     }
 }
コード例 #33
0
        public void op_IsNotEmpty_IEnumerableEmpty()
        {
            var obj = new List<string>();

            Assert.False(obj.IsNotEmpty());
        }
コード例 #34
0
        public void op_IsNotEmpty_IEnumerable()
        {
            var obj = new List<string>
                          {
                              "item"
                          };

            Assert.True(obj.IsNotEmpty());
        }
コード例 #35
0
ファイル: MainModel.cs プロジェクト: Predica/FimExplorer
        public void ExecuteQuery()
        {
            var requiredAttributes = new List<SelectableAttribute>();

            // attributes selection is possible only when directly querying for type selected in the list
            // otherwise there is no smart/easy way to tell if queried object contains any of currently displayed attributes
            if (querying_selected_type())
            {
                if (CurrentAttributes.Any(x => x.IsSelected))
                {
                    requiredAttributes = CurrentAttributes.Where(x => x.IsSelected).ToList();
                }
                else
                {
                    requiredAttributes = CurrentAttributes.ToList();
                }

                if (requiredAttributes.None(x => x.Attribute.Name == RmResource.AttributeNames.ObjectID.Name))
                {
                    requiredAttributes.Add(CurrentAttributes.Single(x => x.Attribute.Name == RmResource.AttributeNames.ObjectID.Name));
                }
            }

            // empty array if querying for other type than selected => all attributes will be fetched
            var attributesToFetch = new AttributesToFetch(requiredAttributes.Select(x => x.Attribute.Name).ToArray());

            string query = XPath.Replace(Environment.NewLine, string.Empty);

            RmResource[] results = _parent.LongRunningOperation(_parent.loadingIndicator,
                () => _fimClient.EnumerateAll<RmResource>(query, attributesToFetch)
                    .ToArray()
                );

            DataTable table = new DataTable();

            if (results.IsNotEmpty())
            {
                // assuming that all results are of the same type
                var firstResult = results.First();
                var resultType = firstResult.GetResourceType();
                var resultTypeAttributes = firstResult.Attributes;

                SelectableAttribute[] fetchedAttributes;
                if (requiredAttributes.IsNotEmpty())
                {
                    fetchedAttributes = requiredAttributes.ToArray();
                }
                else
                {
                    FetchAttributesForObjectType(resultType);
                    fetchedAttributes = _attributesCache[resultType].ToArray();
                }

                var resultTableColumnNames = new List<string>();

                foreach (var a in resultTypeAttributes.OrderBy(x => x.Key.Name))
                {
                    var selectedAttribute = fetchedAttributes.SingleOrDefault(x => x.Attribute.Name == a.Key.Name);
                    if (selectedAttribute == null)
                    {
                        continue;
                    }

                    var column = table.Columns.Add(selectedAttribute.Attribute.DisplayName);
                    resultTableColumnNames.Add(selectedAttribute.Attribute.Name);

                    // window can detect references by their 'object' type as opposed to 'string' defined for all other fields
                    if (selectedAttribute.Attribute.DataType == RmFactory.RmAttributeType.Reference.ToString())
                    {
                        column.DataType = typeof(object);
                    }
                    else
                    {
                        column.DataType = typeof(string);
                    }
                }

                foreach (var resource in results)
                {
                    var newRowValues = resultTableColumnNames
                        .Select(x =>
                            {
                                if (resource.Attributes.Keys.Any(y => y.Name == x))
                                {
                                    return resource.Attributes.First(y => y.Key.Name == x)
                                        .Value.Value;
                                }
                                else
                                {
                                    return null;
                                }
                            })
                        .ToArray();

                    table.Rows.Add(newRowValues);
                }
            }

            QueriedValues = table;
        }
コード例 #36
0
        public bool CreateListeAbonnements(List<Abonnement> abonnements = null)
        {
            try
            {
                Abonnement = new List<SelectListItem>();
                if (abonnements.IsNotEmpty())
                {
                    foreach (var abonnement in abonnements)
                    {
                        Abonnement.Add(new SelectListItem
                        {
                            Value = abonnement.Id.ToString(),
                            Text = abonnement.Titre
                        });
                    }
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
コード例 #37
0
 private long GetMinConsumedMessageOffset(IEnumerable<QueueConsumedOffset> queueConsumedOffsets)
 {
     var messageOffsetList = new List<long>();
     foreach (var queueConsumedOffset in queueConsumedOffsets)
     {
         messageOffsetList.Add(GetMessageOffsetByQueueOffset(queueConsumedOffset.Topic, queueConsumedOffset.QueueId, queueConsumedOffset.ConsumedOffset));
     }
     if (messageOffsetList.IsNotEmpty())
     {
         return messageOffsetList.Min();
     }
     return -1L;
 }
コード例 #38
0
        protected CommandLineConfig(String[] s_args)
        {
            Log = Logger.Get(GetType());
            Log.MinLevel = Level.Info;

            if (s_args.Count() == 1 && s_args[0] == "/?")
            {
                Banners.About();
                throw new ConfigException(String.Empty);
            }
            else
            {
                if (s_args.LastOrDefault() == "/verbose")
                {
                    IsVerbose = true;
                    s_args = s_args.SkipLast().ToArray();

                    Info.WriteLine("Detected the \"/verbose\" switch, entering verbose mode.");
                    Log.MinLevel = Level.Debug;

                    Debug.EnsureBlankLine();
                    Debug.Write("Command line args are: ");
                    if (s_args.IsEmpty()) Debug.WriteLine("empty");
                    else Debug.WriteLine("({0} arg{1})", s_args.Count(), s_args.Count() == 1 ? "" : "s");
                    s_args.ForEach((arg, i) => Debug.WriteLine("{0}: {1}", i + 1, arg));
                }

                Debug.EnsureBlankLine();
                Debug.WriteLine("Pre-parsing arguments...");
                var named_args = new Dictionary<String, String>();
                var shortcut_args = new List<String>();
                foreach (var s_arg in s_args)
                {
                    var m = s_arg.Parse("^-(?<name>.*?):(?<value>.*)$");
                    var name = m != null ? m["name"] : null;
                    var value = m != null ? m["value"] : s_arg;
                    if (m != null) Debug.WriteLine("Parsed \"{0}\" as name/value pair: {1} => \"{2}\".", s_arg, name, value);
                    else Debug.WriteLine("Parsed \"{0}\" as raw value.", s_arg);

                    if (name == null)
                    {
                        if (named_args.IsNotEmpty()) throw new ConfigException("Fatal error: shortcut arguments must be specified before named arguments.");
                        else shortcut_args.Add(value);
                    }
                    else
                    {
                        if (named_args.ContainsKey(name)) throw new ConfigException("Fatal error: duplicate argument \"{0}\".", name);
                        else named_args.Add(name, value);
                    }
                }
                Debug.WriteLine("Pre-parse completed: found {0} named argument{1} and {2} shortcut argument{3}.",
                    named_args.Count(), named_args.Count() == 1 ? "" : "s",
                    shortcut_args.Count(), shortcut_args.Count() == 1 ? "" : "s");

                Debug.EnsureBlankLine();
                Debug.WriteLine("Parsing arguments...");

                var parsed_args = new Dictionary<PropertyInfo, Object>();
                if (named_args.IsNotEmpty())
                {
                    Debug.WriteLine("Parsing named arguments...");
                    parsed_args = ParseArgs(named_args);
                }

                if (shortcut_args.IsNotEmpty())
                {
                    Debug.WriteLine("Parsing shortcut arguments...");

                    Dictionary<PropertyInfo, Object> parsed_shortcut_args = null;
                    var shortcuts = GetType().Attrs<ShortcutAttribute>().OrderBy(shortcut => shortcut.Priority);
                    var bind_errors = new Dictionary<String, String>();
                    foreach (var shortcut in shortcuts)
                    {
                        Debug.WriteLine("Considering shortcut schema \"{0}\"...", shortcut.Schema);
                        var words = shortcut.Schema.SplitWords();
                        if (words.Count() != shortcut_args.Count())
                        {
                            var message = String.Format("argument count mismatch.");
                            bind_errors.Add(shortcut.Schema, message);
                            Debug.WriteLine("Schema \"{0}\" won't work: {1}", shortcut.Schema, message);
                            continue;
                        }

                        try { parsed_shortcut_args = ParseArgs(words.Zip(shortcut_args).ToDictionary(t => t.Item1, t => t.Item2)); }
                        catch (ConfigException cex)
                        {
                            bind_errors.Add(shortcut.Schema, cex.Message);
                            Debug.WriteLine(cex.Message);
                            Debug.WriteLine("Schema \"{0}\" won't work: failed to parse arguments.", shortcut.Schema);

                            continue;
                        }

                        var dupes = Set.Intersect(parsed_args.Keys, parsed_shortcut_args.Keys);
                        if (dupes.IsNotEmpty())
                        {
                            var a = dupes.AssertFirst().Attr<ParamAttribute>();
                            var name = named_args.Keys.Single(k => a.Aliases.Contains(k));
                            Debug.WriteLine("Schema \"{0}\" won't work: shortcut argument duplicates parsed argument \"{1}\".", shortcut.Schema, name);
                            parsed_shortcut_args = null;
                            continue;
                        }
                        else
                        {
                            Debug.WriteLine("Schema \"{0}\" works fine, skipping other schemas (if any).", shortcut.Schema);
                            break;
                        }
                    }

                    if (parsed_shortcut_args == null)
                    {
                        var message = "Fatal error: failed to match the shortcuts.";
                        var bind_summary = bind_errors.Select(kvp => String.Format("Failed to match \"{0}\": {1}", kvp.Key, kvp.Value.Replace("Fatal error: ", String.Empty))).StringJoin(Environment.NewLine);
                        if (!IsVerbose) message = message + Environment.NewLine + bind_summary;
                        throw new ConfigException(message);
                    }
                    else
                    {
                        parsed_args.AddElements(parsed_shortcut_args);
                    }
                }

                Debug.WriteLine("Parse completed.");
                Debug.EnsureBlankLine();
                Debug.WriteLine("Setting configuration parameters...");
                var props = this.GetType().GetProperties(BF.AllInstance).Where(p => p.HasAttr<ParamAttribute>()).OrderBy(p => p.Attr<ParamAttribute>().Priority);
                props.ForEach(p =>
                {
                    if (parsed_args.ContainsKey(p))
                    {
                        var value = parsed_args[p];
                        Debug.WriteLine("Resolved %{0} as {1}.", p.Name, value.ToLog());
                        p.SetValue(this, value, null);
                    }
                    else
                    {
                        var p_default = this.GetType().GetProperty("Default" + p.Name, BF.AllStatic);
                        if (p_default == null) throw new ConfigException("Fatal error: parameter \"{0}\" must be specified.");

                        var value = p_default.GetValue(null, null);
                        Debug.WriteLine("Defaulted %{0} to {1}.", p.Name, value.ToLog());
                        p.SetValue(this, value, null);
                    }
                });
                Debug.WriteLine("Configuration parameters successfully set.");
            }
        }
コード例 #39
0
        public static ControlFlowGraph DoCreateCarcass(IMethodBody cil, out ReadOnlyDictionary<ControlFlowBlock, ReadOnlyCollection<IILOp>> blocks2parts)
        {
            // create the control flow graph
            var cfg = new ControlFlowGraph();

            // partition the code into blocks with continuous control flow
            // todo. support switches and protected regions
            var targets = new HashSet<IILOp>(cil.OfType<Branch>().Select(br => br.Target));
            var l_partitions = new List<ReadOnlyCollection<IILOp>>();
            var l_partition = new List<IILOp>();
            Action qualifyPartition = () => { if (l_partition.IsNotEmpty()) { l_partitions.Add(l_partition.ToReadOnly()); l_partition = new List<IILOp>(); } };
            foreach (var op in cil)
            {
                if (op is Branch || op is Ret) qualifyPartition();
                else 
                {
                    if (targets.Contains(op)) qualifyPartition();
                    l_partition.Add(op);
                    if (op is Throw) qualifyPartition();
                }
            }
            qualifyPartition();
            var partitions = l_partitions.ToReadOnly();

            // create blocks and map those to ops and partitions
            blocks2parts = partitions.ToDictionary(p => new ControlFlowBlock(), p => p).ToReadOnly();
            blocks2parts.ForEach(kvp => cfg.AddVertex(kvp.Key));
            var op2blocks = new Dictionary<IILOp, ControlFlowBlock>();
            blocks2parts.ForEach(kvp => kvp.Value.ForEach(op => op2blocks.Add(op, kvp.Key)));
            cil.ForEach(op => { if (!op2blocks.ContainsKey(op)) op2blocks.Add(op, null); });

            // prepare to link the blocks
            Action<IILOp, IILOp, CilPredicateType?> link = (op1, op2, cil_pred) =>
            {
                var source = op1 == null ? cfg.Start : op2blocks[op1];
                var target = op2 == null ? cfg.Finish : op2blocks[op2];
                var hir_pred = cil_pred == null ? (HirPredicateType?)null :
                    (HirPredicateType)Enum.Parse(typeof(HirPredicateType), cil_pred.Value.ToString());
                cfg.AddEdge(new ControlFlowEdge(source, target, hir_pred));
            };

            // link the blocks (down from 300+ LOC to this simple loop =))
            if (cil.IsEmpty()) link(null, null, null);
            foreach (var op in cil)
            {
                // todo. support switches here
                if (op is Switch) throw AssertionHelper.Fail();

                // todo. support general case of control flow
                // n0te. throw needs something on stack, so br > throw is impossible
                Func<IILOp, bool> isJmp = op1 => op1 is Ret || op1 is Branch;
                if (isJmp(op) && isJmp(op.Prev)) continue;

                if (isJmp(op))
                {
                    Func<IILOp, CilPredicateType?> pred = op1 => op1 is Ret ? null : op1 is Branch ? ((Branch)op1).PredicateType : ((Func<CilPredicateType?>)(() => { throw AssertionHelper.Fail(); }))();
                    Func<IILOp, bool> uncond = op1 => isJmp(op1) && pred(op1) == null;
                    Func<IILOp, bool> cond = op1 => isJmp(op1) && pred(op1) != null;
                    Func<IILOp, IILOp> target = null; target = op1 => 
                        op1 is Ret ? null : op1 is Branch ? target(((Branch)op1).Target) : op1;

                    (target(op) is Branch).AssertFalse();
                    if (target(op) is Ret) link(op.Prev, null, pred(op));
                    else link(op.Prev, target(op), pred(op));

                    isJmp(op.Next).AssertImplies(uncond(op.Next));
                    if (cond(op)) link(op.Prev, target(op.Next), pred(op).Negate());
                }
                else if (op is Throw)
                {
                    // do nothing - throw doesn't create links
                }
                else
                {
                    if (op.Prev == null) link(null, op, null);
                    if (isJmp(op.Next)) continue;

                    var blk = op2blocks.GetOrDefault(op);
                    var blk_next = op2blocks.GetOrDefault(op.Next);
                    if (blk != blk_next) link(op, op.Next, null);
                }
            }

            // yield control to the next step of the pipeline
            return cfg;
        }
コード例 #40
0
        private void TransformBlock(Block hir, Block xhir, bool insideThreadLoop)
        {
            if (hir == null) return;

            var deepFission = new List<Node>();
            var regions = new List<ReadOnlyCollection<Node>>();
            var curr_region = new List<Node>();
            foreach (var stmt in hir)
            {
                if (_callsToSyncThreads.Contains(stmt as Eval))
                {
                    if (curr_region.IsNotEmpty()) regions.Add(curr_region.ToReadOnly());
                    curr_region = new List<Node>();
                }
                else if (_callsToSyncThreads.Any(c => Set.Intersect(c.Hierarchy(), stmt.MkArray()).IsNotEmpty()))
                {
                    if (curr_region.IsNotEmpty()) regions.Add(curr_region.ToReadOnly());
                    curr_region = new List<Node>();

                    deepFission.Add(stmt);
                    regions.Add(stmt.MkArray().ToReadOnly());
                }
                else
                {
                    curr_region.Add(stmt);
                }
            }
            if (curr_region.IsNotEmpty()) regions.Add(curr_region.ToReadOnly());
            curr_region = null;

            var privateLocals = hir.Locals.Where(l => Alloc(l) == allocPrivate).ToReadOnly();
            var privateUsages = privateLocals.ToDictionary(l => l, 
                l => regions.Where(r => r.UsagesOfLocal(l).IsNotEmpty()).ToReadOnly());
            privateUsages.ForEach(kvp =>
            {
                var needsReplication = kvp.Value.Count() > 1;
                _needsReplication[kvp.Key] = needsReplication;
                if (needsReplication)
                {
                    _xhir.Insert(_lastIndex++, _replicatedInits[kvp.Key]);
                    _xhir.Locals.Add(_replicatedLocals[kvp.Key]);
                }
            });

            foreach (var region in regions)
            {
                var xregion = new Block();

                var needsToBeWrapped = !deepFission.Contains(region.SingleOrDefault2());
                var regionIsInsideThreadLoop = insideThreadLoop || needsToBeWrapped;
                foreach (var stmt in region)
                {
                    if (stmt is Expression)
                    {
                        TransformExpression(((Expression)stmt), xregion, regionIsInsideThreadLoop);
                    }
                    else if (stmt is If)
                    {
                        TransformIf(((If)stmt), xregion, regionIsInsideThreadLoop);
                    }
                    else if (stmt is Loop)
                    {
                        TransformLoop(((Loop)stmt), xregion, regionIsInsideThreadLoop);
                    }
                    else
                    {
                        throw AssertionHelper.Fail();
                    }
                }

                if (needsToBeWrapped && !insideThreadLoop)
                {
                    xhir.Add(new Loop
                    {
                        Init = new Block(new Assign(new Ref(_tids["z"]), new Const(0))),
                        Test = Operator.LessThan(new Ref(_tids["z"]), new Fld(typeof(int3).GetField("Z"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true))),
                        Body = new Block(new Loop
                        {
                            Init = new Block(new Assign(new Ref(_tids["y"]), new Const(0))),
                            Test = Operator.LessThan(new Ref(_tids["y"]), new Fld(typeof(int3).GetField("Y"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true))),
                            Body = new Block(new Loop
                            {
                                Init = new Block(new Assign(new Ref(_tids["x"]), new Const(0))),
                                Test = Operator.LessThan(new Ref(_tids["x"]), new Fld(typeof(int3).GetField("X"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true))),
                                Body = new Block(xregion.Children),
                                Iter = new Block(Operator.PreIncrement(new Ref(_tids["x"]))),
                            }),
                            Iter = new Block(Operator.PreIncrement(new Ref(_tids["y"]))),
                        }),
                        Iter = new Block(Operator.PreIncrement(new Ref(_tids["z"]))),
                    });
                }
                else
                {
                    xhir.AddElements(xregion.Children);
                }
            }

            var locals = hir.Locals.Except(_liftedLocals).ToReadOnly();
            locals.ForEach(l => xhir.Locals.Add(l.DeepClone()));
        }