Exemplo n.º 1
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetryTuples)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();

            var totalRequests = telemetryTuples
                                .Where(t => t.MetricName.Equals(MetricConstants.TotalRequestsMetricName, StringComparison.OrdinalIgnoreCase))
                                .Sum(t => t.Value);

            var totalRequestRatio = new Tuple <decimal, Metric>(100m, TotalRequestsRatioMetric);

            result.Add(totalRequestRatio);

            var failedRequests = telemetryTuples
                                 .Where(t => t.MetricName.Equals(MetricConstants.FailedRequestsMetricName, StringComparison.OrdinalIgnoreCase))
                                 .Sum(t => t.Value);

            decimal failedRequestsRatio = 0m;

            if (totalRequests != 0)
            {
                failedRequestsRatio = Math.Round(failedRequests * 100 / totalRequests, 3);
            }
            result.Add(new Tuple <decimal, Metric>(failedRequestsRatio, FailedRequestsRatioMetric));

            return(result);
        }
Exemplo n.º 2
0
        private void SetMenuItems(DropDownMenu dropDownMenu)
        {
            menuItems = new TupleList <string, Func <bool> >();

            if (ActiveTheme.Instance.IsTouchScreen)
            {
                menuItems.Add(new Tuple <string, Func <bool> >("Remove All".Localize(), clearAllMenu_Select));
            }

            menuItems.Add(new Tuple <string, Func <bool> >("Send".Localize(), sendMenu_Selected));
            menuItems.Add(new Tuple <string, Func <bool> >("Add To Library".Localize(), addToLibraryMenu_Selected));

            BorderDouble padding = dropDownMenu.MenuItemsPadding;

            //Add the menu items to the menu itself
            foreach (Tuple <string, Func <bool> > item in menuItems)
            {
                if (item.Item2 == null)
                {
                    dropDownMenu.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
                }
                else
                {
                    dropDownMenu.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
                }

                dropDownMenu.AddItem(item.Item1);
            }

            dropDownMenu.Padding = padding;
        }
Exemplo n.º 3
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetry)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();

            var errorRequestCounts = telemetry.Where(t =>
                                                     Regex.IsMatch(t.MetricName, MetricConstants.FailedRequestsRatioMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) &&
                                                     !t.MetricName.Equals(MetricConstants.Http412MetricName, StringComparison.OrdinalIgnoreCase))
                                     .ToArray();
            decimal failedRequestCount     = 0;
            decimal failedRequestBytesSent = 0;

            if (errorRequestCounts.Length > 0)
            {
                failedRequestCount = errorRequestCounts.Sum(t => t.Value);
            }

            var errorRequestBytes = telemetry.Where(t =>
                                                    Regex.IsMatch(t.MetricName, MetricConstants.FailedRequestsMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) &&
                                                    t.MetricName.EndsWith(MetricConstants.HttpStatusCodeBytesSentMetricNameSuffix, StringComparison.OrdinalIgnoreCase) &&
                                                    !t.MetricName.Equals(MetricConstants.Http412MetricName + MetricConstants.HttpStatusCodeBytesSentMetricNameSuffix, StringComparison.OrdinalIgnoreCase))
                                    .ToArray();

            if (errorRequestBytes.Length > 0)
            {
                failedRequestBytesSent = errorRequestBytes.Sum(t => t.Value);
            }

            var newMetric = new Tuple <decimal, Metric>(failedRequestCount, FailedRequestsMetric);

            result.Add(newMetric);
            result.Add(new Tuple <decimal, Metric>(failedRequestBytesSent, FailedRequestsBytesSentMetric));

            // get the weighted server and e2e latency.
            var requestTimes = telemetry.Where(t =>
                                               Regex.IsMatch(t.MetricName, MetricConstants.FailedRequestsMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) &&
                                               t.MetricName.EndsWith(MetricConstants.HttpStatusCodeServerLatencyMetricNameSuffix, StringComparison.OrdinalIgnoreCase) &&
                                               !t.MetricName.Equals(MetricConstants.Http412MetricName + MetricConstants.HttpStatusCodeServerLatencyMetricNameSuffix, StringComparison.OrdinalIgnoreCase));
            var serverLatency = errorRequestCounts.Zip(requestTimes, (m1, m2) => m1.Value * m2.Value).Sum();

            if (failedRequestCount > 0)
            {
                serverLatency = Math.Round(serverLatency / failedRequestCount, 3);
            }
            result.Add(new Tuple <decimal, Metric>(serverLatency, ServerLatencyMetric));

            requestTimes = telemetry.Where(t =>
                                           Regex.IsMatch(t.MetricName, MetricConstants.FailedRequestsMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) &&
                                           t.MetricName.EndsWith(MetricConstants.HttpStatusCodeE2ELatencyMetricNameSuffix, StringComparison.OrdinalIgnoreCase));
            var e2eLatency = errorRequestCounts.Zip(requestTimes, (m1, m2) => m1.Value * m2.Value).Sum();

            if (failedRequestCount > 0)
            {
                e2eLatency = Math.Round(e2eLatency / failedRequestCount, 3);
            }
            result.Add(new Tuple <decimal, Metric>(e2eLatency, E2ELatencyMetric));

            return(result);
        }
Exemplo n.º 4
0
        public void LogSeperation_DoesNotCall_LogEvent()
        {
            _uut._oldObjects.Add(trackobject1, trackobject2);
            tupleList.Add(trackobject1, trackobject2);
            _uut.LogSeparationEvent(tupleList);

            logWriter.DidNotReceive().LogEvent("Timestamp: 06-10-2015 21:34:56	MAR123 and FRE123 are breaking separation rules");
        }
Exemplo n.º 5
0
        static AccessDbTypeConverter()
        {
            #region fieldTypes

            //fieldTypes.Add(FieldType.AutoNumber, AccessDbType.AutoNumber);
            fieldTypes.Add(FieldType.Binary, AccessDbType.OleObject);
            fieldTypes.Add(FieldType.Byte, AccessDbType.Number);
            fieldTypes.Add(FieldType.Boolean, AccessDbType.YesNo);
            fieldTypes.Add(FieldType.Char, AccessDbType.Text);
            fieldTypes.Add(FieldType.Choice, AccessDbType.Text);
            fieldTypes.Add(FieldType.Calculated, AccessDbType.Calculated);
            fieldTypes.Add(FieldType.Currency, AccessDbType.Currency);
            fieldTypes.Add(FieldType.Date, AccessDbType.DateTime);
            fieldTypes.Add(FieldType.DateTime, AccessDbType.DateTime);
            fieldTypes.Add(FieldType.DateTimeOffset, AccessDbType.Number);
            fieldTypes.Add(FieldType.Decimal, AccessDbType.Number);
            fieldTypes.Add(FieldType.Double, AccessDbType.Number);
            fieldTypes.Add(FieldType.Geometry, AccessDbType.Text);
            fieldTypes.Add(FieldType.Guid, AccessDbType.Text);
            fieldTypes.Add(FieldType.Int16, AccessDbType.Number);
            fieldTypes.Add(FieldType.Int32, AccessDbType.Number);
            fieldTypes.Add(FieldType.Int64, AccessDbType.Number);
            fieldTypes.Add(FieldType.Lookup, AccessDbType.Text);
            fieldTypes.Add(FieldType.MultiChoice, AccessDbType.Text);
            fieldTypes.Add(FieldType.MultiLookup, AccessDbType.Text);
            fieldTypes.Add(FieldType.MultiUser, AccessDbType.Text);
            fieldTypes.Add(FieldType.Object, AccessDbType.OleObject);
            fieldTypes.Add(FieldType.RichText, AccessDbType.Memo);
            fieldTypes.Add(FieldType.SByte, AccessDbType.Number);
            fieldTypes.Add(FieldType.Single, AccessDbType.Number);
            fieldTypes.Add(FieldType.String, AccessDbType.Text);
            fieldTypes.Add(FieldType.Time, AccessDbType.Text);
            fieldTypes.Add(FieldType.Timestamp, AccessDbType.Text);
            fieldTypes.Add(FieldType.UInt16, AccessDbType.Number);
            fieldTypes.Add(FieldType.UInt32, AccessDbType.Number);
            fieldTypes.Add(FieldType.UInt64, AccessDbType.Number);
            fieldTypes.Add(FieldType.Url, AccessDbType.Hyperlink);
            fieldTypes.Add(FieldType.User, AccessDbType.Text);
            fieldTypes.Add(FieldType.Xml, AccessDbType.Memo);

            #endregion fieldTypes

            #region accessDbTypes

            accessDbTypes.Add(AccessDbType.Attachment, FieldType.Object);
            //accessDbTypes.Add(AccessDbType.AutoNumber, FieldType.AutoNumber);
            accessDbTypes.Add(AccessDbType.Calculated, FieldType.Calculated);
            accessDbTypes.Add(AccessDbType.Currency, FieldType.Currency);
            accessDbTypes.Add(AccessDbType.DateTime, FieldType.DateTime);
            accessDbTypes.Add(AccessDbType.Hyperlink, FieldType.Url);
            accessDbTypes.Add(AccessDbType.Memo, FieldType.RichText);
            accessDbTypes.Add(AccessDbType.Number, FieldType.Double);
            accessDbTypes.Add(AccessDbType.OleObject, FieldType.Object);
            accessDbTypes.Add(AccessDbType.Text, FieldType.String);
            accessDbTypes.Add(AccessDbType.YesNo, FieldType.Boolean);

            #endregion accessDbTypes
        }
		private void SetMenuItems()
		{
			menuItems = new TupleList<string, Func<bool>>();

#if !__ANDROID__
			menuItems.Add(new Tuple<string, Func<bool>>("Design".Localize(), null));
			menuItems.Add(new Tuple<string, Func<bool>>(" Export to Zip".Localize(), exportQueueToZipMenu_Click));
			menuItems.Add(new Tuple<string, Func<bool>>("G-Code".Localize(), null));
			menuItems.Add(new Tuple<string, Func<bool>>(" Export to Folder or SD Card".Localize(), exportGCodeToFolderButton_Click));
			//menuItems.Add(new Tuple<string, Func<bool>>("X3G", null));
			//menuItems.Add(new Tuple<string, Func<bool>>("Export to Folder".Localize(), exportX3GButton_Click));
#endif

			if (ActiveSliceSettings.Instance.GetValue<bool>(SettingsKey.has_sd_card_reader))
			{
				menuItems.Add(new Tuple<string, Func<bool>>("SD Card", null));
				menuItems.Add(new Tuple<string, Func<bool>>(" Load Files".Localize(), loadFilesFromSDButton_Click));
				menuItems.Add(new Tuple<string, Func<bool>>(" Eject SD Card".Localize(), ejectSDCardButton_Click));
			}

			// The pdf export library is not working on the mac at the moment so we don't include the
			// part sheet export option on mac.
			if (OsInformation.OperatingSystem == OSType.Windows)
			{
				menuItems.Add(new Tuple<string, Func<bool>>("Other".Localize(), null));
				menuItems.Add(new Tuple<string, Func<bool>>(" Create Part Sheet".Localize(), createPartsSheetsButton_Click));
				menuItems.Add(new Tuple<string, Func<bool>>(" Remove All".Localize(), removeAllFromQueueButton_Click));
			}
			else
			{
				// mac cannot export to pdf
				menuItems.Add(new Tuple<string, Func<bool>>("Other".Localize(), null));
				menuItems.Add(new Tuple<string, Func<bool>>(" Remove All".Localize(), removeAllFromQueueButton_Click));
			}

			BorderDouble padding = MenuDropList.MenuItemsPadding;
			//Add the menu items to the menu itself
			foreach (Tuple<string, Func<bool>> item in menuItems)
			{
				if (item.Item2 == null)
				{
					MenuDropList.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
				}
				else
				{
					MenuDropList.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
				}

				MenuItem menuItem = MenuDropList.AddItem(item.Item1);
				if(item.Item2 == null)
				{
					menuItem.Enabled = false;
				}
			}

			MenuDropList.Padding = padding;
		}
