问:
Redirect to last browser history location in React
I am working on my personal React project.
The React app has a login page. After successfully logging in, the user is redirected to homepage i.e. on path / . And if the user again tries to navigate to login page i.e.  path
/login , then the user will be redirected back to homepage

The app also has protected route on path /profile which is accessible only if the user is authenticated.

But the problem is, when the user navigates to protected route and then refreshes the page, it is redirecting to the  homepage.
How can I make it redirect back to the same protected route from where the user had refreshed?

Here is Login.js

```<code>// Login.js
      if (isUserLoggedIn) {
        return <Redirect to="/" />;
      }
      // else render login page
</code>```

And here is ProtectedRoute.js

```<code>import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { Redirect, Route } from "react-router";

export default function ProtectedRoute({ component: Component, ...rest }) {

  const { isUserLoggedIn } = useSelector((state) => state.common);

  return (
    <Route
      {...rest}
      render={(props) =>
        !isUserLoggedIn ? <Redirect to="/login" /> : <Component {...props} />
      }
    />
  );
}
</code>```

And this is how I'm getting the value of isUserLoggedIn  from cookies and then setting it to the Redux state.

```<code> const [authenticated] = useState(() =>
    Boolean(Number(Cookies.get("isUserLoggedIn")))
  );
  useEffect(() => {
    if (!authenticated) {
      return dispatch({
        type: NOT_AUTHENTICATED,
      });
    } else {
      return dispatch({
        type: AUTHENTICATED,
      });
    }
  }, [authenticated]);
</code>```

答:
You are using Redux, but don't appear to load your auth state from persisted storage and instead use a mounting useEffect hook to dispatch an action with an auth status read from an isUserLoggedIn cookie.

useEffect runs at the end of the initial render cycle, so during the initial render the isUserLoggedIn is likely a falsey default initial reducer value.

In this case your ProtectedRoute component should wait until the isUserLoggedIn state is actually populated.

```<code>export default function ProtectedRoute(props) {
  const { isUserLoggedIn } = useSelector((state) => state.common);

  if (isUserLoggedIn === undefined) { // or whatever the default, indeterminant value is
    return null; // or loading indicator, etc...
  }

  return isUserLoggedIn ? <Route {...props} /> : <Redirect to="/login" />;
}
</code>```

Body:
I am working on my personal React project.
The React app has a login page. After successfully logging in, the user is redirected to homepage i.e. on path / . And if the user again tries to navigate to login page i.e.  path
/login , then the user will be redirected back to homepage

The app also has protected route on path /profile which is accessible only if the user is authenticated.

But the problem is, when the user navigates to protected route and then refreshes the page, it is redirecting to the  homepage.
How can I make it redirect back to the same protected route from where the user had refreshed?

Here is Login.js

// Login.js
      if (isUserLoggedIn) {
        return <Redirect to="/" />;
      }
      // else render login page

And here is ProtectedRoute.js

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { Redirect, Route } from "react-router";

export default function ProtectedRoute({ component: Component, ...rest }) {

  const { isUserLoggedIn } = useSelector((state) => state.common);

  return (
    <Route
      {...rest}
      render={(props) =>
        !isUserLoggedIn ? <Redirect to="/login" /> : <Component {...props} />
      }
    />
  );
}

And this is how I'm getting the value of isUserLoggedIn  from cookies and then setting it to the Redux state.

 const [authenticated] = useState(() =>
    Boolean(Number(Cookies.get("isUserLoggedIn")))
  );
  useEffect(() => {
    if (!authenticated) {
      return dispatch({
        type: NOT_AUTHENTICATED,
      });
    } else {
      return dispatch({
        type: AUTHENTICATED,
      });
    }
  }, [authenticated]);

Body:
You are using Redux, but don't appear to load your auth state from persisted storage and instead use a mounting useEffect hook to dispatch an action with an auth status read from an isUserLoggedIn cookie.

useEffect runs at the end of the initial render cycle, so during the initial render the isUserLoggedIn is likely a falsey default initial reducer value.

In this case your ProtectedRoute component should wait until the isUserLoggedIn state is actually populated.

export default function ProtectedRoute(props) {
  const { isUserLoggedIn } = useSelector((state) => state.common);

  if (isUserLoggedIn === undefined) { // or whatever the default, indeterminant value is
    return null; // or loading indicator, etc...
  }

  return isUserLoggedIn ? <Route {...props} /> : <Redirect to="/login" />;
}


来源: stackexchange

问:
How to find the kth largest element in an unsorted array of length n in O(n)?
I believe there's a way to find the kth largest element in an unsorted array of length n in O(n).  Or perhaps it's "expected" O(n) or something.  How can we do this?</p>

答:
Although not very sure about O(n) complexity, but it will be sure to be between O(n) and nLog(n). Also sure to be closer to O(n) than nLog(n). Function is written in Java

```<code>public int quickSelect(ArrayList<Integer>list, int nthSmallest){
    //Choose random number in range of 0 to array length
    Random random =  new Random();
    //This will give random number which is not greater than length - 1
    int pivotIndex = random.nextInt(list.size() - 1);

    int pivot = list.get(pivotIndex);

    ArrayList<Integer> smallerNumberList = new ArrayList<Integer>();
    ArrayList<Integer> greaterNumberList = new ArrayList<Integer>();

    //Split list into two.
    //Value smaller than pivot should go to smallerNumberList
    //Value greater than pivot should go to greaterNumberList
    //Do nothing for value which is equal to pivot
    for(int i=0; i<list.size(); i++){
        if(list.get(i)<pivot){
            smallerNumberList.add(list.get(i));
        }
        else if(list.get(i)>pivot){
            greaterNumberList.add(list.get(i));
        }
        else{
            //Do nothing
        }
    }

    //If smallerNumberList size is greater than nthSmallest value, nthSmallest number must be in this list
    if(nthSmallest < smallerNumberList.size()){
        return quickSelect(smallerNumberList, nthSmallest);
    }
    //If nthSmallest is greater than [ list.size() - greaterNumberList.size() ], nthSmallest number must be in this list
    //The step is bit tricky. If confusing, please see the above loop once again for clarification.
    else if(nthSmallest > (list.size() - greaterNumberList.size())){
        //nthSmallest will have to be changed here. [ list.size() - greaterNumberList.size() ] elements are already in
        //smallerNumberList
        nthSmallest = nthSmallest - (list.size() - greaterNumberList.size());
        return quickSelect(greaterNumberList,nthSmallest);
    }
    else{
        return pivot;
    }
}
</code>```

OwnerDisplayName: MrDatabase

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: David Nehme

Body:
Although not very sure about O(n) complexity, but it will be sure to be between O(n) and nLog(n). Also sure to be closer to O(n) than nLog(n). Function is written in Java

public int quickSelect(ArrayList<Integer>list, int nthSmallest){
    //Choose random number in range of 0 to array length
    Random random =  new Random();
    //This will give random number which is not greater than length - 1
    int pivotIndex = random.nextInt(list.size() - 1);

    int pivot = list.get(pivotIndex);

    ArrayList<Integer> smallerNumberList = new ArrayList<Integer>();
    ArrayList<Integer> greaterNumberList = new ArrayList<Integer>();

    //Split list into two.
    //Value smaller than pivot should go to smallerNumberList
    //Value greater than pivot should go to greaterNumberList
    //Do nothing for value which is equal to pivot
    for(int i=0; i<list.size(); i++){
        if(list.get(i)<pivot){
            smallerNumberList.add(list.get(i));
        }
        else if(list.get(i)>pivot){
            greaterNumberList.add(list.get(i));
        }
        else{
            //Do nothing
        }
    }

    //If smallerNumberList size is greater than nthSmallest value, nthSmallest number must be in this list
    if(nthSmallest < smallerNumberList.size()){
        return quickSelect(smallerNumberList, nthSmallest);
    }
    //If nthSmallest is greater than [ list.size() - greaterNumberList.size() ], nthSmallest number must be in this list
    //The step is bit tricky. If confusing, please see the above loop once again for clarification.
    else if(nthSmallest > (list.size() - greaterNumberList.size())){
        //nthSmallest will have to be changed here. [ list.size() - greaterNumberList.size() ] elements are already in
        //smallerNumberList
        nthSmallest = nthSmallest - (list.size() - greaterNumberList.size());
        return quickSelect(greaterNumberList,nthSmallest);
    }
    else{
        return pivot;
    }
}


问:
How to use Bitbucket and GitHub at the same time for one project?
I have one repository which I want to push into Bitbucket and GitHub.
It is vital for my repository to be hosted by both.

Is there a way to do this in Git?

答:
I have a similar kind of situation with a twist. Like I have an existing BitBucket branch(s) where I was managing or updating my code form past few months.

Now my requirement is to upload my project in GitHub with the only single 'master' branch.

Step 1 -

This is my existing BitBucket project repo info.

```<code>$ git remote -v show

origin  https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git (fetch)
origin  https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git (push)
</code>```

Step 2 -

add a remote github repo url -

```<code>$ git remote set-url origin --add https://github.com/<USERNAME>/<PROJECT_NAME>.git
</code>```

Now, it has github info too ($ git remote -v show).

```<code>origin  https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git (fetch)
origin  https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git (push)
origin  https://github.com/<USERNAME>/<PROJECT_NAME>.git (push)
</code>```

Step 3 -

Rename repository for better understanding -

```<code>$ git remote add bitbucket https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git
$ git remote add github https://github.com/<USERNAME>/<PROJECT_NAME>.git
</code>```

Now,info updated ($ git remote -v show).

```<code>bitbucket   https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME> (fetch)
bitbucket   https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME> (push)
github      https://github.com/<USERNAME>/<PROJECT_NAME>.git (fetch)
github      https://github.com/<USERNAME>/<PROJECT_NAME>.git (push)
origin      https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME> (fetch)
origin      https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME> (push)
origin      https://github.com/<USERNAME>/<PROJECT_NAME>.git (push)
</code>```

