问:
How to debug an Android Background Service?
I have been developing a PhoneGap application for Android which contains a Background Service. My question is: How can I debug this service? Is it possible to debug using an AVD and go step by step? or can I use my own device to achieve that?

Thanks!

答:
Look for where your background service starts, for example

```<code>public BGcheckService() {
    Log.d("BGcheckService: ", "starting service");
}
</code>```

Then insert one line:

```<code>public BGcheckService() {
    android.os.Debug.waitForDebugger();
    Log.d("BGcheckService: ", "starting service");
}
</code>```

Besides this, if your background service is in a separate process, then when you press the debug button to start debugging your background service, you also need to wait till the background service has started, then press the button to attach to process (see screenshot for Android Studio 3.6.1 .. it is the 3rd button to the right from the debug button). You will be given a choice of processes to attach to, one of which would be the background service's separate process.

NB:

Without the line android.os.Debug.waitForDebugger();, the background service would just start without waiting for the debugger to attach.

Even with the line android.os.Debug.waitForDebugger();, you still need to attach the debugger to the process of the background service.

The timing of when you press the button to attach to the process, needs to be after the background service has started (while it is waiting at android.os.Debug.waitForDebugger();), otherwise the process would not exist and you would not be able to select it.

Body:
Look for where your background service starts, for example

public BGcheckService() {
    Log.d("BGcheckService: ", "starting service");
}

Then insert one line:

public BGcheckService() {
    android.os.Debug.waitForDebugger();
    Log.d("BGcheckService: ", "starting service");
}

Besides this, if your background service is in a separate process, then when you press the debug button to start debugging your background service, you also need to wait till the background service has started, then press the button to attach to process (see screenshot for Android Studio 3.6.1 .. it is the 3rd button to the right from the debug button). You will be given a choice of processes to attach to, one of which would be the background service's separate process.

NB:

Without the line android.os.Debug.waitForDebugger();, the background service would just start without waiting for the debugger to attach.

Even with the line android.os.Debug.waitForDebugger();, you still need to attach the debugger to the process of the background service.

The timing of when you press the button to attach to the process, needs to be after the background service has started (while it is waiting at android.os.Debug.waitForDebugger();), otherwise the process would not exist and you would not be able to select it.


来源: stackexchange

问:
how to rollback to previous build in azure devops using yaml
I have a multi-stage pipeline YAML deploying to different environments (PreDev-Dev-QA-Stage-Prod) and i'm trying to implement rollback strategy to rollback to previous version or previous build artifact and was looking at this page https://learn.microsoft.com/en-us/azure/devops/pipelines/process/deployment-jobs?view=azure-devops but couldn't figure out and also didn't find any examples. Any help is appreciated</p>

答:
According to the doc:

We currently only support the runOnce, rolling, and the canary strategies.

The rollback strategy doesn't seem to support in Yaml definition.

But you can manually run the previous stage again. Then the pipeline could rollback to the previous version.

Step1: Navigate to the build summary page of the previous build.

Step2: Select the stage and use "Rerun Stage" optiom.

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
How do I get the value from HashMap in my ListView?
I've created my own custom adapter by extending BaseAdapter. I just want to be able to grab the string of the value in my onItemClick method (so I can put it as an intent extra). How can I do that?

My custom adapter looks like this:

```<code>   private class HashMapAdapter extends BaseAdapter {

        private HashMap<String, String> mMap = new HashMap<String, String>();
        private String[] mKeys;
        private Context mContext;

        private HashMapAdapter(Context context, HashMap<String, String> map) {
            mContext = context;
            mMap = map;
            mKeys = mMap.keySet().toArray(new String[map.size()]);
        }

        @Override
        public int getCount() {
            return mMap.size();
        }

        @Override
        public Object getItem(int position) {

            return mMap.get(mKeys[position]);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
//          String key = mKeys[position];

            RowView row;
            if(convertView == null) {
                row = new RowView(getBaseContext());
            } else {
                row = (RowView) convertView;
            }
            row.display(mKeys[position]);
            return row;

        }

    }
</code>```

答:
In the getView method you can retrieve the value by using

```<code>mMap.get(mKeys[position]);
</code>```

although I'm not 1000% sure

ContentLicense: CC BY-SA 3.0

Body:
I've created my own custom adapter by extending BaseAdapter. I just want to be able to grab the string of the value in my onItemClick method (so I can put it as an intent extra). How can I do that?

My custom adapter looks like this:

   private class HashMapAdapter extends BaseAdapter {

        private HashMap<String, String> mMap = new HashMap<String, String>();
        private String[] mKeys;
        private Context mContext;

        private HashMapAdapter(Context context, HashMap<String, String> map) {
            mContext = context;
            mMap = map;
            mKeys = mMap.keySet().toArray(new String[map.size()]);
        }

        @Override
        public int getCount() {
            return mMap.size();
        }

        @Override
        public Object getItem(int position) {

            return mMap.get(mKeys[position]);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
//          String key = mKeys[position];

            RowView row;
            if(convertView == null) {
                row = new RowView(getBaseContext());
            } else {
                row = (RowView) convertView;
            }
            row.display(mKeys[position]);
            return row;

        }

    }

Body:
In the getView method you can retrieve the value by using

mMap.get(mKeys[position]);

although I'm not 1000% sure


问:
Navigation bar button image
I am using this code to get a logo on my nav bar.

```<code>override func viewDidAppear(animated: Bool) {

    let image = UIImage(named: "LogoWithTextSmaller.png")
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
    }
</code>```

This is fine, but the logo doesn't have any colour - besides 'blue'. Is it because it is a png file. Is there something I can so it retains the original colours

I have done this:

```<code>self.navigationItem.titleView = UIImageView(image: image)
</code>```

and that brings the image onto the nav bar with the correct colours - but it's in the middle and I want it on the left.

答:
SWIFT 4

```<code>    let back = UIImage(named: "back_white")?.withRenderingMode(.alwaysOriginal)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: back, style:.plain, target: nil, action: nil)
</code>```

Title: Navigation bar button image

Body:
I am using this code to get a logo on my nav bar.

override func viewDidAppear(animated: Bool) {

    let image = UIImage(named: "LogoWithTextSmaller.png")
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
    }

This is fine, but the logo doesn't have any colour - besides 'blue'. Is it because it is a png file. Is there something I can so it retains the original colours

I have done this:

self.navigationItem.titleView = UIImageView(image: image)

and that brings the image onto the nav bar with the correct colours - but it's in the middle and I want it on the left.

Body:
SWIFT 4

    let back = UIImage(named: "back_white")?.withRenderingMode(.alwaysOriginal)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: back, style:.plain, target: nil, action: nil)


问:
Find unique name of device?
I'm developing an app that uses zeroconf (bonjour) to discover devices - so I need to give each android device some kind of name (not just a bunch of numbers and letters, but something meaningful like "Alex's Device"). In iOS it can be easily done - is this possible in android?</p>

答:
There can be many accounts linked to the device. You can use the AccountManager to get them. For example, emails on google accounts:

```<code>AccountManager am = AccountManager.get(this);

Account[] ac = am.getAccountsByType("com.google");

for (Account account : ac) {
  Log.d ("Account", ac.name);
}
</code>```

Alternatively, you can use android.os.Build.MODEL or similar.

Title: Find unique name of device?

Body:
There can be many accounts linked to the device. You can use the AccountManager to get them. For example, emails on google accounts:

AccountManager am = AccountManager.get(this);

Account[] ac = am.getAccountsByType("com.google");

for (Account account : ac) {
  Log.d ("Account", ac.name);
}

Alternatively, you can use android.os.Build.MODEL or similar.


问:
Twig concatenation syntax
I'm struggling to find the correct Twig concatenation syntax.

Here's what I've got:

```<code>{{ this.page.baseFileName|page({ (__SELF__.pageParam): page }) }}
</code>```

it gives the url with the pagination number at the end of the url:

http://sites.local12/category/style/rock/2

Now I want to insert a colon before the pagination number like this:

http://sites.local12/category/style/rock/:2

How to achieve that ?

答:
Ok I've got it. I was confused by the "page" filter (I'm new to Twig).  </p>

```<code>{{ this.page.baseFileName|page( {(__SELF__.pageParam): ':' ~ page }) }}
</code>```

Title: Twig concatenation syntax

Body:
I'm struggling to find the correct Twig concatenation syntax.

Here's what I've got:

{{ this.page.baseFileName|page({ (__SELF__.pageParam): page }) }}

it gives the url with the pagination number at the end of the url:

http://sites.local12/category/style/rock/2

Now I want to insert a colon before the pagination number like this:

http://sites.local12/category/style/rock/:2

How to achieve that ?

Body:
Ok I've got it. I was confused by the "page" filter (I'm new to Twig).

{{ this.page.baseFileName|page( {(__SELF__.pageParam): ':' ~ page }) }}


问:
Quasar change word 'of' in table pagination label
Is it possible to change the word of in table pagination-label?

For example: change 1-10 of 100 for 1-10 de 100

The function to change the label only provides (firstRowIndex, endRowIndex, totalRowsNumber).

Thanks.

Edited | for i18n

For example

```<code>export const ptPT = {
   general: {
     of: 'de',
   }
}
</code>```

.vue file:

How to get pagination of word  to translate?

```<code><p> {{$t("general.of")}} </p>
</code>```

答:
One way is that you can set the language in quasar and it will change it.

```<code>Quasar.lang.set(Quasar.lang.es)
</code>```

codepen - https://codepen.io/Pratik__007/pen/LYpKNRB

Body:
Is it possible to change the word of in table pagination-label?

For example: change 1-10 of 100 for 1-10 de 100

The function to change the label only provides (firstRowIndex, endRowIndex, totalRowsNumber).

Thanks.

Edited | for i18n

For example

export const ptPT = {
   general: {
     of: 'de',
   }
}

.vue file:

How to get pagination of word  to translate?

 {{$t("general.of")}}

Body:
One way is that you can set the language in quasar and it will change it.

Quasar.lang.set(Quasar.lang.es)

