示例#1
0
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
        private static void Postfix(Vector3 ____centerPos, ObstacleData obstacleData, ref BeatmapObjectSpawnMovementData.ObstacleSpawnData __result)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
        {
            if (obstacleData is CustomObstacleData customData)
            {
                dynamic dynData = customData.customData;
                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                IEnumerable <float?> scale    = ((List <object>)Trees.at(dynData, SCALE))?.Select(n => n.ToNullableFloat());
                float?njs         = (float?)Trees.at(dynData, NOTEJUMPSPEED);
                float?spawnoffset = (float?)Trees.at(dynData, NOTESPAWNOFFSET);

                float?startX = position?.ElementAtOrDefault(0);
                float?startY = position?.ElementAtOrDefault(1);

                float?height = scale?.ElementAtOrDefault(1);

                Vector3?finalNoteOffset = null;

                Vector3 moveStartPos   = __result.moveStartPos;
                Vector3 moveEndPos     = __result.moveEndPos;
                Vector3 jumpEndPos     = __result.jumpEndPos;
                float   obstacleHeight = __result.obstacleHeight;
                GetNoteJumpValues(njs, spawnoffset, out float jumpDuration, out float _, out Vector3 _, out Vector3 _, out Vector3 _);

                // Actual wall stuff
                if (startX.HasValue || startY.HasValue || njs.HasValue || spawnoffset.HasValue)
                {
                    GetNoteJumpValues(njs, spawnoffset, out float _, out float _, out Vector3 localMoveStartPos, out Vector3 localMoveEndPos, out Vector3 localJumpEndPos);

                    // Ripped from base game
                    Vector3 noteOffset = GetNoteOffset(obstacleData, startX, null);
                    noteOffset.y = startY.HasValue ? VerticalObstaclePosY + (startY.GetValueOrDefault(0) * NoteLinesDistance) : ((obstacleData.obstacleType == ObstacleType.Top)
                        ? (TopObstaclePosY + JumpOffsetY) : VerticalObstaclePosY);

                    finalNoteOffset = noteOffset;

                    moveStartPos = localMoveStartPos + noteOffset;
                    moveEndPos   = localMoveEndPos + noteOffset;
                    jumpEndPos   = localJumpEndPos + noteOffset;
                }

                if (height.HasValue)
                {
                    obstacleHeight = height.Value * NoteLinesDistance;
                }

                __result = new BeatmapObjectSpawnMovementData.ObstacleSpawnData(moveStartPos, moveEndPos, jumpEndPos, obstacleHeight, __result.moveDuration, jumpDuration, __result.noteLinesDistance);

                if (!finalNoteOffset.HasValue)
                {
                    Vector3 noteOffset = GetNoteOffset(obstacleData, startX, null);
                    noteOffset.y    = (obstacleData.obstacleType == ObstacleType.Top) ? (TopObstaclePosY + JumpOffsetY) : VerticalObstaclePosY;
                    finalNoteOffset = noteOffset;
                }

                dynData.noteOffset = ____centerPos + finalNoteOffset.Value;
                float?width = scale?.ElementAtOrDefault(0);
                dynData.xOffset = ((width.GetValueOrDefault(obstacleData.lineIndex) / 2f) - 0.5f) * NoteLinesDistance;
            }
        }
        private static void Prefix(ObstacleData __instance) // prefix because we need to know the lineIndex before it gets mirrored
        {
            if (__instance is CustomObstacleData customData)
            {
                dynamic dynData = customData.customData;
                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                IEnumerable <float?> scale    = ((List <object>)Trees.at(dynData, SCALE))?.Select(n => n.ToNullableFloat());
                List <float>         localrot = ((List <object>)Trees.at(dynData, LOCALROTATION))?.Select(n => Convert.ToSingle(n)).ToList();
                dynamic rotation = Trees.at(dynData, ROTATION);

                float?startX = position?.ElementAtOrDefault(0);
                float?scaleX = scale?.ElementAtOrDefault(0);

                IDictionary <string, object> dictdata = dynData as IDictionary <string, object>;

                float width = scaleX.GetValueOrDefault(__instance.width);
                if (startX.HasValue)
                {
                    dictdata[POSITION] = new List <object>()
                    {
                        (startX.Value + width) * -1, position.ElementAtOrDefault(1)
                    };
                }
                else if (scaleX.HasValue)
                {
                    float lineIndex = __instance.lineIndex - 2;
                    dictdata[POSITION] = new List <object>()
                    {
                        (lineIndex + width) * -1, position?.ElementAtOrDefault(1) ?? 0
                    };
                }

                if (localrot != null)
                {
                    List <float> rot            = localrot.Select(n => Convert.ToSingle(n)).ToList();
                    Quaternion   modifiedVector = Quaternion.Euler(rot[0], rot[1], rot[2]);
                    Vector3      vector         = new Quaternion(modifiedVector.x, modifiedVector.y * -1, modifiedVector.z * -1, modifiedVector.w).eulerAngles;
                    dictdata[LOCALROTATION] = new List <object> {
                        vector.x, vector.y, vector.z
                    };
                }

                if (rotation != null)
                {
                    if (rotation is List <object> list)
                    {
                        List <float> rot            = list.Select(n => Convert.ToSingle(n)).ToList();
                        Quaternion   modifiedVector = Quaternion.Euler(rot[0], rot[1], rot[2]);
                        Vector3      vector         = new Quaternion(modifiedVector.x, modifiedVector.y * -1, modifiedVector.z * -1, modifiedVector.w).eulerAngles;
                        dictdata[ROTATION] = new List <object> {
                            vector.x, vector.y, vector.z
                        };
                    }
                    else
                    {
                        dictdata[ROTATION] = rotation * -1;
                    }
                }
            }
        }
示例#3
0
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
        private static void Postfix(BeatmapObjectSpawnMovementData __instance, Vector3 ____centerPos, float ____jumpDuration, NoteData noteData, ref BeatmapObjectSpawnMovementData.NoteSpawnData __result)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
        {
            if (noteData is CustomNoteData customData)
            {
                dynamic dynData = customData.customData;
                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                float?flipLineIndex           = (float?)Trees.at(dynData, "flipLineIndex");
                float?njs            = (float?)Trees.at(dynData, NOTEJUMPSPEED);
                float?spawnoffset    = (float?)Trees.at(dynData, NOTESPAWNOFFSET);
                float?startlinelayer = (float?)Trees.at(dynData, "startNoteLineLayer");

                bool gravityOverride = (bool?)Trees.at(dynData, NOTEGRAVITYDISABLE) ?? false;

                float?startRow    = position?.ElementAtOrDefault(0);
                float?startHeight = position?.ElementAtOrDefault(1);

                float jumpDuration = ____jumpDuration;

                Vector3 moveStartPos = __result.moveStartPos;
                Vector3 moveEndPos   = __result.moveEndPos;
                Vector3 jumpEndPos   = __result.jumpEndPos;
                float   jumpGravity  = __result.jumpGravity;

                Vector3 noteOffset = GetNoteOffset(noteData, startRow, startlinelayer ?? (float)noteData.startNoteLineLayer);

                if (position != null || flipLineIndex != null || njs.HasValue || spawnoffset.HasValue || startlinelayer.HasValue || gravityOverride)
                {
                    GetNoteJumpValues(njs, spawnoffset, out float localJumpDuration, out float localJumpDistance, out Vector3 localMoveStartPos, out Vector3 localMoveEndPos, out Vector3 localJumpEndPos);
                    jumpDuration = localJumpDuration;

                    float localNoteJumpMovementSpeed = njs ?? NoteJumpMovementSpeed;

                    float startLayerLineYPos = LineYPosForLineLayer(noteData, startlinelayer ?? (float)noteData.startNoteLineLayer);
                    float lineYPos           = LineYPosForLineLayer(noteData, startHeight);

                    // Magic numbers below found with linear regression y=mx+b using existing HighestJumpPosYForLineLayer values
                    float highestJump = startHeight.HasValue ? (0.875f * lineYPos) + 0.639583f + JumpOffsetY :
                                        __instance.HighestJumpPosYForLineLayer(noteData.noteLineLayer);
                    jumpGravity = 2f * (highestJump - (gravityOverride ? lineYPos : startLayerLineYPos)) /
                                  Mathf.Pow(localJumpDistance / localNoteJumpMovementSpeed * 0.5f, 2f);

                    jumpEndPos = localJumpEndPos + noteOffset;

                    // IsBasicNote() check is skipped so bombs can flip too
                    Vector3 noteOffset2 = GetNoteOffset(noteData, flipLineIndex ?? startRow, gravityOverride ? startHeight : startlinelayer ?? (float)noteData.startNoteLineLayer);
                    moveStartPos = localMoveStartPos + noteOffset2;
                    moveEndPos   = localMoveEndPos + noteOffset2;

                    __result = new BeatmapObjectSpawnMovementData.NoteSpawnData(moveStartPos, moveEndPos, jumpEndPos, jumpGravity, __result.moveDuration, jumpDuration);
                }

                // DEFINITE POSITION IS WEIRD, OK?
                // ty reaxt
                float startVerticalVelocity = jumpGravity * jumpDuration * 0.5f;
                float num     = jumpDuration * 0.5f;
                float yOffset = (startVerticalVelocity * num) - (jumpGravity * num * num * 0.5f);
                dynData.noteOffset = ____centerPos + noteOffset + new Vector3(0, yOffset, 0);
            }
        }
示例#4
0
        private static void Postfix(ObstacleData obstacleData, ref Vector3 moveStartPos, ref Vector3 moveEndPos, ref Vector3 jumpEndPos, ref float obstacleHeight)
        {
            if (obstacleData is CustomObstacleData customData)
            {
                dynamic dynData = customData.customData;
                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                IEnumerable <float?> scale    = ((List <object>)Trees.at(dynData, SCALE))?.Select(n => n.ToNullableFloat());
                float?njs         = (float?)Trees.at(dynData, NOTEJUMPSPEED);
                float?spawnoffset = (float?)Trees.at(dynData, SPAWNOFFSET);

                float?startX = position?.ElementAtOrDefault(0);
                float?startY = position?.ElementAtOrDefault(1);

                float?height = scale?.ElementAtOrDefault(1);

                // Actual wall stuff
                if (startX.HasValue || startY.HasValue || njs.HasValue || spawnoffset.HasValue)
                {
                    GetNoteJumpValues(njs, spawnoffset, out float _, out float _, out Vector3 _localMoveStartPos, out Vector3 _localMoveEndPos, out Vector3 _localJumpEndPos);

                    // Ripped from base game
                    Vector3 noteOffset = GetNoteOffset(obstacleData, startX, null);
                    noteOffset.y = startY.HasValue ? _verticalObstaclePosY + startY.GetValueOrDefault(0) * _noteLinesDistance : ((obstacleData.obstacleType == ObstacleType.Top)
                        ? (_topObstaclePosY + _jumpOffsetY) : _verticalObstaclePosY);
                    moveStartPos = _localMoveStartPos + noteOffset;
                    moveEndPos   = _localMoveEndPos + noteOffset;
                    jumpEndPos   = _localJumpEndPos + noteOffset;
                }
                if (height.HasValue)
                {
                    obstacleHeight = height.Value * _noteLinesDistance;
                }
            }
        }