Step 4 -

Time to commit/push the whole project in GitHub.

```<code>$ git add --all && git commit -m "first commit"

$ git push -u origin master
</code>```

As a result I got this error -

```<code>Everything up-to-date
Branch 'master' set up to track remote branch 'master' from 'origin'.
remote: Repository not found.
fatal: repository 'https://github.com/<USERNAME>/<PROJECT_NAME>.git/' not found
</code>```

Step 5 (SSH key setup) -

After few hours of investigation I have found that this is SSH key issue.

So I generate SSH key for both BitBucket & GitHub and add those keys in my both respective account.

Set up an SSH key for BitBucket

Set up an SSH key for GitHub

Checks if SSH key exists or not

Step 6 (set SSH repo url) -

Change https:// urls to ssh for BitBucket & GitHub.

```<code>$ git remote set-url bitbucket git@bitbucket.org:<USERNAME>/<PROJECT_NAME>.git
$ git remote set-url github git@github.com:<USERNAME>/<PROJECT_NAME>.git
</code>```

Remove origin to change origin repo url.

```<code>$ git remote rm origin
</code>```

Add first origin (BitBucket) -

```<code>$ git remote add origin git@bitbucket.org:<USERNAME>/<PROJECT_NAME>.git
</code>```

Add second origin (GitHub) -

```<code>$ git remote set-url origin --add https://github.com/<USERNAME>/<PROJECT_NAME>.git
</code>```0

All repo url changed to ssh.

```<code>$ git remote set-url origin --add https://github.com/<USERNAME>/<PROJECT_NAME>.git
</code>```1

Step 7 -

Already I have add and commit the code, so just I have to push.

```<code>$ git remote set-url origin --add https://github.com/<USERNAME>/<PROJECT_NAME>.git
</code>```2

Are you sure you want to continue connecting (yes/no/[fingerprint])?
yes

Finally, the whole project pushed to GitHub in master branch.

Push code to both branch -

```<code>$ git push
</code>```

Push code to only GitHub or BitBucket -

$ git push github master  or  $ git push bitbucket master

Change branch -

```<code>$ git checkout <BRANCH_NAME>
</code>```

Live saving infos -

use Bitbucket and GitHub at the same time for one project

remove the remote origin

Important Note

Step 5 & 6 are useful If you are using http:// repo url, then change it to ssh for maintaining repo in a better way.

OR it will be better to use Step 5 & 6 if someone found https:// repo url after Step 1 / $ git remote -v show

Ignore step 5 & 6 if anyone already have ssh repo.

Body:
I have a similar kind of situation with a twist. Like I have an existing BitBucket branch(s) where I was managing or updating my code form past few months.

Now my requirement is to upload my project in GitHub with the only single 'master' branch.

Step 1 -

This is my existing BitBucket project repo info.

$ git remote -v show

origin  https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git (fetch)
origin  https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git (push)

Step 2 -

add a remote github repo url -

$ git remote set-url origin --add https://github.com/<USERNAME>/<PROJECT_NAME>.git

Now, it has github info too ($ git remote -v show).

origin  https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git (fetch)
origin  https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git (push)
origin  https://github.com/<USERNAME>/<PROJECT_NAME>.git (push)

Step 3 -

Rename repository for better understanding -

$ git remote add bitbucket https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME>.git
$ git remote add github https://github.com/<USERNAME>/<PROJECT_NAME>.git

Now,info updated ($ git remote -v show).

bitbucket   https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME> (fetch)
bitbucket   https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME> (push)
github      https://github.com/<USERNAME>/<PROJECT_NAME>.git (fetch)
github      https://github.com/<USERNAME>/<PROJECT_NAME>.git (push)
origin      https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME> (fetch)
origin      https://<USERNAME>@bitbucket.org/<USERNAME>/<PROJECT_NAME> (push)
origin      https://github.com/<USERNAME>/<PROJECT_NAME>.git (push)

Step 4 -

Time to commit/push the whole project in GitHub.

$ git add --all && git commit -m "first commit"

$ git push -u origin master

As a result I got this error -

Everything up-to-date
Branch 'master' set up to track remote branch 'master' from 'origin'.
remote: Repository not found.
fatal: repository 'https://github.com/<USERNAME>/<PROJECT_NAME>.git/' not found

Step 5 (SSH key setup) -

After few hours of investigation I have found that this is SSH key issue.

So I generate SSH key for both BitBucket & GitHub and add those keys in my both respective account.

Set up an SSH key for BitBucket

Set up an SSH key for GitHub

Checks if SSH key exists or not

Step 6 (set SSH repo url) -

Change https:// urls to ssh for BitBucket & GitHub.

$ git remote set-url bitbucket git@bitbucket.org:<USERNAME>/<PROJECT_NAME>.git
$ git remote set-url github git@github.com:<USERNAME>/<PROJECT_NAME>.git

Remove origin to change origin repo url.

$ git remote rm origin

Add first origin (BitBucket) -

$ git remote add origin git@bitbucket.org:<USERNAME>/<PROJECT_NAME>.git

Add second origin (GitHub) -

$ git remote set-url origin --add git@github.com:<USERNAME>/<PROJECT_NAME>.git

All repo url changed to ssh.

$ git remote -v show

bitbucket    git@bitbucket.org:<USERNAME>/<PROJECT_NAME>.git (fetch)
bitbucket    git@bitbucket.org:<USERNAME>/<PROJECT_NAME>.git (push)
github       git@github.com:<USERNAME>/<PROJECT_NAME>.git (fetch)
github       git@github.com:<USERNAME>/<PROJECT_NAME>.git (push)
origin       git@bitbucket.org:<USERNAME>/<PROJECT_NAME>.git (fetch)
origin       git@bitbucket.org:<USERNAME>/<PROJECT_NAME>.git (push)
origin       git@github.com:<USERNAME>/<PROJECT_NAME>.git (push)

Step 7 -

Already I have add and commit the code, so just I have to push.

$ git push -u origin master

Are you sure you want to continue connecting (yes/no/[fingerprint])?
yes

Finally, the whole project pushed to GitHub in master branch.

Push code to both branch -

$ git push

Push code to only GitHub or BitBucket -

$ git push github master  or  $ git push bitbucket master

Change branch -

$ git checkout <BRANCH_NAME>

Live saving infos -

use Bitbucket and GitHub at the same time for one project

remove the remote origin

Important Note

Step 5 & 6 are useful If you are using http:// repo url, then change it to ssh for maintaining repo in a better way.

OR it will be better to use Step 5 & 6 if someone found https:// repo url after Step 1 / $ git remote -v show

Ignore step 5 & 6 if anyone already have ssh repo.

ContentLicense: CC BY-SA 4.0


问:
ServiceBusReceiver PeekMessageAsync only returns maximum of 250 dlq-messages?
I am reading from a deadletter queue on servicebus using the ServiceBusReceiver(which I want to continue using).

However, the receiver.PeekMessagesAsync(550) only fetches a maximum of 250 messages from deadletter queue???
How can I change this? I already have it set to fetch 550 messages so not sure how to do it.

```<code>        string topic = "myTopic";
        string subscriptionAndDeadletterPath = @"mySubscription/$deadletterqueue";
        var paginationSize = 1000;
        var dlqCount = 0;
        var numberOfMessagesToFetchFromDlq = 550;

        try
        {
            await using var client = new ServiceBusClient(connectionString);
            var receiver = client.CreateReceiver(topic, subscriptionAndDeadletterPath, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock, PrefetchCount = paginationSize });

            var messagesFromDlq = await receiver.PeekMessagesAsync(numberOfMessagesToFetchFromDlq);
            dlqCount = messagesFromDlq.Count();

</code>```

dlqCount will not exceed 250 for some reason? The int maxMessages parameter doesn't seem to work above this number?

答:
The number of messages that you're passing to PeekMessagesAsync is the maximum number of messages that will be returned.  There is no way to guarantee a minimum size for the batch; the number of messages included depends on several factors of which the most impactful is how quickly the network can stream messages to the client.

My answer to Optmize receiving messages from Azure Service Bus in batch mode discusses the context in more detail and offers some thoughts that may apply to your scenario as well.

It is important to note that there are some behavioral differences with peeked messages when compared to received messages.  The most impactful is that peeked messages are not locked and can't be settled, so considerations around lock token expiration wouldn't apply here.

Body:
I am reading from a deadletter queue on servicebus using the ServiceBusReceiver(which I want to continue using).

However, the receiver.PeekMessagesAsync(550) only fetches a maximum of 250 messages from deadletter queue???
How can I change this? I already have it set to fetch 550 messages so not sure how to do it.

        string topic = "myTopic";
        string subscriptionAndDeadletterPath = @"mySubscription/$deadletterqueue";
        var paginationSize = 1000;
        var dlqCount = 0;
        var numberOfMessagesToFetchFromDlq = 550;

        try
        {
            await using var client = new ServiceBusClient(connectionString);
            var receiver = client.CreateReceiver(topic, subscriptionAndDeadletterPath, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock, PrefetchCount = paginationSize });

            var messagesFromDlq = await receiver.PeekMessagesAsync(numberOfMessagesToFetchFromDlq);
            dlqCount = messagesFromDlq.Count();

dlqCount will not exceed 250 for some reason? The int maxMessages parameter doesn't seem to work above this number?


问:
Azure DevOps Pipeline yaml file Docker Tag
Hello my expert friends.
I know this question might sound really simple but I am seeking for some advice and best practices to follow/learn.

I have a testing infra in azure divided in 2 environment. One is Staging and the other is Production.

Those environment have the same configurations for on hand practices as I want to learn how to deploy specific docker images from staging to production.

At the current state, I have 1 web app in Staging and 1 web app in Production.

My Build pipeline for this lab is try to trigger the build pipeline in staging only if I push to GitHub a Tag, and I achieved this by setting my pipeline as follow:

```<code>trigger:
  batch: true
  tags:
    include:
      - '*'
  branches:
    exclude:
    - Staging
</code>```