codepen - https://codepen.io/Pratik__007/pen/LYpKNRB


问:
How to read Firebase document with auto generated document id using Javascript
I am trying to read a single document from a Firebase collection using a variable that is populated with the document id. The document id is correct and the document exists in the collection.
When I initiate the code using variable it seems that the read was successful but there is no data in the field I am interested in. (See Code below).

db.collection("Pswref").doc(clpdocid).get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('yyyyyy - Great document found using fixed id for doc id ', docRef.data());
            console.log('yyyyyy - Title from database = >', SingleRecord.title);
            console.log('yyyyyy - Doc id ', clpdocid);
        })
        .catch((error) => {
            console.error('yyyyyy - Error getting document ', error);
        });```
</div>
</div>
</p>

<p>However when I hard-code the document id in the get statement all is well and I can access the information needed. (See code below).</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>db.collection("Pswref").doc("NoA6EBijcgsBIIOZCsWC").get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('xxxxxx - Great document found using fixed id for doc id ',docRef.data());
            console.log('xxxxxx - Title from database = >', SingleRecord.title);
        })
        .catch((error) => {
            console.error('xxxxxx - Error getting document ', error);
        });</code>```

The image shows the console.log output as per the script.
NB: You will note that the above queries are exactly the same accept for the doc id reference used and I get a different result as per the output generated via the console.

Can someone help me to understand why this might happen and what the solution might be?

I have commented on the line out giving the error and rerun so that the output in the console can show that the clpdocid is actually correctly populated.(see snipped below)and then output on the new image.

        db.collection("Pswref").doc(clpdocid).get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('yyyyyy - Great document found using fixed id for doc id ', docRef.data());
            //console.log('yyyyyy - Title from database = >', SingleRecord.title);
            console.log('yyyyyy - Doc id ', clpdocid);
        })
        .catch((error) => {
            console.error('yyyyyy - Error getting document ', error);
        });```

答:
It's certainly the case that clpdocid doesn't actually contain the value you expect.  The undefined that you're printing from docRer.data() is proof that you've requested a document that doesn't exist, since the API documentation for data() says to expect undefined if the document was not found.

Try logging the value of clpdocid before the query to make sure you have the document ID you want.

Body:
I am trying to read a single document from a Firebase collection using a variable that is populated with the document id. The document id is correct and the document exists in the collection.
When I initiate the code using variable it seems that the read was successful but there is no data in the field I am interested in. (See Code below).

db.collection("Pswref").doc(clpdocid).get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('yyyyyy - Great document found using fixed id for doc id ', docRef.data());
            console.log('yyyyyy - Title from database = >', SingleRecord.title);
            console.log('yyyyyy - Doc id ', clpdocid);
        })
        .catch((error) => {
            console.error('yyyyyy - Error getting document ', error);
        });

However when I hard-code the document id in the get statement all is well and I can access the information needed. (See code below).

db.collection("Pswref").doc("NoA6EBijcgsBIIOZCsWC").get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('xxxxxx - Great document found using fixed id for doc id ',docRef.data());
            console.log('xxxxxx - Title from database = >', SingleRecord.title);
        })
        .catch((error) => {
            console.error('xxxxxx - Error getting document ', error);
        });

The image shows the console.log output as per the script.
NB: You will note that the above queries are exactly the same accept for the doc id reference used and I get a different result as per the output generated via the console.

Can someone help me to understand why this might happen and what the solution might be?

I have commented on the line out giving the error and rerun so that the output in the console can show that the clpdocid is actually correctly populated.(see snipped below)and then output on the new image.

        db.collection("Pswref").doc(clpdocid).get().then((docRef) => {
            const SingleRecord = docRef.data();
            console.log('yyyyyy - Great document found using fixed id for doc id ', docRef.data());
            //console.log('yyyyyy - Title from database = >', SingleRecord.title);
            console.log('yyyyyy - Doc id ', clpdocid);
        })
        .catch((error) => {
            console.error('yyyyyy - Error getting document ', error);
        });


问:
Facebook iFrame Vertical Scrollbar Won't Go Away
I created a custom facebook landing page using the same template I have used 3 times before. The problem is, this time, ther vertical scrollbar won't go away. This is the resizing code I have been using:

```<code><script type="text/javascript">// <![CDATA[
    window.fbAsyncInit = function() { FB.Canvas.setSize({ width: 520, height: 1200});}
    function sizeChangeCallback() { FB.Canvas.setSize({ width: 520, height: 1200});}
// ]]></script>
</code>```

and at the bottom of the page:

```<code><div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">// <![CDATA[
    FB.init({
    appId : 'MY_APP_ID',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml : true // parse XFBML
    });
// ]]></script>
</code>```

My CSS uses body {overflow: hidden;}, inside my app "auto resize" is selected. The issue is not that the ifarme won't resize (it does), it's that I have an empty vertical scrollbar on the right that won't go away.

Since the iframe design uses the whole 520px width, the empty vertical srollbar gives me the dreaded horizontal scrollbar. Judging by the width of the horizontal scrollbar, it's the vertical scrollbar causing it and not anything (that I can find or see) in the HTML/CSS making the page wider than 520px. The problem happens in IE8, IE7 and Firefox.

You can see the page here.

I have tried a few variations of the javascript code from a few different sources, but no luck. Not sure if this is something small I'm missing or if it's yet another facebook bug. This problem is not present on any of my other facebook iframe landing pages. After searching around for an answer and coming up with nothing, I've hit a wall with this one.

答:
Its this code

```<code>html {
overflow-Y: scroll;
}
</code>```

in your style.css style sheet thats causing the problem.  When I inspect it with Chrome and remove that value, the scroll bars disappear.

Body:
I created a custom facebook landing page using the same template I have used 3 times before. The problem is, this time, ther vertical scrollbar won't go away. This is the resizing code I have been using:

and at the bottom of the page:

My CSS uses body {overflow: hidden;}, inside my app "auto resize" is selected. The issue is not that the ifarme won't resize (it does), it's that I have an empty vertical scrollbar on the right that won't go away.

Since the iframe design uses the whole 520px width, the empty vertical srollbar gives me the dreaded horizontal scrollbar. Judging by the width of the horizontal scrollbar, it's the vertical scrollbar causing it and not anything (that I can find or see) in the HTML/CSS making the page wider than 520px. The problem happens in IE8, IE7 and Firefox.

You can see the page here.

I have tried a few variations of the javascript code from a few different sources, but no luck. Not sure if this is something small I'm missing or if it's yet another facebook bug. This problem is not present on any of my other facebook iframe landing pages. After searching around for an answer and coming up with nothing, I've hit a wall with this one.

Body:
Its this code

html {
overflow-Y: scroll;
}

in your style.css style sheet thats causing the problem.  When I inspect it with Chrome and remove that value, the scroll bars disappear.


问:
How do I dispatch two different properties to the selector?
I have a selector that is dependent on another one, which they need the userId to be able to "work".

But now I would like to create a selector that receives the "userId" and also receives another property called "userFriend".

What happens is that he is complaining about this parameter pass, as he is only finding one property, which is the "userId".

ERROR 1:

```<code>Property 'userFriend' does not exist on type '{ userId: any; }'
</code>```

ERROR 2:

```<code>TS2339: Property 'userFriend' does not exist on type '{userId: any; } '.