示例#5
0
        public SetDeviceValue(IDeviceRepository deviceRepository, IEnumerable<string> parameters)
        {
            mDeviceRepository = deviceRepository;

            mDeviceToSet = parameters.ElementAtOrDefault(0);
            mValueToSet = parameters.ElementAtOrDefault(1);
        }
 private static void ProcessFlipData(List <CustomNoteData> customNotes, bool defaultFlip = true)
 {
     for (int i = customNotes.Count - 1; i >= 0; i--)
     {
         dynamic dynData           = customNotes[i].customData;
         IEnumerable <float?> flip = ((List <object>)Trees.at(dynData, FLIP))?.Select(n => n.ToNullableFloat());
         float?flipX = flip?.ElementAtOrDefault(0);
         float?flipY = flip?.ElementAtOrDefault(1);
         if (flipX.HasValue || flipY.HasValue)
         {
             if (flipX.HasValue)
             {
                 dynData.flipLineIndex = flipX.Value;
             }
             if (flipY.HasValue)
             {
                 dynData.flipYSide = flipY.Value;
             }
             customNotes.Remove(customNotes[i]);
         }
     }
     if (defaultFlip)
     {
         customNotes.ForEach(c => c.customData.flipYSide = 0);
     }
 }
示例#7
0
        private static void FinalizeCustomObject(Dictionary <string, object?> dynData, NoodleObjectData noodleObjectData, Dictionary <string, PointDefinition> pointDefinitions, Dictionary <string, Track> beatmapTracks)
        {
            object?rotation = dynData.Get <object>(ROTATION);

            if (rotation != null)
            {
                if (rotation is List <object> list)
                {
                    IEnumerable <float> rot = list.Select(n => Convert.ToSingle(n));
                    noodleObjectData.WorldRotationQuaternion = Quaternion.Euler(rot.ElementAt(0), rot.ElementAt(1), rot.ElementAt(2));
                }
                else
                {
                    noodleObjectData.WorldRotationQuaternion = Quaternion.Euler(0, Convert.ToSingle(rotation), 0);
                }
            }

            IEnumerable <float>?localrot = dynData.Get <List <object> >(LOCALROTATION)?.Select(n => Convert.ToSingle(n));

            if (localrot != null)
            {
                noodleObjectData.LocalRotationQuaternion = Quaternion.Euler(localrot.ElementAt(0), localrot.ElementAt(1), localrot.ElementAt(2));
            }

            noodleObjectData.Track = GetTrackArray(dynData, beatmapTracks);

            Dictionary <string, object?>?animationObjectDyn = dynData.Get <Dictionary <string, object?> >(ANIMATION);

            if (animationObjectDyn != null)
            {
                NoodleObjectData.AnimationObjectData animationObjectData = new NoodleObjectData.AnimationObjectData
                {
                    LocalPosition         = TryGetPointData(animationObjectDyn, POSITION, pointDefinitions),
                    LocalRotation         = TryGetPointData(animationObjectDyn, ROTATION, pointDefinitions),
                    LocalScale            = TryGetPointData(animationObjectDyn, SCALE, pointDefinitions),
                    LocalLocalRotation    = TryGetPointData(animationObjectDyn, LOCALROTATION, pointDefinitions),
                    LocalDissolve         = TryGetPointData(animationObjectDyn, DISSOLVE, pointDefinitions),
                    LocalDissolveArrow    = TryGetPointData(animationObjectDyn, DISSOLVEARROW, pointDefinitions),
                    LocalCuttable         = TryGetPointData(animationObjectDyn, CUTTABLE, pointDefinitions),
                    LocalDefinitePosition = TryGetPointData(animationObjectDyn, DEFINITEPOSITION, pointDefinitions),
                };
                noodleObjectData.AnimationObject = animationObjectData;
            }

            noodleObjectData.Cuttable = dynData.Get <bool?>(CUTTABLE);
            noodleObjectData.Fake     = dynData.Get <bool?>(FAKENOTE);

            IEnumerable <float?>?position = dynData.GetNullableFloats(POSITION);

            noodleObjectData.StartX = position?.ElementAtOrDefault(0);
            noodleObjectData.StartY = position?.ElementAtOrDefault(1);

            noodleObjectData.NJS               = dynData.Get <float?>(NOTEJUMPSPEED);
            noodleObjectData.SpawnOffset       = dynData.Get <float?>(NOTESPAWNOFFSET);
            noodleObjectData.AheadTimeInternal = dynData.Get <float?>("aheadTime");
        }
示例#8
0
        private static NoodleObstacleData ProcessCustomObstacle(Dictionary <string, object?> dynData)
        {
            NoodleObstacleData noodleObstacleData = new NoodleObstacleData();

            IEnumerable <float?>?scale = dynData.GetNullableFloats(SCALE);

            noodleObstacleData.Width  = scale?.ElementAtOrDefault(0);
            noodleObstacleData.Height = scale?.ElementAtOrDefault(1);
            noodleObstacleData.Length = scale?.ElementAtOrDefault(2);

            return(noodleObstacleData);
        }
        private static NoodleObstacleData ProcessCustomObstacle(dynamic dynData)
        {
            NoodleObstacleData noodleObstacleData = new NoodleObstacleData();

            IEnumerable <float?> scale = ((List <object>)Trees.at(dynData, SCALE))?.Select(n => n.ToNullableFloat());

            noodleObstacleData.Width  = scale?.ElementAtOrDefault(0);
            noodleObstacleData.Height = scale?.ElementAtOrDefault(1);
            noodleObstacleData.Length = scale?.ElementAtOrDefault(2);

            return(noodleObstacleData);
        }
示例#10
0
        private static void Postfix(NoteData __instance)
        {
            if (__instance is CustomNoteData customData)
            {
                dynamic dynData = customData.customData;
                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                float?flipLineIndex           = (float?)Trees.at(dynData, "flipLineIndex");
                float?rotation = (float?)Trees.at(dynData, ROTATION);

                float?startRow = position?.ElementAtOrDefault(0);

                IDictionary <string, object> dictdata = dynData as IDictionary <string, object>;

                if (startRow.HasValue)
                {
                    dictdata[POSITION] = new List <object>()
                    {
                        ((startRow.Value + 0.5f) * -1) - 0.5f, position.ElementAtOrDefault(1)
                    }
                }
                ;
                if (flipLineIndex.HasValue)
                {
                    dynData.flipLineIndex = ((flipLineIndex.Value + 0.5f) * -1) - 0.5f;
                }
                if (rotation.HasValue)
                {
                    dictdata[ROTATION] = rotation * -1;
                }
            }
        }
    }
示例#11
0
文件: Login.cs 项目: markyme/DH
 public Login(IUserRepository userRepository, ILoginActions loginActions, IEnumerable<string> parameters)
 {
     mUserRepository = userRepository;
     mLoginActions = loginActions;
     mParameters = parameters;
     mUserToLogin = mParameters.ElementAtOrDefault(0);
 }
示例#12
0
    private static string?GetTelephoneTypeFromPhone(IEnumerable <PhoneNumber?>?phones, int index)
    {
        PhoneNumber?phone = phones?.ElementAtOrDefault(index);

        if (phone is null)
        {
            return(null);
        }

        if (phone.IsFax)
        {
            return(phone.IsWork ? TelephoneTypes.FaxWork : TelephoneTypes.FaxHome);
        }

        if (phone.IsMobile)
        {
            return(TelephoneTypes.Cell);
        }

        if (phone.IsWork)
        {
            return(TelephoneTypes.Work);
        }

        if (index == 0)
        {
            return(TelephoneTypes.Home);
        }

        return(TelephoneTypes.Other);
    }
示例#13
0
        private void CreateInlineDiffs(IEnumerable<ILine> originals, IEnumerable<ILine> modifieds)
        {
            if (originals.Count() != modifieds.Count())
            {
                originalLines.AddRange(
                    originals.Select(x => new ModificationLine(new[] { new Span(x.Value, SpanKind.Deletion) }))
                );
                modifiedLines.AddRange(
                    modifieds.Select(x => new ModificationLine(new[] { new Span(x.Value, SpanKind.Addition) }))
                );
                return;
            }

            var maxLines = Math.Max(originals.Count(), modifieds.Count());

            for (var i = 0; i < maxLines; i++)
            {
                var originalLine = originals.ElementAtOrDefault(i);
                var modifiedLine = modifieds.ElementAtOrDefault(i);

                if (originalLine == null && modifiedLine == null)
                    continue;
                if (originalLine != null && modifiedLine == null)
                    originalLines.Add(new ModificationLine(new[] { new Span(originalLine.Value, SpanKind.Deletion) }));
                else if (originalLine == null)
                    modifiedLines.Add(new ModificationLine(new[] { new Span(modifiedLine.Value, SpanKind.Addition) }));
                else
                {
                    var originalToModifiedChanges = DiffInline(originalLine, modifiedLine);

                    originalLines.Add(new ModificationLine(new[] { new Span(originalLine.Value, SpanKind.Equal) }));
                    modifiedLines.Add(new ModificationLine(originalToModifiedChanges));
                }
            }
        }
示例#14
0
        private static void Postfix(ObstacleData __instance)
        {
            if (__instance is CustomObstacleData customData)
            {
                dynamic dynData = customData.customData;
                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                IEnumerable <float?> scale    = ((List <object>)Trees.at(dynData, SCALE))?.Select(n => n.ToNullableFloat());
                List <float>         localrot = ((List <object>)Trees.at(dynData, LOCALROTATION))?.Select(n => Convert.ToSingle(n)).ToList();
                float?rotation = (float?)Trees.at(dynData, ROTATION);

                float?startX = position?.ElementAtOrDefault(0);
                float?scaleX = scale?.ElementAtOrDefault(0);

                IDictionary <string, object> dictdata = dynData as IDictionary <string, object>;

                float width = scaleX.GetValueOrDefault(__instance.width);
                if (startX.HasValue)
                {
                    dictdata[POSITION] = new List <object>()
                    {
                        (startX.Value + width) * -1, position.ElementAtOrDefault(1)
                    }
                }
                ;
                if (localrot != null)
                {
                    dictdata[LOCALROTATION] = localrot.Select(n => n *= 1).Cast <object>().ToList();
                }
                if (rotation.HasValue)
                {
                    dictdata[ROTATION] = rotation * -1;
                }
            }
        }
    }
示例#15
0
        public static IEnumerable<Token> Normalize(
            IEnumerable<Token> tokens, Func<string, bool> nameLookup)
        {
            var indexes =
                from i in
                    tokens.Select(
                        (t, i) =>
                        {
                            var prev = tokens.ElementAtOrDefault(i - 1).ToMaybe();
                            return t.IsValue() && ((Value)t).ExplicitlyAssigned
                                   && prev.MapValueOrDefault(p => p.IsName() && !nameLookup(p.Text), false)
                                ? Maybe.Just(i)
                                : Maybe.Nothing<int>();
                        }).Where(i => i.IsJust())
                select i.FromJustOrFail();

            var toExclude =
                from t in
                    tokens.Select((t, i) => indexes.Contains(i) ? Maybe.Just(t) : Maybe.Nothing<Token>())
                        .Where(t => t.IsJust())
                select t.FromJustOrFail();

            var normalized = tokens.Except(toExclude);

            return normalized;
        }