This runs a docker build with some c# code and deploys it to a container registry.
But in my current pipeline, under the task Docker:

```<code>- task: Docker@2
    name: 'dockerBuildAndPush'
    displayName: 'docker - Build & Push'
    inputs:
      repository: $(imageRepository)
      Dockerfile: $(dockerfilePath)
      containerRegistry: ${{ variables.dockerRegistryServiceConnection }}
      buildContext: ${{ variables.buildContext }}
      tags: |
        $(Build.BuildNumber)
        latest
</code>```

As you can see I have a tags that is based on the Build.BuildNumber
This of course during the build process it get the current date + build number, but I wanted to do is target the latest tag coming from GitHub and pass it to the build.

And this is where I got confuse and not really sure about the best practice to follow.

Assuming that on GitHub I push the update with the tag v1.0, is there a way how I can use the pipeline to pick the tag number and pass it automatically to the build? Or I have to update the Tag value manually in the pipeline every time before to push to GitHub?

So basically what I want to have in my container registry is as follow:

Github push tag v1.0

Azure Container registry have a build docker build:v1.0

In this way, I will be easier to detect quickly which docker image is running on Staging and Production later on.

Sorry if I couldn't explain my dilemma clearly and please if this is the case, don't hesitate to ask for more informations.

UPDATE:

Thank you so much Dave for your reply and you solution. I will look into it asap.
Right I was looking for something a bit easier to achieve to understand the full process and get confident with it.

At the current state I managed my pipeline in the following order.

```<code>parameters:
  - name: tag
    type: string
    default: 'v1.1'

trigger:
  batch: true
  tags:
    include:
      - '*'
  branches:
    exclude:
    - Staging
</code>```

and in my docker task set the tag to the parameters

```<code>- task: Docker@2
    name: 'dockerBuildAndPush'
    displayName: 'docker - Build & Push'
    inputs:
      repository: $(imageRepository)
      Dockerfile: $(dockerfilePath)
      containerRegistry: ${{ variables.dockerRegistryServiceConnection }}
      buildContext: ${{ variables.buildContext }}
      tags: '${{ parameters.tag }}'
</code>```

This process worked exactly how expected. In my container registry in the portal I have a version named 'v.1.1'

The issue I am facing is during the release phase of this image.

In the tag for the release I have the $(Build.BuildNumber) which of course as I am setting a parameters variable to build that image, I don't have a build number but a v1.1.

I have been reading around that I can override the BuildNumber with a specific variable name in the yaml file to map the Build.BuildNumber to a parameter and in the relelease pipeline I can leave the Build.BuildNumber as a reference. But is not 100% clear to me how this can be done.

答:
You could use GitVersion to generate a version number from your repository tags.

This could be used from your pipeline as follows:

```<code>  - task: UseDotNet@2
    displayName: Use .NET Core CLI
    inputs:
      version: "6.x"
  - task: DotNetCoreCLI@2
    displayName: Install GitVersion
    continueOnError: true
    inputs:
      command: "custom"
      custom: "tool"
      arguments: "install GitVersion.Tool --version 5.* --global"
  - task: PowerShell@2
    displayName: Set build version
    inputs:
      targetType: "inline"
      script: |
        Write-Host "##vso[build.updatebuildnumber]$(dotnet-gitversion /showvariable FullSemVer)"
</code>```

The above example will set the Build.BuildNumber variable to a version string based on the last tag. You can, of course, set some other variable instead.

You can also customise the way GitVersion chooses a version number by adding a GitVersion.yml file to your repository.

This answer should serve as a starting point for you - it doesn't produce exactly the format you want, you will need to look at configuration options and such if you want a very specific format.

Also, look at the different modes that GitVersion can run in, since they will affect the version numbers generated for any commits inbetween tagged commits!

Body:
Hello my expert friends.
I know this question might sound really simple but I am seeking for some advice and best practices to follow/learn.

I have a testing infra in azure divided in 2 environment. One is Staging and the other is Production.

Those environment have the same configurations for on hand practices as I want to learn how to deploy specific docker images from staging to production.

At the current state, I have 1 web app in Staging and 1 web app in Production.

My Build pipeline for this lab is try to trigger the build pipeline in staging only if I push to GitHub a Tag, and I achieved this by setting my pipeline as follow:

trigger:
  batch: true
  tags:
    include:
      - '*'
  branches:
    exclude:
    - Staging

This runs a docker build with some c# code and deploys it to a container registry.
But in my current pipeline, under the task Docker:

- task: Docker@2
    name: 'dockerBuildAndPush'
    displayName: 'docker - Build & Push'
    inputs:
      repository: $(imageRepository)
      Dockerfile: $(dockerfilePath)
      containerRegistry: ${{ variables.dockerRegistryServiceConnection }}
      buildContext: ${{ variables.buildContext }}
      tags: |
        $(Build.BuildNumber)
        latest

As you can see I have a tags that is based on the Build.BuildNumber
This of course during the build process it get the current date + build number, but I wanted to do is target the latest tag coming from GitHub and pass it to the build.

And this is where I got confuse and not really sure about the best practice to follow.

Assuming that on GitHub I push the update with the tag v1.0, is there a way how I can use the pipeline to pick the tag number and pass it automatically to the build? Or I have to update the Tag value manually in the pipeline every time before to push to GitHub?

So basically what I want to have in my container registry is as follow:

Github push tag v1.0

Azure Container registry have a build docker build:v1.0

In this way, I will be easier to detect quickly which docker image is running on Staging and Production later on.

Sorry if I couldn't explain my dilemma clearly and please if this is the case, don't hesitate to ask for more informations.

UPDATE:

Thank you so much Dave for your reply and you solution. I will look into it asap.
Right I was looking for something a bit easier to achieve to understand the full process and get confident with it.

At the current state I managed my pipeline in the following order.

parameters:
  - name: tag
    type: string
    default: 'v1.1'

trigger:
  batch: true
  tags:
    include:
      - '*'
  branches:
    exclude:
    - Staging

and in my docker task set the tag to the parameters

- task: Docker@2
    name: 'dockerBuildAndPush'
    displayName: 'docker - Build & Push'
    inputs:
      repository: $(imageRepository)
      Dockerfile: $(dockerfilePath)
      containerRegistry: ${{ variables.dockerRegistryServiceConnection }}
      buildContext: ${{ variables.buildContext }}
      tags: '${{ parameters.tag }}'

This process worked exactly how expected. In my container registry in the portal I have a version named 'v.1.1'

The issue I am facing is during the release phase of this image.

In the tag for the release I have the $(Build.BuildNumber) which of course as I am setting a parameters variable to build that image, I don't have a build number but a v1.1.

I have been reading around that I can override the BuildNumber with a specific variable name in the yaml file to map the Build.BuildNumber to a parameter and in the relelease pipeline I can leave the Build.BuildNumber as a reference. But is not 100% clear to me how this can be done.

Body:
You could use GitVersion to generate a version number from your repository tags.

This could be used from your pipeline as follows:

  - task: UseDotNet@2
    displayName: Use .NET Core CLI
    inputs:
      version: "6.x"
  - task: DotNetCoreCLI@2
    displayName: Install GitVersion
    continueOnError: true
    inputs:
      command: "custom"
      custom: "tool"
      arguments: "install GitVersion.Tool --version 5.* --global"
  - task: PowerShell@2
    displayName: Set build version
    inputs:
      targetType: "inline"
      script: |
        Write-Host "##vso[build.updatebuildnumber]$(dotnet-gitversion /showvariable FullSemVer)"

The above example will set the Build.BuildNumber variable to a version string based on the last tag. You can, of course, set some other variable instead.

You can also customise the way GitVersion chooses a version number by adding a GitVersion.yml file to your repository.

This answer should serve as a starting point for you - it doesn't produce exactly the format you want, you will need to look at configuration options and such if you want a very specific format.

Also, look at the different modes that GitVersion can run in, since they will affect the version numbers generated for any commits inbetween tagged commits!


问:
Pine Script Multi Time Frame - My strategy is repainting and I can't figure out why
I thought I understood how to avoid repainting, but I'm still seeing trades on my chart not lining up with alerts, or vice versa.

My script takes data from the 60m chart to trade on the 15m chart. I'm accessing historical data on the 60m (at least 4 bars back), and I'm only entering trades on the 15m if barstate.isconfirmed. I see trades trigger alerts and then disappear, or trades that never triggered an alert show up retrospectively.

As far as I can tell, I wrote my script so future data should not affect historical decisions, but something is clearly going on. I'm at a loss