34 (latestReadMessages, totalUnreadMessages, {userId, userFriend}) => {
                                                        ~~~~~~~~~~
src / app / services / store / chat / chat-selectors.service.ts: 34: 26 - error TS2769: No overload matches this call.
  Overload 1 of 8, '(mapFn: (state: object, props: {userId: any;}) => IChatFriendLatestMessageList, props ?: {userId: any;}): (source $: Observable <object>) => Observable <...> ', gave the following error.
    Argument of type '{userId: string; userFriend: IUser; } 'is not assignable to parameter of type' {userId: any; } '.
      Object literal may only specify known properties, and 'userFriend' does not exist in type '{userId: any; } '.
  Overload 2 of 8, '(key1: "user" | "chat", key2: "loading" | "data" | "dataError" | "ids" | "entities"): (source $: Observable <IStoreState>) = > Observable <any> ', gave the following error.
    Argument of type 'MemoizedSelectorWithProps <object, {userId: any; }, IChatFriendLatestMessageList, DefaultProjectorFn <IChatFriendLatestMessageList>> 'is not assignable to parameter of type' "user" | "chat" '.
      Type 'MemoizedSelectorWithProps <object, {userId: any; }, IChatFriendLatestMessageList, DefaultProjectorFn <IChatFriendLatestMessageList>> 'is not assignable to type' "chat" '.

34 return this.store.pipe (select (selector.getFriendLatestMessageList, {userId, userFriend}));
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
</code>```

SELECTORS:

```<code>export const messagesById = createSelector(selectAll, (chat: IChat[], { userId }) => {
  let messageIndex = 0;
  return chat.map((props, index) => {
    if (props.id === userId) {
      messageIndex = index;
      return props.messages;
    } else {
      return [];
    }
  })[messageIndex];
});

export const isLoading = createSelector(FEATURE_SELECTOR, ({ loading }) => loading);
export const error = createSelector(FEATURE_SELECTOR, ({ dataError }) => dataError);
export const friendMessages = createSelector(messagesById, messages => messages.filter(msg => !msg.isMain));
export const friendLatestMessage = createSelector(friendMessages, messages => messages[messages.length - 1]);
export const friendLatestReadMessages = createSelector(friendMessages, messages => messages.filter(msg => msg.isRead));
export const friendLatestUnreadMessages = createSelector(friendMessages, messages =>
  messages.filter(msg => !msg.isRead)
);
export const totalUnreadMessagesFriend = createSelector(friendLatestUnreadMessages, messages => messages.length);

export const getFriendLatestMessageList = createSelector(
  friendLatestMessage,
  totalUnreadMessagesFriend,

  (latestReadMessages, totalUnreadMessages, { userId, userFriend }) => {
    const latestMessageList: IChatFriendLatestMessageList = {
      user: userFriend.id,
      informations: {
        chatMessage: [latestReadMessages],
        isNewLastMessage: !userFriend.isClicked && totalUnreadMessages > 0,
        total: totalUnreadMessages,
      },
    };

    return latestMessageList;
  }
);
</code>```

SERVICE FOR DISPATCH SELECTORS:

```<code>getFriendLatestMessageListById(userId: string, user: IUser): Observable<IChatFriendLatestMessageList> {
    return this.store.pipe(select(selector.getFriendLatestMessageList, { userId, user }));
}
</code>```

INTERFACE:

```<code>export interface IChatFriendLatestMessageList {
    userFriend: IUser;
    informations: {
        chatMessage: IChatMessage[];
        isNewLastMessage: boolean;
        total: number;
    };
}
</code>```

ERROR SCREENSHOT

答:
The problem is caused because this selector has own props and in the same time it uses parent selectors that also have own props.

NGRX doesn't support it and to make it working we need to incapsulate the parent selectors.

export const getFriendLatestMessageList = createSelector(
    s => s, // selecting the whole store.
    (store, { userId, userFriend }) => {
        // selecting our state.
        const latestReadMessages = friendLatestMessage(store, { userId });
        const totalUnreadMessages = totalUnreadMessagesFriend(store, { userId });
        // using them.
        const latestMessageList: IChatFriendLatestMessageList = {
            user: userFriend,
            informations: {
                chatMessage: [latestReadMessages],
                isNewLastMessage: !userFriend.isClicked && totalUnreadMessages > 0,
                total: totalUnreadMessages,
            },
        };

        return latestMessageList;
    }
);
```

Body:
I have a selector that is dependent on another one, which they need the userId to be able to "work".

But now I would like to create a selector that receives the "userId" and also receives another property called "userFriend".

What happens is that he is complaining about this parameter pass, as he is only finding one property, which is the "userId".

ERROR 1:

Property 'userFriend' does not exist on type '{ userId: any; }'

ERROR 2:

TS2339: Property 'userFriend' does not exist on type '{userId: any; } '.

34 (latestReadMessages, totalUnreadMessages, {userId, userFriend}) => {
                                                        ~~~~~~~~~~
src / app / services / store / chat / chat-selectors.service.ts: 34: 26 - error TS2769: No overload matches this call.
  Overload 1 of 8, '(mapFn: (state: object, props: {userId: any;}) => IChatFriendLatestMessageList, props ?: {userId: any;}): (source $: Observable <object>) => Observable <...> ', gave the following error.
    Argument of type '{userId: string; userFriend: IUser; } 'is not assignable to parameter of type' {userId: any; } '.
      Object literal may only specify known properties, and 'userFriend' does not exist in type '{userId: any; } '.
  Overload 2 of 8, '(key1: "user" | "chat", key2: "loading" | "data" | "dataError" | "ids" | "entities"): (source $: Observable <IStoreState>) = > Observable <any> ', gave the following error.
    Argument of type 'MemoizedSelectorWithProps <object, {userId: any; }, IChatFriendLatestMessageList, DefaultProjectorFn <IChatFriendLatestMessageList>> 'is not assignable to parameter of type' "user" | "chat" '.
      Type 'MemoizedSelectorWithProps <object, {userId: any; }, IChatFriendLatestMessageList, DefaultProjectorFn <IChatFriendLatestMessageList>> 'is not assignable to type' "chat" '.

34 return this.store.pipe (select (selector.getFriendLatestMessageList, {userId, userFriend}));
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~

SELECTORS:

export const messagesById = createSelector(selectAll, (chat: IChat[], { userId }) => {
  let messageIndex = 0;
  return chat.map((props, index) => {
    if (props.id === userId) {
      messageIndex = index;
      return props.messages;
    } else {
      return [];
    }
  })[messageIndex];
});

export const isLoading = createSelector(FEATURE_SELECTOR, ({ loading }) => loading);
export const error = createSelector(FEATURE_SELECTOR, ({ dataError }) => dataError);
export const friendMessages = createSelector(messagesById, messages => messages.filter(msg => !msg.isMain));
export const friendLatestMessage = createSelector(friendMessages, messages => messages[messages.length - 1]);
export const friendLatestReadMessages = createSelector(friendMessages, messages => messages.filter(msg => msg.isRead));
export const friendLatestUnreadMessages = createSelector(friendMessages, messages =>
  messages.filter(msg => !msg.isRead)
);
export const totalUnreadMessagesFriend = createSelector(friendLatestUnreadMessages, messages => messages.length);

export const getFriendLatestMessageList = createSelector(
  friendLatestMessage,
  totalUnreadMessagesFriend,

  (latestReadMessages, totalUnreadMessages, { userId, userFriend }) => {
    const latestMessageList: IChatFriendLatestMessageList = {
      user: userFriend.id,
      informations: {
        chatMessage: [latestReadMessages],
        isNewLastMessage: !userFriend.isClicked && totalUnreadMessages > 0,
        total: totalUnreadMessages,
      },
    };

    return latestMessageList;
  }
);

SERVICE FOR DISPATCH SELECTORS:

getFriendLatestMessageListById(userId: string, user: IUser): Observable<IChatFriendLatestMessageList> {
    return this.store.pipe(select(selector.getFriendLatestMessageList, { userId, user }));
}

INTERFACE:

export interface IChatFriendLatestMessageList {
    userFriend: IUser;
    informations: {
        chatMessage: IChatMessage[];
        isNewLastMessage: boolean;
        total: number;
    };
}

ERROR SCREENSHOT


答:
Try changing the name of the function param</p>

```<code>getFriendLatestMessageListById(userId: string, userFriend: IUser): Observable<IChatFriendLatestMessageList> {
  return this.store.pipe(select(selector.getFriendLatestMessageList, { userId, userFriend}));
}
</code>```

Title: How do I dispatch two different properties to the selector?

Body:
Try changing the name of the function param

getFriendLatestMessageListById(userId: string, userFriend: IUser): Observable<IChatFriendLatestMessageList> {
  return this.store.pipe(select(selector.getFriendLatestMessageList, { userId, userFriend}));
}


问:
How can I remove a certain pattern from a string?
I have this string like "682_2, 682_3, 682_4". (682 is a random number)

How can i get this string "2, 3, 4" using regex and ruby?

答:
You can do this in ruby

input="682_2, 682_3, 682_4"
output = input.gsub(/\d+_/,"")
puts output
```


问:
How to specify order of Data Annotation errors in Html.ValidationSummary
I'm displaying errors on my form with the use of

```<code><%= Html.ValidationSummary("Please review the errors below") %>
</code>```

My domain object inherits from a base class and I am finding that the base class data annotation properties are being displayed at the bottom of the list. This goes against the order in which they appear in my form.

Is there any way of specifying what order the errors should be displayed?

Example:

```<code>public class ClassA { [Required]public string AProperty; }
public class ClassB : ClassA { [Required]public string BProperty; }
</code>```

My form (strongly typed view of ClassB):

```<code>AProperty: <%= Html.TextBoxFor(m => m.AProperty) %>
BProperty: <%= Html.TextBoxFor(m => m.BProperty) %>
</code>```

Validation errors appear as:

```<code>The BProperty is required.
The AProperty is required.
</code>```

答:
I had this same problem and it wasn't feasible to create a new view model - also if you have custom model binders, these will appear at the end of the validation summary regardless. I expanded on Aphize answer, rather than pass it a list of property names you can pass it the form keys - this will ensure the order is the same as they appear in the form e.g.

```<code>ModelState.OrderByKeys(Request.Form.AllKeys);
</code>```

This worked for me and I created an attribute to do this.. ( I had to do some tweaking to deal with the custom binders but here it is without that):

```<code>public class ForceValidationErrorOrderAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var allFormKeys = filterContext.HttpContext.Request.Form.AllKeys;
        var modelStateDictionary = filterContext.Controller.ViewData.ModelState;

        ModelStateDictionary result = new ModelStateDictionary();
        foreach (string key in allFormKeys)
        {
            if (modelStateDictionary.ContainsKey(key) && !result.ContainsKey(key))
            {
                result.Add(key, modelStateDictionary[key]);
            }
        }
        foreach (string key in modelStateDictionary.Keys)
        {
            if (!result.ContainsKey(key))
            {
                result.Add(key, modelStateDictionary[key]);
            }
        }
        modelStateDictionary.Clear();
        modelStateDictionary.Merge(result);
        }
    }
</code>```

And then on the controller action method:

```<code>    [ForceValidationErrorOrder]
    public ActionResult Apply(ApplicationViewModel viewModel)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm displaying errors on my form with the use of

<%= Html.ValidationSummary("Please review the errors below") %>

My domain object inherits from a base class and I am finding that the base class data annotation properties are being displayed at the bottom of the list. This goes against the order in which they appear in my form.

Is there any way of specifying what order the errors should be displayed?

Example:

public class ClassA { [Required]public string AProperty; }
public class ClassB : ClassA { [Required]public string BProperty; }

My form (strongly typed view of ClassB):

AProperty: <%= Html.TextBoxFor(m => m.AProperty) %>
BProperty: <%= Html.TextBoxFor(m => m.BProperty) %>

Validation errors appear as:

The BProperty is required.
The AProperty is required.

Body:
I had this same problem and it wasn't feasible to create a new view model - also if you have custom model binders, these will appear at the end of the validation summary regardless. I expanded on Aphize answer, rather than pass it a list of property names you can pass it the form keys - this will ensure the order is the same as they appear in the form e.g.

ModelState.OrderByKeys(Request.Form.AllKeys);

This worked for me and I created an attribute to do this.. ( I had to do some tweaking to deal with the custom binders but here it is without that):

public class ForceValidationErrorOrderAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var allFormKeys = filterContext.HttpContext.Request.Form.AllKeys;
        var modelStateDictionary = filterContext.Controller.ViewData.ModelState;

        ModelStateDictionary result = new ModelStateDictionary();
        foreach (string key in allFormKeys)
        {
            if (modelStateDictionary.ContainsKey(key) && !result.ContainsKey(key))
            {
                result.Add(key, modelStateDictionary[key]);
            }
        }
        foreach (string key in modelStateDictionary.Keys)
        {
            if (!result.ContainsKey(key))
            {
                result.Add(key, modelStateDictionary[key]);
            }
        }
        modelStateDictionary.Clear();
        modelStateDictionary.Merge(result);
        }
    }

And then on the controller action method:

    [ForceValidationErrorOrder]
    public ActionResult Apply(ApplicationViewModel viewModel)


问:
What does creating a Solution using a template in Visual Studio actually do versus an empty project?
I am following the Intro to C tutorial by Molly Rocket but am running into an issue running the following code in the Debugger in VisualStudio 2019 while using the Empty Project option.

I am using the Empty Project option instead of loading a template because that is what Molly used, while I could just load a template and run the code there instead I would like to know why I am getting this error so I can better understand Visual Studio and C++.

```<code>#include <Windows.h>

void learnC(void) {

    OutputDebugStringA("Test\n");

}

int CALLBACK WinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{
    learnC();
}
</code>```

Recieving the error LNK2019 which doesn't help at all because it just a generic catch all error code.

error LNK2019: unresolved external symbol main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

I have tried updating the compatiliblity settings of VS2019 as well as other settins that people suggested to use but the error still remains.

Again, when I created the Solution I used the blank document instead of a template becuase that is what Molly Rocket used when writing this code.

When I do use a template (I used the Windows Desktop Application template) and delete all the code and paste in what I had in my original document I do not recieve the Error, and I would like to know why.

Thank you for your time!

答:
When you create an Empty Project, the value of SubSystem defaults to Console.

According to the Doc

An application that uses /SUBSYSTEM:CONSOLE; calls main (or wmain)

An application that uses /SUBSYSTEM:WINDOWS; calls WinMain (or
  wWinMain), which must be defined to use __stdcall

As far as I'm concerned you should Set up SubSystem to windows(Properties -> Linker -> System -> SubSystem)

For more details about /SUBSYSTEM (Specify Subsystem), I suggest you could refer to the link: https://learn.microsoft.com/en-us/cpp/build/reference/subsystem-specify-subsystem?view=vs-2019

Body:
I am following the Intro to C tutorial by Molly Rocket but am running into an issue running the following code in the Debugger in VisualStudio 2019 while using the Empty Project option.

I am using the Empty Project option instead of loading a template because that is what Molly used, while I could just load a template and run the code there instead I would like to know why I am getting this error so I can better understand Visual Studio and C++.

#include <Windows.h>

void learnC(void) {

    OutputDebugStringA("Test\n");

}

int CALLBACK WinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{
    learnC();
}

Recieving the error LNK2019 which doesn't help at all because it just a generic catch all error code.

error LNK2019: unresolved external symbol main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

I have tried updating the compatiliblity settings of VS2019 as well as other settins that people suggested to use but the error still remains.

Again, when I created the Solution I used the blank document instead of a template becuase that is what Molly Rocket used when writing this code.

When I do use a template (I used the Windows Desktop Application template) and delete all the code and paste in what I had in my original document I do not recieve the Error, and I would like to know why.

Thank you for your time!


问:
Symmetric encryption using Fernet in Python - Master password use case
I've been trying to understand how symmetric encryption works and how I can integrate it in my CLI application but I've got stuck at some point which I'm going to describe below.

My use case is the following:

I have a CLI application (SQLAlchemy + click + Python 3.8) which is going to be a very simple Password Manager (personal use).

When started, I want to ask the user for a master password in order for him to be able to retrieve any information from a DB. If the user doesn't have a master password yet, I'll ask him to create one. I want all the data to be encrypted with the same master key.

To do all the above, I thought symmetric encryption would be the most suitable and Fernet came to mind, so I started writing some code:

import base64

from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

def generate_key_derivation(salt, master_password):
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    key = base64.urlsafe_b64encode(kdf.derive(master_password.encode()))
    return key

def encrypt(key, value_to_encrypt):
    f = Fernet(key)
    encrypted_key = f.encrypt(value_to_encrypt.encode())
    return encrypted_key

def decrypt(key, encrypted_key):
    f = Fernet(key)
    try:
        return f.decrypt(encrypted_key)
    except InvalidToken:
        return b''
```

<p>Now, I kinda tried to understand from the docs this:</p>

<blockquote>
  <p>In this scheme, <strong>the salt has to be stored in a retrievable location</strong> in
  order to derive the same key from the password in the future.</p>
</blockquote>

<p>Which, in my head means: store the salt in DB, and use it every time the user tries to use the application. Then, run the master password the user inserted through a key derivation function and check if it matches ... the key? <strong>But I don't have the initial key since I didn't store it the first time along with the salt. And if I were to save it, wouldn't anyone be able to just use it freely to encrypt and decrypt the data?</strong> </p>

<p>What's a common solution used to prevent the above? </p>

<p>Here is a small POC using <code>click</code>:</p>

<pre class="lang-py prettyprint-override"><code>import os
import click

from models import MasterPasswordModel

@click.group(help="Simple CLI Password Manager for personal use")
@click.pass_context
def main(ctx):
    # if the user hasn't stored any master password yet,
    # create a new one
    if MasterPasswordModel.is_empty():

        # ask user for a new master password
        master_password = click.prompt(
            'Please enter your new master password: ',
            hide_input=True
        )

        # generate the salt
        salt = os.urandom(16)

        # generate key_derivation
        # this isn't stored because if it does anyone would be able
        # to access any data
        key = generate_key_derivation(salt, master_password)

        # store the salt to the DB
        MasterPasswordModel.create(salt)

    # if the user stored a master password, check if it's valid and
    # allow him to do other actions
    else:
        # ask user for existing master password
        master_password = click.prompt(
            'Please enter your new master password: ',
            hide_input=True
        )

        # get existing master password salt from DB
        salt = MasterPasswordModel.get_salt()

        # generate key_derivation
        key = generate_key_derivation(salt, master_password)

        # At this point I don't know how to check whether the `key` is
        # valid or not since I don't have anything to check it against.

        # what am I missing?
</code>```

I hope all of this makes sense. As a TL;DR I think the question would be: How can I safely store the key so I can retrieve it for further checks? Or is that even how the things should be done? What am I missing? I'm sure I'm misunderstanding some things :)

LE: As specified in one of the comments, it looks like there might me a solution but I'm still getting stuck somewhere along the process. In this answer it's specified that:

If you're not doing this already, I'd also strongly recommend not
  using the user-supplied key directly, but instead first passing it
  through a deliberately slow key derivation function such as PBKDF2,
  bcrypt or scrypt. You should do this first, before even trying to
  verify the correctness of the key, and immediately discard the
  original user-supplied key and use the derived key for everything
  (both verification and actual en/decryption).

So, let's take for example everything step by step:

1) I am asked for a master password for the first time. It doesn't exist in DB so, obviously, I have to create & store it.

2) Along with the newly generated salt, I have to save a hash of the provided master password (for the sake of example I'll use SHA-256).

3) I now have a record containing the salt and hashed master password so I can proceed further with using the app. I now want to create a new record in DB, which is supposedly going to be encrypted using my key.

The question is... what key? If I were to apply what's written above, I'd have to use my generate_key_derivation() function using the salt and hashed master password from DB and use that for encryption/decryption. But, if I do this, won't anyone be able to just take the hash_key stored in DB, and use the same generate_key_derivation to do whatever he wants?

So, what am I missing?

答:
I'm not a crypto expert, but I think the idea is to store the salt and a hash of the derived key like so:

get master password for first time

generate a salt

derive a new key using the salt and master password

discard the master password

hash the derived key

store the salt and derived key in the db

use the derived key to encrypt the stored passwords

Later use the salt and hash to verify the derived key is authentic like so:

get master password

get salt and hash from db

derive a key using the salt and master password

discard the master password

hash the derived key

authenticate the derived key by seeing if the hash matches the one in the db

if it doesn't match, exit

otherwise, use the derived key to decrypt the other passwords.

Body:
I've been trying to understand how symmetric encryption works and how I can integrate it in my CLI application but I've got stuck at some point which I'm going to describe below.

My use case is the following:

I have a CLI application (SQLAlchemy + click + Python 3.8) which is going to be a very simple Password Manager (personal use).

When started, I want to ask the user for a master password in order for him to be able to retrieve any information from a DB. If the user doesn't have a master password yet, I'll ask him to create one. I want all the data to be encrypted with the same master key.

To do all the above, I thought symmetric encryption would be the most suitable and Fernet came to mind, so I started writing some code:

import base64

from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

def generate_key_derivation(salt, master_password):
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    key = base64.urlsafe_b64encode(kdf.derive(master_password.encode()))
    return key

def encrypt(key, value_to_encrypt):
    f = Fernet(key)
    encrypted_key = f.encrypt(value_to_encrypt.encode())
    return encrypted_key

def decrypt(key, encrypted_key):
    f = Fernet(key)
    try:
        return f.decrypt(encrypted_key)
    except InvalidToken:
        return b''

Now, I kinda tried to understand from the docs this:

In this scheme, the salt has to be stored in a retrievable location in
  order to derive the same key from the password in the future.

Which, in my head means: store the salt in DB, and use it every time the user tries to use the application. Then, run the master password the user inserted through a key derivation function and check if it matches ... the key? But I don't have the initial key since I didn't store it the first time along with the salt. And if I were to save it, wouldn't anyone be able to just use it freely to encrypt and decrypt the data?

What's a common solution used to prevent the above?

Here is a small POC using click:

import os
import click

from models import MasterPasswordModel