示例#16
0
        private static string GetString(this IEnumerable<Cell> source, string location, IEnumerable<string> strings) {
            var cell = source.FirstOrDefault(x => x.Location == location);
            if (string.IsNullOrEmpty(cell?.Node.Value)) return null;

            var id = cell.Node.Value.AsInt();
            return strings.ElementAtOrDefault(id);
        }
示例#17
0
        public void BotAddCommand(CommandContext context, IEnumerable<string> arguments)
        {
            if (arguments.Count() < 1)
            {
                SendInContext(context, "Usage: !bot add name [nick [arguments]]");
                return;
            }

            string botID = arguments.ElementAt(0);
            if (!GameManager.Bots.ContainsKey(botID))
            {
                SendInContext(context, "Invalid bot!");
                return;
            }

            string botNick = arguments.ElementAtOrDefault(1) ?? botID;

            try
            {
                Manager.AddBot(botNick, (IBot)GameManager.Bots[botID].GetConstructor(new Type[] { typeof(GameManager), typeof(IEnumerable<string>) }).Invoke(new object[] { Manager, arguments.Skip(2) }));
                Manager.SendPublic(context.Nick, "Added <{0}> (a bot of type {1})", botNick, botID);
            }
            catch (ArgumentException e)
            {
                SendInContext(context, "Error adding {0}: {1}", botNick, e.Message);
            }
        }
 IHdumNode TryGet(IHdumNode caller, IEnumerable<IHdumNode> parameters)
 {
     var key = parameters.First().As<IHdumContent<String>>().Content;
     if (caller.HasMember(key))
         return caller[key];
     else
         return parameters.ElementAtOrDefault(1);
 }
示例#19
0
 private void OnActionsCleared(Pawn source, IEnumerable<PawnAction> actionsCleared)
 {
     for (int i = _currentStep; i > 0; i--) {
         PawnAction action = actionsCleared.ElementAtOrDefault(i);
         if (action != null) {
             action.Undo();
         }
     }
 }
        private static void ProcessBasicNotesInTimeRow(List <NoteData> basicNotes)
        {
            List <CustomNoteData> customNotes = basicNotes.Cast <CustomNoteData>().ToList();

            ProcessFlipData(customNotes);

            int customNoteCount = customNotes.Count;

            if (customNoteCount == 2)
            {
                float[] lineIndexes = new float[2];
                float[] lineLayers  = new float[2];
                for (int i = 0; i < customNoteCount; i++)
                {
                    dynamic dynData = customNotes[i].customData;
                    IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                    float?startRow    = position?.ElementAtOrDefault(0);
                    float?startHeight = position?.ElementAtOrDefault(1);

                    lineIndexes[i] = startRow.GetValueOrDefault(customNotes[i].lineIndex - 2);
                    lineLayers[i]  = startHeight.GetValueOrDefault((float)customNotes[i].noteLineLayer);
                }

                if (customNotes[0].noteType != customNotes[1].noteType && ((customNotes[0].noteType == NoteType.NoteA && lineIndexes[0] > lineIndexes[1]) ||
                                                                           (customNotes[0].noteType == NoteType.NoteB && lineIndexes[0] < lineIndexes[1])))
                {
                    for (int i = 0; i < customNoteCount; i++)
                    {
                        // apparently I can use customData to store my own variables in noteData, neat
                        dynamic dynData = customNotes[i].customData;
                        dynData.flipLineIndex = lineIndexes[1 - i];

                        float flipYSide = (lineIndexes[i] > lineIndexes[1 - i]) ? 1 : -1;
                        if ((lineIndexes[i] > lineIndexes[1 - i] && lineLayers[i] < lineLayers[1 - i]) || (lineIndexes[i] < lineIndexes[1 - i] &&
                                                                                                           lineLayers[i] > lineLayers[1 - i]))
                        {
                            flipYSide *= -1f;
                        }

                        dynData.flipYSide = flipYSide;
                    }
                }
            }
        }
示例#21
0
        private static void Postfix(NoteData noteData, ref Vector3 moveStartPos, ref Vector3 moveEndPos, ref Vector3 jumpEndPos, ref float jumpGravity)
        {
            if (noteData is CustomNoteData customData)
            {
                dynamic dynData = customData.customData;
                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                float?flipLineIndex           = (float?)Trees.at(dynData, "flipLineIndex");
                float?njs         = (float?)Trees.at(dynData, NOTEJUMPSPEED);
                float?spawnoffset = (float?)Trees.at(dynData, SPAWNOFFSET);

                float?startRow    = position?.ElementAtOrDefault(0);
                float?startHeight = position?.ElementAtOrDefault(1);

                Vector3 movestartposcopy = moveStartPos;
                Vector3 moveendposcopy   = moveEndPos;
                Vector3 jumpendposcopy   = jumpEndPos;

                if (position != null || flipLineIndex != null || njs.HasValue || spawnoffset.HasValue)
                {
                    GetNoteJumpValues(njs, spawnoffset, out float _, out float localJumpDistance, out Vector3 localMoveStartPos, out Vector3 localMoveEndPos, out Vector3 localJumpEndPos);

                    float localNoteJumpMovementSpeed = njs ?? _noteJumpMovementSpeed;

                    // NoteLineLayer.Base == noteData.startNoteLineLayer
                    // we avoid some math where the base game avoids spawning stacked notes together
                    Vector3 noteOffset = GetNoteOffset(noteData, startRow, (float)NoteLineLayer.Base);

                    float startLayerLineYPos = beatmapObjectSpawnMovementData.LineYPosForLineLayer(NoteLineLayer.Base);
                    float lineYPos           = LineYPosForLineLayer(noteData, startHeight);
                    // Magic numbers below found with linear regression y=mx+b using existing HighestJumpPosYForLineLayer values
                    float highestJump = startHeight.HasValue ? ((0.875f * lineYPos) + 0.639583f) + _jumpOffsetY :
                                        beatmapObjectSpawnMovementData.HighestJumpPosYForLineLayer(noteData.noteLineLayer);
                    jumpGravity = 2f * (highestJump - startLayerLineYPos) /
                                  Mathf.Pow(localJumpDistance / localNoteJumpMovementSpeed * 0.5f, 2f);

                    jumpEndPos = localJumpEndPos + noteOffset;

                    // IsBasicNote() check is skipped so bombs can flip too
                    Vector3 noteOffset2 = GetNoteOffset(noteData, flipLineIndex ?? startRow, (float)NoteLineLayer.Base);
                    moveStartPos = localMoveStartPos + noteOffset2;
                    moveEndPos   = localMoveEndPos + noteOffset2;
                }
            }
        }
示例#22
0
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
        private static void Postfix(NoteData __instance)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
        {
            if (__instance is CustomNoteData customData)
            {
                dynamic dynData = customData.customData;
                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                float?       flipLineIndex    = (float?)Trees.at(dynData, "flipLineIndex");
                List <float> localrot         = ((List <object>)Trees.at(dynData, LOCALROTATION))?.Select(n => Convert.ToSingle(n)).ToList();
                dynamic      rotation         = Trees.at(dynData, ROTATION);

                float?startRow = position?.ElementAtOrDefault(0);

                IDictionary <string, object> dictdata = dynData as IDictionary <string, object>;

                if (startRow.HasValue)
                {
                    dictdata[POSITION] = new List <object>()
                    {
                        ((startRow.Value + 0.5f) * -1) - 0.5f, position.ElementAtOrDefault(1)
                    };
                }

                if (flipLineIndex.HasValue)
                {
                    dynData.flipLineIndex = ((flipLineIndex.Value + 0.5f) * -1) - 0.5f;
                }

                if (localrot != null)
                {
                    List <float> rot            = localrot.Select(n => Convert.ToSingle(n)).ToList();
                    Quaternion   modifiedVector = Quaternion.Euler(rot[0], rot[1], rot[2]);
                    Vector3      vector         = new Quaternion(modifiedVector.x, modifiedVector.y * -1, modifiedVector.z * -1, modifiedVector.w).eulerAngles;
                    dictdata[LOCALROTATION] = new List <object> {
                        vector.x, vector.y, vector.z
                    };
                }

                if (rotation != null)
                {
                    if (rotation is List <object> list)
                    {
                        List <float> rot            = list.Select(n => Convert.ToSingle(n)).ToList();
                        Quaternion   modifiedVector = Quaternion.Euler(rot[0], rot[1], rot[2]);
                        Vector3      vector         = new Quaternion(modifiedVector.x, modifiedVector.y * -1, modifiedVector.z * -1, modifiedVector.w).eulerAngles;
                        dictdata[ROTATION] = new List <object> {
                            vector.x, vector.y, vector.z
                        };
                    }
                    else
                    {
                        dictdata[ROTATION] = rotation * -1;
                    }
                }
            }
        }
        private static void Postfix(List <NoteData> colorNotesData)
        {
            if (colorNotesData.FirstOrDefault() is CustomNoteData)
            {
                List <CustomNoteData> customNotes = colorNotesData.Cast <CustomNoteData>().ToList();

                int customNoteCount = customNotes.Count;
                if (customNoteCount == 2)
                {
                    float[] lineIndexes = new float[2];
                    float[] lineLayers  = new float[2];
                    for (int i = 0; i < customNoteCount; i++)
                    {
                        dynamic dynData = customNotes[i].customData;
                        IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                        lineIndexes[i] = position?.ElementAtOrDefault(0) ?? (customNotes[i].lineIndex - 2);
                        lineLayers[i]  = position?.ElementAtOrDefault(1) ?? (float)customNotes[i].noteLineLayer;
                    }

                    if (customNotes[0].colorType != customNotes[1].colorType && ((customNotes[0].colorType == ColorType.ColorA && lineIndexes[0] > lineIndexes[1]) ||
                                                                                 (customNotes[0].colorType == ColorType.ColorB && lineIndexes[0] < lineIndexes[1])))
                    {
                        for (int i = 0; i < customNoteCount; i++)
                        {
                            // apparently I can use customData to store my own variables in noteData, neat
                            dynamic dynData = customNotes[i].customData;
                            dynData.flipLineIndex = lineIndexes[1 - i];

                            float flipYSide = (lineIndexes[i] > lineIndexes[1 - i]) ? 1 : -1;
                            if ((lineIndexes[i] > lineIndexes[1 - i] && lineLayers[i] < lineLayers[1 - i]) || (lineIndexes[i] < lineIndexes[1 - i] &&
                                                                                                               lineLayers[i] > lineLayers[1 - i]))
                            {
                                flipYSide *= -1f;
                            }

                            dynData.flipYSide = flipYSide;
                        }
                    }
                }
            }
        }