```<code>//@version=4
strategy(title="60-15 ETH/USD", precision=2, default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)

// get input
i_length        = input(group="Stochastic", title="Stochastic Length", minval=1, defval=15)
i_k             = input(group="Stochastic", title="Stochastic %K", minval=1, defval=2)
i_d             = input(group="Stochastic", title="Stochastic %D", minval=1, defval=10)
i_trailingStop  = input(group="Trade Settings", title="Trailing Stop?", type=input.bool, defval=true)                           // should stop loss be dynamic, based on most recent high, or static, based on entry price?
i_stopPercent   = input(group="Trade Settings", title="Stop Percent", type=input.float, defval=0.05, maxval=1.0, minval=0.001)  // how much (percentage) can price fall before exiting the trade
i_takeProfit    = input(group="Trade Settings", title="Take Profit", type=input.float, defval=0.06, maxval=1.0, minval=0.001)   // how much (percentage) can price rise before exiting the trade
i_sellThreshold = input(group="Trade Settings", title="Sell Threshold", type=input.float, defval=75.0, maxval=100, minval=0.0)  // when stochastic %D crosses under this value, exit the trade
i_buyThreshold  = input(group="Trade Settings", title="Buy Threshold", type=input.float, defval=40.0, maxval=100, minval=0.0)   // stochastic %D must be below this value to enter a trade

// declare order variables
var recentHigh  = 0.0   // the highest high while in a trade
var stop        = 0.0   // the price that will trigger as stop loss
var entryPrice  = 0.0   // the price when the trade was entered

// build stochastic
sto = stoch(close, high, low, i_length)
K   = sma(sto, i_k)
D   = sma(K, i_d)

// get stochastic trend
stoch_upTrend = D > D[1]

// get stochastic trend for 60 minute
stoch_60         = security(syminfo.tickerid, "60", D)
stoch_60_upTrend = (stoch_60[4] >= stoch_60[8])

// entry
if (D < i_buyThreshold) and stoch_upTrend and stoch_60_upTrend and barstate.isconfirmed and strategy.position_size == 0
    recentHigh := close
    entryPrice := close
    stop       := (close * (1-i_stopPercent))
    strategy.entry(id="60-15-Long", long=strategy.long, comment='buy')

// update recent high, trailing stop
if close > recentHigh
    recentHigh := close
    stop       := i_trailingStop ? (recentHigh * i_stopPercent) : stop

// exit
strategy.exit(id="60-15-Long", stop=stop, comment='sell-stop')
if close > (entryPrice * (1+i_takeProfit)) and barstate.isconfirmed
    strategy.close(id="60-15-Long", comment='sell-profit')
if crossunder(D, i_sellThreshold) and barstate.isconfirmed
    strategy.close(id="60-15-Long", comment='sell-trend')

// plot
plot(K, title="%K", color=color.blue, linewidth=1)
plot(D, title="%D", color=color.orange, linewidth=1)
plot(stoch_60, title="Hourly Stochastic (D)", color= stoch_60_upTrend ? color.green : color.red, style=plot.style_stepline)
upperBand  = hline(i_sellThreshold, title="Upper Limit", linestyle=hline.style_dashed)
middleBand = hline(50, title="Midline", linestyle=hline.style_dotted)
lowerBand  = hline(i_buyThreshold, title="Lower Limit", linestyle=hline.style_dashed)
fill(lowerBand, upperBand, color=color.purple, transp=75)
</code>```

答:
I realize this is pretty old now but I think the issue is that (D < i_buyThreshold) can repaint and stoch_upTrend = D > D[1] can also repaint.
You could try adding if barstate.isconfirmed as the parent scope, then add the other if statements below that.

But if that doesn't work, then you need to change D < i_buyThreshold) to D[1] < i_buyThreshold) and change stoch_upTrend = D > D[1] to stoch_upTrend = D[1] > D[2].
That way you are looking back at the previous bar to check if condition was met, and this bar will have been closed already. Since the bar you are looking at has already closed, it will not change. It is either true or not true. As a result you also would not need the barstate.isconfirmed as part of the if statement.

Body:
I thought I understood how to avoid repainting, but I'm still seeing trades on my chart not lining up with alerts, or vice versa.

My script takes data from the 60m chart to trade on the 15m chart. I'm accessing historical data on the 60m (at least 4 bars back), and I'm only entering trades on the 15m if barstate.isconfirmed. I see trades trigger alerts and then disappear, or trades that never triggered an alert show up retrospectively.

As far as I can tell, I wrote my script so future data should not affect historical decisions, but something is clearly going on. I'm at a loss

//@version=4
strategy(title="60-15 ETH/USD", precision=2, default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)

// get input
i_length        = input(group="Stochastic", title="Stochastic Length", minval=1, defval=15)
i_k             = input(group="Stochastic", title="Stochastic %K", minval=1, defval=2)
i_d             = input(group="Stochastic", title="Stochastic %D", minval=1, defval=10)
i_trailingStop  = input(group="Trade Settings", title="Trailing Stop?", type=input.bool, defval=true)                           // should stop loss be dynamic, based on most recent high, or static, based on entry price?
i_stopPercent   = input(group="Trade Settings", title="Stop Percent", type=input.float, defval=0.05, maxval=1.0, minval=0.001)  // how much (percentage) can price fall before exiting the trade
i_takeProfit    = input(group="Trade Settings", title="Take Profit", type=input.float, defval=0.06, maxval=1.0, minval=0.001)   // how much (percentage) can price rise before exiting the trade
i_sellThreshold = input(group="Trade Settings", title="Sell Threshold", type=input.float, defval=75.0, maxval=100, minval=0.0)  // when stochastic %D crosses under this value, exit the trade
i_buyThreshold  = input(group="Trade Settings", title="Buy Threshold", type=input.float, defval=40.0, maxval=100, minval=0.0)   // stochastic %D must be below this value to enter a trade

// declare order variables
var recentHigh  = 0.0   // the highest high while in a trade
var stop        = 0.0   // the price that will trigger as stop loss
var entryPrice  = 0.0   // the price when the trade was entered

// build stochastic
sto = stoch(close, high, low, i_length)
K   = sma(sto, i_k)
D   = sma(K, i_d)

// get stochastic trend
stoch_upTrend = D > D[1]

// get stochastic trend for 60 minute
stoch_60         = security(syminfo.tickerid, "60", D)
stoch_60_upTrend = (stoch_60[4] >= stoch_60[8])

// entry
if (D < i_buyThreshold) and stoch_upTrend and stoch_60_upTrend and barstate.isconfirmed and strategy.position_size == 0
    recentHigh := close
    entryPrice := close
    stop       := (close * (1-i_stopPercent))
    strategy.entry(id="60-15-Long", long=strategy.long, comment='buy')

// update recent high, trailing stop
if close > recentHigh
    recentHigh := close
    stop       := i_trailingStop ? (recentHigh * i_stopPercent) : stop

// exit
strategy.exit(id="60-15-Long", stop=stop, comment='sell-stop')
if close > (entryPrice * (1+i_takeProfit)) and barstate.isconfirmed
    strategy.close(id="60-15-Long", comment='sell-profit')
if crossunder(D, i_sellThreshold) and barstate.isconfirmed
    strategy.close(id="60-15-Long", comment='sell-trend')

// plot
plot(K, title="%K", color=color.blue, linewidth=1)
plot(D, title="%D", color=color.orange, linewidth=1)
plot(stoch_60, title="Hourly Stochastic (D)", color= stoch_60_upTrend ? color.green : color.red, style=plot.style_stepline)
upperBand  = hline(i_sellThreshold, title="Upper Limit", linestyle=hline.style_dashed)
middleBand = hline(50, title="Midline", linestyle=hline.style_dotted)
lowerBand  = hline(i_buyThreshold, title="Lower Limit", linestyle=hline.style_dashed)
fill(lowerBand, upperBand, color=color.purple, transp=75)


问:
How SSL certficates are loaded into (or removed from) the memory of a Java process
First of all, I must say I'm not a Java developer but a sys admin.

I thought when a Java process is launched with no   javax.net.ssl.trustStore  and javax.net.ssl.keyStore   properties, the certificates in its $JAVA_HOME/jre/lib/security/cacerts always are loaded and used.

But I have found that one JBoss war loads another keystore and ignore the certificates in the default cacerts.

The problem was a PKIX typical error message

