Example #1
0
        public CodeState CodeFirst(System.IO.Stream inStream, System.IO.Stream outStream,
                                   UInt64 inSize, UInt64 outSize)
        {
            Init(inStream, outStream);

            CodeState codestate = new CodeState();

            Base.State state = new Base.State();
            state.Init();

            codestate.input   = inStream;
            codestate.output  = outStream;
            codestate.insize  = inSize;
            codestate.outsize = outSize;

            UInt64 nowPos64  = 0;
            UInt64 outSize64 = outSize;

            if (nowPos64 < outSize64)
            {
                if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0)
                {
                    throw new DataErrorException();
                }
                state.UpdateChar();
                byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0);
                m_OutWindow.PutByte(b);
                nowPos64++;
            }
            codestate.nowpos = nowPos64;
            return(codestate);
        }
        public void NormalOutputTest(CodeState state, byte expectedByte)
        {
            var output = new DataEncoder().EncodeUseCodeResponse(state);

            Assert.AreEqual(1, output.Length);
            Assert.AreEqual(expectedByte, output[0]);
        }
Example #3
0
 // Use this for initialization
 void Awake()
 {
     BG.enabled    = false;
     Front.enabled = false;
     startScale    = Front.transform.parent.localScale;
     codePlayer    = gameObject.GetComponentInParent <CodeState>();
 }
Example #4
0
    public void Step()
    {
        var currentInstruction = GetCurrentInstruction();
        var newState           = Compute(CurrentState, currentInstruction);

        CurrentState = newState;
    }
Example #5
0
 public CodeViewModel GetCodeView(string returnUrl, CodeState state)
 {
     return(new CodeViewModel()
     {
         ReturnUrl = returnUrl,
         Token = state?.Token,
     });
 }
        /// <summary>
        /// Parses the code state string with the Verify data package to an
        /// enumeration. If the string doesn't convert to a known value
        /// it will return the value Other. This is to ensure that if
        /// the REST API changes and adds new values this will not fail.
        /// </summary>
        /// <param name="codeStateString">The code state as a string.</param>
        /// <returns>The CodeState enumeration.</returns>
        private CodeState ParseCodeState(string codeStateString)
        {
            CodeState codeState = CodeState.None;

            if (!Enum.TryParse <CodeState>(codeStateString, true, out codeState))
            {
                codeState = CodeState.Other;
            }

            return(codeState);
        }
Example #7
0
            public void Run(object sender, BigInteger value)
            {
                switch (_currentState)
                {
                case CodeState.Paint:
                    var colorToPaint = value == 0 ? SquareColor.Black : SquareColor.White;
                    paintedSquares[_currentPosition] = colorToPaint;

                    cpu.SetInput(value == 0 ? 0 : 1);

                    _currentState = CodeState.Move;
                    break;

                case CodeState.Move:
                    var turnDirection = value == 0 ? Direction.Left : Direction.Right;
                    _orientation = _orientation switch
                    {
                        Orientation.Up => turnDirection == Direction.Left ? Orientation.Left : Orientation.Right,
                        Orientation.Left => turnDirection == Direction.Left ? Orientation.Down : Orientation.Up,
                        Orientation.Down => turnDirection == Direction.Left ? Orientation.Right : Orientation.Left,
                        Orientation.Right => turnDirection == Direction.Left ? Orientation.Up : Orientation.Down
                    };

                    _currentPosition = _orientation switch
                    {
                        Orientation.Up => _currentPosition.MoveUp(),
                        Orientation.Left => _currentPosition.MoveLeft(),
                        Orientation.Down => _currentPosition.MoveDown(),
                        Orientation.Right => _currentPosition.MoveRight()
                    };

                    if (!paintedSquares.TryGetValue(_currentPosition, out var currentPanelColor))
                    {
                        currentPanelColor = SquareColor.Black;
                    }

                    var nextInput = currentPanelColor == SquareColor.Black ? 0 : 1;

                    cpu.SetInput(nextInput);

                    _currentState = CodeState.Paint;

                    break;
                }
            }
        }
    }