示例#24
0
        private static void Prefix(List <NoteData> colorNotesData)
        {
            if (colorNotesData.FirstOrDefault() is CustomNoteData)
            {
                int customNoteCount = colorNotesData.Count;
                if (customNoteCount == 2)
                {
                    float[] lineIndexes = new float[2];
                    float[] lineLayers  = new float[2];
                    for (int i = 0; i < customNoteCount; i++)
                    {
                        Dictionary <string, object?> dynData  = ((CustomNoteData)colorNotesData[i]).customData;
                        IEnumerable <float?>?        position = dynData.GetNullableFloats(POSITION);
                        lineIndexes[i] = position?.ElementAtOrDefault(0) ?? (colorNotesData[i].lineIndex - 2);
                        lineLayers[i]  = position?.ElementAtOrDefault(1) ?? (float)colorNotesData[i].noteLineLayer;
                    }

                    if (colorNotesData[0].colorType != colorNotesData[1].colorType && ((colorNotesData[0].colorType == ColorType.ColorA && lineIndexes[0] > lineIndexes[1]) ||
                                                                                       (colorNotesData[0].colorType == ColorType.ColorB && lineIndexes[0] < lineIndexes[1])))
                    {
                        for (int i = 0; i < customNoteCount; i++)
                        {
                            // apparently I can use customData to store my own variables in noteData, neat
                            // ^ comment from a very young and naive aero
                            Dictionary <string, object?> dynData = ((CustomNoteData)colorNotesData[i]).customData;
                            dynData["flipLineIndex"] = lineIndexes[1 - i];

                            float flipYSide = (lineIndexes[i] > lineIndexes[1 - i]) ? 1 : -1;
                            if ((lineIndexes[i] > lineIndexes[1 - i] && lineLayers[i] < lineLayers[1 - i]) || (lineIndexes[i] < lineIndexes[1 - i] &&
                                                                                                               lineLayers[i] > lineLayers[1 - i]))
                            {
                                flipYSide *= -1f;
                            }

                            dynData["flipYSide"] = flipYSide;
                        }
                    }
                }
            }
        }
 private static float GetCustomLength(float @default, ObstacleData obstacleData)
 {
     if (obstacleData is CustomObstacleData customData)
     {
         dynamic dynData            = customData.customData;
         IEnumerable <float?> scale = ((List <object>)Trees.at(dynData, SCALE))?.Select(n => n.ToNullableFloat());
         float?length = scale?.ElementAtOrDefault(2);
         if (length.HasValue)
         {
             return(length.Value * _noteLinesDistance);
         }
     }
     return(@default);
 }
示例#26
0
        /// <summary>
        /// Calculates Average True Range indicator
        /// </summary>
        /// <param name="highs">Signal representing price highs</param>
        /// <param name="lows">Signal representing price lows</param>
        /// <param name="closes">Signal representing closing prices</param>
        /// <param name="periods">Number of periods</param>
        /// <returns>Object containing operation results</returns>
        public static ATRResult ATR(IEnumerable<double> highs, IEnumerable<double> lows, IEnumerable<double> closes, int periods)
        {
            // calculate True Range first
            var trueRangeList = new List<double>();
            
            for (int i = 0; i < highs.Count(); i++)
            {
                double currentHigh = highs.ElementAt(i);
                double currentLow = lows.ElementAt(i);
                double previousClose = closes.ElementAtOrDefault(i - 1);

                double highMinusLow = currentHigh - currentLow;
                double highMinusPrevClose = i != 0 ? Math.Abs(currentHigh - previousClose) : 0;
                double lowMinusPrevClose = i != 0 ? Math.Abs(currentLow - previousClose) : 0;

                double trueRangeValue = highMinusLow;

                if (highMinusPrevClose > trueRangeValue)
                {
                    trueRangeValue = highMinusPrevClose;
                }
                if (lowMinusPrevClose > trueRangeValue)
                {
                    trueRangeValue = lowMinusPrevClose;
                }

                trueRangeList.Add(trueRangeValue);
            }

            // calculate Average True Range
            var atrList = new List<double>();

            double initialATR = trueRangeList.Take(periods).Average();
            atrList.Add(initialATR);

            for (int i = periods; i < trueRangeList.Count; i++)
            {
                double currentATR = (atrList[i - periods] * (periods - 1) + trueRangeList[i]) / periods;
                atrList.Add(currentATR);
            }

            var result = new ATRResult()
            {
                StartIndexOffset = periods - 1,
                Values = atrList
            };

            return result;
        }
        private IEnumerable<ScenarioLine> PreprocessLines(IEnumerable<ScenarioLine> lines, IEnumerable<string> fieldNames,
                                                    IEnumerable<string> example)
        {
            foreach (var line in lines)
            {
                var processed = line.Text;

                for (var fieldIndex = 0; fieldIndex < fieldNames.ToArray().Length; fieldIndex++)
                {
                    var name = fieldNames.ToArray()[fieldIndex];
                    processed = processed.Replace("<" + name + ">", example.ElementAtOrDefault(fieldIndex));
                }
                yield return new ScenarioLine {Text = processed, LineNumber = line.LineNumber};
            }
        }
示例#28
0
文件: Program.cs 项目: RogaDanar/Dnd
        /// <summary>
        /// Gets the ability scores from the program argumentlist by index. If the element is missing 
        /// a default value is used
        /// </summary>
        private static Dictionary<AbilityType, int> GetAbilityScores(IEnumerable<string> abilities)
        {
            const string defaultScore = "11";
            var str = Int32.Parse(abilities.ElementAtOrDefault(0) ?? defaultScore);
            var dex = Int32.Parse(abilities.ElementAtOrDefault(1) ?? defaultScore);
            var con = Int32.Parse(abilities.ElementAtOrDefault(2) ?? defaultScore);
            var intel = Int32.Parse(abilities.ElementAtOrDefault(3) ?? defaultScore);
            var wis = Int32.Parse(abilities.ElementAtOrDefault(4) ?? defaultScore);
            var cha = Int32.Parse(abilities.ElementAtOrDefault(5) ?? defaultScore);

            var abilityScores = new Dictionary<AbilityType, int>() {
                {AbilityType.Strength, str},
                {AbilityType.Dexterity, dex},
                {AbilityType.Constitution, con},
                {AbilityType.Intelligence, intel},
                {AbilityType.Wisdom, wis},
                {AbilityType.Charisma, cha}
            };
            return abilityScores;
        }
示例#29
0
        public Servico Obter(int idServico)
        {
            IEnumerable <Servico> servicos = GetQuery().Where(servicoModel => servicoModel.Id.Equals(idServico));

            return(servicos.ElementAtOrDefault(0));
        }
示例#30
0
 public IFixtureMethod this[int index] => methods.ElementAtOrDefault(index);