```<code>javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

but I was sure the certificate needed was in the default cacerts.

I had to put the property javax.net.debug=all to shed some light on this issue and found that another keystore was loaded -- one having an old expired certificate, and which I didn't know.

After adding the valid certificate on the second keystore, the PKIX error message disappeared.

Then, how SSL certificates are dealed in a Java process?

When a new keystore is loaded, previously loaded certificates are deleted from memory?

Best regards

答:
No, when a new keystore is loaded, previously loaded certificates are not replaced/discarded by default.

Internally Java handles keystores like you open a document in Word: You can open/load a keystore, retrieve certificates, delete certificates, add new certificates and of course save the whole keystore after modifying it.

When performing an HTTPS call you can specify a TrustManager and this TrustManager holds a references to loaded keystores.
As it is simply to just replace the default keystore by the custom keystore then Java will consider only the custom keystore.

You could also use both keystore, the default Java one and the custom one as shown in this answer (uses two TrustManager instances that are chained).

Alternatively the developer could modify the loaded keystore in memory and add the certificates from the Java default store.

As you can see it is up to the developer how a Java program handles this situation.

Body:
First of all, I must say I'm not a Java developer but a sys admin.

I thought when a Java process is launched with no   javax.net.ssl.trustStore  and javax.net.ssl.keyStore   properties, the certificates in its $JAVA_HOME/jre/lib/security/cacerts always are loaded and used.

But I have found that one JBoss war loads another keystore and ignore the certificates in the default cacerts.

The problem was a PKIX typical error message

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

but I was sure the certificate needed was in the default cacerts.

I had to put the property javax.net.debug=all to shed some light on this issue and found that another keystore was loaded -- one having an old expired certificate, and which I didn't know.

After adding the valid certificate on the second keystore, the PKIX error message disappeared.

Then, how SSL certificates are dealed in a Java process?

When a new keystore is loaded, previously loaded certificates are deleted from memory?

Best regards


问:
Hashing and salting a password field
I have been tossing around the question of how to store the passwords in my DB for some time now. This is my first time at making a secure application with a web login, so i wanted to set up some good practices.

First, i read up on hashing and salting. It seems that the idea is...

Get hashing algorithm

Get password from user

Add 'salt' to plain text password from user

hash the entire password (including salt)

Store the salt in the db so that you can retrieve it later (for verification of PSWD)

And that got me thinking... If a hacker knows your salt (because it is stored in the DB somewhere, maybe a column called this_is_not_the_salt_ur_looking_for or something equally ambiguous) they can re-generate the password dictionary and gain access.

Then i had an idea. What if you stored your salt inside the hashed password field. So follow steps 1-4 (randomly generating the salt), then in step 5, insert the salt in the password somewhere known by the password interpreting class or service:

xxxxxsaltvaluexxxxxxxxxxxxxxxx

where x is the hashed string values. Can anyone see any issues with this? is it just completely unnecessary?

Answer:

There is no reason why this couldnt be done. As Yahia states, other methods of securing a password include double (or n) hashing. On another note, BCrypt looks like a good method of stopping brute force attacks almost entirely, but I couldnt find a trusted library for C#

Thanks!

TTD

答:
From a security standpoint that is not necessary as long you only store the hashed password (NEVER store the cleartext password!) plus the salt... an attacker is "allowed" to know the salt - your security must be designed in a way that even with the knowledge of the salt it is still secure.

What does the salt do ?

Salt aids in defending against brute-force attacks using pre-computed "rainbow-tables".

Salt makes brute-force much more expensive (in time/memory terms) for the attacker.

Calculating such a table is expensive and usually only done when it can be used for more than one attack/password.

IF you use the same salt for all password an attacker could pre-compute such a table and then brute-force your passwords into cleartext...

As long as you generate a new (best cryptogrpahically strong) random salt for every password you want to store the hash of there is no problem.

As for your idea in "disguising" the salt

That is more of "security by obscurity" which should be avoided.

Although in this case I neither see any positive nor negative effect.

IF you want to strengthen the security further

You could calculate the hash several times over (hash the hash etc.) - this doesn't cost you much but it makes a brute-force attack / calculating "rainbow-tables" even more expensive... please don't invent yourself - there are proven standard methods to do so, see for example http://en.wikipedia.org/wiki/PBKDF2 and http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx

Title: Hashing and salting a password field


问:
My app crushed for a java.lang.NullPointerException
I'm trying to develop an android app with my api and retrofit 2 but unfortunaly my app crush many time, and I got a message like this,
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apitest.firsttry/com.apitest.firsttry.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.apitest.firsttry.api.ApiInterface.getAllData()' on a null object reference and Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.apitest.firsttry.api.ApiInterface.getAllData()' on a null object reference here is code of ApiInterface.java

```<code>
import com.apitest.firsttry.Models.DataModels;
import com.apitest.firsttry.Response.GetDataResponse;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    @GET("fetchdata.php")
    Call<GetDataResponse> getAllData();

}
</code>```

and here is code of ApiClient.java

```<code>package com.apitest.firsttry.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static Retrofit RETROFIT=null;

    public static Retrofit getClient(){

        if (RETROFIT==null) {

            OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
            Gson gson = new GsonBuilder().create();

            RETROFIT = new Retrofit.Builder().baseUrl("https://wight-baths.000webhostapp.com/").client(okHttpClient).addConverterFactory(GsonConverterFactory.create(gson)).build();
        }
        return RETROFIT;

    }

}
</code>```

And this is code  of MainActivity

```<code>package com.apitest.firsttry;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.apitest.firsttry.Adapter.DataAdapter;
import com.apitest.firsttry.Models.DataModels;
import com.apitest.firsttry.Response.GetDataResponse;
import com.apitest.firsttry.api.ApiClient;
import com.apitest.firsttry.api.ApiInterface;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
DataAdapter dataAdapter;
ApiInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    getdata();
    initializing();

    }
    private void initializing(){
        recyclerView=findViewById(R.id.recycler_view);
        Retrofit retrofit= ApiClient.getClient();
        apiInterface=retrofit.create(ApiInterface.class);
    }
    private void setDataAdapter(List<DataModels>dataModels){
        dataAdapter=new DataAdapter(this, dataModels);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);

        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(dataAdapter);
    }
    private void getdata(){
        apiInterface.getAllData().enqueue(new Callback<GetDataResponse>() {
            @Override
            public void onResponse(Call<GetDataResponse> call, Response<GetDataResponse> response) {
                try {
                    if (response!=null){
                        if (response.body().getStatus().equals("1")){

                            setDataAdapter(response.body().getData());

                        }else {
                            Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }

                }catch (Exception e){
                    Log.e("exp",e.getLocalizedMessage());
                }

            }

            @Override
            public void onFailure(Call<GetDataResponse> call, Throwable t) {
                Log.e("failer",t.getLocalizedMessage());

            }
        });

    }
}
</code>```

How to fix it?

答:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    getdata();
    initializing();

    }
```

Call initializing() before calling getdata(). You set up apiInterface in initializing() and cannot use it before initializing() returns.

Body:
I'm trying to develop an android app with my api and retrofit 2 but unfortunaly my app crush many time, and I got a message like this,
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apitest.firsttry/com.apitest.firsttry.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.apitest.firsttry.api.ApiInterface.getAllData()' on a null object reference and Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.apitest.firsttry.api.ApiInterface.getAllData()' on a null object reference here is code of ApiInterface.java

import com.apitest.firsttry.Models.DataModels;
import com.apitest.firsttry.Response.GetDataResponse;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    @GET("fetchdata.php")
    Call<GetDataResponse> getAllData();

}

and here is code of ApiClient.java

package com.apitest.firsttry.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static Retrofit RETROFIT=null;

    public static Retrofit getClient(){

        if (RETROFIT==null) {

            OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
            Gson gson = new GsonBuilder().create();

            RETROFIT = new Retrofit.Builder().baseUrl("https://wight-baths.000webhostapp.com/").client(okHttpClient).addConverterFactory(GsonConverterFactory.create(gson)).build();
        }
        return RETROFIT;

    }

}

And this is code  of MainActivity

package com.apitest.firsttry;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.apitest.firsttry.Adapter.DataAdapter;
import com.apitest.firsttry.Models.DataModels;
import com.apitest.firsttry.Response.GetDataResponse;
import com.apitest.firsttry.api.ApiClient;
import com.apitest.firsttry.api.ApiInterface;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
DataAdapter dataAdapter;
ApiInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    getdata();
    initializing();

    }
    private void initializing(){
        recyclerView=findViewById(R.id.recycler_view);
        Retrofit retrofit= ApiClient.getClient();
        apiInterface=retrofit.create(ApiInterface.class);
    }
    private void setDataAdapter(List<DataModels>dataModels){
        dataAdapter=new DataAdapter(this, dataModels);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);

        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(dataAdapter);
    }
    private void getdata(){
        apiInterface.getAllData().enqueue(new Callback<GetDataResponse>() {
            @Override
            public void onResponse(Call<GetDataResponse> call, Response<GetDataResponse> response) {
                try {
                    if (response!=null){
                        if (response.body().getStatus().equals("1")){

                            setDataAdapter(response.body().getData());

                        }else {
                            Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }

                }catch (Exception e){
                    Log.e("exp",e.getLocalizedMessage());
                }

            }

            @Override
            public void onFailure(Call<GetDataResponse> call, Throwable t) {
                Log.e("failer",t.getLocalizedMessage());

            }
        });

    }
}

How to fix it?

Body:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    getdata();
    initializing();

    }

Call initializing() before calling getdata(). You set up apiInterface in initializing() and cannot use it before initializing() returns.


问:
Format Select2 dropdown results having json
I am using select2 dropdown control to display list of facilities e.g facility A,B,C...etc. along with its location details. I am looking for following output,

Currently I can display "facility name", but would like to display City and State from my json objects.
How can I format my results to display them as above html format?
Here's my code so far.

```<code><input type="hidden" id="ddlFacility" style="width:100%" />

$("#ddlFacility").select2({
        placeholder: "Select a Facility",
        ajax: {
            url: "my url",
            dataType: 'json',
            type: "GET",
            quietMillis: 50,
            data: function ( term ) { return { term: term }; },
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return { text: item.FacilityName, id: item.FacilityId }
                    })
                };
            }
        }
    });
</code>```

答:
Please note that nowadays if using select2 version 4 or above the formatSelection and formatResult were replaced by templateSelection and templateResult
More details on the official documentation:
https://select2.org/upgrading/migrating-from-35

Body:
I am using select2 dropdown control to display list of facilities e.g facility A,B,C...etc. along with its location details. I am looking for following output,

Currently I can display "facility name", but would like to display City and State from my json objects.
How can I format my results to display them as above html format?
Here's my code so far.

<input type="hidden" id="ddlFacility" style="width:100%" />

$("#ddlFacility").select2({
        placeholder: "Select a Facility",
        ajax: {
            url: "my url",
            dataType: 'json',
            type: "GET",
            quietMillis: 50,
            data: function ( term ) { return { term: term }; },
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return { text: item.FacilityName, id: item.FacilityId }
                    })
                };
            }
        }
    });


问:
Sending an email with an Excel file as an attachment (nodemailer)
I'm trying to send an email to a user with the nodemailer library. However, I also need to send an Excel file (.xlsx) as an attachment. I've had some success sending a .csv file, but I need to send it as an .xlsx.
Here's my code so far

```<code>import xlsx from 'xlsx';
import nodemailer from 'nodemailer';
import os from 'os';
import path from 'path';
import fs from 'fs-extra';

const mail = 'testmail@something.com';

const transporter = nodemailer.createTransport({...});

const wb = xlsx.utils.book_new();
wb.Props = { Title: 'Excel', Subject: 'Excel' };
wb.SheetNames.push('Excel');
const wData = [['Some','Data']];
const ws = xlsx.utils.aoa_to_sheet(wData);
wb.Sheets['Excel'] = ws;
const wbout = xlsx.write(wb, { bookType: 'xlsx', type: 'binary' });

const fileName = '${mail}_${Date.now()}.xlsx';
const tempFile = path.join(os.tmpdir(), fileName);
await fs.writeFile(tempFile, wbout);

const mailOptions = {
  from: 'johndoe@test.com',
  to: mail,
  subject: 'Excel',
  attachments: {
    filename,
    content: wbout,
    path: tempFile
  }
};

return transporter.sendMail(mailOptions);
</code>```

So far I haven't been able to send it as intended, so can you guys help me?
Also, I've tried looking at:
This post

However, they seem to base their solutions on sending the file as a .csv, something I don't want.

答:
I had the same struggles and in my case what worked was setting the contentType to 'application/octet-stream':

```<code>const mailOptions = {
    from: this.sender,
    to: this.recipient,
    subject: "report",
    text: "report",
    attachments: [
        {
            filename: 'report' + '.xlsx',
            content: Buffer.from(buffer),
            contentType: 'application/octet-stream',
        }
    ],
    headers: {'x-myheader': 'test header'}
};
</code>```