Exemplo n.º 7
0
        private void FillMultiLinkForEntity(IList <CompletionSet> completionSets, ITrackingSpan applicableTo, ConnectionIntellisenseData intellisenseData, EntityIntellisenseData entityData)
        {
            TupleList <string, string> childEntities = new TupleList <string, string>();

            if (entityData.OneToManyRelationships != null)
            {
                foreach (var item in entityData.OneToManyRelationships.Values)
                {
                    childEntities.Add(item.ChildEntityName, item.ChildEntityAttributeName);
                }
            }

            if (!entityData.IsIntersectEntity.GetValueOrDefault() && entityData.ManyToManyRelationships != null)
            {
                foreach (var item in entityData.ManyToManyRelationships.Values)
                {
                    if (string.Equals(entityData.EntityLogicalName, item.Entity1Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        childEntities.Add(item.IntersectEntityName, item.Entity1IntersectAttributeName);
                    }
                    else if (string.Equals(entityData.EntityLogicalName, item.Entity2Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        childEntities.Add(item.IntersectEntityName, item.Entity2IntersectAttributeName);
                    }
                }
            }

            List <CrmCompletion> list = new List <CrmCompletion>();

            foreach (var relation in childEntities.OrderBy(e => e.Item1).ThenBy(e => e.Item2))
            {
                if (intellisenseData.Entities.ContainsKey(relation.Item1))
                {
                    var childEntityData = intellisenseData.Entities[relation.Item1];

                    if (childEntityData.Attributes != null && childEntityData.Attributes.ContainsKey(relation.Item2))
                    {
                        var childAttribute = childEntityData.Attributes[relation.Item2];

                        List <string> compareValues = CrmIntellisenseCommon.GetCompareValuesForEntity(childEntityData);

                        compareValues.Add(relation.Item2);

                        var insertText = string.Format("multi {0} {1}", relation.Item2, relation.Item1);

                        list.Add(CreateCompletion(CrmIntellisenseCommon.GetDisplayTextEntityAndAttribute(childEntityData, childAttribute), insertText, CrmIntellisenseCommon.CreateEntityAndAttributeDescription(childEntityData, childAttribute), _defaultGlyph, compareValues));
                    }
                }
            }

            if (list.Count > 0)
            {
                completionSets.Add(new CrmCompletionSet(SourceNameMoniker, "Child Entities", applicableTo, list, Enumerable.Empty <CrmCompletion>()));
            }
        }
Exemplo n.º 8
0
        static SQLiteDbTypeConverter()
        {
            #region fieldTypes

            //fieldTypes.Add(FieldType.AutoNumber, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.Binary, SQLiteDbType.None);
            fieldTypes.Add(FieldType.Byte, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.Boolean, SQLiteDbType.Numeric);
            fieldTypes.Add(FieldType.Char, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.Choice, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.Calculated, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.Currency, SQLiteDbType.Real);
            fieldTypes.Add(FieldType.Date, SQLiteDbType.Numeric);
            fieldTypes.Add(FieldType.DateTime, SQLiteDbType.Numeric);
            fieldTypes.Add(FieldType.DateTimeOffset, SQLiteDbType.Numeric);
            fieldTypes.Add(FieldType.Decimal, SQLiteDbType.Real);
            fieldTypes.Add(FieldType.Double, SQLiteDbType.Real);
            fieldTypes.Add(FieldType.Geometry, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.Guid, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.Int16, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.Int32, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.Int64, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.Lookup, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.MultiChoice, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.MultiLookup, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.MultiUser, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.Object, SQLiteDbType.None);
            fieldTypes.Add(FieldType.RichText, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.SByte, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.Single, SQLiteDbType.Real);
            fieldTypes.Add(FieldType.String, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.Time, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.Timestamp, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.UInt16, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.UInt32, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.UInt64, SQLiteDbType.Integer);
            fieldTypes.Add(FieldType.Url, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.User, SQLiteDbType.Text);
            fieldTypes.Add(FieldType.Xml, SQLiteDbType.Text);

            #endregion fieldTypes

            #region sQLiteDbTypes

            sQLiteDbTypes.Add(SQLiteDbType.Integer, FieldType.Int32);
            sQLiteDbTypes.Add(SQLiteDbType.None, FieldType.Binary);
            sQLiteDbTypes.Add(SQLiteDbType.Numeric, FieldType.Decimal);
            sQLiteDbTypes.Add(SQLiteDbType.Real, FieldType.Double);
            sQLiteDbTypes.Add(SQLiteDbType.Text, FieldType.String);

            #endregion sQLiteDbTypes
        }
Exemplo n.º 9
0
        public TupleList <T, T> GetDiff(SchemaComparableList <T> other)
        {
            if (other == null)
            {
                throw new ArgumentNullException("other");
            }

            TupleList <T, T> diff = new TupleList <T, T>();
            int i = 0, j = 0;

            while (i < this.Count || j < other.Count)
            {
                if (i == this.Count)
                {
                    diff.Add(default(T), other[j]);
                    j++;
                }
                else if (j == other.Count)
                {
                    diff.Add(this[i], default(T));
                    i++;
                }
                else
                {
                    int nameCmp = this[i].NameCompareTo(other[j]);
                    if (nameCmp < 0)
                    {
                        diff.Add(this[i], default(T));
                        i++;
                    }
                    else if (nameCmp > 0)
                    {
                        diff.Add(default(T), other[j]);
                        j++;
                    }
                    else
                    {
                        if (this[i].FullCompareTo(other[j]) != 0)
                        {
                            diff.Add(this[i], other[j]);
                        }
                        i++;
                        j++;
                    }
                }
            }

            return(diff);
        }
Exemplo n.º 10
0
        public string Receipt(Format format)
        {
            var totalAmount = 0d;
            var reportLines = new TupleList<Line, string>();
            foreach (var line in _lines)
            {
                var thisAmount = 0d;
                thisAmount += CalculateAmountPlusDiscount(line.Bike, line.Quantity);
                reportLines.Add(line, thisAmount.ToString("C"));
                totalAmount += thisAmount;
            }
            var tax = totalAmount * TaxRate;

            var data = new ReceiptData(Company,
                                       totalAmount.ToString("C"),
                                       reportLines,
                                       tax.ToString("C"),
                                       (totalAmount + tax).ToString("C"));
            if (format == Format.Text)
                return new TextReceipt(data).TransformText();
            else if (format == Format.HTML)
                return new HtmlReceipt(data).TransformText();
            else if (format == Format.PDF)
            {
                return new PdfReceipt(data).TransformText();
            }
            else
                throw new Exception("Unsupported format type!");
        }
Exemplo n.º 11
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetryTuples)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();

            var incomingBitrate = telemetryTuples.FirstOrDefault(t => t.MetricName.Equals(MetricConstants.IncomingBitrateMetricName, StringComparison.OrdinalIgnoreCase));

            if (incomingBitrate != null)
            {
                var encodedBitrate = telemetryTuples.FirstOrDefault(t => t.MetricName.Equals(MetricConstants.EncodedBitrateMetricName, StringComparison.OrdinalIgnoreCase));
                if (encodedBitrate != null)
                {
                    var currentIncomingBitrateValue = incomingBitrate.Value;
                    var currentEncodedBitrateValue  = encodedBitrate.Value;

                    decimal value = (currentIncomingBitrateValue == 0) ? 0 : 1;
                    if (currentEncodedBitrateValue != 0)
                    {
                        value = Math.Round(Math.Abs(1 - (currentIncomingBitrateValue / currentEncodedBitrateValue)), 3);
                    }

                    var newMetric = new Tuple <decimal, Metric>(
                        value,
                        BitrateRatioMetric);

                    result.Add(newMetric);
                }
            }

            return(result);
        }