@click.group(help="Simple CLI Password Manager for personal use")
@click.pass_context
def main(ctx):
    # if the user hasn't stored any master password yet,
    # create a new one
    if MasterPasswordModel.is_empty():

        # ask user for a new master password
        master_password = click.prompt(
            'Please enter your new master password: ',
            hide_input=True
        )

        # generate the salt
        salt = os.urandom(16)

        # generate key_derivation
        # this isn't stored because if it does anyone would be able
        # to access any data
        key = generate_key_derivation(salt, master_password)

        # store the salt to the DB
        MasterPasswordModel.create(salt)

    # if the user stored a master password, check if it's valid and
    # allow him to do other actions
    else:
        # ask user for existing master password
        master_password = click.prompt(
            'Please enter your new master password: ',
            hide_input=True
        )

        # get existing master password salt from DB
        salt = MasterPasswordModel.get_salt()

        # generate key_derivation
        key = generate_key_derivation(salt, master_password)

        # At this point I don't know how to check whether the `key` is
        # valid or not since I don't have anything to check it against.

        # what am I missing?

I hope all of this makes sense. As a TL;DR I think the question would be: How can I safely store the key so I can retrieve it for further checks? Or is that even how the things should be done? What am I missing? I'm sure I'm misunderstanding some things :)

LE: As specified in one of the comments, it looks like there might me a solution but I'm still getting stuck somewhere along the process. In this answer it's specified that:

If you're not doing this already, I'd also strongly recommend not
  using the user-supplied key directly, but instead first passing it
  through a deliberately slow key derivation function such as PBKDF2,
  bcrypt or scrypt. You should do this first, before even trying to
  verify the correctness of the key, and immediately discard the
  original user-supplied key and use the derived key for everything
  (both verification and actual en/decryption).

So, let's take for example everything step by step:

1) I am asked for a master password for the first time. It doesn't exist in DB so, obviously, I have to create & store it.

2) Along with the newly generated salt, I have to save a hash of the provided master password (for the sake of example I'll use SHA-256).

3) I now have a record containing the salt and hashed master password so I can proceed further with using the app. I now want to create a new record in DB, which is supposedly going to be encrypted using my key.

The question is... what key? If I were to apply what's written above, I'd have to use my generate_key_derivation() function using the salt and hashed master password from DB and use that for encryption/decryption. But, if I do this, won't anyone be able to just take the hash_key stored in DB, and use the same generate_key_derivation to do whatever he wants?

So, what am I missing?


问:
Error during installation of omnetpp on MAC(5.6.1)
I found couple of answers but none of them was helpful, I downloaded omnetpp for MAC (omnetpp-5.6.1-src-macosx.tar) if i open the IDE directly I get "“Omnetpp” is damaged and can’t be opened." I tried installing it like 5 times. I found that I should execute setenv, I got this error "Error: not a login shell -- run this script as 'source setenv' or '. setenv'"
Can someone please help me with the steps to install/use omnetpp? Thank you so much in advance.

答:
You have to put the "omnetpp-5.6.1" directory right in the home path: i.e. ~/Users/yourname

Open the "doc" directory in "omnetpp-5.6.1" directory and there you can see an installation guide which helps you what to do step by step.
Do the instruction. be careful writing the command ./configure it may not work. If it doesn't you should use ./configure WITH_TKENV=no WITH_QTENV=no instead of that.
Also before you run $ make command in terminal you have to run $ . setenv .

I did the instruction but I couldn't run the software yet, then I noticed that the problem is my java version!
write:

```<code>$java -version
</code>```

in your terminal it will show you the actual version your system is using, It must be java8 for running this software if it's not, try to downgrade or upgrade it to java8

I hope it helps you! GL!

Body:
You have to put the "omnetpp-5.6.1" directory right in the home path: i.e. ~/Users/yourname

Open the "doc" directory in "omnetpp-5.6.1" directory and there you can see an installation guide which helps you what to do step by step.
Do the instruction. be careful writing the command ./configure it may not work. If it doesn't you should use ./configure WITH_TKENV=no WITH_QTENV=no instead of that.
Also before you run $ make command in terminal you have to run $ . setenv .

I did the instruction but I couldn't run the software yet, then I noticed that the problem is my java version!
write:

$java -version

in your terminal it will show you the actual version your system is using, It must be java8 for running this software if it's not, try to downgrade or upgrade it to java8

I hope it helps you! GL!


问:
How to transition text using CSS onto an image with hover?
I spent the last two hours creating the following code, and I'm almost done. I just want the text to transition upwards on the image when hovering (image to still be visible). I have looked at other questions/answers that are similar, but the code they use isn't working with mine. Any suggestions?

HTML

```<code><div class="One">
    <p class="img-description">TEST!</p>
<img src="https://media2.giphy.com/media/vFKqnCdLPNOKc/giphy.gif?cid=ecf05e47eb603b7921279bc600f6c24e2c59bff5d8050e4b&rid=giphy.gif">
</div>

    <div class="Two"> <p class="img-description-two">TEST!</p>
        <img src="https://media0.giphy.com/media/26xBEez1vnVb2WgBq/200w.webp?cid=ecf05e47eb603b7921279bc600f6c24e2c59bff5d8050e4b&rid=200w.webp">
    </div>

        <div class="Three">
            <p class="img-description-three">TEST!</p>
            <img src="https://media.giphy.com/media/Y7l6oTRsxCC1a/giphy.gif">
        </div>
</code>```

CSS

```<code>body {
    position: relative;
    height: 500px;
    border: #ffd28a 5px solid;
}

.One {
    display: inline-flex;
    justify-content: space-evenly;
    background-color: #ffd28a;
    width: 250px;
    height: 250px;
    position: relative;
    top: 100px;
    left: 110px;
    margin: 0 100px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.img-description {
    display: none;
    width: 240px;
    height: 240px;
    background-color: #ffd28a;
    position: relative;
    margin: 0 90px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
    visibility: hidden;
    opacity: 0;
}

.One:hover .img-description {
    display: inline-block;
    visibility: visible;
    opacity: .5;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 5px;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.Two {
    display: inline-flex;
    justify-content: space-evenly;
    background-color: #ffd28a;
    border: royalblue;
    width: 250px;
    height: 250px;
    position: relative;
    top: 100px;
    left: 175px;
    margin: 0 100px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.img-description-two {
    display: none;
    width: 240px;
    height: 240px;
    background-color: #ffd28a;
    position: relative;
    margin: 0 90px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
    visibility: hidden;
    opacity: 0;
}

.Two:hover .img-description-two {
    display: inline-block;
    visibility: visible;
    opacity: .5;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 5px;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.Three {
    display: inline-flex;
    justify-content: space-evenly;
    background-color: #ffd28a;
    border: sandybrown;
    width: 250px;
    height: 250px;
    position: relative;
    top: 100px;
    left: 220px;
    margin: 0 100px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.img-description-three {
    display: none;
    width: 240px;
    height: 240px;
    background-color: #ffd28a;
    position: relative;
    margin: 0 90px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
    visibility: hidden;
    opacity: 0;
}

.Three:hover .img-description-three {
    display: inline-block;
    visibility: visible;
    opacity: .5;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 5px;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

img {
    width: 250px;
    height: 250px;
    border: 5px ;
    border-radius: 7px;
}
</code>```

答:
Basic idea is

Make container position to relative, hide overflowing content.

Make text absolute position and push it bottom (hide it).

Reveal it on hover

.img-container {
  position: relative;
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  overflow: hidden;
}

.img-container p {
 background: #fff;
  position: absolute;
  bottom: -50px;
  z-index: 1;
  left: 35%;
  transition: 1s;
}

.img-container:hover p {
  bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="img-container">
  <img src="https://i.picsum.photos/id/83/300/250.jpg" />
  <p>Image Caption</p>
</div></code>```

Body:
I spent the last two hours creating the following code, and I'm almost done. I just want the text to transition upwards on the image when hovering (image to still be visible). I have looked at other questions/answers that are similar, but the code they use isn't working with mine. Any suggestions?

HTML

TEST!

TEST!

TEST!

CSS

body {
    position: relative;
    height: 500px;
    border: #ffd28a 5px solid;
}

.One {
    display: inline-flex;
    justify-content: space-evenly;
    background-color: #ffd28a;
    width: 250px;
    height: 250px;
    position: relative;
    top: 100px;
    left: 110px;
    margin: 0 100px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.img-description {
    display: none;
    width: 240px;
    height: 240px;
    background-color: #ffd28a;
    position: relative;
    margin: 0 90px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
    visibility: hidden;
    opacity: 0;
}

.One:hover .img-description {
    display: inline-block;
    visibility: visible;
    opacity: .5;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 5px;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.Two {
    display: inline-flex;
    justify-content: space-evenly;
    background-color: #ffd28a;
    border: royalblue;
    width: 250px;
    height: 250px;
    position: relative;
    top: 100px;
    left: 175px;
    margin: 0 100px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.img-description-two {
    display: none;
    width: 240px;
    height: 240px;
    background-color: #ffd28a;
    position: relative;
    margin: 0 90px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
    visibility: hidden;
    opacity: 0;
}

.Two:hover .img-description-two {
    display: inline-block;
    visibility: visible;
    opacity: .5;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 5px;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.Three {
    display: inline-flex;
    justify-content: space-evenly;
    background-color: #ffd28a;
    border: sandybrown;
    width: 250px;
    height: 250px;
    position: relative;
    top: 100px;
    left: 220px;
    margin: 0 100px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

.img-description-three {
    display: none;
    width: 240px;
    height: 240px;
    background-color: #ffd28a;
    position: relative;
    margin: 0 90px 0 0;
    border: 5px solid #ffd28a;
    border-radius: 8px;
    visibility: hidden;
    opacity: 0;
}

.Three:hover .img-description-three {
    display: inline-block;
    visibility: visible;
    opacity: .5;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 5px;
    border: 5px solid #ffd28a;
    border-radius: 8px;
}

img {
    width: 250px;
    height: 250px;
    border: 5px ;
    border-radius: 7px;
}

Body:
Basic idea is

Make container position to relative, hide overflowing content.

Make text absolute position and push it bottom (hide it).

Reveal it on hover

.img-container {
  position: relative;
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  overflow: hidden;
}

.img-container p {
 background: #fff;
  position: absolute;
  bottom: -50px;
  z-index: 1;
  left: 35%;
  transition: 1s;
}

.img-container:hover p {
  bottom: 20px;
}

<div class="img-container">
  <img src="https://i.picsum.photos/id/83/300/250.jpg" />
  <p>Image Caption</p>
</div>


问:
I want to change price depending on checkboxes ticked. How to remove if statement from onSubmit()
I want the users to select items form checkbox and submit a numerical price according to the items selected. I have tried it here using if statement. How to do this efficiently??
i had tried to map the states using this.state.map() but its not working also. </p>

```<code>  constructor(props) {
    super();
    this.state = {
      check1: false,
      check2: false,
      check3: false,
      check4: false,
    };
    this.onCheckChange = this.onCheckChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onCheckChange(e) {
    this.setState({
      [e.target.name]: e.target.checked,
    });
  }

//**************i want to change this ****************

  onSubmit(e) {
    e.preventDefault();
    var price = 0;
    if (this.state.check1 === true) {
      price = price + 10;
    }
    if (this.state.check2 === true) {
      price = price + 20;
    }
    if (this.state.check3 === true) {
      price = price + 30;
    }
    if (this.state.check4 === true) {
      price = price + 40;
    }
    console.log(price);
  }

  render() {
    return (
      <div>
        <Form onSubmit={onSubmit}>
          checkboxes are placed
        </form>
      </div>
    );
  }
}

export default SellComponent;
</code>```

答:
If you're just looking to reduce redundancy (and assuming the pattern holds*) then a reduction over the array of state values could work.

Array::map returns a new array of equal length, it's a 1-1 relationship. The callback used with array::map should also be a pure function, meaning it has zero side-effects. Contrast this with array::reduce, which uses a pure function callback and returns a single value, i.e. price, or array::forEach that can have side-effects in the callback, i.e. it can update an external price, but is a void return.

* Summation pattern:

```<code>price = SUM[v, i=0_n] v_i ? (i + 1) * 10) : 0
</code>```

Price computation using array::reduce

```<code>const computePrice = values =>
  values.reduce((price, value, index) => price + (value ? (index + 1) * 10 : 0), 0);