示例#31
0
        public void LimitCommand(CommandContext context, IEnumerable<string> arguments)
        {
            if (arguments.Count() == 0)
            {
                SendInContext(context, "The current limit is: {0} {1}", Manager.Limit, Manager.LimitType);
            }
            else
            {
                int result;
                if (int.TryParse(arguments.First(), out result))
                {
                    Manager.Limit = result;

                    if (arguments.ElementAtOrDefault(1)?.ToLowerInvariant()?.StartsWith("r") == true)
                        Manager.LimitType = GameManager.LimitMode.Rounds;
                    else
                        Manager.LimitType = GameManager.LimitMode.Points;

                    Manager.SendPublic(context.Nick, "Set the limit to {0} {1}!", result, Manager.LimitType);
                }
                else
                {
                    SendInContext(context, "Failed to set the limit");
                }
            }
        }
        public ActionResult UploadImage(IEnumerable<HttpPostedFileBase> files, int productID)
        {
            string uploadMessage = FILE_UPLOAD_SUCCESSFUL;
            bool fileUploadFailed = false;
            bool fileIsValid = true;
            try
            {
                var request = System.Web.HttpContext.Current.Request;

                if (productID == 0)
                {
                    uploadMessage = "Can't except product id 0. Add a product -> Save Changes -> Select the row -> Upload image";
                    fileIsValid = false;
                    fileUploadFailed = true;
                }

                var product = productHandler.GetProduct(productID);
                string destinationFilePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/products");
                string nowTicks = DateTime.Now.Ticks.ToString();


                if (files.ElementAtOrDefault(0) != null)
                {
                    fileIsValid = true;
                    FileInfo fi = new FileInfo(files.ElementAtOrDefault(0).FileName);
                    if (!fi.Extension.ToLower().Equals(".jpg"))
                    {
                        uploadMessage = "Please upload a valid [.jpg] image file";
                        fileIsValid = false;
                    }

                    if (fileIsValid)
                    {
                        string sourceFile = string.Format(@"{0}\{1}", destinationFilePath, product.OriginalImageId);
                        files.ElementAtOrDefault(0).SaveAs(sourceFile);

                        logger.InfoFormat("Saved input file as {0}", sourceFile);



                        Bitmap bmOriginal = new Bitmap(sourceFile);
                        ImageHandler ih = new ImageHandler();


                        if (product != null)
                        {
                            ih.Save(bmOriginal, 100, 100, 100, string.Format(@"{0}\{1}", destinationFilePath, product.SmallImageId));
                            logger.InfoFormat("Resized input file and saved as {0}", product.SmallImageId);

                            ih.Save(bmOriginal, 400, 400, 100, string.Format(@"{0}\{1}", destinationFilePath, product.MediumImageId));
                            logger.InfoFormat("Resized input file and saved as {0}", product.MediumImageId);

                            ih.Save(bmOriginal, 400, 400, 100, string.Format(@"{0}\{1}", destinationFilePath, product.LargeImageId));
                            logger.InfoFormat("Resized input file and saved as {0}", product.LargeImageId);
                        }


                        logger.InfoFormat("Resized input file and saved as {0}", destinationFilePath);
                    }
                }

                fileIsValid = true;
                if (files.ElementAtOrDefault(1) != null)
                {
                    FileInfo fi = new FileInfo(files.ElementAtOrDefault(1).FileName);
                    if (!fi.Extension.ToLower().Equals(".jpg"))
                    {
                        uploadMessage = "Please upload a valid [.jpg] image 1 file";
                        fileIsValid = false;
                    }

                    if (fileIsValid)
                    {
                        if(string.IsNullOrEmpty(product.ImageIdOne))
                            product.ImageIdOne = string.Format("AMZ_Image_1_{0}.jpg", nowTicks);

                        string sourceFile = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdOne);
                        files.ElementAtOrDefault(1).SaveAs(sourceFile);

                        logger.InfoFormat("Saved input file as {0}", sourceFile);
                    }
                }


                if (files.ElementAtOrDefault(2) != null)
                {
                    FileInfo fi = new FileInfo(files.ElementAtOrDefault(2).FileName);
                    if (!fi.Extension.ToLower().Equals(".jpg"))
                    {
                        uploadMessage = "Please upload a valid [.jpg] image 2 file";
                        fileIsValid = false;
                    }

                    if (fileIsValid)
                    {
                        if (string.IsNullOrEmpty(product.ImageIdTwo))
                            product.ImageIdTwo = string.Format("AMZ_Image_2_{0}.jpg", nowTicks);

                        string sourceFile = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdTwo);
                        files.ElementAtOrDefault(2).SaveAs(sourceFile);

                        logger.InfoFormat("Saved input file as {0}", sourceFile);
                    }
                }

                if (files.ElementAtOrDefault(3) != null)
                {
                    FileInfo fi = new FileInfo(files.ElementAtOrDefault(3).FileName);
                    if (!fi.Extension.ToLower().Equals(".jpg"))
                    {
                        uploadMessage = "Please upload a valid [.jpg] image 3 file";
                        fileIsValid = false;
                    }

                    if (fileIsValid)
                    {
                        if (string.IsNullOrEmpty(product.ImageIdThree))
                            product.ImageIdThree = string.Format("AMZ_Image_3_{0}.jpg", nowTicks);

                        string sourceFile = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdThree);
                        files.ElementAtOrDefault(3).SaveAs(sourceFile);

                        logger.InfoFormat("Saved input file as {0}", sourceFile);
                    }
                }

                if (files.ElementAtOrDefault(4) != null)
                {
                    FileInfo fi = new FileInfo(files.ElementAtOrDefault(4).FileName);
                    if (!fi.Extension.ToLower().Equals(".jpg"))
                    {
                        uploadMessage = "Please upload a valid [.jpg] image 4 file";
                        fileIsValid = false;
                    }

                    if (fileIsValid)
                    {
                        if (string.IsNullOrEmpty(product.ImageIdFour))
                            product.ImageIdFour = string.Format("AMZ_Image_4_{0}.jpg", nowTicks);

                        string sourceFile = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdFour);
                        files.ElementAtOrDefault(4).SaveAs(sourceFile);

                        logger.InfoFormat("Saved input file as {0}", sourceFile);
                    }
                }

                if (files.ElementAtOrDefault(5) != null)
                {
                    FileInfo fi = new FileInfo(files.ElementAtOrDefault(5).FileName);
                    if (!fi.Extension.ToLower().Equals(".jpg"))
                    {
                        uploadMessage = "Please upload a valid [.jpg] image 5 file";
                        fileIsValid = false;
                    }

                    if (fileIsValid)
                    {
                        if (string.IsNullOrEmpty(product.ImageIdFive))
                            product.ImageIdFive = string.Format("AMZ_Image_5_{0}.jpg", nowTicks);

                        string sourceFile = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdFive);
                        files.ElementAtOrDefault(5).SaveAs(sourceFile);

                        logger.InfoFormat("Saved input file as {0}", sourceFile);
                    }
                }


                productHandler.UpdateProduct(product);
                logger.InfoFormat(FILE_UPLOAD_SUCCESSFUL);
            }
            catch(Exception ex)
            {
                logger.Error(ex);
                uploadMessage = string.Format("File upload failed: Error: {0}", ex.Message);
                fileUploadFailed = true;
            }


            return RedirectToAction("ManageProduct", new RouteValueDictionary(
                                                new { controller = "ProductAdmin", action = "ManageProduct", message =  uploadMessage, status = fileUploadFailed }));
        }
        /// <summary>
        /// Reads all permissions from user right object table and creates bit masks and saves them
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="colName"></param>
        /// <param name="ids"></param>
        /// <param name="idents">if given, will be used as row id</param>
        private void MigrateAccessRights(IList <MigrationResult> migrationResults, string tableName, string colName, IEnumerable <Guid> ids, IEnumerable <int> idents = null)
        {
            int rowCounter = 0;

            sqlService.OpenConnection((connection) =>
            {
                int counter = 0;
                foreach (var id in ids)
                {
                    rowCounter++;

                    if (rowCounter % 500 == 0)
                    {
                        MemAlloc.FinalizeCollectedData();
                    }

                    IEnumerable <RightObject> rightObjects = null;

                    try
                    {
                        rightObjects = connection.Query <RightObject>("SELECT (select Ident from ESS_MS_Intern_Groups where GroupId = ESS_MS_Intern_RightObjects.GroupId) as GroupIdent, UserIdent, RightType from ESS_MS_Intern_RightObjects where Guid = :Guid and AllowAccess = 1", new { Guid = id });

                        migrationResults.Add(new MigrationResult
                        {
                            TableName = "ESS_MS_Intern_Groups",
                            Status    = MigrationStatus.Done
                        });
                    }
                    catch (Exception ex)
                    {
                        migrationResults.Add(new MigrationResult
                        {
                            TableName = "ESS_MS_Intern_Groups",
                            Status    = MigrationStatus.Failed,
                            Exception = ex
                        });
                    }

                    if (rightObjects == null)
                    {
                        continue;
                    }

                    var userReadIds  = new List <int>();
                    var userWriteIds = new List <int>();
                    var userFullIds  = new List <int>();

                    var groupReadIds  = new List <int>();
                    var groupWriteIds = new List <int>();
                    var groupFullIds  = new List <int>();

                    foreach (var rightObj in rightObjects)
                    {
                        if (rightObj.GroupIdent > 0 && rightObj.GroupIdent < 32000)
                        {
                            // We need to set full acccess here, because the other access types are never used...
                            groupFullIds.Add(rightObj.GroupIdent);
                        }

                        if (rightObj.UserIdent > 0 && rightObj.UserIdent < 32000)
                        {
                            // We need to set full acccess here, because the other access types are never used...
                            userFullIds.Add(rightObj.UserIdent);
                        }
                    }

                    if (userReadIds.Count == 0 && userWriteIds.Count == 0 && userFullIds.Count == 0 &&
                        groupReadIds.Count == 0 && groupWriteIds.Count == 0 && groupFullIds.Count == 0)
                    {
                        continue;
                    }

                    userReadIds   = userReadIds.Distinct().ToList();
                    userWriteIds  = userWriteIds.Distinct().ToList();
                    userFullIds   = userFullIds.Distinct().ToList();
                    groupReadIds  = groupReadIds.Distinct().ToList();
                    groupWriteIds = groupWriteIds.Distinct().ToList();
                    groupFullIds  = groupFullIds.Distinct().ToList();

                    // Sort is a void, so is not part of the method chain above.
                    userReadIds.Sort(); userWriteIds.Sort(); userFullIds.Sort();
                    groupReadIds.Sort(); groupWriteIds.Sort(); groupFullIds.Sort();

                    var newAccessRights = new RowAccess();
                    if (userReadIds.Count > 0)
                    {
                        newAccessRights.UserReadAccess = userReadIds;
                    }
                    if (userWriteIds.Count > 0)
                    {
                        newAccessRights.UserWriteAccess = userWriteIds;
                    }
                    if (userFullIds.Count > 0)
                    {
                        newAccessRights.UserFullAccess = userFullIds;
                    }
                    if (groupReadIds.Count > 0)
                    {
                        newAccessRights.GroupReadAccess = groupReadIds;
                    }
                    if (groupWriteIds.Count > 0)
                    {
                        newAccessRights.GroupWriteAccess = groupWriteIds;
                    }
                    if (groupFullIds.Count > 0)
                    {
                        newAccessRights.GroupFullAccess = groupFullIds;
                    }

                    try
                    {
                        if (idents != null)
                        {
                            SetAccess(tableName, colName, idents.ElementAtOrDefault(counter), newAccessRights);
                        }
                        else
                        {
                            SetAccess(tableName, colName, id, newAccessRights);
                        }

                        migrationResults.Add(new MigrationResult
                        {
                            TableName = tableName,
                            Status    = MigrationStatus.Done
                        });
                    }
                    catch (Exception ex)
                    {
                        migrationResults.Add(new MigrationResult {
                            TableName = tableName,
                            Status    = MigrationStatus.Failed,
                            Exception = ex
                        });
                    }

                    counter++;
                }

                return(0);
            });
        }
示例#34
0
 public void ElementAtOrDefault(IEnumerable <int> source, int index, int expected)
 {
     Assert.Equal(expected, source.ElementAtOrDefault(index));
 }
示例#35
0
        public void AddRange(IEnumerable <TEntity> data)
        {
            if (CanAdd(data, true) == false)
            {
                return;
            }
            if (data.ElementAtOrDefault(1) == default(TEntity))
            {
                Add(data.First());
                return;
            }
            if (_tableIdentitys.Length > 0)
            {
                //有自增,马上执行
                switch (_db.OrmOriginal.Ado.DataType)
                {
                case DataType.SqlServer:
                case DataType.OdbcSqlServer:
                case DataType.PostgreSQL:
                case DataType.OdbcPostgreSQL:
                case DataType.KingbaseES:
                case DataType.OdbcKingbaseES:
                case DataType.ShenTong:
                    DbContextFlushCommand();
                    var rets = this.OrmInsert(data).ExecuteInserted();
                    if (rets.Count != data.Count())
                    {
                        throw new Exception($"特别错误:批量添加失败,{_db.OrmOriginal.Ado.DataType} 的返回数据,与添加的数目不匹配");
                    }
                    _db._entityChangeReport.AddRange(rets.Select(a => new DbContext.EntityChangeReport.ChangeInfo {
                        Object = a, Type = DbContext.EntityChangeType.Insert
                    }));
                    var idx = 0;
                    foreach (var s in data)
                    {
                        _db.OrmOriginal.MapEntityValue(_entityType, rets[idx++], s);
                    }
                    IncrAffrows(rets.Count);
                    AttachRange(rets);
                    if (_db.Options.EnableAddOrUpdateNavigateList)
                    {
                        foreach (var item in data)
                        {
                            AddOrUpdateNavigateList(item, true);
                        }
                    }
                    return;

                default:
                    foreach (var s in data)
                    {
                        AddPriv(s, false);
                    }
                    return;
                }
            }
            else
            {
                //进入队列,等待 SaveChanges 时执行
                foreach (var item in data)
                {
                    EnqueueToDbContext(DbContext.EntityChangeType.Insert, CreateEntityState(item));
                }
                AttachRange(data);
                if (_db.Options.EnableAddOrUpdateNavigateList)
                {
                    foreach (var item in data)
                    {
                        AddOrUpdateNavigateList(item, true);
                    }
                }
            }
        }
示例#36
0
        private IEnumerable<IEnumerable<string>> ShareBlocks(IEnumerable<string> shares)
        {
            List<string> batch = new List<string>();
            for (int i = 0; i < shares.Count(); i++)
            {
                if (batch.Count() == 0 || batch.Count() < maxShares)
                    batch.Add(shares.ElementAt(i));

                if (batch.Count() >= maxShares || shares.ElementAtOrDefault(i+1) == null )
                {
                    if (batch.Count() > 0)
                        yield return batch;
                    batch = new List<string>();
                }

            }
        }
示例#37
0
 public DataTuple(IEnumerable<string> items)
 {
     Label = items.ElementAtOrDefault(0) ?? "";
     Value = items.ElementAtOrDefault(1) ?? "";
     Unit = items.ElementAtOrDefault(2) ?? "";
 }
示例#38
0
        public RegistryHost SelectHost(IEnumerable <RegistryHost> hosts, JobInfo jobInfo)
        {
            int num = random.Next(0, hosts.Count());

            return(hosts.ElementAtOrDefault(num));
        }