Exemplo n.º 12
0
    private IEnumerator SpawnPlayers()
    {
        yield return(new WaitForSeconds(1.6f));

        if (readyPlayers != null)
        {
            for (int i = 0; i < readyPlayers.Length; i++)
            {
                if (!readyPlayers[i].Active)
                {
                    continue;
                }

                int playerId = readyPlayers[i].PlayerID;
                var spawn    = GetSpawnPoint(playerId);
                if (spawn != null)
                {
                    Spawn(playerId, spawn.transform);
                }
                else
                {
                    Debug.LogError("Could not fint spawn for player id " + playerId);
                }
            }


            foreach (var playerController in Players)
            {
                Score.Add(playerController, 0);
            }
        }
    }
Exemplo n.º 13
0
        public Autobrand()
        {
            foreach (Tuple <Vector3, float> tuple in RoadsideSpawns.TrafficStopSpawnPointsWithHeadings)
            {
                if ((Vector3.Distance(tuple.Item1, Game.Player.Character.Position) < 750f) && (Vector3.Distance(tuple.Item1, Game.Player.Character.Position) > 280f))
                {
                    ValidTrafficStopSpawnPointsWithHeadings.Add(tuple);
                }
            }

            if (ValidTrafficStopSpawnPointsWithHeadings.Count == 0)
            {
                locatie = Common.Around(Game.Player.Character.Position, 1000.0f);
                float heading = 3.0f;
                API.GetClosestVehicleNodeWithHeading(locatie.X, locatie.Y, locatie.Z, ref locatie, ref heading, 0,
                                                     3.0f, 0);
                //API.GetClosestMajorVehicleNode(locatie.X, locatie.Y, locatie.Z, ref locatie, 3.0f, 0);
            }
            else
            {
                ChosenSpawnData = ValidTrafficStopSpawnPointsWithHeadings[rnd.Next(ValidTrafficStopSpawnPointsWithHeadings.Count)];
                locatie         = ChosenSpawnData.Item1;
                heading         = ChosenSpawnData.Item2;
            }
            uint streetname = new uint();
            uint crossing   = new uint();

            API.GetStreetNameAtCoord(locatie.X, locatie.Y, locatie.Z, ref streetname, ref crossing);
            adres = API.GetStreetNameFromHashKey(streetname);
            car   = Common.randomCar();
        }
Exemplo n.º 14
0
        private void GenerateDistances()
        {
            for (int i = 0; i < InternalModules.Count; i++)
            {
                List <double> tempDistances = new List <double>();

                //We are going to get the distance of Pn-Pn+1 and Plast-Pfirst. If addlCheck > 2,
                //we need to check Pn-Pn+2 for n < addlCheck+1.
                int addlCheck = 0;
                if (ConstraintCount > 3)
                {
                    addlCheck = InternalModules[i].InternalModulePoints.Count - 2;
                }
                for (int j = 0; j < ConstraintCount - 1; j++)
                {
                    double tempDist = DistanceToPoint(InternalModules[i].InternalModulePoints[j], InternalModules[i].InternalModulePoints[j + 1]);
                    tempDistances.Add(tempDist);
                }
                double firstToLastDist = DistanceToPoint(InternalModules[i].InternalModulePoints[ConstraintCount - 1], InternalModules[i].InternalModulePoints[0]);
                tempDistances.Add(firstToLastDist);

                //Add the additional check distances.
                for (int y = 0; y < addlCheck; y++)
                {
                    double tempAddlCheck = DistanceToPoint(InternalModules[i].InternalModulePoints[y], InternalModules[i].InternalModulePoints[y + 2]);
                    tempDistances.Add(tempAddlCheck);
                }

                allDistancesList.Add(i, tempDistances);
            }
        }
Exemplo n.º 15
0
        private static Dictionary <int, TupleList <long, short> > ReadWordModel(string inFile)
        {
            using (BinaryReader brWordMap = new BinaryReader(File.OpenRead(inFile)))
            {
                Dictionary <int, TupleList <long, short> > model = new Dictionary <int, TupleList <long, short> >();

                int numWords = brWordMap.ReadInt32();

                for (int i = 0; i < numWords; i++)
                {
                    int wordIdx     = brWordMap.ReadInt32();
                    int numSegments = brWordMap.ReadInt32();

                    TupleList <long, short> segmentInfo = new TupleList <long, short>();
                    for (int j = 0; j < numSegments; j++)
                    {
                        long  offset   = brWordMap.ReadInt64();
                        short location = brWordMap.ReadInt16();
                        segmentInfo.Add(offset, location);
                    }
                    model.Add(wordIdx, segmentInfo);
                }

                return(model);
            }
        }
Exemplo n.º 16
0
 public static void VerifySuspectIsInTrafficStopInfo(Ped Suspect)
 {
     if (!SuspectsTrafficStopQuestionsInfo.Select(x => x.Item1).Contains(Suspect))
     {
         SuspectsTrafficStopQuestionsInfo.Add(Suspect, new TrafficStopQuestionsInfo());
     }
 }
Exemplo n.º 17
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetry)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();


            // Look at all HttpXXX metrics.
            var requestCounts = telemetry.Where(t =>
                                                t.MetricName.StartsWith(MetricConstants.HttpStatusCodeMetricNamePrefix, StringComparison.OrdinalIgnoreCase) &&
                                                t.MetricName.Length == 7);

            var totalRequests = requestCounts.Sum(metric => metric.Value);

            result.Add(new Tuple <decimal, Metric>(totalRequests, TotalRequestsMetric));

            var bytesSent = telemetry.Where(t =>
                                            t.MetricName.StartsWith(MetricConstants.HttpStatusCodeMetricNamePrefix, StringComparison.OrdinalIgnoreCase) &&
                                            t.MetricName.EndsWith(MetricConstants.HttpStatusCodeBytesSentMetricNameSuffix, StringComparison.OrdinalIgnoreCase))
                            .Sum(metric => metric.Value);

            result.Add(new Tuple <decimal, Metric>(bytesSent, BytesSentMetric));

            // get the weighted server and e2e latency.
            var requestTimes = telemetry.Where(t =>
                                               t.MetricName.StartsWith(MetricConstants.HttpStatusCodeMetricNamePrefix, StringComparison.OrdinalIgnoreCase) &&
                                               t.MetricName.EndsWith(MetricConstants.HttpStatusCodeServerLatencyMetricNameSuffix, StringComparison.OrdinalIgnoreCase));
            var serverLatency = requestCounts.Zip(requestTimes, (m1, m2) => m1.Value * m2.Value).Sum();

            serverLatency = (totalRequests > 0) ? Math.Round(serverLatency / totalRequests, 3) : 0;
            result.Add(new Tuple <decimal, Metric>(serverLatency, ServerLatencyMetric));

            requestTimes = telemetry.Where(t =>
                                           t.MetricName.StartsWith(MetricConstants.HttpStatusCodeMetricNamePrefix, StringComparison.OrdinalIgnoreCase) &&
                                           t.MetricName.EndsWith(MetricConstants.HttpStatusCodeE2ELatencyMetricNameSuffix, StringComparison.OrdinalIgnoreCase));
            var e2eLatency = requestCounts.Zip(requestTimes, (m1, m2) => m1.Value * m2.Value).Sum();

            e2eLatency = (totalRequests > 0) ? Math.Round(e2eLatency / totalRequests, 3) : 0;
            result.Add(new Tuple <decimal, Metric>(e2eLatency, E2ELatencyMetric));

            return(result);
        }