</code>```

Usage:

```<code>onSubmit(e) {
  e.preventDefault();
  const price = computePrice(Object.values(this.state));
  console.log(price);
}
</code>```

const computePrice = values =>
  values.reduce((price, value, i) => price + (value ? (i + 1) * 10 : 0), 0);

const generalizedData = [
  [false], // 0
  [true], // 10
  [false, true], // 20
  [false, true, true], // 50
  [true, false, true, false], // 40
  [true, true, true, true, true], // 150
  [true, true, false, true, true, false, true, false], // 190
];

generalizedData.forEach(state => console.log('price', computePrice(state)));```
</div>
</div>
</p>

<p>Price computation using array::forEach</p>

```const computePrice = values => {
  let price = 0;
  values.forEach((value, i) => {
    price += value ? (i + 1) * 10 : 0;
  });
  return price;
};
```

<p>Usage: <em>Same as before</em></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const computePrice = values => {
  let price = 0;
  values.forEach((value, i) => {
    price += value ? (i + 1) * 10 : 0;
  });
  return price;
};

const generalizedData = [
  [false], // 0
  [true], // 10
  [false, true], // 20
  [false, true, true], // 50
  [true, false, true, false], // 40
  [true, true, true, true, true], // 150
  [true, true, false, true, true, false, true, false], // 190
];

generalizedData.forEach(state => console.log('price', computePrice(state)));</code>```

Body:
I want the users to select items form checkbox and submit a numerical price according to the items selected. I have tried it here using if statement. How to do this efficiently??
i had tried to map the states using this.state.map() but its not working also.

  constructor(props) {
    super();
    this.state = {
      check1: false,
      check2: false,
      check3: false,
      check4: false,
    };
    this.onCheckChange = this.onCheckChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onCheckChange(e) {
    this.setState({
      [e.target.name]: e.target.checked,
    });
  }

//**************i want to change this ****************

  onSubmit(e) {
    e.preventDefault();
    var price = 0;
    if (this.state.check1 === true) {
      price = price + 10;
    }
    if (this.state.check2 === true) {
      price = price + 20;
    }
    if (this.state.check3 === true) {
      price = price + 30;
    }
    if (this.state.check4 === true) {
      price = price + 40;
    }
    console.log(price);
  }

  render() {
    return (

        <Form onSubmit={onSubmit}>
          checkboxes are placed
        </form>

    );
  }
}

export default SellComponent;

Body:
If you're just looking to reduce redundancy (and assuming the pattern holds*) then a reduction over the array of state values could work.

Array::map returns a new array of equal length, it's a 1-1 relationship. The callback used with array::map should also be a pure function, meaning it has zero side-effects. Contrast this with array::reduce, which uses a pure function callback and returns a single value, i.e. price, or array::forEach that can have side-effects in the callback, i.e. it can update an external price, but is a void return.

* Summation pattern:

price = SUM[v, i=0_n] v_i ? (i + 1) * 10) : 0

Price computation using array::reduce

const computePrice = values =>
  values.reduce((price, value, index) => price + (value ? (index + 1) * 10 : 0), 0);

Usage:

onSubmit(e) {
  e.preventDefault();
  const price = computePrice(Object.values(this.state));
  console.log(price);
}

const computePrice = values =>
  values.reduce((price, value, i) => price + (value ? (i + 1) * 10 : 0), 0);

const generalizedData = [
  [false], // 0
  [true], // 10
  [false, true], // 20
  [false, true, true], // 50
  [true, false, true, false], // 40
  [true, true, true, true, true], // 150
  [true, true, false, true, true, false, true, false], // 190
];

generalizedData.forEach(state => console.log('price', computePrice(state)));

Price computation using array::forEach

const computePrice = values => {
  let price = 0;
  values.forEach((value, i) => {
    price += value ? (i + 1) * 10 : 0;
  });
  return price;
};

Usage: Same as before

const computePrice = values => {
  let price = 0;
  values.forEach((value, i) => {
    price += value ? (i + 1) * 10 : 0;
  });
  return price;
};

const generalizedData = [
  [false], // 0
  [true], // 10
  [false, true], // 20
  [false, true, true], // 50
  [true, false, true, false], // 40
  [true, true, true, true, true], // 150
  [true, true, false, true, true, false, true, false], // 190
];

generalizedData.forEach(state => console.log('price', computePrice(state)));


问:
Pub/Sub input in templated Dataflow is completely ignoring NestedValueProvider
I've create template for Dataflow which is reading messages from Pub/Sub
The problem is that NestedValueProvider is not possible to modify sended via options value and I do not have clue why - below some screens

Passed parameter:

Code:

Result:

If anyone would ask why I needto nest it - I wanted to only require to add subscriptionID and just add prefix with rest of the path..

EDIT

My steps:

1.Created pipeline which is reading from Pub/Sub subscription and for subscription name is using NestedValueProvider for creating subscription name

```<code>pipeline.apply(
                            "Read PubSub messages",
                            PubsubIO.readStrings().fromSubscription(
                                    NestedValueProvider.of(
                                            options.getSubscriptionID(),
                                            input -> "projects/ozone-analytics-dev/subscriptions/" + input)
                            )
                    )
</code>```

2.Created template

3.Running template with valid and existing subscriptionID

4.Seeing an error while creating dataflow job (I think that job didn't even start and this error is through some pre validation cause I can run this flow locally or normally with DataflowRunner but not via template)

答:
After analyse - this is rather Google Dataflow bug which only is related to template creation validation (because every other way of Dataflow run is behaving correctly)

I've created issue for that
https://issuetracker.google.com/u/1/issues/157584222

And for now it is the answer for that problem

Body:
I've create template for Dataflow which is reading messages from Pub/Sub
The problem is that NestedValueProvider is not possible to modify sended via options value and I do not have clue why - below some screens

Passed parameter:

Code:

Result:

If anyone would ask why I needto nest it - I wanted to only require to add subscriptionID and just add prefix with rest of the path..

EDIT

My steps:

1.Created pipeline which is reading from Pub/Sub subscription and for subscription name is using NestedValueProvider for creating subscription name

pipeline.apply(
                            "Read PubSub messages",
                            PubsubIO.readStrings().fromSubscription(
                                    NestedValueProvider.of(
                                            options.getSubscriptionID(),
                                            input -> "projects/ozone-analytics-dev/subscriptions/" + input)
                            )
                    )

2.Created template

3.Running template with valid and existing subscriptionID

4.Seeing an error while creating dataflow job (I think that job didn't even start and this error is through some pre validation cause I can run this flow locally or normally with DataflowRunner but not via template)


问:
Finding grok pattern for Log file
I have a log file in the following format :

```<code>net.ipv4.tcp_keepalive_time = 30
</code>```

I tried to write a grok file, but am not able to correctly encode the = 30 part of the expression.

This is my implmentation so far :

```<code>%{WORD:word1}.%{WORD:word2}.%{WORD:word3}|%{SPACE:space}%{URIPARAM:sign}%{SPACE:space}%{NONNEGINT:num}
</code>```

答:
I hope either of these two pattern will help to solve your problem.

%{WORD:word1}.%{WORD:word2}.%{WORD:word3} = %{INT:number}

or

%{WORD:word1}.%{WORD:word2}.%{WORD:word3}\s\S\s%{INT:number}

I have used grok debugger https://grokdebug.herokuapp.com/ to create the pattern. Here is the screenshot of the output.

Title: Finding grok pattern for Log file

Body:
I have a log file in the following format :

net.ipv4.tcp_keepalive_time = 30

I tried to write a grok file, but am not able to correctly encode the = 30 part of the expression.

This is my implmentation so far :

%{WORD:word1}.%{WORD:word2}.%{WORD:word3}|%{SPACE:space}%{URIPARAM:sign}%{SPACE:space}%{NONNEGINT:num}


问:
am trying to hide scrollbar from angular material sidenav
am trying to hide the scrollbar from the side while keeping the ability to scroll

StackBlitz Demo: https://stackblitz.com/edit/github-443roq

答:
Demo to do this kind of things, best way to open developer console and find inspected element then override css on this element in style.css if it is 3rd party library. For your situation, your scroll element is mat-drawer-inner-container then to hide it use webkit-scrollbar pseudo code.
 put below code in style.css

```<code>.mat-drawer-inner-container::-webkit-scrollbar {
    display: none;
}
</code>```

Body:
Demo to do this kind of things, best way to open developer console and find inspected element then override css on this element in style.css if it is 3rd party library. For your situation, your scroll element is mat-drawer-inner-container then to hide it use webkit-scrollbar pseudo code.
 put below code in style.css

.mat-drawer-inner-container::-webkit-scrollbar {
    display: none;
}


问:
How to add a download button or custom layout in center of progress bar?
I want to create a custom progress bar to display downloading progress with an icon and textview in center of it.

There are libraries and some samples but only with textview inside progress bar so how do i add this imageview also? Please help.

答:
You should create customView. In your customView will be textView, and you will add circle and arrow in the onDraw method.
In this code I show you process of drawing circle

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.lucid.dreaming.ui.guide.views.CustomView
            android:id="@+id/custom_view"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginTop="@dimen/big_padding"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Some text"
            android:textColor="@color/colorWhite"
            app:layout_constraintBottom_toBottomOf="@id/custom_view"
            app:layout_constraintEnd_toEndOf="@id/custom_view"
            app:layout_constraintStart_toStartOf="@id/custom_view"
            app:layout_constraintTop_toTopOf="@id/custom_view" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Here I added CountDownTimer, which will show work of progress bar (progress bar filled after 20 seconds). You can regulate this number.

```<code>override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.your_xml, container, false)
        object : CountDownTimer(20000, 200) {
            override fun onTick(millisUntilFinished: Long) {
                customView.setProgress(counter)
                counter++
            }

            override fun onFinish() {

            }
        }.start()

        return view
    }
