精华内容
下载资源
问答
  • 1.state state是什么? 定义:state(vuex) ≈ data (vue) vuex的state和vue的data有很多相似之处,都是用于存储一些数据,或者说状态值.这些值都将被挂载 数据和dom的双向绑定事件,也就是当你改变值的时候可以触发...

      上一章大概说明了vuex的设计初衷和基本用法,从这一章开始详解一下vuex的几个关键配置.

    1.state

      state是什么?

      定义:state(vuex) ≈ data (vue)

      vuex的state和vue的data有很多相似之处,都是用于存储一些数据,或者说状态值.这些值都将被挂载 数据和dom的双向绑定事件,也就是当你改变值的时候可以触发dom的更新.

      虽然state和data有很多相似之处,但state在使用的时候一般被挂载到子组件的computed计算属性上,这样有利于state的值发生改变的时候及时响应给子组件.如果你用data去接收$store.state,当然可以接收到值,但由于这只是一个简单的赋值操作,因此state中的状态改变的时候不能被vue中的data监听到,当然你也可以通过watch $store去解决这个问题,那你可以针是一个杠精

      综上所述,请用computed去接收state,如下

    //state.js
    let state = {
      count: 1,
      name: 'dkr',
      sex: '男',
      from: 'china'
    }
    export default state
    
    <template>
      <div id="example">
        <button @click="decrement">-</button>
        {{count}}
        {{dataCount}}
        <button @click="increment">+</button>
      </div>
    </template>
    <script>
    export default {
      data () {
        return {
          dataCount: this.$store.state.count //用data接收
        }
      },
      computed:{
        count(){
          return this.$store.state.count //用computed接收
        }
      }
      methods: {
        increment () {
          this.$store.commit('increment')
        },
        decrement () {
          this.$store.commit('decrement')
        }
      }
    }
    </script>

    结果如下,用data接收的值不能及时响应更新,用computed就可以.

     

    2.mapState 辅助函数

      mapState是什么?

      表面意思:mapState是state的辅助函数.这么说可能很难理解

      抽象形容:mapState是state的语法糖,这么说可能你还想骂我,因为你根本不了解什么叫做语法糖,事实上我说的语法糖有自己的定义,什么是语法糖?我对语法糖的理解就是,用之前觉得,我明明已经对一种操作很熟练了,并且这种操作也不存在什么问题,为什么要用所谓的"更好的操作",用了一段时间后,真香!

     

      实际作用:当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键

      在使用mapState之前,要导入这个辅助函数.

    import { mapState } from 'vuex'

      然后就是使用方式了

     

    <template>
      <div id="example">
        <button @click="decrement">-</button>
        {{count}}
        {{dataCount}}
        <button @click="increment">+</button>
        <div>{{sex}}</div>
        <div>{{from}}</div>
        <div>{{myCmpted}}</div>
      </div>
    </template>
    <script>
    import { mapState } from 'vuex'
    export default {
      data () {
        return {
          str: '国籍',
          dataCount: this.$store.state.count
        }
      },
      computed: mapState({
        count: 'count', // 第一种写法
        sex: (state) => state.sex, // 第二种写法
        from: function (state) { // 用普通函数this指向vue实例,要注意
          return this.str + ':' + state.from
        },
        // 注意下面的写法看起来和上面相同,事实上箭头函数的this指针并没有指向vue实例,因此不要滥用箭头函数
        // from: (state) => this.str + ':' + state.from
        myCmpted: function () {
          // 这里不需要state,测试一下computed的原有用法
          return '测试' + this.str
        }
      }),
      methods: {
        increment () {
          this.$store.commit('increment')
        },
        decrement () {
          this.$store.commit('decrement')
        }
      },
      created () {
        // 写个定时器,发现computed依旧保持了只要内部有相关属性发生改变不管是当前实例data中的改变,还是vuex中的值改变都会触发dom和值更新
        setTimeout(() => {
          this.str = '国家'
        }, 1000)
      }
    }
    </script>
    
    

      在使用的时候,computed接收mapState函数的返回值,你可以用三种方式去接收store中的值,具体可以看注释.

      事实上第二种和第三种是同一种,只是前者用了ES6的偷懒语法,箭头函数,在偷懒的时候要注意一个问题,this指针的指向问题,我已经在很多篇文章中提到不要在vue中为了偷懒使用箭头函数,会导致很多很难察觉的错误,如果你在用到state的同时还需要借助当前vue实例的this,请务必使用常规写法.

      当然computed不会因为引入mapState辅助函数而失去原有的功能---用于扩展当前vue的data,只是写法会有一些奇怪,如果你已经写了一大堆的computed计算属性,做了一半发现你要引入vuex,还想使用mapState辅助函数的方便,你可以需要做下列事情.

    //之前的computed
    computed:{
        fn1(){ return ...},
        fn2(){ return ...},
        fn3(){ return ...}
        ........
    }
    //引入mapState辅助函数之后
    
    computed:mapState({
        //先复制粘贴
        fn1(){ return ...},
        fn2(){ return ...},
        fn3(){ return ...}
        ......
        //再维护vuex
        count:'count'
        .......
    })

       从上述写法可以看出来,这不符合代码的某些说不明道不清的特性,我们希望我们可以不用去做一些复制粘贴的无用操作,而是直接使用mapState,希望它能自动融入到当前生产环境中,ok,ES6+(或者说ES7)提供了这个方便.

    3 ...mapState

      事实上...mapState并不是mapState的扩展,而是...对象展开符的扩展.当然如果你把他用在这里会发现他能使得代码看起来变得,更加符合常规逻辑了,为什么这么说,你等下就会知道了.

      首先,来回顾一下...对象展开符在数组中的表现,这在ES6语法学习分类里有相关说明,如果有兴趣可以关注我的ES6分类中的文章.

    let arr = [1,2,3]
    console.log(...arr) //1,2,3

     然后来看一个例子.

    let MapState = mapState({
          count: 'count',
          sex: (state) => state.sex
        })
        let json = {
          'a': '我是json自带的',
          ...MapState
        }
        console.log(json)

    这里的json可以成功将mapState return的json格式,和json自带的a属性成功融合成一个新的对象.你可以将这个称为对象混合

    这样,你就可以自由的使用mapState了.

    //之前的computed
    computed:{
        fn1(){ return ...},
        fn2(){ return ...},
        fn3(){ return ...}
        ........
    }
    //引入mapState辅助函数之后
    
    computed:{
        //原来的继续保留
        fn1(){ return ...},
        fn2(){ return ...},
        fn3(){ return ...}
        ......
        //再维护vuex
        ...mapState({  //这里的...不是省略号了,是对象扩展符
            count:'count'
        })
    }

     

    觉得文章有帮到你的py求你别关注了,求你点赞或者收藏吧,实在觉得好的话评论区骂我两句也行,谢谢了昂~

    对博主感兴趣的童鞋可以扫描左侧二维码,也可以添加博主粉丝群708637831,欢迎女粉加入~

     

    展开全文
  • Design Pattern - State(C#)

    万次阅读 多人点赞 2019-02-12 15:38:33
    分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍...Allow an object to alter its behavior when its internal state changes. The object will appear to change its clas...

    分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net 

    Definition

    Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

    Participants

        The classes and/or objects participating in this pattern are:

    • Context (Account)
      • Defines the interface of interest to clients
      • Maintains an instance of a ConcreteState subclass that defines the current state.
    • State (State)
      • Defines an interface for encapsulating the behavior associated with a particular state of the Context.
    • Concrete State (RedState, SilverState, GoldState)
      • Each subclass implements a behavior associated with a state of Context

    Sample Code in C#

    This structural code demonstrates the State pattern which allows an object to behave differently depending on its internal state. The difference in behavior is delegated to objects that represent this state.

    /*
     * Structural State Design Pattern.
     */
    
    namespace State.Sample
    {
        using System;
    
        /// <summary>
        /// Startup class for Structural State Design Pattern.
        /// </summary>
        internal static class Program
        {
            #region Methods
    
            /// <summary>
            /// Entry point into console application.
            /// </summary>
            private static void Main()
            {
                // Setup context in a state.
                var c = new Context(new ConcreteStateA());
    
                // Issue requests, which toggles state.
                c.Request();
                c.Request();
                c.Request();
                c.Request();
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'State' abstract class.
        /// </summary>
        internal abstract class State
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// Handle.
            /// </summary>
            /// <param name="context">
            /// The context.
            /// </param>
            public abstract void Handle(Context context);
    
            #endregion
        }
    
        /// <summary>
        /// A 'ConcreteState' class.
        /// </summary>
        internal class ConcreteStateA : State
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// Handle.
            /// </summary>
            /// <param name="context">
            /// The context.
            /// </param>
            public override void Handle(Context context)
            {
                context.State = new ConcreteStateB();
            }
    
            #endregion
        }
    
        /// <summary>
        /// A 'ConcreteState' class.
        /// </summary>
        internal class ConcreteStateB : State
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// Handle.
            /// </summary>
            /// <param name="context">
            /// The context.
            /// </param>
            public override void Handle(Context context)
            {
                context.State = new ConcreteStateA();
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Context' class.
        /// </summary>
        internal class Context
        {
            #region Fields
    
            /// <summary>
            /// The state.
            /// </summary>
            private State _state;
    
            #endregion
    
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="Context"/> class.
            /// </summary>
            /// <param name="state">
            /// The state.
            /// </param>
            public Context(State state)
            {
                State = state;
            }
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// Gets or sets the state.
            /// </summary>
            public State State
            {
                get { return _state; }
    
                set
                {
                    _state = value;
                    Console.WriteLine("State: " + _state.GetType().Name);
                }
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// Request.
            /// </summary>
            public void Request()
            {
                _state.Handle(this);
            }
    
            #endregion
        }
    }
    
    // Output:
    /*
    State: ConcreteStateA
    State: ConcreteStateB
    State: ConcreteStateA
    State: ConcreteStateB
    State: ConcreteStateA
    
    */

    This real-world code demonstrates the State pattern which allows an Account to behave differently depending on its balance. The difference in behavior is delegated to State objects called RedState, SilverState and GoldState. These states represent overdrawn accounts, starter accounts, and accounts in good standing.

    /*
     * Real-World State Design Pattern.
     */
    
    namespace State.RealWorld
    {
        using System;
    
        /// <summary>
        /// Startup class for Real-World State Design Pattern.
        /// </summary>
        internal static class Program
        {
            #region Methods
    
            /// <summary>
            /// Entry point into console application.
            /// </summary>
            private static void Main()
            {
                // Open a new account.
                var account = new Account("Jim Johnson");
    
                // Apply financial transactions.
                account.Deposit(500.0);
                account.Deposit(300.0);
                account.Deposit(550.0);
                account.PayInterest();
                account.Withdraw(2000.00);
                account.Withdraw(1100.00);
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'State' abstract class.
        /// </summary>
        internal abstract class State
        {
            #region Fields
    
            /// <summary>
            /// The account.
            /// </summary>
            protected Account account;
    
            /// <summary>
            /// The balance.
            /// </summary>
            protected double balance;
    
            /// <summary>
            /// The interest.
            /// </summary>
            protected double interest;
    
            /// <summary>
            /// The lower limit.
            /// </summary>
            protected double lowerLimit;
    
            /// <summary>
            /// The upper limit.
            /// </summary>
            protected double upperLimit;
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// Gets or sets the account.
            /// </summary>
            public Account Account
            {
                get { return account; }
    
                set { account = value; }
            }
    
            /// <summary>
            /// Gets or sets the balance.
            /// </summary>
            public double Balance
            {
                get { return balance; }
    
                set { balance = value; }
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// Deposit.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public abstract void Deposit(double amount);
    
            /// <summary>
            /// Pay interest.
            /// </summary>
            public abstract void PayInterest();
    
            /// <summary>
            /// Withdraw.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public abstract void Withdraw(double amount);
    
            #endregion
        }
    
        /// <summary>
        /// A 'ConcreteState' class.
        /// <remarks>
        /// Red indicates that account is overdrawn.
        /// </remarks>
        /// </summary>
        internal class RedState : State
        {
            #region Fields
    
            /// <summary>
            /// The service fee.
            /// </summary>
            private double _serviceFee;
    
            #endregion
    
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="RedState"/> class.
            /// </summary>
            /// <param name="state">
            /// The state.
            /// </param>
            public RedState(State state)
            {
                balance = state.Balance;
                account = state.Account;
                Initialize();
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// Deposit.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public override void Deposit(double amount)
            {
                balance += amount;
                CheckStateChange();
            }
    
            /// <summary>
            /// Pay interest.
            /// </summary>
            public override void PayInterest()
            {
                // No interest is paid
            }
    
            /// <summary>
            /// Withdraw.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public override void Withdraw(double amount)
            {
                amount = amount - _serviceFee;
                Console.WriteLine("No funds available for withdrawal!");
            }
    
            #endregion
    
            #region Methods
    
            /// <summary>
            /// Initialize.
            /// </summary>
            private void Initialize()
            {
                // Should come from a data source.
                interest = 0.0;
                lowerLimit = -100.0;
                upperLimit = 0.0;
                _serviceFee = 15.00;
            }
    
            /// <summary>
            /// Check state change.
            /// </summary>
            private void CheckStateChange()
            {
                if (balance > upperLimit)
                {
                    account.State = new SilverState(this);
                }
            }
    
            #endregion
        }
    
        /// <summary>
        /// A 'ConcreteState' class.
        /// <remarks>
        /// Silver indicates a non-interest bearing state.
        /// </remarks>
        /// </summary>
        internal class SilverState : State
        {
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="SilverState"/> class.
            /// </summary>
            /// <param name="state">
            /// The state.
            /// </param>
            public SilverState(State state)
                : this(state.Balance, state.Account)
            {
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="SilverState"/> class.
            /// </summary>
            /// <param name="balance">
            /// The balance.
            /// </param>
            /// <param name="account">
            /// The account.
            /// </param>
            public SilverState(double balance, Account account)
            {
                this.balance = balance;
                this.account = account;
                Initialize();
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// Deposit.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public override void Deposit(double amount)
            {
                balance += amount;
                CheckStateChange();
            }
    
            /// <summary>
            /// Pay interest.
            /// </summary>
            public override void PayInterest()
            {
                balance += interest * balance;
                CheckStateChange();
            }
    
            /// <summary>
            /// Withdraw.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public override void Withdraw(double amount)
            {
                balance -= amount;
                CheckStateChange();
            }
    
            #endregion
    
            #region Methods
    
            /// <summary>
            /// Initialize.
            /// </summary>
            private void Initialize()
            {
                // Should come from a data source.
                interest = 0.0;
                lowerLimit = 0.0;
                upperLimit = 1000.0;
            }
    
            /// <summary>
            /// Check state change.
            /// </summary>
            private void CheckStateChange()
            {
                if (balance < lowerLimit)
                {
                    account.State = new RedState(this);
                }
                else if (balance > upperLimit)
                {
                    account.State = new GoldState(this);
                }
            }
    
            #endregion
        }
    
        /// <summary>
        /// A 'ConcreteState' class.
        /// <remarks>
        /// Gold indicates an interest bearing state.
        /// </remarks>
        /// </summary>
        internal class GoldState : State
        {
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="GoldState"/> class.
            /// </summary>
            /// <param name="state">
            /// The state.
            /// </param>
            public GoldState(State state)
                : this(state.Balance, state.Account)
            {
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="GoldState"/> class.
            /// </summary>
            /// <param name="balance">
            /// The balance.
            /// </param>
            /// <param name="account">
            /// The account.
            /// </param>
            private GoldState(double balance, Account account)
            {
                this.balance = balance;
                this.account = account;
                Initialize();
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// Deposit.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public override void Deposit(double amount)
            {
                balance += amount;
                CheckStateChange();
            }
    
            /// <summary>
            /// Pay interest.
            /// </summary>
            public override void PayInterest()
            {
                balance += interest * balance;
                CheckStateChange();
            }
    
            /// <summary>
            /// Withdraw.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public override void Withdraw(double amount)
            {
                balance -= amount;
                CheckStateChange();
            }
    
            #endregion
    
            #region Methods
    
            /// <summary>
            /// Initialize.
            /// </summary>
            private void Initialize()
            {
                // Should come from a database.
                interest = 0.05;
                lowerLimit = 1000.0;
                upperLimit = 10000000.0;
            }
    
            /// <summary>
            /// Check state change.
            /// </summary>
            private void CheckStateChange()
            {
                if (balance < 0.0)
                {
                    account.State = new RedState(this);
                }
                else if (balance < lowerLimit)
                {
                    account.State = new SilverState(this);
                }
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Context' class.
        /// </summary>
        internal class Account
        {
            #region Fields
    
            /// <summary>
            /// The owner.
            /// </summary>
            private string _owner;
    
            /// <summary>
            /// The state.
            /// </summary>
            private State _state;
    
            #endregion
    
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="Account"/> class.
            /// </summary>
            /// <param name="owner">
            /// The owner.
            /// </param>
            public Account(string owner)
            {
                // New accounts are 'Silver' by default.
                _owner = owner;
                _state = new SilverState(0.0, this);
            }
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// Gets the balance.
            /// </summary>
            private double Balance => _state.Balance;
    
            /// <summary>
            /// Gets or sets the state.
            /// </summary>
            public State State
            {
                private get { return _state; }
    
                set { _state = value; }
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// Deposit.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public void Deposit(double amount)
            {
                _state.Deposit(amount);
                Console.WriteLine("Deposited {0:C} --- ", amount);
                Console.WriteLine(" Balance = {0:C}", Balance);
                Console.WriteLine(" Status = {0}", State.GetType().Name);
                Console.WriteLine(string.Empty);
            }
    
            /// <summary>
            /// Pay interest.
            /// </summary>
            public void PayInterest()
            {
                _state.PayInterest();
                Console.WriteLine("Interest Paid --- ");
                Console.WriteLine(" Balance = {0:C}", Balance);
                Console.WriteLine(" Status = {0}\n", State.GetType().Name);
            }
    
            /// <summary>
            /// Withdraw.
            /// </summary>
            /// <param name="amount">
            /// The amount.
            /// </param>
            public void Withdraw(double amount)
            {
                _state.Withdraw(amount);
                Console.WriteLine("Withdrew {0:C} --- ", amount);
                Console.WriteLine(" Balance = {0:C}", Balance);
                Console.WriteLine(" Status = {0}\n", State.GetType().Name);
            }
    
            #endregion
        }
    }
    
    // Output:
    /*
    Deposited ¥500.00 ---
     Balance = ¥500.00
     Status = SilverState
    
    Deposited ¥300.00 ---
     Balance = ¥800.00
     Status = SilverState
    
    Deposited ¥550.00 ---
     Balance = ¥1,350.00
     Status = GoldState
    
    Interest Paid ---
     Balance = ¥1,417.50
     Status = GoldState
    
    Withdrew ¥2,000.00 ---
     Balance = ¥-582.50
     Status = RedState
    
    No funds available for withdrawal!
    Withdrew ¥1,100.00 ---
     Balance = ¥-582.50
     Status = RedState
    
    
    */

     

    展开全文
  • Android M对应用的授权策略做了变动,如果我们想调用getDeviceId()获取手机串码,只在Manifest里添加android.permission.READ_PHONE_STATE权限是不够的,如果不做权限的动态申请和处理,可能会报如下错误: Android...

    Android M对应用的授权策略做了变动,如果我们想调用getDeviceId()获取手机串码,只在Manifest里添加android.permission.READ_PHONE_STATE权限是不够的,如果不做权限的动态申请和处理,可能会报如下错误:

     AndroidRuntime: java.lang.SecurityException: getDeviceId: Neither user 10201 nor current process has android.permission.READ_PHONE_STATE.
    

    那如何在代码中动态申请权限呢?分四步进行:

    第一步,在Manifest文件中添加权限:

    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    

    第二步, 要获取权限进行操作的Activity实现 ActivityCompat.OnRequestPermissionsResultCallback接口(这一步视情况而定,有的Activity基类已经默认实现了这个接口,比如FragmentActivity,就不用再实现了):

    public class MainActivity extends Activity
            implements ActivityCompat.OnRequestPermissionsResultCallback {
    

    第三步,动态申请权限并做处理:

            int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
    
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
            } else {
                //TODO
            }
    

    其中REQUEST_READ_PHONE_STATE 是自定义的类常量,可以像下面这样在activity中定义:
    public final static int REQUEST_READ_PHONE_STATE = 1;

    第四步, 重写onRequestPermissionsResult()方法,对权限申请结果做处理:

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_READ_PHONE_STATE:
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    //TODO
                }
                break;
    
            default:
                break;
        }
    }
    

    下面对关键方法做一个解释:

    1、检查是否有权限:
    ActivityCompat.checkSelfPermission

    eg:检查是否有读取联系人权限
    ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED

    2、是否重新请求授权(用户之前拒绝过):
    ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_CONTACTS)
    如果应用之前请求过此权限但用户拒绝了请求,此方法将返回 true,意思是说要给用户一个 解释,告诉用户为什么要这个权限。
    然而,在实际开发中,很多手机对原生系统做了修改,比如小米4的6.0的shouldShowRequestPermissionRationale 就一直返回false,而且在申请权限时,如果用户选择了拒绝,则不会再弹出对话框了。如果是这样,我们可以在回调里面处理,如果用户拒绝了这个权限,则打开本应用信息界面,由用户自己手动开启这个权限。

    3、请求授权:
    ActivityCompat.requestPermissions
    注意的是,调用此方法后,系统会弹出一个权限申请框,供用户选择,这个选择框我们无法更改:
    这里写图片描述

    而且此时activity会调用onPause()方法,用户做了选择之后,此对话框消失,onResume()方法又会执行。

    注:在华为设备上测试,如果用户勾选了“不再询问”的选项的话,shouldShowRequestPermissionRationale会返回false。而且如果再次调用requestPermissions申请权限,就不会有申请框弹出,而是直接返回申请失败。但是activity的生命周期方法的执行顺序和有系统提示框弹出时的顺序是一样的。

    4、搜权结果,通过 ActivityCompat.OnRequestPermissionsResultCallback 回调获取授权结果,判断是否授权。

        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == REQUEST_CODE_INFO_OF_PHONE_SETTINGS) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    	            L.d("imei", "permission is granted after requested!");
                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED){
    	            L.d("imei", "permission is not granted after requested!");
    	            //这里表示申请权限后被用户拒绝了
                } else {
                    L.d("imei", "permission is not granted after requested!");
                }
            }
        }
    

    关于更多运行时请求权限的问题,可以查看https://developer.android.com/training/permissions/requesting.html
    更详细请看http://mdsa.51cto.com/art/201508/489882_all.htm#topx

    展开全文
  • State是指流计算过程中计算节点的中间计算结果或元数据属性,比如 在aggregation过程中要在state中记录中间聚合结果,比如 Apache Kafka 作为数据源时候,我们也要记录已经读取记录的offset,这些State数据在计算...

    在这里插入图片描述

    添加微信公众号可以索取资料
    添加QQ群一起分享技术:895467044

    State:

    State是指流计算过程中计算节点的中间计算结果或元数据属性,比如 在aggregation过程中要在state中记录中间聚合结果,比如 Apache Kafka 作为数据源时候,我们也要记录已经读取记录的offset,这些State数据在计算过程中会进行持久化(插入或更新)。所以Apache Flink中的State就是与时间相关的,Apache Flink任务的内部数据(计算数据和元数据属性)的快照。
    在这里插入图片描述


    State分类:Keyed State和Operator State🤣🤣

    Keyed State

    Keyed State是一种基于key的,它永远和key绑定,key和key之间的state没有关系,不会相互影响

    Operator State

    Operator State是一种基于Operate的,每个操作有状态的,每个操作之间不会相互影响。举例来说,Flink中的Kafka Connector,就使用了operator state。它会在每个connector实例中,保存该实例中消费topic的所有(partition, offset)映射。

    Raw State和Managed State
    • Raw即原始状态:由用户自行管理状态具体的数据结构,框架在做checkpoint的时候,使用byte[]来读写状态内容,对其内部数据结构一无所知。
    • Managed State:即托管状态,托管状态是由Flink框架管理的状态,如ValueState, ListState, MapState等。

    Keyed State ---- Managed State

    • ValueState:这将保留一个可以更新和检索的值(如上所述,作用域为输入元素的键,因此该操作看到的每个键可能会有一个值)。该值可以使用设置update(T)和使用检索 T value()。
      实例:
    package flinkscala.State.Keyed_State
    
    import org.apache.flink.api.common.functions.RichFlatMapFunction
    import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor}
    import org.apache.flink.api.common.typeinfo.TypeInformation
    import org.apache.flink.configuration.Configuration
    import org.apache.flink.streaming.api.scala._
    import org.apache.flink.util.Collector
    
    object valueStateTest {
      def main(args: Array[String]): Unit = {
        val env = StreamExecutionEnvironment.getExecutionEnvironment
        env.setParallelism(1)
        env.fromCollection(List(
          (1L, 3L),
          (1L, 5L),
          (1L, 7L),
          (1L, 4L),
          (1L, 2L),
          (1L, 6L),
          (1L, 2L),
          (1L, 9L),
          (1L, 2L),
          (1L, 3L)
        )).keyBy(_._1)
          .flatMap(new CountWindowAverage())
          .print()
        env.execute("average Test")
      }
    }
    
    class CountWindowAverage extends RichFlatMapFunction[(Long,Long),(Long,Long)]{
    
      //定义一个ValueState,保存着(元素的个数,元素的和)
      private var sum: ValueState[(Long,Long)] = _
    
      override def flatMap(value: (Long, Long), out: Collector[(Long, Long)]): Unit = {
        //先访问ValueState,取出ValueState中的和
        //当然,如果是空的话,也就是初次使用的话,就初始化为0,0
        var tmpCurrentSum = sum.value()
        val surrentSum = if(tmpCurrentSum !=null){
          tmpCurrentSum
        }else {(0L,0L)}
    
    
        /*
        * 元素个数+1,元素和+当前进来的元素
        *
        */
        val newSum = (surrentSum._1+1,surrentSum._2+value._2)
    
        //更新状态State
        sum.update(newSum)
    
        //如果达到了两个元素,就计算一次平均值
        if(newSum._1>=2){
          out.collect((value._1,newSum._2/newSum._1))
          sum.clear()//清空状态
        }
      }
    
      override def open(parameters: Configuration): Unit ={
        sum = getRuntimeContext
            .getState(
              new ValueStateDescriptor[(Long, Long)]("average",createTypeInformation[(Long,Long)])
            )
      }
    }
    
    

    在这里插入图片描述

    ListState:这保留了元素列表。您可以追加元素并检索Iterable 所有当前存储的元素。使用add(T)或添加元素addAll(List),可以使用检索Iterable Iterable get()。您还可以使用以下方法覆盖现有列表update(List)

    ReducingState:这将保留一个值,该值代表添加到状态的所有值的集合。介面与相似,ListState但使用新增的元素 add(T)会使用指定的简化为汇总ReduceFunction。

    AggregatingState<IN, OUT>:这将保留一个值,该值代表添加到状态的所有值的集合。与相反ReducingState,聚合类型可能不同于添加到状态中的元素的类型。该接口与for相同,ListState但是使用添加的元素add(IN)是使用指定的聚合的AggregateFunction。

    FoldingState<T, ACC>:这将保留一个值,该值代表添加到状态的所有值的集合。与相反ReducingState,聚合类型可能不同于添加到状态中的元素的类型。该接口类似于,ListState但是使用添加的元素add(T)使用指定的折叠为一个集合FoldFunction。在1.4中已经弃用了,用AggregatingState代替

    MapState<UK, UV>:这将保留一个映射列表。您可以将键值对放入状态,并检索Iterable所有当前存储的映射。使用put(UK, UV)或 添加映射putAll(Map<UK, UV>)。可以使用检索与用户密钥关联的值get(UK)。对于映射,键和值可迭代视图可以使用被检索entries(),keys()并values()分别。您还可以isEmpty()用来检查此映射是否包含任何键值映射。

    我们可以通过getRunTimeContext的getstate方法来获取state,一个state与一个句柄StateDescriptor绑定着,不同的状态保存不同的值,这种情况可能需要多种状态,通过StateDescriptor来获取对应的状态。
    在这里插入图片描述

    State Time-To-Live (TTL)


    对于状态,我们有时候可以设置它的年龄,或者说过期,即到达一定时间就自动清除,或者做相关操作,有点儿像Redis里面的过期。

    import org.apache.flink.api.common.state.StateTtlConfig
    import org.apache.flink.api.common.state.ValueStateDescriptor
    import org.apache.flink.api.common.time.Time
    
    val ttlConfig = StateTtlConfig
    //这个是用来配置生存的过期时间
        .newBuilder(Time.seconds(1))
    //配置什么时候对状态TTL进行刷新:OnCreateAndWrite-仅在创建和写访问时,OnReadAndWrite-有读取访问时
        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
    //配置状态可见性用于配置是否清除尚未过期的默认值(   
        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
        .build
        
    val stateDescriptor = new ValueStateDescriptor[String]("text state", classOf[String])
    stateDescriptor.enableTimeToLive(ttlConfig)
    

    清理过期状态

    val ttlConfig = StateTtlConfig
        .newBuilder(Time.seconds(1))
        .disableCleanupInBackground//防止清理掉后台状态
        .build
    

    Managed Operator State


    前面说了,操作状态是基于操作算子的,然后又是托管的,即用Flink已经有的ValueState等等
    要使用托管操作状态,有状态功能可以实现更通用的CheckpointedFunction 接口,也可以实现ListCheckpointed< T extends Serializable>接口。

    CheckpointedFunction

    每当必须执行检查点时,都会调用snapshotState()。
    每次初始化用户定义函数时,都会调用对应的initializeState()
    void snapshotState(FunctionSnapshotContext context) throws Exception;
    void initializeState(FunctionInitializationContext context) throws Exception;
    无论是在首次初始化函数时,还是在实际从以前的检查点恢复函数时。
    因此,initializeState()不仅是初始化不同类型状态的地方,而且也是包含状态恢复逻辑的地方。
    

    当前,支持列表样式的托管操作符状态。该状态应为彼此独立List的可序列化对象,

    • Even-split redistribution:每个operator返回一个状态元素列表。整个状态在逻辑上是所有列表的串联。在还原/重新分发时,列表被均匀地划分为尽可能多的子列表,因为有并行operator。每个运算符都得到一个子列表,该子列表可以为空,也可以包含一个或多个元素。例如,如果并行度为1时,operator的检查点状态包含元素element1和element2,则当并行度增加到2时,element1可能会在operator实例0中结束,而element2将转到operator实例1。
    • Union redistribution:每个operator都返回状态元素列表。从逻辑上讲,整个状态是所有列表的串联。在还原/重新分发时,每个operator都会获得状态元素的完整列表。
    Even-split redistribution演示
    package flinkscala.State.Operatior_State
    
    import org.apache.flink.api.common.state.{ListState, ListStateDescriptor}
    import org.apache.flink.api.common.typeinfo.{TypeHint, TypeInformation}
    import org.apache.flink.runtime.state.{FunctionInitializationContext, FunctionSnapshotContext}
    import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction
    import org.apache.flink.streaming.api.functions.sink.SinkFunction
    
    import scala.collection.mutable.ListBuffer
    
    object opratorTest {
      def main(args: Array[String]): Unit = {
    
      }
    
    }
    class BufferingSink(threshold: Int = 0) extends SinkFunction[(String,Int)] with CheckpointedFunction{
    
      private var checkpointedState: ListState[(String,Int)] = _
    
      private val bufferedElements = ListBuffer[(String,Int)]()
    
      override def invoke(value: (_root_.scala.Predef.String, Int), context: _root_.org.apache.flink.streaming.api.functions.sink.SinkFunction.Context[_]): Unit = {
        bufferedElements += value
        if(bufferedElements.size == threshold){
          for(element <- bufferedElements){
            //这里面将它发送到Sink
          }
          //发完之后就清空
          bufferedElements.clear()
        }
      }
    
    
      override def snapshotState(context: FunctionSnapshotContext): Unit = {
        checkpointedState.clear()
        for (element <- bufferedElements) {
          checkpointedState.add(element)
        }
      }
    
      override def initializeState(context: FunctionInitializationContext): Unit = {
        val descriptor = new ListStateDescriptor[(String,Int)](
          "buffered-elements",
          TypeInformation.of(new TypeHint[(String,Int)] {})
        )
    
        checkpointedState = context.getOperatorStateStore.getListState(descriptor)
    
        if(context.isRestored){
          for(element <- checkpointedState.get()){
            bufferedElements += element
          }
    
        }
      }
    }
    
    

    ListCheckpointed

    该ListCheckpointed接口是的一个更有限的变体CheckpointedFunction,它仅支持列表样式状态,并在还原时使用偶数拆分的重新分配方案。它还需要实现两种方法:

    List<T> snapshotState(long checkpointId, long timestamp) throws Exception;
    
    void restoreState(List<T> state) throws Exception;
    

    在snapshotState()操作员上应将对象列表返回给检查点,并且 restoreState在恢复时必须处理此类列表。如果状态不是重新分区,可以随时返回Collections.singletonList(MY_STATE)的snapshotState()。

    展开全文
  • stateflow

    千次阅读 2020-06-29 08:11:33
    stateflow状态图中如果有流程图,而流程图不加自循环,那么他只在进入默认转移时执行一次,如果加了自循环那么他每一次外部事件触发他就执行一次,而状态动作during和entry,entry只在进入状态图时执行一次,而...
  • LSTM中的cell state 和 hidden state

    千次阅读 2019-06-18 14:20:40
    TensorFlow中使用tf.contrib.rnn.BasicLSTMCell()的方法来搭建LSTM网络,其中有一项参数为state_is_tuple,官方建议设置为True,这个参数的实际就是使LSTM的state以tuple的形式输出,shape为batch size和num_step,...
  • 一 vm_state1 虚拟机处在稳定状态,通过api产生的状态。2 有Active,Error,Reboot,Build,Shutoff五种状态。二 task_state虚拟机处在中间状态,通过api产生表示虚拟机正在执行某种任务(操作)当任务执行完成后,task ...
  • Qt State StateMachine

    千次阅读 2011-12-26 15:30:28
    状态机顾名思义,应该有...上面状态机图中,我们提供了两种状态state1和state2。而状态的区分是由状态的属性来描述的,比如p1,p2…等等。从一个状态到另一个状态的转化,必须由触发条件来完成,上图state1到s
  • Android系统自带的层次状态机StateMachine(Hierarchical State Machine) Android在framework层自己实现一套层次状态机,总共有三个类:StateMachine,State和IState,这三个类直接从Android平台代码中没有公开...
  • load_state_dict(state_dict, strict=True)

    千次阅读 2019-09-30 15:39:51
    load_state_dict(state_dict, strict=True)[source] Copies parameters and buffers from state_dict into this module and its descendants. If strict is True, then the keys of state_dict must exactly match ...
  • Flink的State概述

    千次阅读 2019-01-18 23:14:02
    文章目录前言Flink的State类型基本类型划分组织形式划分 前言 当我们经常在谈论一个Flink任务是否是有状态的,此时我们谈论的点其实就是Flink内部的State的概念。但是这里的State的概念已经不是单纯指我们平时所...
  • State模式

    2014-03-03 14:37:23
    State模式将状态逻辑和动作实现进行分离。当一个操作中要维护大量的case分支语句,并且这些分支依赖于对象的状态。State模式将每个分支都封装到独立的类中。 State.h //state.h #ifndef _STATE_H_ #define _STATE_...
  • 在react中正确修改state

    万次阅读 2018-07-01 19:17:54
    一,在react中可以通过this.state.{属性}的方式直接获取state,但是当我们修改state的时候,往往有许多的坑需要注意。以下 为三种常见的陷阱:1,不能直接修改state。 组件修改state,并不会重新触发render。列如:/...
  • State Estimation Deep Variational Bayes Filters: Unsupervised Learning of State Space Models from Raw Data, M. Carl et al., ICLR 2017 ⭐️ Deep Kalman Filters R. G. Krishnan et al., arXiv 2015 ...
  • ConnectionState详解

    千次阅读 2018-11-19 16:40:00
    ConnectionState有六个属性值ConnectionState.Broken;与数据源连接断开。只有在连接打开后才有可能发生这种情况。可以关闭处于这种状态下的连接,然后重新打开。ConnectionState.Closed;连接处于关闭状态。...
  • 了解react-hook以及State Hook

    万次阅读 2019-05-18 23:28:00
    react更新到16.8版本后最主要的内容就是增加了hook这个特性,它的主要作用可以理解为对react的函数组件进行了一次升级,使react的...Hook 是一些可以让你在函数组件里“钩入” React state 及生命周期等特性的函数。...
  • ROS中 ERROR: cannot launch node of type [joint_state_publisher/joint_state_publisher]: joint_state_publisher问题如下问题原因解决方法 ) 问题如下 ERROR: cannot launch node of type [joint_state_publisher...
  • Android学习 StateMachine与State模式

    千次阅读 2015-06-14 14:52:03
     目录(?)[-] ... Android学习 StateMachine与State模式 一 State模式 意图:  允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。(Objects for States) ...
  • Openstack VMState

    千次阅读 2017-01-04 13:38:25
    1 Nova state machine simplification 1.1 power_state 1.2 vm_state 1.3 task_state Nova state machine simplification There are vm_states, task_states, and power_states for each VM. The us
  • 【cpufreq子系统】P State和C State

    千次阅读 2018-05-18 16:02:28
    cpufreq子系统是在linux2.6.0之后导入的,cpufreq主要由两个部分组成:调控器(类似interactive变速器)+守护程序CPU电源状态:C stateCPU性能状态:P state实际上在linara的官网脚本上统计出来的c-state是指的idle...
  • state.sls和state.highstate的区别

    千次阅读 2017-05-13 08:33:24
    state.highstate会读取所有环境(包括base环境)的top.sls文件,并且执行top.sls文件内容里面定义的sls文件,不在top.sls文件里面记录的sls则不会被执行; state.sls默认读取base环境,但是它并不会读取top.sls文件...
  • 初始化 State

    千次阅读 2017-05-01 13:04:01
    初始化State的方法有以下方法: 1.在创建store 的时候,createStore()方法的第二个参数preloadeState参数是初始化state的。 2.在reducer中设置state的初始值state={...},也可以使用ES6中默认的参数语法: ...
  • ERROR: cannot launch node of type [robot_state_publisher/robot_state_publisher]: robot_state_publisher ROS path [0]=/opt/ros/kinetic/share/ros ROS path [1]=/home/wxw/catkin_ws/src ROS path [2...
  • Android 开发之PhoneState与CallState

    千次阅读 2014-11-05 13:22:22
    Android 开发之PhoneState与CallState 最近在研究Phone
  • 使用vuex修改state时,有两种方式: 1)可以直接使用 this.$store.state.变量 = xxx; 2)this.$store.dispatch(actionType, payload)   或者: this.$store.commit(commitType, payload)     二. 异同点 ...
  • set_task_state和set_current_state

    千次阅读 2017-03-07 00:27:21
    set_task_state和set_current_state宏定义#define mb() __asm__ __volatile__ ("" ::: "memory")#define set_task_state(tsk, state_value) \ set_mb((tsk)->state, (state_value))#define set_current_state(state_...
  • 本文将重点跟大家讲解Flink的状态管理机制,包括状态要解决的问题、Flink几种不同类型的状态、Keyed State和Operator List State的使用方法等。相关代码参见的github:...
  • stateflow使用

    万次阅读 2016-04-04 14:47:03
    matlab stateflow使用

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 303,577
精华内容 121,430
关键字:

state