Exemplo n.º 18
0
        public override bool OnBeforeCalloutDisplayed()
        {
            Game.LogTrivial("AssortedCallouts.PrisonerTransportRequired");
            foreach (Tuple <Vector3, float> tuple in Albo1125.Common.CommonLibrary.CommonVariables.TrafficStopSpawnPointsWithHeadings)
            {
                //tuple.Item1 = PedInTuple
                //tuple.Item2 = Vector3 in tuple
                //tuple.Item3 = FloatinTuple
                //Game.LogTrivial(tuple.Item1.ToString());
                //Game.LogTrivial(tuple.Item2.ToString());

                if ((Vector3.Distance(tuple.Item1, Game.LocalPlayer.Character.Position) < 750f) && (Vector3.Distance(tuple.Item1, Game.LocalPlayer.Character.Position) > 280f))
                {
                    ValidTrafficStopSpawnPointsWithHeadings.Add(tuple);
                }
            }
            if (ValidTrafficStopSpawnPointsWithHeadings.Count == 0)
            {
                return(false);
            }
            ChosenSpawnData = ValidTrafficStopSpawnPointsWithHeadings[AssortedCalloutsHandler.rnd.Next(ValidTrafficStopSpawnPointsWithHeadings.Count)];


            SpawnPoint   = ChosenSpawnData.Item1;
            SpawnHeading = ChosenSpawnData.Item2;
            uint zoneHash = Rage.Native.NativeFunction.CallByHash <uint>(0x7ee64d51e8498728, SpawnPoint.X, SpawnPoint.Y, SpawnPoint.Z);


            if (Game.GetHashKey("city") == zoneHash)
            {
                CopCarModel = new Model(CityCarModels[AssortedCalloutsHandler.rnd.Next(CityCarModels.Length)]);
            }
            else
            {
                CopCarModel = new Model(CountrysideCarModels[AssortedCalloutsHandler.rnd.Next(CountrysideCarModels.Length)]);
            }
            CopCarModel.LoadAndWait();
            ShowCalloutAreaBlipBeforeAccepting(SpawnPoint, 10f);
            CalloutMessage = "Prisoner Transport Required";

            CalloutPosition = SpawnPoint;

            ComputerPlusRunning = AssortedCalloutsHandler.IsLSPDFRPluginRunning("ComputerPlus", new Version("1.3.0.0"));
            if (ComputerPlusRunning)
            {
                CalloutID = API.ComputerPlusFuncs.CreateCallout("Prisoner Transport Required", "Prisoner Transport", SpawnPoint, 0, "Officer is requesting transport for a prisoner. Situation currently under control. Please respond code 2.",
                                                                1, null, null);
            }
            Functions.PlayScannerAudioUsingPosition("DISP_ATTENTION_UNIT " + AssortedCalloutsHandler.DivisionUnitBeatAudioString + " WE_HAVE CRIME_OFFICER_IN_NEED_OF_ASSISTANCE IN_OR_ON_POSITION", SpawnPoint);


            return(base.OnBeforeCalloutDisplayed());
        }
Exemplo n.º 19
0
        public void Merge(TupleList<Vector2, float> listToSort, int begin, int end, int mid)
        {
            int lengthbeginpart = mid - begin + 1;
            int lengthendpart = end - mid;

            TupleList<Vector2, float> beginlist = new TupleList<Vector2, float>();
            TupleList<Vector2, float> endlist = new TupleList<Vector2, float>();

            for (int i = 0; i < lengthbeginpart; i++)
            {
                beginlist.Add(listToSort[i + begin]);
            }
            for (int i = 0; i < lengthendpart; i++)
            {
                endlist.Add(listToSort[mid + i + 1]);
            }

            beginlist.Add(new Vector2(float.MaxValue), float.MaxValue);
            endlist.Add(new Vector2(float.MaxValue), float.MaxValue);

            int indexbegin = 0;
            int indexend = 0;

            for (int i = begin; i <= end; i++)
            {
                if (beginlist[indexbegin].Item2 < endlist[indexend].Item2)
                {
                    listToSort[i] = beginlist[indexbegin];
                    indexbegin++;
                }
                else
                {
                    listToSort[i] = endlist[indexend];
                    indexend++;
                }
            }
        }
Exemplo n.º 20
0
        private static TupleList <string, string> GetTextFromEditorAsDictionary()
        {
            var requestLength = int.MaxValue;
            var currentText   = editor.GetText(requestLength);
            var textlist      = new TupleList <string, string>();

            using (StringReader sr = new StringReader(currentText))
            {
                string line = null;
                while (null != (line = sr.ReadLine()))
                {
                    textlist.Add(line.ToUpper(), line);
                }
            }
            return(textlist);
        }
Exemplo n.º 21
0
        public void PropagateOutput()
        {
            var nodeInput = new TupleList <float, float>();

            foreach (int inputNodeID in inValues.Keys)
            {
                nodeInput.Add(Tuple.Create(inValues[inputNodeID], inWeights[inputNodeID]));
            }

            float nodeOutput = Function.GetOutput(nodeInput);

            foreach (InternalNetworkNode node in outConnections)
            {
                node.Notify(nodeID, nodeOutput);
            }
        }
Exemplo n.º 22
0
        private UpdateChecker(string ModificationName, Version curVersion, string FileID, string DownloadLink)
        {
            try
            {
                Game.LogTrivial("Albo1125.Common " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + ", developed by Albo1125. Checking for " + ModificationName + " updates.");

                Thread FetchVersionThread = new Thread(() =>
                {
                    using (WebClient client = new WebClient())
                    {
                        try
                        {
                            string s = client.DownloadString("http://www.lcpdfr.com/applications/downloadsng/interface/api.php?do=checkForUpdates&fileId=" + FileID + "&textOnly=1");

                            NewVersion = new Version(s);
                        }
                        catch (Exception)
                        {
                            LSPDFRUpdateAPIRunning = false;
                            Game.LogTrivial("LSPDFR Update API down. Aborting checks.");
                        }
                    }
                });
                FetchVersionThread.Start();
                while (FetchVersionThread.ThreadState != System.Threading.ThreadState.Stopped)
                {
                    GameFiber.Yield();
                }

                // compare the versions
                if (curVersion.CompareTo(NewVersion) < 0)
                {
                    // ask the user if he would like
                    // to download the new version
                    PluginsDownloadLink.Add(ModificationName, DownloadLink);
                    Game.LogTrivial("Update available for " + ModificationName);
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                // do nothing
            }
            catch (Exception)
            {
                Game.LogTrivial("Error while checking " + ModificationName + " for updates.");
            }
        }
Exemplo n.º 23
0
        private TupleList <Func <Privilege, bool>, bool> GetFilters()
        {
            var funcs = new TupleList <Func <Privilege, bool>, bool>();

            this.Dispatcher.Invoke(() =>
            {
                foreach (var checkbox in _checkBoxes.Where(c => c.IsChecked.HasValue))
                {
                    if (checkbox.Tag is Func <Privilege, bool> func)
                    {
                        funcs.Add(func, checkbox.IsChecked.Value);
                    }
                }
            });

            return(funcs);
        }
Exemplo n.º 24
0
        public void TupleList_6_can_construct_easily()
        {
            // Arrange


            // Act
            // ReSharper disable once UseObjectOrCollectionInitializer
            var list = new TupleList <int, int, int, int, int, int>
            {
                { 1, 2, 3, 4, 5, 6 }
            };

            list.Add(1, 2, 3, 4, 5, 6);

            // Assert
            list.ShouldNotBeNull();
            list.Count.ShouldBe(2);
        }
Exemplo n.º 25
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetryTuples)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();

            var totalRequests  = telemetryTuples.FirstOrDefault(t => t.MetricName.Equals(MetricConstants.TotalRequestsMetricName, StringComparison.OrdinalIgnoreCase));
            var failedRequests = telemetryTuples.FirstOrDefault(t => t.MetricName.Equals(MetricConstants.FailedRequestsMetricName, StringComparison.OrdinalIgnoreCase));

            if (totalRequests != null && failedRequests != null)
            {
                var value     = (totalRequests.Value > 0) ? Math.Round(failedRequests.Value / totalRequests.Value, 3) : 0;
                var newMetric = new Tuple <decimal, Metric>(
                    value,
                    FailedRequestsRatioMetric);

                result.Add(newMetric);
            }

            return(result);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Add a new sample of a value at a given position.
        /// </summary>
        /// <param name = "sample">The value.</param>
        /// <param name = "at">The position of the value.</param>
        public void AddSample(TValue sample, TOver at)
        {
            if (_samples.Count > 0 && at.CompareTo(_samples.Last().Item2) < 0)
            {
                throw new ArgumentException("Samples are required to be added in order.", "at");
            }

            _samples.Add(sample, at);

            // Clean up samples older than the specified interval.
            // TODO: This LINQ query probably isn't optimized for lists. What's the performance impact?
            if (_samples.Count > 2)
            {
                var toRemove = _samples
                               .Reverse <Tuple <TValue, TOver> >()
                               .Skip(2)
                               .SkipWhile(s => Operator <TOver> .Subtract(at, s.Item2).CompareTo(Interval) <= 0)
                               .ToList();
                toRemove.ForEach(r => _samples.Remove(r));
            }
        }