</code>```

And customView

```<code>import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.View

class CustomView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attributeSet, defStyleAttr) {

    private var paint: Paint
    private var radius: Float = 0f
    private var angle = 0f

    init {
        paint = Paint()
        paint.color = Color.GRAY
        paint.setAntiAlias(true)
        paint.strokeWidth = 5f
        paint.style = Paint.Style.STROKE
        Log.e("tag", "init")
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        radius = (width/2f -1f)
        paint.color = Color.GRAY
        canvas.drawCircle(width.toFloat()/2, height.toFloat()/2, radius, paint)
        paint.color = Color.GREEN
        val oval = RectF(0f,0f,width.toFloat()-2,width.toFloat()-2)
        canvas.drawArc(oval, -90f,angle,false ,paint)
    }

    fun setProgress(percent: Int) {
        angle = percent*3.6f
        invalidate()
    }

}
</code>```

https://i.stack.imgur.com/4x874.png

Body:
You should create customView. In your customView will be textView, and you will add circle and arrow in the onDraw method.
In this code I show you process of drawing circle

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.lucid.dreaming.ui.guide.views.CustomView
            android:id="@+id/custom_view"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginTop="@dimen/big_padding"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Some text"
            android:textColor="@color/colorWhite"
            app:layout_constraintBottom_toBottomOf="@id/custom_view"
            app:layout_constraintEnd_toEndOf="@id/custom_view"
            app:layout_constraintStart_toStartOf="@id/custom_view"
            app:layout_constraintTop_toTopOf="@id/custom_view" />

    </androidx.constraintlayout.widget.ConstraintLayout>

Here I added CountDownTimer, which will show work of progress bar (progress bar filled after 20 seconds). You can regulate this number.

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.your_xml, container, false)
        object : CountDownTimer(20000, 200) {
            override fun onTick(millisUntilFinished: Long) {
                customView.setProgress(counter)
                counter++
            }

            override fun onFinish() {

            }
        }.start()

        return view
    }

And customView

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.View

class CustomView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attributeSet, defStyleAttr) {

    private var paint: Paint
    private var radius: Float = 0f
    private var angle = 0f

    init {
        paint = Paint()
        paint.color = Color.GRAY
        paint.setAntiAlias(true)
        paint.strokeWidth = 5f
        paint.style = Paint.Style.STROKE
        Log.e("tag", "init")
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        radius = (width/2f -1f)
        paint.color = Color.GRAY
        canvas.drawCircle(width.toFloat()/2, height.toFloat()/2, radius, paint)
        paint.color = Color.GREEN
        val oval = RectF(0f,0f,width.toFloat()-2,width.toFloat()-2)
        canvas.drawArc(oval, -90f,angle,false ,paint)
    }

    fun setProgress(percent: Int) {
        angle = percent*3.6f
        invalidate()
    }

}

https://i.stack.imgur.com/4x874.png


问:
horizontal gradient doesn't work on dynamic width content
I am trying to implement gradient for button or view depending on requirement. But whenever I try to do so for button/view who's width is dynamic (for horizontal gradient) it only loads half the same.

```<code>func applyGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = colours.map { $0.cgColor }
    gradient.startPoint = orientation.startPoint
    gradient.endPoint = orientation.endPoint
    self.layer.insertSublayer(gradient, at: 0)
}
</code>```

GradientOrientation is obtained by following code.

```<code>enum GradientOrientation {
case topRightBottomLeft
case topLeftBottomRight
case horizontal
case vertical

var startPoint: CGPoint {
    return points.startPoint
}

var endPoint: CGPoint {
    return points.endPoint
}

var points: GradientPoints {
    switch self {
    case .topRightBottomLeft:
        return (CGPoint.init(x: 0.0, y: 1.0), CGPoint.init(x: 1.0, y: 0.0))
    case .topLeftBottomRight:
        return (CGPoint.init(x: 0.0, y: 0.0), CGPoint.init(x: 1, y: 1))
    case .horizontal:
        return (CGPoint.init(x: 0.0, y: 0.5), CGPoint.init(x: 1.0, y: 0.5))
    case .vertical:
        return (CGPoint.init(x: 0.0, y: 0.0), CGPoint.init(x: 0.0, y: 1.0))
    }
}
}
</code>```

But if the width is 150 it loads up perfectly for both view/button. Any help is appreciated.

答:
```<code><gradientlayer>.layoutIfNeeded()
</code>```

Call this method after you done calculating the width of the dynamic component.

Body:
I am trying to implement gradient for button or view depending on requirement. But whenever I try to do so for button/view who's width is dynamic (for horizontal gradient) it only loads half the same.

func applyGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = colours.map { $0.cgColor }
    gradient.startPoint = orientation.startPoint
    gradient.endPoint = orientation.endPoint
    self.layer.insertSublayer(gradient, at: 0)
}

GradientOrientation is obtained by following code.

enum GradientOrientation {
case topRightBottomLeft
case topLeftBottomRight
case horizontal
case vertical

var startPoint: CGPoint {
    return points.startPoint
}

var endPoint: CGPoint {
    return points.endPoint
}

var points: GradientPoints {
    switch self {
    case .topRightBottomLeft:
        return (CGPoint.init(x: 0.0, y: 1.0), CGPoint.init(x: 1.0, y: 0.0))
    case .topLeftBottomRight:
        return (CGPoint.init(x: 0.0, y: 0.0), CGPoint.init(x: 1, y: 1))
    case .horizontal:
        return (CGPoint.init(x: 0.0, y: 0.5), CGPoint.init(x: 1.0, y: 0.5))
    case .vertical:
        return (CGPoint.init(x: 0.0, y: 0.0), CGPoint.init(x: 0.0, y: 1.0))
    }
}
}

But if the width is 150 it loads up perfectly for both view/button. Any help is appreciated.

Body:
<gradientlayer>.layoutIfNeeded()

Call this method after you done calculating the width of the dynamic component.


问:
x86 how does Linux signal interrupt instruction stream
How does a Linux signal lead to the instruction stream of the X86 processor getting interrupted? So what CPU facility is used?

You have synchronous and asynchronous interrupts.

Synchronous interrupts are for issues like page faults, exceptions etc. Problems that are caused by the instructions that are executing on the CPU.

Asynchronous interrupts are from an IPI from the LAPIC, timer interrupt or for an interrupt picked up by the I/O-APIC and routed to the right LAPIC which then interrupts the processor. So these are external events.

But which X86 mechanism does the Signal use to interrupt the instruction stream and start processing the signal handler.

It isn't an asynchronous interrupt AFAIK because interrupts are handled within the kernel and signals in user-space. But its behavior is very similar to that of an asynchronous interrupt.

答:
The kernel has to deliver a signal to user-space.  You're right that that doesn't just happen on its own in hardware.  That's why signal handling can respect the user-space red-zone, sigaltstack, and default actions if there's no handler registered.

As soon as the kernel has control, it can deliver the signal to user-space (or do the default action of ignoring it or killing the process).

If the signal was sent by a process running on another core, to a process running on this core, then probably it's delivered to user-space from an IPI handler, or else just at the next timer interrupt or system call that gives the kernel a chance to check for a pending signal.

When the IPI interrupt handler is preparing to return to user-space, it notices that there's a pending interrupt for the process that it's about to return to.  (Either with a special case for one type of IPI, or by running the scheduler since we're in the kernel anyway).  Instead of using iret to return to the interrupt frame pushed by hardware for the async interrupt, the kernel instead can iret to the address of the user-space signal handler.

The whole point of using an IPI (if that's what Linux even does) is to transfer control to the kernel sooner, instead of just waiting for it to notice the pending signal the next time it calls schedule().

If the process the signal is sent to isn't currently running on any core, then it either wakes the process up if there's a free CPU, or the signal just sits there for that task until the scheduler on some core decides to run it on this core.  At that point it will notice and deliver the pending signal.


问:
IsNumeric() allowing minus at last of the values
I am using IsNumeric() function in my code to validate numbers.

IsNumeric(100)  - true,
IsNumeric(-100) - true,
IsNumeric(+100) - true,

IsNumeric(100-) - true - I have doubt in this. (100-) Is this a valid number? IsNumeric () returns true to this value.

```<code>    Dim latitude As String = "12.56346-"
    If IsNumeric(latitude) Then
        If (Convert.ToDouble(latitude) >= -90 And Convert.ToDouble(latitude) <= 90) Then
            isValidLatitude.Text = "true"
        Else
            isValidLatitude.Text = "false"
        End If
     Else
        isValidLatitude.Text = "false"
     End If