示例#39
0
        public override CompileResult Compile(IEnumerable<Expression> children, ParsingContext context)
        {
            // 2 is allowed, Excel returns FALSE if false is the outcome of the expression
            if(children.Count() < 2) throw new ExcelErrorValueException(eErrorType.Value);
            var args = new List<FunctionArgument>();
            Function.BeforeInvoke(context);
            var firstChild = children.ElementAt(0);
            var v = firstChild.Compile().Result;

            /****  Handle names and ranges ****/
            if (v is ExcelDataProvider.INameInfo)
            {
                v = ((ExcelDataProvider.INameInfo)v).Value;
            }

            if (v is ExcelDataProvider.IRangeInfo)
            {
                var r=((ExcelDataProvider.IRangeInfo)v);
                if(r.GetNCells()>1)
                {
                    throw(new ArgumentException("Logical can't be more than one cell"));
                }
                v = r.GetOffset(0, 0);
            }
            bool boolVal;
            if(v is bool)
            {
                boolVal = (bool)v;
            }
            else if(!Utils.ConvertUtil.TryParseBooleanString(v, out boolVal))
            {
                if(OfficeOpenXml.Utils.ConvertUtil.IsNumeric(v))
                {
                    boolVal = OfficeOpenXml.Utils.ConvertUtil.GetValueDouble(v)!=0;
                }
                else
                {
                    throw (new ArgumentException("Invalid logical test"));
                }
            }
            /****  End Handle names and ranges ****/

            args.Add(new FunctionArgument(boolVal));
            if (boolVal)
            {
                var val = children.ElementAt(1).Compile().Result;
                args.Add(new FunctionArgument(val));
                args.Add(new FunctionArgument(null));
            }
            else
            {
                object val;
                var child = children.ElementAtOrDefault(2);
                if (child == null)
                {
                    // if no false expression given, Excel returns false
                    val = false;
                }
                else
                {
                    val = child.Compile().Result;
                }
                args.Add(new FunctionArgument(null));
                args.Add(new FunctionArgument(val));
            }
            return Function.Execute(args, context);
        }
        public void UpdateGame()
        {
            if (Followee != null) { Target = Followee.Pos; }
            if (Target == null) { return; }
            if (_krtransform.Pos == Target) {
                Target = null;
                Followee = null; // TEST
                return;
            }

            if (_currentFrame > 0) {
                --_currentFrame;
                return;
            } else {
                _currentFrame = Speed;
            }

            _waypoints = KRFacade.FindPath(_krtransform.Pos, Target);
            __waynodes.AddRange(_waypoints.Where(w => !__waynodes.Contains(w)));

            if (_waypoints == null) {
                Target = null;
            } else {
                QuadTreeNode<KRTransform> node;
                Vec2 nextPos = _krtransform.Pos;

                if (!_waypoints.Any()) {
                    nextPos = Target;
                } else {
                    bool canTraceStraightLine = true;
                    do {
                        node = _waypoints.ElementAtOrDefault(1);
                        nextPos = (node == null) ? Target : node.Pos;
                        Bresenham.Line(_krtransform.Pos.X, _krtransform.Pos.Y, nextPos.X, nextPos.Y, delegate(int x, int y) {
                            if (!KRFacade.IsEmpty(new Vec2(x,y))) {
                                canTraceStraightLine = false;
                                if (nextPos == Target) { nextPos = _waypoints.First().Pos; }
                                return false;
                            }
                            return true;
                        });
                        if (canTraceStraightLine) {
                            if (nextPos != Target) { _waypoints = _waypoints.Skip(1); }
                        } else {
                            node = _waypoints.FirstOrDefault();
                            nextPos = (node == null) ? Target : node.Pos;
                        }
                    } while(canTraceStraightLine && nextPos != Target);

                }

                var lt = new List<Vec2>();

                Bresenham.Line(_krtransform.Pos.X, _krtransform.Pos.Y, nextPos.X, nextPos.Y, delegate(int x, int y) {
                    if (lt.Count == 0) {
                        nextPos = new Vec2(x,y);
                    }
                    lt.Add(new Vec2(x,y));
                    return true;
                });
                if (nextPos != _krtransform.Pos && KRFacade.IsEmpty(nextPos)) {
                    KRFacade.Remove(GetComponent<KRTransform>());
                    _krtransform.Pos = nextPos;
                    KRFacade.Add(GetComponent<KRTransform>());
            #if UNITY_EDITOR
                    __way.Add(_krtransform.Pos);
            #endif
                } else {
                    _waypoints = null;
                    Target = null;
                    Followee = null;
                }
            }
        }
示例#41
0
        private IEnumerable<IEnumerable<IField>> FieldBlocks(IEnumerable<IField> fields)
        {
            List<IField> batch = new List<IField>();
            for (int i = 0; i < fields.Count(); i++)
            {
                if (batch.Count() == 0 || (batch.Last().CompareTo(fields.ElementAtOrDefault(i))==0 && batch.Count() < maxFields))
                {
                    batch.Add(fields.ElementAt(i));
                }

                if (batch.Last().CompareTo(fields.ElementAtOrDefault(i+1)) != 0 || batch.Count() >= maxFields)
                {
                    if (batch.Count()>0)
                        yield return batch;
                    batch = new List<IField>();
                }
            }
        }
示例#42
0
 /// <summary>
 /// Sets all courses states.
 /// </summary>
 /// <param name="courses">The courses.</param>
 /// <param name="states">The states.</param>
 private void SetAllCoursesStates(IEnumerable<string> courses, IEnumerable<CloudEDU.Common.Constants.CourseAvaiStates> states)
 {
     for (int i = 0; i < courses.Count(); ++i)
     {
         string courseName = courses.ElementAtOrDefault(i);
         SetCourseState(courseName, states.ElementAtOrDefault(i));
     }
 }
示例#43
0
        private List<PricingModelItem> BuildCalendar(int daysInMonth, IEnumerable<RateCategory> rateCategories, IEnumerable<RoomTypeInventory> roomTypeInventories)
        {
            var result = new List<PricingModelItem>();

            for (var i = 0; i < daysInMonth; i++)
            {
                var roomTypeInventory = roomTypeInventories.ElementAtOrDefault(i);
                if (roomTypeInventory.IsNull())
                {
                    result.Add(new PricingModelItem { Id = 0, Color = "ffffff" });
                }
                else
                {
                    if(roomTypeInventory.RateCategoryId.IsNull())
                    {
                        result.Add(new PricingModelItem { Id = 0, Color = "ffffff" });
                    }
                    else
                    {
                        var rateCategory = rateCategories.First(x => x.Id == roomTypeInventory.RateCategoryId);
                        result.Add(new PricingModelItem { Id = rateCategory.Id, Color = rateCategory.Color });
                    }
                }
            }

            return result;
        }
        private static void Postfix(List <NoteData> notes)
        {
            if (notes.FirstOrDefault() is CustomNoteData)
            {
                List <CustomNoteData> customNotes = notes.Cast <CustomNoteData>().ToList();

                _notesInColumns.Clear();
                for (int i = 0; i < customNotes.Count; i++)
                {
                    CustomNoteData noteData = customNotes[i];

                    IEnumerable <float?> position = ((List <object>)Trees.at(noteData.customData, POSITION))?.Select(n => n.ToNullableFloat());
                    float lineIndex = position?.ElementAtOrDefault(0) ?? (noteData.lineIndex - 2);
                    float lineLayer = position?.ElementAtOrDefault(1) ?? (float)noteData.noteLineLayer;

                    if (!_notesInColumns.TryGetValue(lineIndex, out List <CustomNoteData> list))
                    {
                        list = new List <CustomNoteData>();
                        _notesInColumns.Add(lineIndex, list);
                    }

                    bool flag = false;
                    for (int k = 0; k < list.Count; k++)
                    {
                        IEnumerable <float?> listPosition = ((List <object>)Trees.at(list[k].customData, POSITION))?.Select(n => n.ToNullableFloat());
                        float listLineLayer = listPosition?.ElementAtOrDefault(1) ?? (float)list[k].noteLineLayer;
                        if (listLineLayer > lineLayer)
                        {
                            list.Insert(k, noteData);
                            flag = true;
                            break;
                        }
                    }

                    if (!flag)
                    {
                        list.Add(noteData);
                    }
                }

                foreach (KeyValuePair <float, List <CustomNoteData> > keyValue in _notesInColumns)
                {
                    List <CustomNoteData> list2 = keyValue.Value;
                    for (int m = 0; m < list2.Count; m++)
                    {
                        list2[m].customData.startNoteLineLayer = m;
                    }
                }

                // Process flip data
                List <CustomNoteData> flipNotes = new List <CustomNoteData>(customNotes);
                for (int i = flipNotes.Count - 1; i >= 0; i--)
                {
                    dynamic dynData           = flipNotes[i].customData;
                    IEnumerable <float?> flip = ((List <object>)Trees.at(dynData, FLIP))?.Select(n => n.ToNullableFloat());
                    float?flipX = flip?.ElementAtOrDefault(0);
                    float?flipY = flip?.ElementAtOrDefault(1);
                    if (flipX.HasValue || flipY.HasValue)
                    {
                        if (flipX.HasValue)
                        {
                            dynData.flipLineIndex = flipX.Value;
                        }

                        if (flipY.HasValue)
                        {
                            dynData.flipYSide = flipY.Value;
                        }

                        flipNotes.Remove(flipNotes[i]);
                    }
                }

                flipNotes.ForEach(c => c.customData.flipYSide = 0);
            }
        }
示例#45
0
 public TextSection(IEnumerable<string> items)
 {
     Header = items.ElementAtOrDefault(0) ?? "";
     Body = items.ElementAtOrDefault(1) ?? "";
 }