Exemplo n.º 27
0
        private static void PickRandomInstalledGame()
        {
            using (dynamic steamPlayerServices = WebAPI.GetInterface("IPlayerService", steamApiKey))
            {
                try
                {
                    KeyValue kvGames      = steamPlayerServices.GetOwnedGames(steamid: steamUser.SteamID.ConvertToUInt64(), include_appinfo: 1);
                    var      apps         = SteamDrives.getAllInstalledGames();
                    var      matchedGames = new TupleList <String, int>();
                    foreach (KeyValue game in kvGames["games"].Children)
                    {
                        if (apps.Contains(game["appid"].AsInteger()))
                        {
                            matchedGames.Add(game["name"].AsString(), game["appid"].AsInteger());
                        }
                    }
                    Random r = new Random();
                    Tuple <String, int> randomGame = matchedGames[r.Next(matchedGames.Count)];
                    Console.Write("Would you like to play {0}? [Y/n] : ", randomGame.Item1);
                    switch (Console.ReadLine())
                    {
                    case "Y":
                    case "y":
                        Console.WriteLine("Launching {0} - AppID {1}", randomGame.Item1, randomGame.Item2);
                        var uri = String.Format("steam://run/{0}", randomGame.Item2.ToString());
                        System.Diagnostics.Process.Start(uri);
                        break;

                    default:
                        Console.WriteLine("Not launching game {0}", randomGame.Item1);
                        break;
                    }
                }
                catch (WebException ex)
                {
                    Console.WriteLine("Unable to make API request:{0}", ex.Message);
                }
            }
        }
Exemplo n.º 28
0
        public BrokenDownVehicle(bool createBlip, bool displayMessage)
        {
            foreach (Tuple <Vector3, float> tuple in CommonVariables.TrafficStopSpawnPointsWithHeadings)
            {
                if ((Vector3.Distance(tuple.Item1, Game.LocalPlayer.Character.Position) < 300f) && (Vector3.Distance(tuple.Item1, Game.LocalPlayer.Character.Position) > 140f))
                {
                    if (Rage.Native.NativeFunction.Natives.CALCULATE_TRAVEL_DISTANCE_BETWEEN_POINTS(tuple.Item1.X, tuple.Item1.Y, tuple.Item1.Z, Game.LocalPlayer.Character.Position.X, Game.LocalPlayer.Character.Position.Y, Game.LocalPlayer.Character.Position.Z) < 500f)
                    {
                        ValidTrafficStopSpawnPointsWithHeadings.Add(tuple);
                    }
                }
            }
            if (ValidTrafficStopSpawnPointsWithHeadings.Count > 0)
            {
                ChosenSpawnData = ValidTrafficStopSpawnPointsWithHeadings[TrafficPolicerHandler.rnd.Next(ValidTrafficStopSpawnPointsWithHeadings.Count)];
                SpawnPoint      = ChosenSpawnData.Item1;
                SpawnHeading    = ChosenSpawnData.Item2;
                car             = new Vehicle(vehiclesToSelectFrom[TrafficPolicerHandler.rnd.Next(vehiclesToSelectFrom.Length)], SpawnPoint, SpawnHeading);
                car.MakePersistent();
                driver = car.CreateRandomDriver();
                car.RandomiseLicencePlate();
                driver.MakeMissionPed();
                car.EngineHealth = 0;
                car.IsDriveable  = false;
                car.Doors[4].Open(true);

                if (displayMessage)
                {
                    Game.DisplayNotification("Creating Broken Down Vehicle Event.");
                }
                if (createBlip)
                {
                    driverBlip       = driver.AttachBlip();
                    driverBlip.Color = System.Drawing.Color.Beige;
                    driverBlip.Scale = 0.7f;
                }
                MainLogic();
            }
        }
Exemplo n.º 29
0
        public static T GetInstance(Type type, string key = null)
        {
            CheckType(type);

            // no key, return a new instance
            if (string.IsNullOrEmpty(key) == true)
            {
                return((T)Activator.CreateInstance(type));
            }

            // try to find an existing instance with that key
            var tuple = _instancesWithKey.FirstOrDefault(o => o.Item1 == type && o.Item2 == key);

            if (tuple != null)
            {
                return(tuple.Item3);
            }

            // create a new instance and register it
            T instance = (T)Activator.CreateInstance(type);

            _instancesWithKey.Add(type, key, instance);
            return(instance);
        }
Exemplo n.º 30
0
 static void Main()
 {
     string[] people_list = GetPeople();
     if (!people_list.Any())
     {
         RunAgain("This file is empty.");
     }
     else
     {
         var people = new TupleList <int, int>();
         foreach (string person in people_list)
         {
             //separates the birth and end years, then adds them into the TupleList as a tuple
             try
             {
                 int birth_year = int.Parse(person.Split(',')[0]);
                 int end_year   = int.Parse(person.Split(',')[1]);
                 if (birth_year < 1900 || end_year < 1900 || birth_year > 2000 || end_year > 2000)
                 {
                     RunAgain("Not every year was from 1900 to 2000.");
                 }
                 if (birth_year > end_year)
                 {
                     RunAgain("Birth years cannot be later than end years.");
                 }
                 people.Add(birth_year, end_year);
             }
             catch (FormatException)
             {
                 RunAgain("The contents of this file do not have the correct format.");
             }
         }
         int YearWithMost = FindYearWithMost(people);
         RunAgain($"The year in which the most of the given people were alive was {YearWithMost}.");
     }
 }
Exemplo n.º 31
0
        private async Task IncludingReferencesToDependencyXml(IOrganizationServiceExtented service, List <SelectedFile> selectedFiles)
        {
            TupleList <SelectedFile, WebResource> list = new TupleList <SelectedFile, WebResource>();

            // Репозиторий для работы с веб-ресурсами
            WebResourceRepository webResourceRepository = new WebResourceRepository(service);

            bool allForOther = false;

            var groups = selectedFiles.GroupBy(sel => sel.Extension);

            foreach (var gr in groups)
            {
                var names = gr.Select(sel => sel.FriendlyFilePath).ToArray();

                var dict = webResourceRepository.FindMultiple(gr.Key, names);

                foreach (var selectedFile in gr)
                {
                    if (!File.Exists(selectedFile.FilePath))
                    {
                        this._iWriteToOutput.WriteToOutput(service.ConnectionData, "File not founded: {0}", selectedFile.FilePath);
                        continue;
                    }

                    this._iWriteToOutput.WriteToOutput(service.ConnectionData, "Try to find web-resource by name: {0}. Searching...", selectedFile.Name);

                    string key = selectedFile.FriendlyFilePath.ToLower();

                    var contentFile = Convert.ToBase64String(File.ReadAllBytes(selectedFile.FilePath));

                    var webresource = WebResourceRepository.FindWebResourceInDictionary(dict, key, gr.Key);

                    if (webresource != null)
                    {
                        this._iWriteToOutput.WriteToOutput(service.ConnectionData, "WebResource founded by name. WebResourceId: {0} Name: {1}", webresource.Id, webresource.Name);
                    }

                    if (webresource == null)
                    {
                        if (selectedFile.FileName.StartsWith(service.ConnectionData.Name + "."))
                        {
                            string newFileName = selectedFile.FileName.Replace(service.ConnectionData.Name + ".", string.Empty);

                            string newFilePath = Path.Combine(Path.GetDirectoryName(selectedFile.FilePath), newFileName);

                            var newSelectedFile = new SelectedFile(newFilePath, selectedFile.SolutionDirectoryPath);

                            var newDict = webResourceRepository.FindMultiple(newSelectedFile.Extension, new[] { newSelectedFile.FriendlyFilePath });

                            webresource = WebResourceRepository.FindWebResourceInDictionary(newDict, newSelectedFile.FriendlyFilePath.ToLower(), newSelectedFile.Extension);

                            if (webresource != null)
                            {
                                this._iWriteToOutput.WriteToOutput(service.ConnectionData, "WebResource founded by name with Connection Prefix. WebResourceId: {0} Name: {1}", webresource.Id, webresource.Name);
                            }
                        }
                    }

                    if (webresource == null)
                    {
                        this._iWriteToOutput.WriteToOutput(service.ConnectionData, "WebResource not founded by name. FileName: {0}. Open linking dialog...", selectedFile.Name);

                        Guid?webId = service.ConnectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                        bool?dialogResult          = null;
                        Guid?selectedWebResourceId = null;

                        var t = new Thread(() =>
                        {
                            try
                            {
                                var form = new Views.WindowWebResourceSelectOrCreate(this._iWriteToOutput, service, selectedFile, webId);
                                form.ShowCreateButton(allForOther);

                                dialogResult = form.ShowDialog();

                                allForOther = form.ForAllOther;

                                selectedWebResourceId = form.SelectedWebResourceId;
                            }
                            catch (Exception ex)
                            {
                                DTEHelper.WriteExceptionToOutput(service.ConnectionData, ex);
                            }
                        });
                        t.SetApartmentState(ApartmentState.STA);
                        t.Start();

                        t.Join();

                        if (string.IsNullOrEmpty(service.ConnectionData?.LastSelectedSolutionsUniqueName?.FirstOrDefault()))
                        {
                            allForOther = false;
                        }

                        service.ConnectionData.Save();

                        if (dialogResult.GetValueOrDefault())
                        {
                            if (selectedWebResourceId.HasValue)
                            {
                                webresource = await webResourceRepository.GetByIdAsync(selectedWebResourceId.Value);
                            }
                            else
                            {
                                this._iWriteToOutput.WriteToOutput(service.ConnectionData, "!Warning. WebResource not linked. name: {0}.", selectedFile.Name);
                            }
                        }
                        else
                        {
                            this._iWriteToOutput.WriteToOutput(service.ConnectionData, "Updating Content and Publishing was cancelled.");
                            return;
                        }
                    }

                    if (webresource != null)
                    {
                        // Запоминается файл
                        service.ConnectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                        list.Add(selectedFile, webresource);
                    }
                }
            }

            //Сохранение настроек после публикации
            service.ConnectionData.Save();

            if (!list.Any())
            {
                return;
            }

            List <WebResource> webResourceToPublish = new List <WebResource>();

            PublishActionsRepository repository = new PublishActionsRepository(service);
            await repository.PublishWebResourcesAsync(webResourceToPublish.Select(e => e.Id));
        }