Body:
I'm trying to send an email to a user with the nodemailer library. However, I also need to send an Excel file (.xlsx) as an attachment. I've had some success sending a .csv file, but I need to send it as an .xlsx.
Here's my code so far

import xlsx from 'xlsx';
import nodemailer from 'nodemailer';
import os from 'os';
import path from 'path';
import fs from 'fs-extra';

const mail = 'testmail@something.com';

const transporter = nodemailer.createTransport({...});

const wb = xlsx.utils.book_new();
wb.Props = { Title: 'Excel', Subject: 'Excel' };
wb.SheetNames.push('Excel');
const wData = [['Some','Data']];
const ws = xlsx.utils.aoa_to_sheet(wData);
wb.Sheets['Excel'] = ws;
const wbout = xlsx.write(wb, { bookType: 'xlsx', type: 'binary' });

const fileName = '${mail}_${Date.now()}.xlsx';
const tempFile = path.join(os.tmpdir(), fileName);
await fs.writeFile(tempFile, wbout);

const mailOptions = {
  from: 'johndoe@test.com',
  to: mail,
  subject: 'Excel',
  attachments: {
    filename,
    content: wbout,
    path: tempFile
  }
};

return transporter.sendMail(mailOptions);

So far I haven't been able to send it as intended, so can you guys help me?
Also, I've tried looking at:
This post

However, they seem to base their solutions on sending the file as a .csv, something I don't want.

Body:
I had the same struggles and in my case what worked was setting the contentType to 'application/octet-stream':

const mailOptions = {
    from: this.sender,
    to: this.recipient,
    subject: "report",
    text: "report",
    attachments: [
        {
            filename: 'report' + '.xlsx',
            content: Buffer.from(buffer),
            contentType: 'application/octet-stream',
        }
    ],
    headers: {'x-myheader': 'test header'}
};


问:
Replace items in a list ansible playbook
I have the following dictionary:

{
  "test1": ["300m","","0","4","1050m"],
  "test2": ["600m","","","0","2"]
}
```
<p>I would execute a replacement over the items of the above lists and tried this:</p>
<pre class="lang-yaml prettyprint-override"><code>- set_fact:
    result: "{{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}"
  with_items: "{{dict_ns_cpu | dict2items}}"
  ignore_errors: true
</code>```

With the values of the list:

If the value ends with m, I want to remove it and divide the value per 1000.

If the value is only a number, multiply per 1000

I get the following error:

"msg": "Unexpected templating type error occurred on ({{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}): unhashable type: 'slice'"

Could anyone help me?

答:
For example, given the data

    dict_ns_cpu:
      test1: ["300m","50m","0","4","1050m"]
      test2: ["600m","400m","10m","0","2"]
```
<p>the task below does the job</p>
<pre class="lang-yaml prettyprint-override"><code>    - set_fact:
        result: "{{ result|d({})|combine({item.key: _list|from_yaml}) }}"
      loop: "{{ dict_ns_cpu|dict2items }}"
      vars:
        _list: |-
          {% for i in item.value %}
          {% if i is match('.*m') %}
          - {{ i[:-1]|int / 1000 }}
          {% else %}
          - {{ i|int * 1000 }}
          {% endif %}
          {% endfor %}
</code>```

gives

  result:
    test1: [0.3, 0.05, 0, 4000, 1.05]
    test2: [0.6, 0.4, 0.01, 0, 2000]
```
<hr>
<p>If you change the data</p>
<pre class="lang-yaml prettyprint-override"><code>    dict_ns_cpu:
      test1: ["300m","","0","4","1050m"]
      test2: ["600m","","","0","2"]
</code>```

the result will be (ansible [core 2.12.1])

```<code>  result:
    test1: [0.3, 0, 0, 4000, 1.05]
    test2: [0.6, 0, 0, 0, 2000]
</code>```

Use select if you want to silently omit empty items. For example, change the line

          {% for i in item.value|select %}
```
<p>The result will be</p>
<pre class="lang-yaml prettyprint-override"><code>  result:
    test1: [0.3, 0, 4000, 1.05]
    test2: [0.6, 0, 2000]
</code>```

Body:
I have the following dictionary:

{
  "test1": ["300m","","0","4","1050m"],
  "test2": ["600m","","","0","2"]
}

I would execute a replacement over the items of the above lists and tried this:

- set_fact:
    result: "{{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}"
  with_items: "{{dict_ns_cpu | dict2items}}"
  ignore_errors: true

With the values of the list:

If the value ends with m, I want to remove it and divide the value per 1000.

If the value is only a number, multiply per 1000

I get the following error:

"msg": "Unexpected templating type error occurred on ({{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}): unhashable type: 'slice'"

Could anyone help me?

Body:
For example, given the data

    dict_ns_cpu:
      test1: ["300m","50m","0","4","1050m"]
      test2: ["600m","400m","10m","0","2"]

the task below does the job

    - set_fact:
        result: "{{ result|d({})|combine({item.key: _list|from_yaml}) }}"
      loop: "{{ dict_ns_cpu|dict2items }}"
      vars:
        _list: |-
          {% for i in item.value %}
          {% if i is match('.*m') %}
          - {{ i[:-1]|int / 1000 }}
          {% else %}
          - {{ i|int * 1000 }}
          {% endif %}
          {% endfor %}

gives

  result:
    test1: [0.3, 0.05, 0, 4000, 1.05]
    test2: [0.6, 0.4, 0.01, 0, 2000]

If you change the data

    dict_ns_cpu:
      test1: ["300m","","0","4","1050m"]
      test2: ["600m","","","0","2"]

the result will be (ansible [core 2.12.1])

  result:
    test1: [0.3, 0, 0, 4000, 1.05]
    test2: [0.6, 0, 0, 0, 2000]

Use select if you want to silently omit empty items. For example, change the line

          {% for i in item.value|select %}

The result will be

  result:
    test1: [0.3, 0, 4000, 1.05]
    test2: [0.6, 0, 2000]


问:
wildfly cli | write-attribute does not work
I am trying to update the mdb-delivery-group active value in the wildfly cli.

Reading with this command is working:

```<code>./subsystem=ejb3/mdb-delivery-group=<group>:read-attribute(name=active)
</code>```

it returns:

```<code>{
    "outcome" => "success",
    "result" => true
}
</code>```

When I try to write the attribute with this command:

```<code>./subsystem=ejb3/mdb-delivery-group=<group>:write-attribute(name=active,value=false)
</code>```

it returns:

```<code>{
    "outcome" => "failed",
    "failure-description" => "WFLYCTL0158: Operation handler failed: java.lang.IllegalArgumentException: WFLYCTL0484: A
ttribute definition of attribute 'active' is null",
    "rolled-back" => true
}
</code>```

The wildfly server logs tells me the same:

```<code>12:44:02,437 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 2) WFLYCTL0013: Operation ("write-attribute") failed - address: ([
        ("subsystem" => "ejb3"),
        ("mdb-delivery-group" => "<group>")
    ]): java.lang.IllegalArgumentException: WFLYCTL0484: Attribute definition of attribute 'active' is null
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractWriteAttributeHandler.getAttributeDefinition(AbstractWriteAttributeHandler.java:259)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractWriteAttributeHandler.execute(AbstractWriteAttributeHandler.java:88)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.operations.global.WriteAttributeHandler.doExecuteInternal(WriteAttributeHandler.java:208)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.operations.global.WriteAttributeHandler.execute(WriteAttributeHandler.java:116)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractOperationContext.executeStep(AbstractOperationContext.java:1045)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractOperationContext.processStages(AbstractOperationContext.java:777)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractOperationContext.executeOperation(AbstractOperationContext.java:466)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.OperationContextImpl.executeOperation(OperationContextImpl.java:1427)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.internalExecute(ModelControllerImpl.java:448)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.lambda$executeForResponse$0(ModelControllerImpl.java:259)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.SecurityIdentity.runAs(SecurityIdentity.java:304)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.SecurityIdentity.runAs(SecurityIdentity.java:270)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.executeForResponse(ModelControllerImpl.java:259)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.executeOperation(ModelControllerImpl.java:253)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.execute(ModelControllerImpl.java:236)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler.doExecute(ModelControllerClientOperationHandler.java:241)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler.access$400(ModelControllerClientOperationHandler.java:139)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler$1$1.run(ModelControllerClientOperationHandler.java:163)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler$1$1.run(ModelControllerClientOperationHandler.java:159)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.SecurityIdentity.runAs(SecurityIdentity.java:328)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.SecurityIdentity.runAs(SecurityIdentity.java:285)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AccessAuditContext.doAs(AccessAuditContext.java:254)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AccessAuditContext.doAs(AccessAuditContext.java:225)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler$1.execute(ModelControllerClientOperationHandler.java:159)
        at org.jboss.as.protocol@17.0.3.Final//org.jboss.as.protocol.mgmt.ManagementRequestContextImpl$1.doExecute(ManagementRequestContextImpl.java:70)
        at org.jboss.as.protocol@17.0.3.Final//org.jboss.as.protocol.mgmt.ManagementRequestContextImpl$AsyncTaskRunner.run(ManagementRequestContextImpl.java:160)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at java.base/java.lang.Thread.run(Thread.java:834)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.JBossThread.run(JBossThread.java:513)
</code>```

We recently upgraded our wildfly version from wildfly-21.0.2.Final to wildfly-25.0.1.Final. On version 21 it was working with those commands.

Can somebody help me out? Thanks

答: You should fill a Jira for this on https://issue.redhat.com . The fix is simple</p>

Body:
I am trying to update the mdb-delivery-group active value in the wildfly cli.

Reading with this command is working:

./subsystem=ejb3/mdb-delivery-group=<group>:read-attribute(name=active)

it returns:

{
    "outcome" => "success",
    "result" => true
}

When I try to write the attribute with this command:

./subsystem=ejb3/mdb-delivery-group=<group>:write-attribute(name=active,value=false)

it returns:

{
    "outcome" => "failed",
    "failure-description" => "WFLYCTL0158: Operation handler failed: java.lang.IllegalArgumentException: WFLYCTL0484: A
ttribute definition of attribute 'active' is null",
    "rolled-back" => true
}

The wildfly server logs tells me the same:

12:44:02,437 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 2) WFLYCTL0013: Operation ("write-attribute") failed - address: ([
        ("subsystem" => "ejb3"),
        ("mdb-delivery-group" => "<group>")
    ]): java.lang.IllegalArgumentException: WFLYCTL0484: Attribute definition of attribute 'active' is null
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractWriteAttributeHandler.getAttributeDefinition(AbstractWriteAttributeHandler.java:259)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractWriteAttributeHandler.execute(AbstractWriteAttributeHandler.java:88)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.operations.global.WriteAttributeHandler.doExecuteInternal(WriteAttributeHandler.java:208)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.operations.global.WriteAttributeHandler.execute(WriteAttributeHandler.java:116)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractOperationContext.executeStep(AbstractOperationContext.java:1045)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractOperationContext.processStages(AbstractOperationContext.java:777)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AbstractOperationContext.executeOperation(AbstractOperationContext.java:466)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.OperationContextImpl.executeOperation(OperationContextImpl.java:1427)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.internalExecute(ModelControllerImpl.java:448)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.lambda$executeForResponse$0(ModelControllerImpl.java:259)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.SecurityIdentity.runAs(SecurityIdentity.java:304)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.SecurityIdentity.runAs(SecurityIdentity.java:270)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.executeForResponse(ModelControllerImpl.java:259)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.executeOperation(ModelControllerImpl.java:253)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.ModelControllerImpl.execute(ModelControllerImpl.java:236)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler.doExecute(ModelControllerClientOperationHandler.java:241)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler.access$400(ModelControllerClientOperationHandler.java:139)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler$1$1.run(ModelControllerClientOperationHandler.java:163)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler$1$1.run(ModelControllerClientOperationHandler.java:159)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.SecurityIdentity.runAs(SecurityIdentity.java:328)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.SecurityIdentity.runAs(SecurityIdentity.java:285)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AccessAuditContext.doAs(AccessAuditContext.java:254)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.AccessAuditContext.doAs(AccessAuditContext.java:225)
        at org.jboss.as.controller@17.0.3.Final//org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler$1.execute(ModelControllerClientOperationHandler.java:159)
        at org.jboss.as.protocol@17.0.3.Final//org.jboss.as.protocol.mgmt.ManagementRequestContextImpl$1.doExecute(ManagementRequestContextImpl.java:70)
        at org.jboss.as.protocol@17.0.3.Final//org.jboss.as.protocol.mgmt.ManagementRequestContextImpl$AsyncTaskRunner.run(ManagementRequestContextImpl.java:160)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at java.base/java.lang.Thread.run(Thread.java:834)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.JBossThread.run(JBossThread.java:513)

We recently upgraded our wildfly version from wildfly-21.0.2.Final to wildfly-25.0.1.Final. On version 21 it was working with those commands.

Can somebody help me out? Thanks


问:
Plotting column graph with multiple groups using ggplot
I have dataset below and would like to have the results in the picture attached using ggplot.

```<code>bar_df

class   boys  girls
  a     20     30
  b     40     30
  c     50     50
  d     30     70
</code>```

I tried code below

```<code>bar_df <- melt(bar_df, id.vars = 'class')

ggplot(bar_df,aes(x = variable,y = value)) +
  geom_bar(aes(fill = variable),stat = "identity",position = "dodge")

</code>```

答:
Another option is to use pivot_longer from tidyverse.

```<code>library(tidyverse)

df %>%
  pivot_longer(-class) %>%
  ggplot(aes(fill=name, y=value, x=class)) +
  geom_bar(position="dodge", stat="identity")
</code>```

Or with melt (as shown by @r2evans):

```<code>melt(df, id.vars = 'class') %>%
  ggplot(aes(y=value, x=class)) +
  geom_bar(aes(fill = variable),stat = "identity",position = "dodge")
</code>```

Output

Data

```<code>df <-
  structure(list(
    class = c("a", "b", "c", "d"),
    boys = c(20L, 40L,
             50L, 30L),
    girls = c(30L, 30L, 50L, 70L)
  ),
  class = "data.frame",
  row.names = c(NA,-4L))
</code>```

Body:
I have dataset below and would like to have the results in the picture attached using ggplot.

bar_df

class   boys  girls
  a     20     30
  b     40     30
  c     50     50
  d     30     70

I tried code below

bar_df <- melt(bar_df, id.vars = 'class')

ggplot(bar_df,aes(x = variable,y = value)) +
  geom_bar(aes(fill = variable),stat = "identity",position = "dodge")

Body:
Another option is to use pivot_longer from tidyverse.

library(tidyverse)

df %>%
  pivot_longer(-class) %>%
  ggplot(aes(fill=name, y=value, x=class)) +
  geom_bar(position="dodge", stat="identity")

Or with melt (as shown by @r2evans):

melt(df, id.vars = 'class') %>%
  ggplot(aes(y=value, x=class)) +
  geom_bar(aes(fill = variable),stat = "identity",position = "dodge")

Output

Data

df <-
  structure(list(
    class = c("a", "b", "c", "d"),
    boys = c(20L, 40L,
             50L, 30L),
    girls = c(30L, 30L, 50L, 70L)
  ),
  class = "data.frame",
  row.names = c(NA,-4L))


问:
How to get a variable type in Typescript?
I have a variable.

```<code>abc:number|string;
</code>```

How can I check its type? I want to do something like below:

```<code>if (abc.type === "number") {
    // do something
}
</code>```

答:
I have searched a lot how to check if my string variable is equal to my type and didn't found anything meaningful because any type of interface is not exist in runtime.
So we need have this in runtime.
There is solution that I figure out for my case.</p>
```<code>type MyType = 'one'|'two';
function isMyType(val: string): val is MyType {
    const list:MyType[] = ['one','two'];
    return list.includes(val as MyType);
}
...
const incomingValue = 'one';
if(isMyType(incomingValue)) {
    // here typescript see incomingValue as MyType
}
</code>```

Body:
I have a variable.

abc:number|string;

How can I check its type? I want to do something like below:

if (abc.type === "number") {
    // do something
}

Body:
I have searched a lot how to check if my string variable is equal to my type and didn't found anything meaningful because any type of interface is not exist in runtime.
So we need have this in runtime.
There is solution that I figure out for my case.

type MyType = 'one'|'two';
function isMyType(val: string): val is MyType {
    const list:MyType[] = ['one','two'];
    return list.includes(val as MyType);
}
...
const incomingValue = 'one';
if(isMyType(incomingValue)) {
    // here typescript see incomingValue as MyType
}


问:
VBA Opening a Word document from info in excell cell but dont have full file name
I have a list of document IDS in excel each in an individaul cell.

In the same folder as my excel sheet are the documents which are all named something like 0001 Issue 2, 0002 Issue 1 etc.

Currently I have it set up with a command button where the user selects the cell they want hits the button and it opens, however I have to have the full name of the file in the cell e.g. 0002 Issue 1.

I ideally would like it to work if just the first 4 digits of the file name was in the cell e.g. 0001 so that if a new issue is released the file doesnt need to be updated.

Ive tried using * as wild cards in lots of differnt locations, none of which worked for me. I also tried instead of using the TextBox1.Value I typed the first 4 digits and then * and that didnt work.

Also if it matters I cant guarantee how many characters will come after the first 4 digits, it can vary.

This is what I have so far with regards to the code.

```<code>Private Sub CommandButton1_Click()

Set wordapp = CreateObject("word.application")
wordapp.documents.Open ThisWorkbook.Path & "\" & TextBox1.Value & ".docx"
wordapp.Visible = True

End Sub

Private Sub TextBox1_Change()

End Sub

Private Sub UserForm_Initialize()

TextBox1.Value = ActiveCell.Value

End Sub
</code>```

答:
The Open method doesn't support wildcards, so you need to first use (eg) Dir() to identify a matching file (ie. file name starts with textbox content and has a docx extension).

Edit: added handling multiple matched files

Private Sub CommandButton1_Click()
    Dim allFiles As Collection, f, txt

    txt = TextBox1.Value
    'find any matching files....
    Set allFiles = FileMatches(ThisWorkbook.Path & "\", _
                               txt & "*.docx")

    If allFiles.Count > 0 Then        'any files found?
        With CreateObject("word.application")
            .Visible = True
            For Each f In allFiles    'loop and open found files
                .documents.Open pth & f
            Next f
        End With
    Else
        MsgBox "No file found with name beginning '" & txt & "'", vbExclamation
    End If
End Sub

'return all files whose name matches `pattern` in folder `fPath`
Function FileMatches(fPath As String, pattern As String) As Collection
    Dim rv As New Collection, f
    If Right(fPath, 1) <> "\" Then fPath = fPath & "\" 'ensure ends with "\"
    f = Dir(fPath & pattern, vbNormal)
    Do While Len(f) > 0
        rv.Add fPath & f 'add full path to the collection
    Loop
    Set FileMatches = rv