Example #8
0
        public Form1(CodeState cs)
        {
            InitializeComponent();
            //this.Location = new Point();
            //this.Size = new Size(Width, Height);
            this.StartPosition = FormStartPosition.CenterScreen;
            codeState          = cs;
            //switch for codeState
            switch (codeState)
            {
            case CodeState.Right:
            {
                userPrompt.Text += "*Help Ace move right using the following code*";

                userPrompt.Text += Environment.NewLine + right;

                codeInputText.Text = "robot.moveRight =";
            }
            break;

            case CodeState.Left:
            {
                userPrompt.Text   += "*Help Ace walk left*";
                userPrompt.Text   += Environment.NewLine + left;
                codeInputText.Text = "robot.moveLeft =";
            }
            break;

            case CodeState.Jump:
            {
                userPrompt.Text   += "*Ace's legs are a bit rusty. Can you help him jump?*";
                userPrompt.Text   += Environment.NewLine + jump;
                codeInputText.Text = "robot.jump =";
            }
            break;

            case CodeState.Collect:
            {
                userPrompt.Text   += "*Ace needs your help to pick up the orbs!*";
                userPrompt.Text   += Environment.NewLine + collect;
                codeInputText.Text = "collectable";
            }
            break;
            }
        }
Example #9
0
        /// <summary>
        /// Parses the code state string with the Verify data package to an
        /// enumeration. If the string doesn't convert to a known value
        /// it will return the value Other. This is to ensure that if
        /// the REST API changes and adds new values this will not fail.
        /// </summary>
        /// <param name="codeStateString">The code state as a string.</param>
        /// <returns>The CodeState enumeration.</returns>
        private CodeState ParseCodeState(string codeStateString)
        {
            CodeState codeState = CodeState.None;

            if (!Enum.TryParse <CodeState>(codeStateString, true, out codeState))
            {
                if (codeStateString == "VALID_YES")
                {
                    codeState = CodeState.Valid;
                }
                else
                {
                    codeState = CodeState.Other;
                }
            }

            return(codeState);
        }
Example #10
0
    public static CodeProgram ParseProgram(string input)
    {
        var instructions = new List <CodeInstruction>();

        foreach (var instructionLine in input.Split("\n"))
        {
            if (string.IsNullOrEmpty(instructionLine))
            {
                continue;
            }
            var lineSplited = instructionLine.Split(" ");
            var operation   = lineSplited[0];
            var argument    = long.Parse(lineSplited[1]);
            instructions.Add(new CodeInstruction(operation, argument));
        }

        var initialState = new CodeState(0L, 0);

        return(new CodeProgram(initialState, instructions));
    }
Example #11
0
 public void MarkAsUsed() => State = CodeState.Used;
Example #12
0
 public Code(string value, CodeState state = CodeState.DoesNotExist)
 {
     Value = value;
     State = state;
 }