Exemplo n.º 32
0
 public void addItem(string name, Func <bool> clickFunction)
 {
     this.AddItem(name);
     menuItems.Add(name, clickFunction);
 }
Exemplo n.º 33
0
        private void SetMenuItems()
        {
            menuItems = new TupleList <string, Func <bool> >();

#if !__ANDROID__
            menuItems.Add(new Tuple <string, Func <bool> >("Design".Localize(), null));
            menuItems.Add(new Tuple <string, Func <bool> >(" Export to Zip".Localize(), exportQueueToZipMenu_Click));
            menuItems.Add(new Tuple <string, Func <bool> >("G-Code".Localize(), null));
            menuItems.Add(new Tuple <string, Func <bool> >(" Export to Folder or SD Card".Localize(), exportGCodeToFolderButton_Click));
            //menuItems.Add(new Tuple<string, Func<bool>>("X3G", null));
            //menuItems.Add(new Tuple<string, Func<bool>>("Export to Folder".Localize(), exportX3GButton_Click));
#endif

            if (ActiveSliceSettings.Instance.GetValue <bool>(SettingsKey.has_sd_card_reader))
            {
                menuItems.Add(new Tuple <string, Func <bool> >("SD Card".Localize(), null));
                menuItems.Add(new Tuple <string, Func <bool> >(" Load Files".Localize(), loadFilesFromSDButton_Click));
                menuItems.Add(new Tuple <string, Func <bool> >(" Eject SD Card".Localize(), ejectSDCardButton_Click));
            }

            // The pdf export library is not working on the mac at the moment so we don't include the
            // part sheet export option on mac.
            if (OsInformation.OperatingSystem == OSType.Windows)
            {
                menuItems.Add(new Tuple <string, Func <bool> >("Other".Localize(), null));
                menuItems.Add(new Tuple <string, Func <bool> >(" Create Part Sheet".Localize(), createPartsSheetsButton_Click));
                menuItems.Add(new Tuple <string, Func <bool> >(" Remove All".Localize(), removeAllFromQueueButton_Click));
            }
            else
            {
                // mac cannot export to pdf
                menuItems.Add(new Tuple <string, Func <bool> >("Other".Localize(), null));
                menuItems.Add(new Tuple <string, Func <bool> >(" Remove All".Localize(), removeAllFromQueueButton_Click));
            }

            BorderDouble padding = MenuDropList.MenuItemsPadding;
            //Add the menu items to the menu itself
            foreach (Tuple <string, Func <bool> > item in menuItems)
            {
                if (item.Item2 == null)
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
                }
                else
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
                }

                MenuItem menuItem = MenuDropList.AddItem(item.Item1);
                if (item.Item2 == null)
                {
                    menuItem.Enabled = false;
                }
            }

            MenuDropList.Padding = padding;
        }
Exemplo n.º 34
0
        private static void PickRandomInstalledGame()
        {
            using (dynamic steamPlayerServices = WebAPI.GetInterface("IPlayerService", steamApiKey))
            {

                try
                {
                    KeyValue kvGames = steamPlayerServices.GetOwnedGames(steamid: steamUser.SteamID.ConvertToUInt64(), include_appinfo: 1);
                    var apps = SteamDrives.getAllInstalledGames();
                    var matchedGames = new TupleList<String, int>();
                    foreach (KeyValue game in kvGames["games"].Children)
                    {
                        if (apps.Contains(game["appid"].AsInteger()))
                            matchedGames.Add(game["name"].AsString(), game["appid"].AsInteger());
                    }
                    Random r = new Random();
                    Tuple<String, int> randomGame = matchedGames[r.Next(matchedGames.Count)];
                    Console.Write("Would you like to play {0}? [Y/n] : ", randomGame.Item1);
                    switch (Console.ReadLine())
                    {
                        case "Y":
                        case "y":
                            Console.WriteLine("Launching {0} - AppID {1}", randomGame.Item1, randomGame.Item2);
                            var uri = String.Format("steam://run/{0}", randomGame.Item2.ToString());
                            System.Diagnostics.Process.Start(uri);
                            break;
                        default :
                            Console.WriteLine("Not launching game {0}", randomGame.Item1);
                            break;
                    }
                }
                catch (WebException ex)
                {
                    Console.WriteLine("Unable to make API request:{0}", ex.Message);
                }
            }
        }
Exemplo n.º 35
0
		private void SetMenuItems(DropDownMenu dropDownMenu)
		{
			menuItems = new TupleList<string, Func<bool>>();

			if (ActiveTheme.Instance.IsTouchScreen)
			{
				menuItems.Add(new Tuple<string, Func<bool>>("Remove All".Localize(), clearAllMenu_Select));
			}

			menuItems.Add(new Tuple<string, Func<bool>>("Send".Localize(), sendMenu_Selected));
			menuItems.Add(new Tuple<string, Func<bool>>("Add To Library".Localize(), addToLibraryMenu_Selected));

			BorderDouble padding = dropDownMenu.MenuItemsPadding;
			//Add the menu items to the menu itself
			foreach (Tuple<string, Func<bool>> item in menuItems)
			{
				if (item.Item2 == null)
				{
					dropDownMenu.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
				}
				else
				{
					dropDownMenu.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
				}

				dropDownMenu.AddItem(item.Item1);
			}

			dropDownMenu.Padding = padding;
		}