示例#46
0
        /// <summary>
        /// Obtém pelo identificado do autor
        /// </summary>
        /// <param name="idAutor"></param>
        /// <returns></returns>
        public Autor Obter(int idAutor)
        {
            IEnumerable <Autor> autores = GetQuery().Where(autorModel => autorModel.IdAutor.Equals(idAutor));

            return(autores.ElementAtOrDefault(0));
        }
        private static IRenderer createNewDefaultClassBreaksRenderer(GraphicsLayer graphicsLayer, FieldInfo attributeField, double min, double max, int numOfClassBreaks, LinearGradientBrush defaultColorRampGradientBrush, IEnumerable<Symbol> existingSymbolSet)
        {
            Symbol defaultSymbol = graphicsLayer.GetDefaultSymbolClone();
            ClassBreaksRenderer renderer = new ClassBreaksRenderer()
            {
                Field = attributeField != null ? attributeField.Name : null,
                DefaultSymbol = defaultSymbol,
            };
            List<Symbol> symbols = new List<Symbol>();
            if (numOfClassBreaks < 2) // classbreaks renderer must have atleast 2 classbreaks
                numOfClassBreaks = 2;
            double rangeSize = Math.Round((max - min) / numOfClassBreaks, 2);
            double rangeDelta = 1.0; // delta between 2 class ranges // we choose an integral size
            double lastRangeDeltaIncr = 1.0; // SL core api requires the last classbreak to be greater than max value of dataset
            bool fractionalIncrement = false;
            if (Math.Round(max, 0) != max)// we are dealing with a non-integeral values, so our delta's are in fractional increments
            {
                fractionalIncrement = true;
                rangeDelta = 0.01;
                lastRangeDeltaIncr = 0.01;
            }

            double startValue = min;
            for (int i = 0; i < numOfClassBreaks; i++)
            {
                Symbol symbol = null;
                if (existingSymbolSet != null)
                    symbol = existingSymbolSet.ElementAtOrDefault(i);
                if (symbol == null)
                    symbol = graphicsLayer.GetDefaultSymbolClone();
                double endValue = (startValue + rangeSize) - rangeDelta;
                ClassBreakInfo classBreak = new ClassBreakInfo()
                {
                    MinimumValue = fractionalIncrement ? startValue : Math.Floor(startValue),
                    MaximumValue = fractionalIncrement ? endValue : Math.Floor(endValue),
                    Symbol = symbol,
                };
                if (i == numOfClassBreaks - 1) // last class break
                {
                    classBreak.MaximumValue = max + lastRangeDeltaIncr;
                    if (max > 1000000) // SL has a limitation on values greater than a million http://msdn.microsoft.com/en-us/library/bb412393.aspx
                        classBreak.MaximumValue += 2.0;// the +2 is to workaround Silverlights limitation of single precision values
                }
                symbols.Add(symbol);
                renderer.Classes.Add(classBreak);
                startValue += rangeSize;
            }
            if (defaultColorRampGradientBrush != null)
            {
                if (existingSymbolSet == null) // apply the gradient brush, only if symbols have not been pre-defined
                {
                    applyLinearGradientBrushToSymbolSet(symbols, defaultColorRampGradientBrush, defaultSymbol);
                }
            }
            return renderer;
        }
示例#48
0
        public override CompileResult Compile(IEnumerable <Expression> children, ParsingContext context)
        {
            // 2 is allowed, Excel returns FALSE if false is the outcome of the expression
            if (children.Count() < 2)
            {
                throw new ExcelErrorValueException(eErrorType.Value);
            }
            var args = new List <FunctionArgument>();

            Function.BeforeInvoke(context);
            var firstChild = children.ElementAt(0);
            var v          = firstChild.Compile().Result;

            /****  Handle names and ranges ****/
            if (v is ExcelDataProvider.INameInfo)
            {
                v = ((ExcelDataProvider.INameInfo)v).Value;
            }

            if (v is ExcelDataProvider.IRangeInfo)
            {
                var r = ((ExcelDataProvider.IRangeInfo)v);
                if (r.GetNCells() > 1)
                {
                    throw(new ArgumentException("Logical can't be more than one cell"));
                }
                v = r.GetOffset(0, 0);
            }
            bool boolVal;

            if (v is bool)
            {
                boolVal = (bool)v;
            }
            else if (!Utils.ConvertUtil.TryParseBooleanString(v, out boolVal))
            {
                if (OfficeOpenXml.Utils.ConvertUtil.IsNumeric(v))
                {
                    boolVal = OfficeOpenXml.Utils.ConvertUtil.GetValueDouble(v) != 0;
                }
                else
                {
                    throw (new ArgumentException("Invalid logical test"));
                }
            }
            /****  End Handle names and ranges ****/

            args.Add(new FunctionArgument(boolVal));
            if (boolVal)
            {
                var val = children.ElementAt(1).Compile().Result;
                args.Add(new FunctionArgument(val));
                args.Add(new FunctionArgument(null));
            }
            else
            {
                object val;
                var    child = children.ElementAtOrDefault(2);
                if (child == null)
                {
                    // if no false expression given, Excel returns false
                    val = false;
                }
                else
                {
                    val = child.Compile().Result;
                }
                args.Add(new FunctionArgument(null));
                args.Add(new FunctionArgument(val));
            }
            return(Function.Execute(args, context));
        }
 public void ElementAtOrDefault(IEnumerable<int> source, int index, int expected)
 {
     Assert.Equal(expected, source.ElementAtOrDefault(index));
 }
示例#50
0
        public Delaunator(IEnumerable <IPoint> points)
        {
            if (points.Count() < 2)
            {
                throw new ArgumentOutOfRangeException("Need at least 3 points");
            }
            Points = points.ToList();
            coords = new double[Points.Count() * 2];

            for (var i = 0; i < Points.Count(); i++)
            {
                var p = Points.ElementAtOrDefault(i);
                coords[2 * i]     = p.X;
                coords[2 * i + 1] = p.Y;
            }

            var n            = coords.Length >> 1;
            var maxTriangles = 2 * n - 5;

            Triangles = new int[maxTriangles * 3];

            Halfedges = new int[maxTriangles * 3];
            hashSize  = (int)Math.Ceiling(Math.Sqrt(n));

            hullPrev = new int[n];
            hullNext = new int[n];
            hullTri  = new int[n];
            hullHash = new int[hashSize];

            var ids = new int[n];

            var minX = double.PositiveInfinity;
            var minY = double.PositiveInfinity;
            var maxX = double.NegativeInfinity;
            var maxY = double.NegativeInfinity;

            for (var i = 0; i < n; i++)
            {
                var x = coords[2 * i];
                var y = coords[2 * i + 1];
                if (x < minX)
                {
                    minX = x;
                }
                if (y < minY)
                {
                    minY = y;
                }
                if (x > maxX)
                {
                    maxX = x;
                }
                if (y > maxY)
                {
                    maxY = y;
                }
                ids[i] = i;
            }

            var cx = (minX + maxX) / 2;
            var cy = (minY + maxY) / 2;

            var minDist = double.PositiveInfinity;
            int i0 = 0, i1 = 0, i2 = 0;

            // pick a seed point close to the center
            for (int i = 0; i < n; i++)
            {
                var d = Dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
                if (d < minDist)
                {
                    i0      = i;
                    minDist = d;
                }
            }
            var i0x = coords[2 * i0];
            var i0y = coords[2 * i0 + 1];

            minDist = double.PositiveInfinity;

            // find the point closest to the seed
            for (int i = 0; i < n; i++)
            {
                if (i == i0)
                {
                    continue;
                }
                var d = Dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
                if (d < minDist && d > 0)
                {
                    i1      = i;
                    minDist = d;
                }
            }

            var i1x = coords[2 * i1];
            var i1y = coords[2 * i1 + 1];

            var minRadius = double.PositiveInfinity;

            // find the third point which forms the smallest circumcircle with the first two
            for (int i = 0; i < n; i++)
            {
                if (i == i0 || i == i1)
                {
                    continue;
                }
                var r = Circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
                if (r < minRadius)
                {
                    i2        = i;
                    minRadius = r;
                }
            }
            var i2x = coords[2 * i2];
            var i2y = coords[2 * i2 + 1];

            if (minRadius == double.PositiveInfinity)
            {
                throw new Exception("No Delaunay triangulation exists for this input.");
            }

            if (Orient(i0x, i0y, i1x, i1y, i2x, i2y))
            {
                var i = i1;
                var x = i1x;
                var y = i1y;
                i1  = i2;
                i1x = i2x;
                i1y = i2y;
                i2  = i;
                i2x = x;
                i2y = y;
            }

            var center = Circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);

            _cx = center.X;
            _cy = center.Y;

            var dists = new double[n];

            for (var i = 0; i < n; i++)
            {
                dists[i] = Dist(coords[2 * i], coords[2 * i + 1], center.X, center.Y);
            }

            // sort the points by distance from the seed triangle circumcenter
            Quicksort(ids, dists, 0, n - 1);

            // set up the seed triangle as the starting hull
            hullStart = i0;
            hullSize  = 3;

            hullNext[i0] = hullPrev[i2] = i1;
            hullNext[i1] = hullPrev[i0] = i2;
            hullNext[i2] = hullPrev[i1] = i0;

            hullTri[i0] = 0;
            hullTri[i1] = 1;
            hullTri[i2] = 2;

            hullHash[HashKey(i0x, i0y)] = i0;
            hullHash[HashKey(i1x, i1y)] = i1;
            hullHash[HashKey(i2x, i2y)] = i2;

            trianglesLen = 0;
            AddTriangle(i0, i1, i2, -1, -1, -1);

            double xp = 0;
            double yp = 0;

            for (var k = 0; k < ids.Length; k++)
            {
                var i = ids[k];
                var x = coords[2 * i];
                var y = coords[2 * i + 1];

                // skip near-duplicate points
                if (k > 0 && Math.Abs(x - xp) <= EPSILON && Math.Abs(y - yp) <= EPSILON)
                {
                    continue;
                }
                xp = x;
                yp = y;

                // skip seed triangle points
                if (i == i0 || i == i1 || i == i2)
                {
                    continue;
                }

                // find a visible edge on the convex hull using edge hash
                var start = 0;
                for (var j = 0; j < hashSize; j++)
                {
                    var key = HashKey(x, y);
                    start = hullHash[(key + j) % hashSize];
                    if (start != -1 && start != hullNext[start])
                    {
                        break;
                    }
                }


                start = hullPrev[start];
                var e = start;
                var q = hullNext[e];

                while (!Orient(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1]))
                {
                    e = q;
                    if (e == start)
                    {
                        e = int.MaxValue;
                        break;
                    }

                    q = hullNext[e];
                }

                if (e == int.MaxValue)
                {
                    continue;                    // likely a near-duplicate point; skip it
                }
                // add the first triangle from the point
                var t = AddTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);

                // recursively flip triangles from the point until they satisfy the Delaunay condition
                hullTri[i] = Legalize(t + 2);
                hullTri[e] = t; // keep track of boundary triangles on the hull
                hullSize++;

                // walk forward through the hull, adding more triangles and flipping recursively
                var next = hullNext[e];
                q = hullNext[next];

                while (Orient(x, y, coords[2 * next], coords[2 * next + 1], coords[2 * q], coords[2 * q + 1]))
                {
                    t              = AddTriangle(next, i, q, hullTri[i], -1, hullTri[next]);
                    hullTri[i]     = Legalize(t + 2);
                    hullNext[next] = next; // mark as removed
                    hullSize--;
                    next = q;

                    q = hullNext[next];
                }

                // walk backward from the other side, adding more triangles and flipping
                if (e == start)
                {
                    q = hullPrev[e];

                    while (Orient(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1]))
                    {
                        t = AddTriangle(q, i, e, -1, hullTri[e], hullTri[q]);
                        Legalize(t + 2);
                        hullTri[q]  = t;
                        hullNext[e] = e; // mark as removed
                        hullSize--;
                        e = q;

                        q = hullPrev[e];
                    }
                }

                // update the hull indices
                hullStart   = hullPrev[i] = e;
                hullNext[e] = hullPrev[next] = i;
                hullNext[i] = next;

                // save the two new edges in the hash table
                hullHash[HashKey(x, y)] = i;
                hullHash[HashKey(coords[2 * e], coords[2 * e + 1])] = e;
            }

            hull = new int[hullSize];
            var s = hullStart;

            for (var i = 0; i < hullSize; i++)
            {
                hull[i] = s;
                s       = hullNext[s];
            }

            hullPrev = hullNext = hullTri = null; // get rid of temporary arrays

            //// trim typed triangle mesh arrays
            Triangles = Triangles.Take(trianglesLen).ToArray();
            Halfedges = Halfedges.Take(trianglesLen).ToArray();
        }
        private void ValuePatternSetValue(CruciatusElement element, IEnumerable<JToken> args)
        {
            var value = args.ElementAtOrDefault(1);
            if (value == null)
            {
                var msg = string.Format(HelpArgumentsErrorMsg, HelpUrlAutomationScript);
                throw new AutomationException(msg, ResponseStatus.JavaScriptError);
            }

            element.GetPattern<ValuePattern>(ValuePattern.Pattern).SetValue(value.ToString());
        }
        public Almoxarifado Obter(int idAlmoxarifado)
        {
            IEnumerable <Almoxarifado> almoxarifados = GetQuery().Where(almoxarifadoModel => almoxarifadoModel.Id.Equals(idAlmoxarifado));

            return(almoxarifados.ElementAtOrDefault(0));
        }
 private static IEnumerable<string> CreateSegment(IEnumerable<string> current, IEnumerable<string> previous)
 {
     return current.TakeWhile((step, index) => step == previous.ElementAtOrDefault(index)).ToArray();
 }