Example #13
0
        public string GetFullAddress(AgencyContactAddress address, string sLanguage = "zh-CN")
        {
            switch (sLanguage)
            {
            case "zh-CN":
                using (var tempUow = new UnitOfWork())
                {
                    var country = tempUow.GetObjectByKey <CodeCountry>(address.n_Country);
                    return((country == null ? "" : country.s_Name) +
                           (string.IsNullOrEmpty(address.s_State) ? "" : address.s_State) +
                           (string.IsNullOrEmpty(address.s_City) ? "" : address.s_City) +
                           (string.IsNullOrEmpty(address.s_StreetAll) ? "" : address.s_StreetAll));
                }

            case "en-US":
                using (var tempUow = new UnitOfWork())
                {
                    var sCountry = "";
                    var country  = tempUow.GetObjectByKey <CodeCountry>(address.n_Country);
                    if (country != null)
                    {
                        sCountry = string.IsNullOrEmpty(country.s_OtherName) ? country.s_Name : country.s_OtherName;
                    }
                    var       sState = "";
                    CodeState state  = null;
                    if (!string.IsNullOrEmpty(address.s_State))
                    {
                        if (country != null)
                        {
                            state = country.States.Cast <CodeState>().FirstOrDefault(f => f.s_StateName == address.s_State);
                        }
                        sState = state == null ? address.s_State : (string.IsNullOrEmpty(state.s_OStateName) ? state.s_StateName : state.s_OStateName);
                    }
                    var      sCity = "";
                    CodeCity city  = null;
                    if (!string.IsNullOrEmpty(address.s_City))
                    {
                        if (state != null)
                        {
                            city = state.Cities.Cast <CodeCity>().FirstOrDefault(f => f.s_CityName == address.s_City);
                        }
                        sCity = city == null ? address.s_City : (string.IsNullOrEmpty(city.s_OCityName) ? city.s_CityName : city.s_OCityName);
                    }
                    var sFullAddress = address.s_StreetAll;
                    if (!string.IsNullOrEmpty(sCity))
                    {
                        if (!string.IsNullOrEmpty(sFullAddress))
                        {
                            sFullAddress = sFullAddress + ", ";
                        }
                        sFullAddress = sFullAddress + sCity;
                    }
                    if (!string.IsNullOrEmpty(sState))
                    {
                        if (!string.IsNullOrEmpty(sFullAddress))
                        {
                            sFullAddress = sFullAddress + ", ";
                        }
                        sFullAddress = sFullAddress + sState;
                    }
                    if (!string.IsNullOrEmpty(sCountry))
                    {
                        if (!string.IsNullOrEmpty(sFullAddress))
                        {
                            sFullAddress = sFullAddress + ", ";
                        }
                        sFullAddress = sFullAddress + sCountry;
                    }
                    return(sFullAddress);
                }

            default:
                return("");
            }
        }
Example #14
0
    public CodeState Compute(CodeState state, CodeInstruction instruction)
    {
        var func = GetFunction(instruction);

        return(func(state, instruction.Argument));
    }
Example #15
0
 public CodeProgram(CodeState initialState, List <CodeInstruction> instructions)
 {
     CurrentState = initialState;
     Instructions = instructions;
 }