Exemplo n.º 36
0
        //TODO: MakeInvCopy is going to be called over and over again by DesignScript, not us, so there is no opportunity to pass the count into this method.  
        //UniqueModuleEvaluator needs to be modified each time this is called so we know which module we are on.

        //TODO:  ApprenticeServer instance creation and lifetime management needs to be handled by InventorServices.Persistance

        //TODO: OccurrenceList needs to be set on each Module instance during UniqueModuleEvaluator's construction.

        //TODO: Refactor this method, it is so big.
        private void MakeInvCopy(ApprenticeServer appServ, 
                                 string templateAssemblyPath, 
                                 string templateDrawingPath, 
                                 string targetDirectory, 
                                 OccurrenceList occList, 
                                 int count, 
                                 UniqueModuleEvaluator uniqueModuleEvaluator)
        {
            // TODO Test for the existance of folders and assemblies.
            ApprenticeServer oAppServ = appServ;
            int panelID = count;
            OccurrenceList oOccs = occList;
            string topFileFullName;
            string targetPath = targetDirectory;
            TemplateAssemblyPath = templateAssemblyPath;
            TemplateDrawingPath = templateDrawingPath;
            string panelIDString = System.Convert.ToString(panelID);
            UniqueModules = uniqueModuleEvaluator;

            //Instead of using "panelID" to create unique folders for all instances, redirect to the GeometryMapIndex
            string geoMapString = System.Convert.ToString(GeometryMapIndex);
            string folderName;
            if (CreateAllCopies == false)
            {
                if (GeometryMapIndex < 10)
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " 00" + geoMapString;
                }

                else if (10 <= GeometryMapIndex && GeometryMapIndex < 100)
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " 0" + geoMapString;
                }
                else
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " " + geoMapString;
                }
            }

            else
            {
                if (panelID < 10)
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " 00" + panelIDString;
                }
                else if (10 <= panelID && panelID < 100)
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " 0" + panelIDString;
                }
                else
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " " + panelIDString;
                }
            }
            //if(panelID < 10){
            //Need to get number of the parent occ, top level name as foldername
            string pathString = System.IO.Path.Combine(targetPath, folderName);

            topFileFullName = oOccs.TargetAssembly.FullDocumentName;
            string topFileNameOnly = System.IO.Path.GetFileName(topFileFullName);
            ModulePath = System.IO.Path.Combine(pathString, topFileNameOnly);


            TupleList<string, string> filePathPair = new TupleList<string, string>();

            for (int i = 0; i < occList.Items.Count; i++)
            {
                string targetOccPath = occList.Items[i].ReferencedFileDescriptor.FullFileName;
                string newCopyName = System.IO.Path.GetFileName(targetOccPath);
                string newFullCopyName = System.IO.Path.Combine(pathString, newCopyName);
                filePathPair.Add(targetOccPath, newFullCopyName);
            }

            //Check if an earlier panel already made the folder, if not, create it.
            if (!System.IO.Directory.Exists(pathString))
            {
                firstTime = true;
                System.IO.Directory.CreateDirectory(pathString);
                //AssemblyReplaceRef(oAppServ, oOccs.TargetAssembly, filePathPair, pathString);
                ApprenticeServerDocument oAssDoc;
                oAssDoc = oAppServ.Open(TemplateAssemblyPath);
                FileSaveAs fileSaver;
                fileSaver = oAppServ.FileSaveAs;
                fileSaver.AddFileToSave(oAssDoc, ModulePath);
                fileSaver.ExecuteSaveCopyAs();

                //Need to copy presentation files if there are any.  For now this is only going to work with the top assembly.
                string templateDirectory = System.IO.Path.GetDirectoryName(TemplateAssemblyPath);
                string[] presentationFiles = System.IO.Directory.GetFiles(templateDirectory, "*.ipn");
                //If we want the ability to have subassemblies with .ipn files or multiple ones, this will have to be changed
                //to iterate over all the .ipn files.
                if (presentationFiles.Length != 0)
                {
                    string newCopyPresName = System.IO.Path.GetFileName(presentationFiles[0]);
                    string newFullCopyPresName = System.IO.Path.Combine(pathString, newCopyPresName);

                    ApprenticeServerDocument presentationDocument = oAppServ.Open(presentationFiles[0]);
                    DocumentDescriptorsEnumerator presFileDescriptors = presentationDocument.ReferencedDocumentDescriptors;
                    foreach (DocumentDescriptor refPresDocDescriptor in presFileDescriptors)
                    {
                        if (refPresDocDescriptor.FullDocumentName == TemplateAssemblyPath)
                        {
                            refPresDocDescriptor.ReferencedFileDescriptor.ReplaceReference(ModulePath);
                            FileSaveAs fileSavePres;
                            fileSavePres = oAppServ.FileSaveAs;
                            fileSavePres.AddFileToSave(presentationDocument, newFullCopyPresName);
                        }
                    }
                }

                string newCopyDrawingName = System.IO.Path.GetFileName(TemplateDrawingPath);
                string newFullCopyDrawingName = System.IO.Path.Combine(pathString, newCopyDrawingName);

                if (TemplateDrawingPath != "")
                {
                    ApprenticeServerDocument drawingDoc = oAppServ.Open(TemplateDrawingPath);
                    DocumentDescriptorsEnumerator drawingFileDescriptors = drawingDoc.ReferencedDocumentDescriptors;
                    //This needs to be fixed.  It was written with the assumption that only the template assembly would be in 
                    //the details and be first in the collection of document descriptors.  Need to iterate through 
                    //drawingFileDescriptors and match names and replace correct references.
                    //Possibly can use the "filePathPair" object for name matching/reference replacing.
                    //drawingFileDescriptors[1].ReferencedFileDescriptor.ReplaceReference(topAssemblyNewLocation);
                    foreach (DocumentDescriptor refDocDescriptor in drawingFileDescriptors)
                    {
                        foreach (Tuple<string, string> pathPair in filePathPair)
                        {
                            string newFileNameLower = System.IO.Path.GetFileName(pathPair.Item2);
                            string drawingReferenceLower = System.IO.Path.GetFileName(refDocDescriptor.FullDocumentName);
                            string topAssemblyLower = System.IO.Path.GetFileName(ModulePath);
                            if (topAssemblyLower == drawingReferenceLower)
                            {
                                refDocDescriptor.ReferencedFileDescriptor.ReplaceReference(ModulePath);
                            }
                            if (newFileNameLower == drawingReferenceLower)
                            {
                                refDocDescriptor.ReferencedFileDescriptor.ReplaceReference(pathPair.Item2);
                            }
                        }
                    }

                    FileSaveAs fileSaveDrawing;
                    fileSaveDrawing = oAppServ.FileSaveAs;
                    fileSaveDrawing.AddFileToSave(drawingDoc, newFullCopyDrawingName);
                    fileSaveDrawing.ExecuteSaveCopyAs();
                    firstTime = true;

                    if (!UniqueModules.DetailDocumentPaths.Contains(newFullCopyDrawingName))
                    {
                        UniqueModules.DetailDocumentPaths.Add(newFullCopyDrawingName);
                    }
                }
            }
        }
Exemplo n.º 37
0
        void SetMenuItems()
        {
            menuItems = new TupleList<string, Func<bool>>();
            menuItems.Add(new Tuple<string,Func<bool>>("STL", null));
            menuItems.Add(new Tuple<string,Func<bool>>(LocalizedString.Get(" Import from Zip"), importQueueFromZipMenu_Click));
            menuItems.Add(new Tuple<string,Func<bool>>(LocalizedString.Get(" Export to Zip"), exportQueueToZipMenu_Click));
            menuItems.Add(new Tuple<string,Func<bool>>("GCode", null));
            menuItems.Add(new Tuple<string,Func<bool>>(LocalizedString.Get(" Export to Folder"), exportGCodeToFolderButton_Click));
            //menuItems.Add(new Tuple<string, Func<bool>>("X3G", null));
            //menuItems.Add(new Tuple<string, Func<bool>>(LocalizedString.Get("Export to Folder"), exportX3GButton_Click));

            if (ActiveSliceSettings.Instance.HasSdCardReader())
            {
                menuItems.Add(new Tuple<string, Func<bool>>("SD Card", null));
                menuItems.Add(new Tuple<string, Func<bool>>(LocalizedString.Get(" Load Files"), loadFilesFromSDButton_Click));
                menuItems.Add(new Tuple<string, Func<bool>>(LocalizedString.Get(" Eject SD Card"), ejectSDCardButton_Click));
            }
            
            // The pdf export library is not working on the mac at the moment so we don't include the 
            // part sheet export option on mac.
            if (OsInformation.OperatingSystem == OSType.Mac)
            {
                // mac cannot export to pdf
                menuItems.Add(new Tuple<string,Func<bool>>(LocalizedString.Get("Other"), null));
                menuItems.Add(new Tuple<string,Func<bool>>(LocalizedString.Get(" Remove All"), removeAllFromQueueButton_Click));
            }
            else
            {
                menuItems.Add(new Tuple<string,Func<bool>>(LocalizedString.Get("Other"), null));
                menuItems.Add(new Tuple<string,Func<bool>>(LocalizedString.Get(" Create Part Sheet"), createPartsSheetsButton_Click));
                menuItems.Add(new Tuple<string,Func<bool>>(LocalizedString.Get(" Remove All"), removeAllFromQueueButton_Click));
            }

            BorderDouble padding = MenuDropList.MenuItemsPadding;
            //Add the menu items to the menu itself
            foreach (Tuple<string, Func<bool>> item in menuItems)
            {
                if (item.Item2 == null)
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
                }
                else
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
                }

                MenuDropList.AddItem(item.Item1);
            }

            MenuDropList.Padding = padding;
        }
Exemplo n.º 38
0
		private void AddSaveAndSaveAs(FlowLayoutWidget flowToAddTo)
		{
			TupleList<string, Func<bool>> buttonList = new TupleList<string, Func<bool>>();
			buttonList.Add("Save", () =>
			{
				MergeAndSavePartsToCurrentMeshFile();
				return true;
			});
			
			buttonList.Add("Save As", () =>
			{
				UiThread.RunOnIdle(OpenSaveAsWindow);
				return true;
			});

			SplitButtonFactory splitButtonFactory = new SplitButtonFactory();
			splitButtonFactory.FixedHeight = 40 * TextWidget.GlobalPointSizeScaleRatio;
			saveButtons = splitButtonFactory.Generate(buttonList, Direction.Up, imageName: "icon_save_32x32.png");
			saveButtons.Visible = false;

			saveButtons.Margin = new BorderDouble();
			saveButtons.VAnchor |= VAnchor.ParentCenter;

			flowToAddTo.AddChild(saveButtons);
		}
Exemplo n.º 39
0
        private void PopulateZipCodeBoundries(List<GeographicModel> regionList)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            try
            {
                if (regionList.Count() == 0)
                {
                    log.Warn("regionList is Empty!");
                }
                else
                {
                    log.DebugFormat("Getting Boundaries for {0} regions!", regionList.Count());
                }
                using (var connection = GetConnection())
                {
                    using (SqlCommand cmd = new SqlCommand("IRM.spGeographicExplorerGetZipCodeBoundries", connection))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        //Fill param table with indexes of the selected Gender.
                        var ZipCodeTempTable = new DataTable();
                        ZipCodeTempTable.Columns.Add("ID", typeof(string));
                        foreach (var region in regionList)
                        {
                            ZipCodeTempTable.Rows.Add(region.ZipCode);
                        }
                        SqlParameter tvparam = cmd.Parameters.AddWithValue("@ZipCodeList", ZipCodeTempTable);
                        tvparam.SqlDbType = SqlDbType.Structured;

                        List<polygons> zipcodePolygonLists = new List<polygons>();

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            GeographicModel rgn = null;

                            while (reader.Read())
                            {
                                var oneItem = new polygons()
                                {
                                    City = reader.FieldToString("City"),
                                    PolygonID = reader.FieldToInt("ZipcodePolygonID"),
                                    ZipCode = reader.FieldToString("ZipCode"),
                                    Latitude = reader.FieldToDouble("Latitude"),
                                    Longitude = reader.FieldToDouble("Longitude")
                                };
                                zipcodePolygonLists.Add(oneItem);
                            }

                            if (zipcodePolygonLists.Count() > 0)
                            {
                                rgn = null;

                                var groups = zipcodePolygonLists.GroupBy(x => x.PolygonID);

                                foreach (var group in groups)
                                {
                                    var lst = new TupleList<double, double>();
                                    var zip = string.Empty;
                                    foreach (var item in group)
                                    {
                                        zip = item.ZipCode;
                                        lst.Add(item.Latitude, item.Longitude);
                                    }
                                    rgn = regionList.FirstOrDefault(r => r.ZipCode == zip);
                                    if (rgn != null)
                                    {
                                        rgn.Polygons.Add(lst);
                                    }
                                }
                            }
                        }
                    }
                }

            }
            finally
            {
                sw.Stop();
                LoggerHelper.RecordTiming(System.Reflection.MethodBase.GetCurrentMethod().Name, sw, log);
                log.DebugFormat("{0} rows returned", regionList.Count);
                if (regionList.Count == 0)
                {
                    log.Error("RegionList is empty!");
                }
            }
        }