End Function
```

Body:
I have a list of document IDS in excel each in an individaul cell.

In the same folder as my excel sheet are the documents which are all named something like 0001 Issue 2, 0002 Issue 1 etc.

Currently I have it set up with a command button where the user selects the cell they want hits the button and it opens, however I have to have the full name of the file in the cell e.g. 0002 Issue 1.

I ideally would like it to work if just the first 4 digits of the file name was in the cell e.g. 0001 so that if a new issue is released the file doesnt need to be updated.

Ive tried using * as wild cards in lots of differnt locations, none of which worked for me. I also tried instead of using the TextBox1.Value I typed the first 4 digits and then * and that didnt work.

Also if it matters I cant guarantee how many characters will come after the first 4 digits, it can vary.

This is what I have so far with regards to the code.

Private Sub CommandButton1_Click()

Set wordapp = CreateObject("word.application")
wordapp.documents.Open ThisWorkbook.Path & "\" & TextBox1.Value & ".docx"
wordapp.Visible = True

End Sub

Private Sub TextBox1_Change()

End Sub

Private Sub UserForm_Initialize()

TextBox1.Value = ActiveCell.Value

End Sub


问:
Denying a permission to a specific library/module
We use this SDK within our app. It's imported as its own module, and is packaged as a .AAR file. Last year, our app was removed from the Play Store multiple times for uploading contact information without displaying a prominent disclosure. This SDK was to blame for some of these removals. Our response was to remove all contact-related features from our app and to remove the READ_CONTACTS permission in both our app's AndroidManifest and the SDK's AndroidManifest. However, now we're reimplementing these contact-related features, so we can't remove this permission in our app's AndroidManifest any more. We need our app to have this permission, but the SDK must not have it.

My question is this: if our app has READ_CONTACTS permission, does that also grant this permission to the SDK? Or does the SDK's AndroidManifest need to explicitly include the READ_CONTACTS permission in order to be able to use it?

答:
We need our app to have this permission, but the SDK must not have it.

That is not a thing, sorry.

if our app has READ_CONTACTS permission, does that also grant this permission to SDK?

Yes. There is no difference between a library and code that you typed in yourself.


问:
Function not working properly inside a class instance
I have this module which stores a class, an instance of that class, a counter, and a dictionary:

```<code>#test_module.py:

class TestClass:
    def __init__(self, name='name', attr='attr'):
        self.name = name
        self.attr = attr
    def func(self, test_list):
        test_dict[count] = test_list[-1].name + '_' + test_list[-1].attr

test_inst = TestClass()

count = 0
test_dict = {}
</code>```

What I want is for the dictionary to store each consecutive value of the counter (1,2,3...) as a key and the name and attribute of the last class instance in a test_list. (All the code here is simplified for the sake of reproducing the problem, the actual number of classes and instances is greater).

In a notebook, I have the following code:

```<code>from test_module import *
test_list = []
test_list.append(test_inst)
count += 1
test_list_item = test_list[-1]
test_dict[count] = test_list_item.name + '_' + test_list_item.attr

test_list.append(test_inst)
count += 1
test_list_item = test_list[-1]
test_list_item.func(test_list)
</code>```

What now is in the dictionary is:
{1: 'name_attr', 0: 'name_attr'}

Why am I getting zero as the second key?
I've tried specifying the count and the test_dict as global variables in the TestClass definition, but to no avail.

All works OK if I copy the contents of the test_module into the notebook, but this is not what I'm after. My goal is to have as much code as possible in the test_module. What am I doing wrong? How can I make it work properly?

答:
I just copied your code and the output is

{1: 'name_attr', 2: 'name_attr'}
```

Body:
I have this module which stores a class, an instance of that class, a counter, and a dictionary:

#test_module.py:

class TestClass:
    def __init__(self, name='name', attr='attr'):
        self.name = name
        self.attr = attr
    def func(self, test_list):
        test_dict[count] = test_list[-1].name + '_' + test_list[-1].attr

test_inst = TestClass()

count = 0
test_dict = {}

What I want is for the dictionary to store each consecutive value of the counter (1,2,3...) as a key and the name and attribute of the last class instance in a test_list. (All the code here is simplified for the sake of reproducing the problem, the actual number of classes and instances is greater).

In a notebook, I have the following code:

from test_module import *
test_list = []
test_list.append(test_inst)
count += 1
test_list_item = test_list[-1]
test_dict[count] = test_list_item.name + '_' + test_list_item.attr

test_list.append(test_inst)
count += 1
test_list_item = test_list[-1]
test_list_item.func(test_list)

What now is in the dictionary is:
{1: 'name_attr', 0: 'name_attr'}

Why am I getting zero as the second key?
I've tried specifying the count and the test_dict as global variables in the TestClass definition, but to no avail.

All works OK if I copy the contents of the test_module into the notebook, but this is not what I'm after. My goal is to have as much code as possible in the test_module. What am I doing wrong? How can I make it work properly?


问:
Last Transaction of each day
```<code>Sales Invoice   02-01-21 10:52
Invoice 02-01-21 10:55
Sales Invoice   02-01-21 11:54
Invoice 02-01-21 12:18
 Dev Invoice    02-01-21 12:37
 Dev Invoice    02-01-21 12:41
Sales Invoice   02-01-21 13:32
Sales Invoice   03-01-21 11:50
 Dev Invoice    03-01-21 13:37
 Dev Invoice    03-01-21 13:42
Invoice 03-01-21 13:57
Sales Invoice   03-01-21 14:50
Invoice 04-01-21 9:39
 Dev Invoice    04-01-21 9:40
Sales Invoice   04-01-21 10:04
Sales Invoice   04-01-21 11:52
Sales Invoice   04-01-21 12:35
 Dev Invoice    04-01-21 13:11
Sales Invoice   04-01-21 14:04
Sales Invoice   04-01-21 14:40
Sales Invoice   04-01-21 15:49
Sales Invoice   04-01-21 16:24
Sales Invoice   05-01-21 9:21
Invoice 05-01-21 10:15
Sales Invoice   05-01-21 10:53
Invoice 05-01-21 10:55
Sales Invoice   05-01-21 10:58
Invoice 05-01-21 12:32
Invoice 05-01-21 12:37
 Dev Invoice    05-01-21 13:01
Invoice 05-01-21 13:57
Sales Invoice   05-01-21 14:47
Sales Invoice   05-01-21 16:23
Invoice       05-01-21 16:54
 Dev Invoice    06-01-21 10:55
Sales Invoice   06-01-21 11:04
Sales Invoice   06-01-21 12:43
Sales Invoice   01-02-21 9:29
Sales Invoice   01-02-21 9:40
</code>```

i have Data set as above and i want to extract the last Transact for each day,the data has transactions for a year
i used the below code

```<code>df = pd.read_csv("C:\\Users\\user\\Documents\\TransactionsByTenderTypeCSV.csv")
df['DateCreated'] = pd.to_datetime(df['DateCreated'], format='%Y-%m-%d %H:%M')

df.sort_values(by ='DateCreated',ascending=True).apply

dfFandL=df.groupby(df['DateCreated'].dt.date).apply(lambda x: x.iloc[np.r_[:,-1:0]])
</code>```

but for Some reason the code only works for the 1st 4 months of data and the last 3 months ,some times it does not give the correct last transaction

答:
When i run you code I get an error because it seems the formatting in the to_datetime function is not coherent with your data. To read it correctly I had to use this:

```<code>df['DateCreated'] = pd.to_datetime(df['DateCreated'], format='%d-%m-%y %H:%M')
</code>```

Nevertheless, I would change approach and separate the date from the time:

```<code>df['Dates'] = pd.to_datetime(df['DateCreated']).dt.date
df['Time'] = pd.to_datetime(df['DateCreated']).dt.time
df.groupby('Dates').max()
</code>```

Title: Last Transaction of each day

Body:
Sales Invoice   02-01-21 10:52
Invoice 02-01-21 10:55
Sales Invoice   02-01-21 11:54
Invoice 02-01-21 12:18
 Dev Invoice    02-01-21 12:37
 Dev Invoice    02-01-21 12:41
Sales Invoice   02-01-21 13:32
Sales Invoice   03-01-21 11:50
 Dev Invoice    03-01-21 13:37
 Dev Invoice    03-01-21 13:42
Invoice 03-01-21 13:57
Sales Invoice   03-01-21 14:50
Invoice 04-01-21 9:39
 Dev Invoice    04-01-21 9:40
Sales Invoice   04-01-21 10:04
Sales Invoice   04-01-21 11:52
Sales Invoice   04-01-21 12:35
 Dev Invoice    04-01-21 13:11
Sales Invoice   04-01-21 14:04
Sales Invoice   04-01-21 14:40
Sales Invoice   04-01-21 15:49
Sales Invoice   04-01-21 16:24
Sales Invoice   05-01-21 9:21
Invoice 05-01-21 10:15
Sales Invoice   05-01-21 10:53
Invoice 05-01-21 10:55
Sales Invoice   05-01-21 10:58
Invoice 05-01-21 12:32
Invoice 05-01-21 12:37
 Dev Invoice    05-01-21 13:01
Invoice 05-01-21 13:57
Sales Invoice   05-01-21 14:47
Sales Invoice   05-01-21 16:23
Invoice       05-01-21 16:54
 Dev Invoice    06-01-21 10:55
Sales Invoice   06-01-21 11:04
Sales Invoice   06-01-21 12:43
Sales Invoice   01-02-21 9:29
Sales Invoice   01-02-21 9:40

i have Data set as above and i want to extract the last Transact for each day,the data has transactions for a year
i used the below code

df = pd.read_csv("C:\\Users\\user\\Documents\\TransactionsByTenderTypeCSV.csv")
df['DateCreated'] = pd.to_datetime(df['DateCreated'], format='%Y-%m-%d %H:%M')

df.sort_values(by ='DateCreated',ascending=True).apply

dfFandL=df.groupby(df['DateCreated'].dt.date).apply(lambda x: x.iloc[np.r_[:,-1:0]])

but for Some reason the code only works for the 1st 4 months of data and the last 3 months ,some times it does not give the correct last transaction

Body:
When i run you code I get an error because it seems the formatting in the to_datetime function is not coherent with your data. To read it correctly I had to use this:

df['DateCreated'] = pd.to_datetime(df['DateCreated'], format='%d-%m-%y %H:%M')

Nevertheless, I would change approach and separate the date from the time:

df['Dates'] = pd.to_datetime(df['DateCreated']).dt.date
df['Time'] = pd.to_datetime(df['DateCreated']).dt.time
df.groupby('Dates').max()