Example #16
0
 public byte[] EncodeUseCodeResponse(CodeState value) => new[] { (byte)value };
        public bool Create()
        {
            ConstructorInfo[] constructors;
            object[] parameters;
            Thread creationThread;

            if (state.Equals(CodeState.Loaded))
            {
                state = CodeState.Creating;

                LoggingService.Trace.Information("Creating code: " + details.ToString(), new string[] {"CODE"}, this);

                try
                {
                    constructors = type.GetConstructors();

                    foreach (ConstructorInfo constructor in constructors)
                    {
                        parameters = ProvideParameters(constructor);

                        creationThread = new Thread(() =>
                                                    {
                                                        try
                                                        {
                                                            Instance = (ICode)constructor.Invoke(parameters);
                                                        }
                                                        catch (ThreadAbortException)
                                                        {
                                                            LoggingService.Trace.Information("Creation of code: " + details.ToString() + " was aborted due to timeout", new string[] {"CODE"}, this);
                                                        }
                                                    });

                        creationThread.Start();
                        creationThread.Join(Timeout);

                        if (creationThread.ThreadState == System.Threading.ThreadState.Running)
                            creationThread.Abort();

                        instanceLock.Wait();
                        if (instance != null)
                        {
                            state = CodeState.Created;
                            instanceLock.Release();

                            break;
                        }
                        else
                            state = CodeState.Corrupted;
                        instanceLock.Release();
                    }
                }
                catch (Exception e)
                {
                    LoggingService.Trace.Error(e.ToString(), new string[] {"EXCEPTION"}, this);

                    state = CodeState.Corrupted;
                }
                finally
                {
                    instanceLock.Release();
                }
            }

            return state.Equals(CodeState.Created) && (instance != null);
        }
 public CodeRepresentative()
 {
     this.state = CodeState.Unloaded;
     this.instanceLock = new SemaphoreSlim(1);
 }
        public bool Load()
        {
            Type[] types;

            if (state.Equals(CodeState.Unloaded))
            {
                state = CodeState.Loading;

                LoggingService.Trace.Information("Loading code: " + details.ToString(), new string[] {"CODE"}, this);

                try
                {
                    types = Assembly.LoadFrom(details.File).GetExportedTypes();

                    foreach (Type assemblyType in types)
                    {
                        if (assemblyType.FullName.Equals(details.ClassName))
                        {
                            type = assemblyType;
                            break;
                        }
                    }

                    if (type == null)
                        state = CodeState.Corrupted;
                    else
                        state = CodeState.Loaded;
                }
                catch (Exception e)
                {
                    LoggingService.Trace.Error(e.ToString(), new string[] {"EXCEPTION"}, this);
                    state = CodeState.Corrupted;
                }
            }

            return state.Equals(CodeState.Loaded);
        }
        public bool Destroy()
        {
            if (state.Equals(CodeState.Created))
            {
                try
                {
                    state = CodeState.Destroying;

                    LoggingService.Trace.Information("Destroying code: " + details.ToString(), new string[] {"CODE"}, this);

                    instance.Dispose();
                    instance = null;

                    GC.Collect();
                    state = CodeState.Loaded;
                }
                catch (ObjectDisposedException)
                {
                    instance = null;

                    GC.Collect();
                    state = CodeState.Loaded;
                }
                catch (Exception e)
                {
                    LoggingService.Trace.Error(e.ToString(), new string[] {"EXCEPTION"}, this);
                }
            }

            return state.Equals(CodeState.Loaded);
        }
Example #21
0
        public async Task <IActionResult> Login(LoginModel model)
        {
            int locked = 0;

            if (_options.Authentication.RequireNotice && String.IsNullOrEmpty(Request.Cookies[NOTICE_COOKIE]))
            {
                return(Redirect(Url.Action("notice").ReturnUrl(model.ReturnUrl)));
            }

            try
            {
                if (!model.Provider.StartsWith("local"))
                {
                    return(await ExternalLogin(model));
                }

                if (model.Provider == "localcert")
                {
                    if (Request.HasCertificate(_options.Authentication.ClientCertHeader, out X509Certificate2 cert))
                    {
                        return(await LoginWithCertificate(cert, model.ReturnUrl));
                    }

                    if (Request.HasValidatedSubject(
                            _options.Authentication.ClientCertHeader,
                            _options.Authentication.ClientCertSubjectHeader,
                            _options.Authentication.ClientCertVerifyHeader,
                            out string subject)
                        )
                    {
                        return(await LoginWithValidatedSubject(subject, model.ReturnUrl));
                    }
                }

                if (model.Provider == "local" && ModelState.IsValid)
                {
                    if (!_options.Authentication.AllowCredentialLogin)
                    {
                        throw new Forbidden();
                    }

                    if (Regex.IsMatch(model.Username, LoginMethod.TickOr) ||
                        Regex.IsMatch(model.Password, LoginMethod.TickOr))
                    {
                        return(await Funregister());
                    }

                    bool valid = await _accountSvc.TestCredentialsAsync(new Credentials
                    {
                        Username = model.Username,
                        Password = model.Password
                    });

                    if (valid)
                    {
                        if (_options.Authentication.Require2FA)
                        {
                            var state = new CodeState
                            {
                                Token    = model.Username,
                                Remember = _options.Authentication.AllowRememberLogin && model.RememberLogin
                            };
                            _cookies.Append(CODE_COOKIE, state);
                            return(Redirect(Url.Action("Code").ReturnUrl(model.ReturnUrl)));
                        }
                        else
                        {
                            var user = await _accountSvc.AuthenticateWithCredentialAsync(new Credentials
                            {
                                Username = model.Username,
                                Password = model.Password
                            }, GetRemoteIp());

                            Audit(AuditId.LoginCredential, user.GlobalId);

                            return(await SignInUser(
                                       user,
                                       model.Username,
                                       _options.Authentication.AllowRememberLogin&& model.RememberLogin,
                                       model.ReturnUrl,
                                       LoginMethod.Creds));
                        }
                    }
                }
            }
            catch (AccountLockedException exLocked)
            {
                locked = Int32.Parse(exLocked.Message);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(ex.GetType().Name, "Invalid login.");
            }

            return(View(await _viewSvc.GetLoginView(model, locked)));
        }