Exemplo n.º 40
0
        /// <summary>
        /// Creates a type representing the given <see cref="EnumParameterType"/>.
        /// </summary>
        private string GenerateType(EnumParameterType enumType, string propertyName, string moduleName)
        {
            string typeName = moduleName + propertyName;

            Dictionary<EnumParameterType, string> moduleTypes;

            if (m_enumTypeNames.TryGetValue(moduleName, out moduleTypes))
            {
                int i = 2;
                while (moduleTypes.Values.Contains(typeName))
                    typeName = moduleName + propertyName + i++;
            }

            var fixedMemberNameMapping = new TupleList<string, string>();
            var memberNames = new List<string>();

            foreach (var name in enumType.Values)
            {
                var fixedName = FixEnumMemberName(name);

                if (name != fixedName.TrimStart('@'))
                    fixedMemberNameMapping.Add(fixedName, name);

                memberNames.Add(fixedName);
            }

            var members = enumType.Values.Select(
                memberName =>
                SyntaxEx.FieldDeclaration(
                    new[] { SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword, SyntaxKind.ReadOnlyKeyword },
                    typeName, FixEnumMemberName(memberName),
                    SyntaxEx.ObjectCreation(typeName, SyntaxEx.Literal(memberName))));

            var constructorParameter = SyntaxEx.Parameter("string", "value");
            var contructor = SyntaxEx.ConstructorDeclaration(
                new[] { SyntaxKind.InternalKeyword }, typeName, new[] { constructorParameter },
                constructorInitializer: SyntaxEx.BaseConstructorInitializer((NamedNode)constructorParameter));

            var firstParameter = SyntaxEx.Parameter(typeName, "first");
            var secondParameter = SyntaxEx.Parameter(typeName, "second");

            Func<SyntaxKind, ExpressionSyntax, OperatorDeclarationSyntax> createOperator =
                (op, result) => SyntaxEx.OperatorDeclaration(
                    Syntax.ParseTypeName("bool"), op,
                    new[] { firstParameter, secondParameter },
                    new[] { SyntaxEx.Return(result) });

            var equalsExpression = SyntaxEx.Invocation(
                Syntax.IdentifierName("Equals"), (NamedNode)firstParameter, (NamedNode)secondParameter);
            var notEqualsExpression = SyntaxEx.Not(equalsExpression);

            var equalsOperator = createOperator(SyntaxKind.EqualsEqualsToken, equalsExpression);
            var notEqualsOPerator = createOperator(SyntaxKind.ExclamationEqualsToken, notEqualsExpression);

            var equalsParameter = SyntaxEx.Parameter("object", "obj");
            var equalsMethod = SyntaxEx.MethodDeclaration(
                new[] { SyntaxKind.PublicKeyword, SyntaxKind.OverrideKeyword }, "bool", "Equals",
                new[] { equalsParameter },
                SyntaxEx.Return(
                    SyntaxEx.Invocation(SyntaxEx.MemberAccess("base", "Equals"), (NamedNode)equalsParameter)));

            var getHashCodeMethod = SyntaxEx.MethodDeclaration(
                new[] { SyntaxKind.PublicKeyword, SyntaxKind.OverrideKeyword }, "int", "GetHashCode",
                new ParameterSyntax[0],
                SyntaxEx.Return(SyntaxEx.Invocation(SyntaxEx.MemberAccess("base", "GetHashCode"))));

            var classDeclaration =
                SyntaxEx.ClassDeclaration(typeName, Syntax.ParseTypeName("StringValue"), contructor)
                        .AddMembers(equalsOperator, notEqualsOPerator, equalsMethod, getHashCodeMethod)
                        .AddMembers(members.ToArray<MemberDeclarationSyntax>());

            var namespaceDeclaration = m_wiki.Files[Wiki.Names.Enums].SingleDescendant<NamespaceDeclarationSyntax>();

            m_wiki.Files[Wiki.Names.Enums] = m_wiki.Files[Wiki.Names.Enums].ReplaceNode(
                namespaceDeclaration, namespaceDeclaration.AddMembers(classDeclaration));

            m_enumTypeNames.Add(moduleName, enumType, typeName);

            return typeName;
        }
Exemplo n.º 41
0
        internal void MakeInvCopy(string templateAssemblyPath,
                         string targetDirectory,
                         OccurrenceList occurrenceList,
                         UniqueModuleEvaluator uniqueModuleEvaluator)
        {
            // TODO Test for the existance of folders and assemblies.
            TemplateAssemblyPath = templateAssemblyPath;        
            UniqueModules = uniqueModuleEvaluator;

            
            //Get the folder name that will be used to store the files associated with this Module.
            string folderName = GetModuleFolderPath();

            //Need to get number of the parent occ, top level name as foldername
            ModulePath = System.IO.Path.Combine(targetDirectory, folderName);

            string topFileFullName = occurrenceList.TargetAssembly.FullDocumentName;
            string topFileNameOnly = System.IO.Path.GetFileName(topFileFullName);
            ModuleAssemblyPath = System.IO.Path.Combine(ModulePath, topFileNameOnly);

            //If this file already exists in the current location, for now we are
            //going to just skip the file creation, and assume it was previously done
            //correctly.  Probably need to give the user the option to redo and 
            //overwrite files if they want to.
            if (!System.IO.File.Exists(ModuleAssemblyPath))
            {
                FilePathPair = new TupleList<string, string>();

                for (int i = 0; i < occurrenceList.Items.Count; i++)
                {
                    string targetOccPath = occurrenceList.Items[i].ReferencedFileDescriptor.FullFileName;
                    string newCopyName = System.IO.Path.GetFileName(targetOccPath);
                    string newFullCopyName = System.IO.Path.Combine(ModulePath, newCopyName);
                    FilePathPair.Add(targetOccPath, newFullCopyName);
                }

                //Check if an earlier module already made the folder, if not, create it.
                if (!System.IO.Directory.Exists(ModulePath))
                {
                    //This property is needed later when placing occurrences of the assembly this Module instance 
                    //refers to.  If FirstTime is false, we will want to have a slightly different strategry for constraint
                    //placement.  If FirstTime is true, all constraints are important and we need not relax them.  If 
                    //FirstTime is false, then we need tolerance in the constraints because of double precision.  When
                    //FirstTime is false, we really just want to position the occurrence correctly, not drive its 
                    //geometry.

                    if (FirstTime == null)
                    {
                        FirstTime = true;
                    }

                    System.IO.Directory.CreateDirectory(ModulePath);
                    ReplaceReferences(occurrenceList.TargetAssembly, FilePathPair, ModulePath);
                    AssemblyDocument oAssDoc = (AssemblyDocument)PersistenceManager.InventorApplication.Documents.Open(TemplateAssemblyPath, false);
                    oAssDoc.SaveAs(ModuleAssemblyPath, true);
                    oAssDoc.Close(true);


                    //Need to copy presentation files if there are any.  For now this is only going to work with the top assembly.
                    string templateDirectory = System.IO.Path.GetDirectoryName(TemplateAssemblyPath);
                    string[] presentationFiles = System.IO.Directory.GetFiles(templateDirectory, "*.ipn");
                    //If we want the ability to have subassemblies with .ipn files or multiple ones, this will have to be changed
                    //to iterate over all the .ipn files.
                    if (presentationFiles.Length != 0)
                    {
                        string newCopyPresName = System.IO.Path.GetFileName(presentationFiles[0]);
                        string newFullCopyPresName = System.IO.Path.Combine(ModulePath, newCopyPresName);
                        PresentationDocument presentationDocument = (PresentationDocument)PersistenceManager.InventorApplication.Documents.Open(presentationFiles[0], false);
                        DocumentDescriptorsEnumerator presFileDescriptors = presentationDocument.ReferencedDocumentDescriptors;
                        foreach (DocumentDescriptor refPresDocDescriptor in presFileDescriptors)
                        {
                            if (refPresDocDescriptor.FullDocumentName == TemplateAssemblyPath)
                            {
                                refPresDocDescriptor.ReferencedFileDescriptor.ReplaceReference(ModuleAssemblyPath);
                                presentationDocument.SaveAs(newFullCopyPresName, true);
                                presentationDocument.Close(true);
                            }
                        }
                    }
                }

                else
                {
                    FirstTime = false;
                }
            }
        }