示例#54
0
 public static T RandomOrDefault <T>(this IEnumerable <T> input) => input.ElementAtOrDefault(Memory.Random.Next(input.Count()));
 /// <summary>
 /// ランダムに要素を1つ取得します。
 /// </summary>
 public static T SampleOrDefault <T>(this IEnumerable <T> em)
 {
     return(em.ElementAtOrDefault(Random.Range(0, em.Count())));
 }
            public IEnumerable<StatementSyntax> RemoveInitializedDeclarationAndReturnPattern(IEnumerable<StatementSyntax> statements)
            {
                // if we have inline temp variable as service, we could just use that service here.
                // since it is not a service right now, do very simple clean up
                if (statements.ElementAtOrDefault(2) != null)
                {
                    return statements;
                }

                var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
                var returnStatement = statements.ElementAtOrDefault(1) as ReturnStatementSyntax;
                if (declaration == null || returnStatement == null)
                {
                    return statements;
                }

                if (declaration.Declaration == null ||
                    declaration.Declaration.Variables.Count != 1 ||
                    declaration.Declaration.Variables[0].Initializer == null ||
                    declaration.Declaration.Variables[0].Initializer.Value == null ||
                    declaration.Declaration.Variables[0].Initializer.Value is StackAllocArrayCreationExpressionSyntax ||
                    returnStatement.Expression == null)
                {
                    return statements;
                }

                if (!ContainsOnlyWhitespaceTrivia(declaration) ||
                    !ContainsOnlyWhitespaceTrivia(returnStatement))
                {
                    return statements;
                }

                var variableName = declaration.Declaration.Variables[0].Identifier.ToString();
                if (returnStatement.Expression.ToString() != variableName)
                {
                    return statements;
                }

                return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.ReturnStatement(declaration.Declaration.Variables[0].Initializer.Value));
            }
        public ActionResult UploadProduct(IEnumerable<HttpPostedFileBase> files, string productName, string productDescription, string productLongDescription, decimal unitPrice, int unitInStock)
        {
            string uploadMessage = PRODUCT_UPLOAD_SUCCESSFUL;
            bool fileUploadFailed = false;
            bool fileIsValid = true;
            try
            {
                var request = System.Web.HttpContext.Current.Request;

                FileInfo fi = new FileInfo(files.ElementAtOrDefault(0).FileName);
                if (!fi.Extension.ToLower().Equals(".jpg"))
                {
                    uploadMessage = "Please upload a valid [.jpg] image file";
                }


                
                if (fileIsValid)
                {
                    AmzProduct product = new AmzProduct()
                    {
                        ProductName = productName
                        ,ProductDescription = productDescription
                        ,ProductLongDescription = productLongDescription
                        ,UnitPrice = unitPrice
                        ,UnitsInStock = unitInStock
                    };
                    
                    //string path = System.Web.HttpContext.Current.Server.MapPath("~/UploadedImages");
                    //DirectoryInfo di = new DirectoryInfo(path);
                    //if (!di.Exists)
                    //{
                    //    di.Create();
                    //}

                    string nowTicks = DateTime.Now.Ticks.ToString();
                    string destinationFilePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/products");

                    string originalImageId = string.Format("AMZ_Original_{0}.jpg",nowTicks);
                    string sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);

                    files.ElementAtOrDefault(0).SaveAs(sourceFile);
                    logger.InfoFormat("Saved input file as {0}", sourceFile);
                    product.OriginalImageId = originalImageId;


                    Bitmap bmOriginal = new Bitmap(sourceFile);
                    ImageHandler ih = new ImageHandler();

                    

                    product.SmallImageId =  string.Format(@"AMZ_Small_{0}.jpg", nowTicks);
                    ih.Save(bmOriginal, 100, 100, 100, string.Format(@"{0}\{1}",destinationFilePath,product.SmallImageId));
                    logger.InfoFormat("Resized input file and saved as {0}", product.SmallImageId);

                    product.MediumImageId = string.Format(@"AMZ_Medium_{0}.jpg", nowTicks);
                    ih.Save(bmOriginal, 400, 400, 100, string.Format(@"{0}\{1}",destinationFilePath, product.MediumImageId));
                    logger.InfoFormat("Resized input file and saved as {0}", product.MediumImageId);

                    product.LargeImageId = string.Format(@"AMZ_Large_{0}.jpg", nowTicks);
                    ih.Save(bmOriginal, 400, 400, 100, string.Format(@"{0}\{1}",destinationFilePath, product.LargeImageId));
                    logger.InfoFormat("Resized input file and saved as {0}",product.LargeImageId);


                    if(files.ElementAtOrDefault(1) != null )
                    {
                        originalImageId = string.Format("AMZ_Image_1_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdOne = originalImageId;
                        files.ElementAtOrDefault(1).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image one file as {0}", sourceFile);
                    }

                    if (files.ElementAtOrDefault(2) != null)
                    {
                        originalImageId = string.Format("AMZ_Image_2_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdTwo = originalImageId;
                        files.ElementAtOrDefault(2).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image two file as {0}", sourceFile);
                    }

                    if (files.ElementAtOrDefault(3) != null)
                    {
                        originalImageId = string.Format("AMZ_Image_3_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdThree = originalImageId;
                        files.ElementAtOrDefault(3).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image three file as {0}", sourceFile);
                    }

                    if (files.ElementAtOrDefault(4) != null)
                    {
                        originalImageId = string.Format("AMZ_Image_4_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdFour = originalImageId;
                        files.ElementAtOrDefault(4).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image four file as {0}", sourceFile);
                    }

                    if (files.ElementAtOrDefault(5) != null)
                    {
                        originalImageId = string.Format("AMZ_Image_5_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdFive = originalImageId;
                        files.ElementAtOrDefault(5).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image five file as {0}", sourceFile);
                    }





                    product.ImageUploadSuccessful = true;

                    productHandler.AddProduct(product);

                    logger.InfoFormat(PRODUCT_UPLOAD_SUCCESSFUL);

                    //try
                    //{
                    //    FileInfo fiFileToDelete = new FileInfo(sourceFile);
                    //    if (fiFileToDelete.Exists)
                    //        fiFileToDelete.Delete();
                    //    logger.InfoFormat("Removed file {0}", sourceFile);

                    //}
                    //catch (Exception ex1)
                    //{
                    //    logger.Error(ex1);

                    //}
                }

            }
            catch (Exception ex)
            {
                logger.Error(ex);
                uploadMessage = string.Format("Product upload failed: Error: {0}", ex.Message);
                fileUploadFailed = true;
            }


            return RedirectToAction("Index", new RouteValueDictionary(
                                                new { controller = "ProductAdmin", action = "Index", message = uploadMessage, status = fileUploadFailed }));
        }
            public IEnumerable<StatementSyntax> RemoveDeclarationAssignmentPattern(IEnumerable<StatementSyntax> statements)
            {
                // if we have inline temp variable as service, we could just use that service here.
                // since it is not a service right now, do very simple clean up
                var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
                var assignment = statements.ElementAtOrDefault(1) as ExpressionStatementSyntax;
                if (declaration == null || assignment == null)
                {
                    return statements;
                }

                if (ContainsAnyInitialization(declaration) ||
                    declaration.Declaration == null ||
                    declaration.Declaration.Variables.Count != 1 ||
                    assignment.Expression == null ||
                    assignment.Expression.Kind() != SyntaxKind.SimpleAssignmentExpression)
                {
                    return statements;
                }

                if (!ContainsOnlyWhitespaceTrivia(declaration) ||
                    !ContainsOnlyWhitespaceTrivia(assignment))
                {
                    return statements;
                }

                var variableName = declaration.Declaration.Variables[0].Identifier.ToString();

                var assignmentExpression = assignment.Expression as AssignmentExpressionSyntax;
                if (assignmentExpression.Left == null ||
                    assignmentExpression.Right == null ||
                    assignmentExpression.Left.ToString() != variableName)
                {
                    return statements;
                }

                var variable = declaration.Declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(assignmentExpression.Right));
                return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
                    declaration.WithDeclaration(
                        declaration.Declaration.WithVariables(
                            SyntaxFactory.SingletonSeparatedList(variable)))).Concat(statements.Skip(2));
            }
 private static UniqueValueRenderer createNewDefaultUniqueValueRenderer(GraphicsLayer graphicsLayer, IEnumerable<object> uniqueValues, FieldInfo attributeField, LinearGradientBrush defaultColorRampGradientBrush, IEnumerable<Symbol> existingSymbolSet)
 {
     Symbol defaultSymbol = graphicsLayer.GetDefaultSymbol();
     UniqueValueRenderer uniqueValueRenderer = new UniqueValueRenderer()
     {
         Field = attributeField != null ? attributeField.Name : null,
         DefaultSymbol = defaultSymbol,
     };
     if (uniqueValues != null)
     {
         List<Symbol> symbols = new List<Symbol>();
         int i = 0;
         foreach (object uniqueValue in uniqueValues)
         {
             Symbol symbol = null;
             if (existingSymbolSet != null)
                 symbol = existingSymbolSet.ElementAtOrDefault(i);
             if (symbol == null)
                 symbol = graphicsLayer.GetDefaultSymbolClone();
             uniqueValueRenderer.Infos.Add(new UniqueValueInfoObj()
             {
                 Symbol = symbol,
                 SerializedValue = uniqueValue,
                 FieldType = attributeField.FieldType,
             });
             symbols.Add(symbol);
             i++;
         }
         if (defaultColorRampGradientBrush != null)
         {
             if (existingSymbolSet == null) // apply the gradient brush, only if symbols have not been pre-defined
             {
                 applyLinearGradientBrushToSymbolSet(symbols, defaultColorRampGradientBrush, defaultSymbol);
             }
         }
     }
     return uniqueValueRenderer;
 }