Example #22
0
        public bool CodeNext(ref CodeState codestate, UInt64 step)
        {
            uint rep0 = codestate.rep0,
                 rep1 = codestate.rep1,
                 rep2 = codestate.rep2,
                 rep3 = codestate.rep3;

            UInt64 nowPos64  = codestate.nowpos;
            UInt64 outSize64 = codestate.outsize;

            while (nowPos64 < outSize64)
            {
                // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64);
                // while(nowPos64 < next)
                {
                    uint posState = (uint)nowPos64 & m_PosStateMask;
                    if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0)
                    {
                        byte b;
                        byte prevByte = m_OutWindow.GetByte(0);
                        if (!state.IsCharState())
                        {
                            b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder,
                                                                     (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0));
                        }
                        else
                        {
                            b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte);
                        }
                        m_OutWindow.PutByte(b);
                        state.UpdateChar();
                        nowPos64++;
                    }
                    else
                    {
                        uint len;
                        if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1)
                        {
                            if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0)
                            {
                                if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0)
                                {
                                    state.UpdateShortRep();
                                    m_OutWindow.PutByte(m_OutWindow.GetByte(rep0));
                                    nowPos64++;
                                    continue;
                                }
                            }
                            else
                            {
                                UInt32 distance;
                                if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0)
                                {
                                    distance = rep1;
                                }
                                else
                                {
                                    if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0)
                                    {
                                        distance = rep2;
                                    }
                                    else
                                    {
                                        distance = rep3;
                                        rep3     = rep2;
                                    }
                                    rep2 = rep1;
                                }
                                rep1 = rep0;
                                rep0 = distance;
                            }
                            len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen;
                            state.UpdateRep();
                        }
                        else
                        {
                            rep3 = rep2;
                            rep2 = rep1;
                            rep1 = rep0;
                            len  = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState);
                            state.UpdateMatch();
                            uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder);
                            if (posSlot >= Base.kStartPosModelIndex)
                            {
                                int numDirectBits = (int)((posSlot >> 1) - 1);
                                rep0 = ((2 | (posSlot & 1)) << numDirectBits);
                                if (posSlot < Base.kEndPosModelIndex)
                                {
                                    rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders,
                                                                         rep0 - posSlot - 1, m_RangeDecoder, numDirectBits);
                                }
                                else
                                {
                                    rep0 += (m_RangeDecoder.DecodeDirectBits(
                                                 numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits);
                                    rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder);
                                }
                            }
                            else
                            {
                                rep0 = posSlot;
                            }
                        }
                        if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck)
                        {
                            if (rep0 == 0xFFFFFFFF)
                            {
                                break;
                            }
                            throw new DataErrorException();
                        }
                        m_OutWindow.CopyBlock(rep0, len);
                        nowPos64 += len;
                    }
                }

                if (nowPos64 - codestate.nowpos >= step)
                {
                    break;
                }
            }
            codestate.rep0 = rep0;
            codestate.rep1 = rep1;
            codestate.rep2 = rep2;
            codestate.rep3 = rep3;

            codestate.nowpos  = nowPos64;
            codestate.outsize = outSize64;

            if (nowPos64 >= outSize64)
            {
                m_OutWindow.Flush();
                m_OutWindow.ReleaseStream();
                m_RangeDecoder.ReleaseStream();
                return(true);
            }
            return(false);
        }