</code>```

Error while converting latitude to double

```<code>Input string was not in a correct format.
</code>```

答:
Note: my previous answers were wrong about assuming it was a bug. As the answer of @Damien_The_Unbeliever states, this function tries to validate the string as a lot of data types. And actually, the value "100-" is a valid Decimal number. That's why it returns true (as it's a "valid" Decimal) but gives a exception when converting to Double (as it's not a valid Double). @Damien_The_Unbeliever really deserves your +1 for pointing that.

From the documentation (showing all the data types that IsNumeric tries to validate):

IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort. It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number. Expression can contain non-numeric characters. IsNumeric returns True if Expression is a string that contains a valid hexadecimal or octal number. IsNumeric also returns True if Expression contains a valid numeric expression that begins with a + or - character or contains commas.

Also, @CaiusJard did a nice search and pointed out that inner methods use a NumberStyles.AllowTrailingSign option, which allows this behavior.

Ok, now to the solution:

Just use a TryParse method, from your desired data type (int, long, etc...). The cool thing is that it'll behaves exactly as you expect, and if the parsing is successful, we have the parsed value already available to use!

```<code>if (Int32.TryParse(value, out int number))
{
    // String is a valid number, and is already parsed in the 'number' variable!
}

else
{
    // String is not a valid number!
}
</code>```

Solution's VB.Net version:

```<code>Dim value As String = "12.56346-"
Dim number As Double = 0
If Double.TryParse(value, number) Then
    ' String is a valid number, and is already parsed in the "number" variable!
    isValidLatitude.Text = "true"
Else
    ' String is not a valid number!
    isValidLatitude.Text = "false"
End If
</code>```

Body:
I am using IsNumeric() function in my code to validate numbers.

IsNumeric(100)  - true,
IsNumeric(-100) - true,
IsNumeric(+100) - true,

IsNumeric(100-) - true - I have doubt in this. (100-) Is this a valid number? IsNumeric () returns true to this value.

    Dim latitude As String = "12.56346-"
    If IsNumeric(latitude) Then
        If (Convert.ToDouble(latitude) >= -90 And Convert.ToDouble(latitude) <= 90) Then
            isValidLatitude.Text = "true"
        Else
            isValidLatitude.Text = "false"
        End If
     Else
        isValidLatitude.Text = "false"
     End If

Error while converting latitude to double

Input string was not in a correct format.

Body:
Note: my previous answers were wrong about assuming it was a bug. As the answer of @Damien_The_Unbeliever states, this function tries to validate the string as a lot of data types. And actually, the value "100-" is a valid Decimal number. That's why it returns true (as it's a "valid" Decimal) but gives a exception when converting to Double (as it's not a valid Double). @Damien_The_Unbeliever really deserves your +1 for pointing that.

From the documentation (showing all the data types that IsNumeric tries to validate):

IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort. It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number. Expression can contain non-numeric characters. IsNumeric returns True if Expression is a string that contains a valid hexadecimal or octal number. IsNumeric also returns True if Expression contains a valid numeric expression that begins with a + or - character or contains commas.

Also, @CaiusJard did a nice search and pointed out that inner methods use a NumberStyles.AllowTrailingSign option, which allows this behavior.

Ok, now to the solution:

Just use a TryParse method, from your desired data type (int, long, etc...). The cool thing is that it'll behaves exactly as you expect, and if the parsing is successful, we have the parsed value already available to use!

if (Int32.TryParse(value, out int number))
{
    // String is a valid number, and is already parsed in the 'number' variable!
}

else
{
    // String is not a valid number!
}

Solution's VB.Net version:

Dim value As String = "12.56346-"
Dim number As Double = 0
If Double.TryParse(value, number) Then
    ' String is a valid number, and is already parsed in the "number" variable!
    isValidLatitude.Text = "true"
Else
    ' String is not a valid number!
    isValidLatitude.Text = "false"
End If


问:
Ngrx store: updating common state outside of the ActionReducerMap
I have an ngrx store with an initial state similar to:

```<code>const state = {
    child1: {...},
    child2: {...},
}
</code>```

with an ActionReducerMap as follows:

```<code>const reducerMap = {
    child1: reducer1,
    child2: reducer2,
}
</code>```

Now I'd like to add a 'loading' state at the same level as child1 and child2 to track the loading of both the children (which are interconnected). To achieve this, I updated the initial state as follows:

```<code>const state = {
    child1: {...},
    child2: {...},
    loading: false,
}
</code>```

And I tried to use  metareducer that sits at the top of reducer1 and reducer2 like this:

```<code>export function metaReducer(reducer) {
    return function reduce(state, action) {
        switch(action.type) {
            case CommonActionTypes.UpdateLoading: {
                return {
                    ...,
                    loading: action.loading
                }
            }
            default:
                return reducer(state, action);
        }
    }
}
</code>```

I added this to the feature store as follows:

```<code>StoreModule.forFeature('myStore', compose(metaReducer, combineReducers)(reducerMap))
</code>```

In the application I invoke the UpdateLoading actions during some effects that update the child1 and child2.
However, this doesn't work as I expected it to.

To begin with, the initial state does not honor the 'loading' variable at all - it still thinks the original state is

```<code>{
    child1: {...},
    child2: {...},
}
</code>```

The 'loading' variable in the state, is only updated when the UpdateLoading action is called. With all the subsequent actions, it is removed from the state. This is strange as the only reducer that acts on it is the meta-reducer while reducer1 and reducer2 act on child-states child1 and child2 respectively.

Is it the right approach to update a common state using meta-reducer? How can I make this work?

答:
Try to use the reducer function in both cases:

export function metaReducer(reducer) {
    return function reduce(state, action) {
        switch(action.type) {
            case CommonActionTypes.UpdateLoading: {
                return reducer({ // <- wrap it.
                    ...state,
                    loading: action.loading
                }, action);
            }
            default:
                return reducer(state, action);
        }
    }
}
```

<p>And in <code>.forRoot</code> like that:</p>

<pre class="lang-js prettyprint-override"><code>StoreModule.forRoot({/*...*/}, {
  metaReducers: [metaReducer],
}),
</code>```

Body:
I have an ngrx store with an initial state similar to:

const state = {
    child1: {...},
    child2: {...},
}

with an ActionReducerMap as follows:

const reducerMap = {
    child1: reducer1,
    child2: reducer2,
}

Now I'd like to add a 'loading' state at the same level as child1 and child2 to track the loading of both the children (which are interconnected). To achieve this, I updated the initial state as follows:

const state = {
    child1: {...},
    child2: {...},
    loading: false,
}

And I tried to use  metareducer that sits at the top of reducer1 and reducer2 like this:

export function metaReducer(reducer) {
    return function reduce(state, action) {
        switch(action.type) {
            case CommonActionTypes.UpdateLoading: {
                return {
                    ...,
                    loading: action.loading
                }
            }
            default:
                return reducer(state, action);
        }
    }
}

I added this to the feature store as follows:

StoreModule.forFeature('myStore', compose(metaReducer, combineReducers)(reducerMap))

In the application I invoke the UpdateLoading actions during some effects that update the child1 and child2.
However, this doesn't work as I expected it to.

To begin with, the initial state does not honor the 'loading' variable at all - it still thinks the original state is

{
    child1: {...},
    child2: {...},
}

The 'loading' variable in the state, is only updated when the UpdateLoading action is called. With all the subsequent actions, it is removed from the state. This is strange as the only reducer that acts on it is the meta-reducer while reducer1 and reducer2 act on child-states child1 and child2 respectively.

Is it the right approach to update a common state using meta-reducer? How can I make this work?

Body:
Try to use the reducer function in both cases:

export function metaReducer(reducer) {
    return function reduce(state, action) {
        switch(action.type) {
            case CommonActionTypes.UpdateLoading: {
                return reducer({ // <- wrap it.
                    ...state,
                    loading: action.loading
                }, action);
            }
            default:
                return reducer(state, action);
        }
    }
}

And in .forRoot like that:

StoreModule.forRoot({/*...*/}, {
  metaReducers: [metaReducer],
}),


问:
MSAL - userIdentifier versus idToken.oid
I am using MSAL to validate a user against Microsoft Azure AD and am getting a valid token back.

The MSAL library is handing me back a User object which contains a property called userIdentifier.

This is a string, not a GUID.

The documentation says to use a field called oid to uniquely identify users across the Microsoft Identity platform.  I have this property available under User.idToken.oid.

This value is a GUID as the documentation says.

My question is, what is this User.userIdentifier and should I be using this?  I need to know what to store on the database side to tie this local user to an Azure AD user.

答:
For clarity's sake it is advised to use the accountIdentifier property as it will always be populated, even in the edge cases where oid might not be available:

const accountIdentifier: string = idToken.objectId || idToken.subject;
```

More info on GitHub.

Body:
For clarity's sake it is advised to use the accountIdentifier property as it will always be populated, even in the edge cases where oid might not be available:

const accountIdentifier: string = idToken.objectId || idToken.subject;

More info on GitHub.


问:
google cloud instance terminate after close browser
I have a bash script. I would like to run it continuously on google cloud server. I connected to my VM via SSH in browser but after I've closed my browser, script was stopped.
I tried to use Cloud Shell but if I restart my laptop, script launches from start. It doesn't work continuously!
Is it possible to launch my script in google cloud, shut down laptop and be sure what my script works?</p>

答:
I faced similar issue. I logged into Virtual Machine through google cloud command on my local machine, tried to exit by closing the terminal, It halted the script running in the instance.

Use command exit to log out of cloud consoles in local machine putty console (twice).