问:
How to have a Gitlab CI Pipeline run some jobs always and other jobs only on merge-requests?
TL/DR:
My goal is to have a Gitlab (CE-12.4.2) pipeline that executes some jobs only on merge-requests and other jobs always (on merge-requests and on all normal pushes). How must the .gitlab-ci.yml look to do this?

My use-case:
I have a big pipeline running a lot of jobs (tests, validation, dep's, build, doc's, ...). Now I have added a staging environment (using kubernetes) and have the pipeline build a new image and deploy that in the staging-environment. This allows me to instantly open up the changed (web-)application and see how the changes behave and look without having to check them out locally. Now building an image and deploying it to staging would be much too resource-heavy to do for every push, so I only want deployments to staging when someone creates a merge-request for me to review.

A very simplified example:

```<code>install:
  script: ...

test:
  script: ...

build-image:
  script: ...
  only: [merge_requests]

deploy-staging:
  script: ...
  only: [merge_requests]
</code>```

For all normal pushes, the jobs install and test should be executed.

For merge-requests, the jobs install, test, build-image and deploy-staging should be executed.

What i have tried: Gitlab has this feature to define only: [merge_requests] on a job, this causes that job to only be executed when the pipeline is executed for a merge-request. Sounds like exactly what I am looking for, but there is a big catch. Once that attribute is applied to one job in a pipeline, all other jobs in that pipeline that do not have that attribute will be removed from the pipeline when executed inside merge-requests. That seemed like a bug to me at first, but is actually documented behaviour:

```<code>In the above example, the pipeline contains only a test job. Since the build and deploy jobs don’t have the only: [merge_requests] parameter, they will not run in the merge request.
</code>```

In order to re-introduce all the other jobs to the pipeline for merge-requests, I have to apply only: [merge_requests] to all other jobs. The problem with that approach is that now these regular jobs do not get executed for normal git-pushes anymore. And I have no way to re-introduce these regular jobs to pipelines for normal pushes, because Gitlab has no support for only: [always] or anything like that.

Now I also have noticed that the only syntax is candidate for deprecation and one should prefer the rules syntax instead, so I took a look at that. There are multiple problems with that approach:

The only way to detect with rules whether the pipeline is executed for a merge-request or not is to evaluate the variables related to merge-requests, like $CI_MERGE_REQUEST_ID. Unfortunately these variables only exist when only: [merge_requests] is used, which would re-introduce the above problems.

Rules only allow the conditional application of other attributes, so I still would have to use only, except or when attributes to actually remove or add jobs from or to the pipeline. Unfortunately Gitlab does not support anything like only: [never] or when: never, so i have no way to actually remove or add the jobs.

I also tried to have the jobs depend on another using need or dependencies attributes, this seemed to have no effect on whether the job is included to the pipeline or not.

The last thing I desperately tried was including all jobs always and just mark them as when: manual to be triggered manually by pushing a button. This somewhat works, but is very tedious because the deployment to staging is a multi-job process with every job taking quite some time to finish. So I would see a merge-request, push the button for the first job, wait 5 minutes, press the next button, wait 5 minutes again, and only then am able to use the staging. For many small merge-requests, this would take up a lot of my time and would not be a efficient solution. I also cannot just mark the first of these jobs as manual because Gitlab will then just skip that job and execute that later ones out of order (And again, needs and dependencies seem to have no effect on this when dealing with manually triggered jobs).

What i am a bit baffled about is that after searching the net, I have found nobody having the same problem. Either I am the only Gitlab User that wants to execute some jobs only for merge-requests without excluding all other jobs (which seems highly unlikely) or I am missing something obvious (which seems more likely). Am I missing something or does Gitlab really not support this use-case?

答:
I had the same problem.

As described on the GitLab Docs you have to configure your entrire pipeline to run in merge requests pipelines.

This can be achieved by adding following on top of the .gitlab-ci.yml.

```<code>workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
</code>```

Hope I could help!

Body:
TL/DR:
My goal is to have a Gitlab (CE-12.4.2) pipeline that executes some jobs only on merge-requests and other jobs always (on merge-requests and on all normal pushes). How must the .gitlab-ci.yml look to do this?

My use-case:
I have a big pipeline running a lot of jobs (tests, validation, dep's, build, doc's, ...). Now I have added a staging environment (using kubernetes) and have the pipeline build a new image and deploy that in the staging-environment. This allows me to instantly open up the changed (web-)application and see how the changes behave and look without having to check them out locally. Now building an image and deploying it to staging would be much too resource-heavy to do for every push, so I only want deployments to staging when someone creates a merge-request for me to review.

A very simplified example:

install:
  script: ...

test:
  script: ...

build-image:
  script: ...
  only: [merge_requests]

deploy-staging:
  script: ...
  only: [merge_requests]

For all normal pushes, the jobs install and test should be executed.

For merge-requests, the jobs install, test, build-image and deploy-staging should be executed.

What i have tried: Gitlab has this feature to define only: [merge_requests] on a job, this causes that job to only be executed when the pipeline is executed for a merge-request. Sounds like exactly what I am looking for, but there is a big catch. Once that attribute is applied to one job in a pipeline, all other jobs in that pipeline that do not have that attribute will be removed from the pipeline when executed inside merge-requests. That seemed like a bug to me at first, but is actually documented behaviour:

In the above example, the pipeline contains only a test job. Since the build and deploy jobs don’t have the only: [merge_requests] parameter, they will not run in the merge request.

In order to re-introduce all the other jobs to the pipeline for merge-requests, I have to apply only: [merge_requests] to all other jobs. The problem with that approach is that now these regular jobs do not get executed for normal git-pushes anymore. And I have no way to re-introduce these regular jobs to pipelines for normal pushes, because Gitlab has no support for only: [always] or anything like that.

Now I also have noticed that the only syntax is candidate for deprecation and one should prefer the rules syntax instead, so I took a look at that. There are multiple problems with that approach:

The only way to detect with rules whether the pipeline is executed for a merge-request or not is to evaluate the variables related to merge-requests, like $CI_MERGE_REQUEST_ID. Unfortunately these variables only exist when only: [merge_requests] is used, which would re-introduce the above problems.

Rules only allow the conditional application of other attributes, so I still would have to use only, except or when attributes to actually remove or add jobs from or to the pipeline. Unfortunately Gitlab does not support anything like only: [never] or when: never, so i have no way to actually remove or add the jobs.

I also tried to have the jobs depend on another using need or dependencies attributes, this seemed to have no effect on whether the job is included to the pipeline or not.

The last thing I desperately tried was including all jobs always and just mark them as when: manual to be triggered manually by pushing a button. This somewhat works, but is very tedious because the deployment to staging is a multi-job process with every job taking quite some time to finish. So I would see a merge-request, push the button for the first job, wait 5 minutes, press the next button, wait 5 minutes again, and only then am able to use the staging. For many small merge-requests, this would take up a lot of my time and would not be a efficient solution. I also cannot just mark the first of these jobs as manual because Gitlab will then just skip that job and execute that later ones out of order (And again, needs and dependencies seem to have no effect on this when dealing with manually triggered jobs).

What i am a bit baffled about is that after searching the net, I have found nobody having the same problem. Either I am the only Gitlab User that wants to execute some jobs only for merge-requests without excluding all other jobs (which seems highly unlikely) or I am missing something obvious (which seems more likely). Am I missing something or does Gitlab really not support this use-case?

Body:
I had the same problem.

As described on the GitLab Docs you have to configure your entrire pipeline to run in merge requests pipelines.

This can be achieved by adding following on top of the .gitlab-ci.yml.

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'

Hope I could help!


来源: stackexchange

问:
I have base class which implemented IClientValidatable
I have base class(CompareAttribute) which implemented IClientValidatable

```<code>[AttributeUsage(AttributeTargets.Property)]
public class NotContainsAttribute : CompareAttribute
{
}
</code>```

I want to override method IEnumerable<ModelClientValidationRule> GetClientValidationRules

but i can't do that because it is not virtual(cannot override inherited member, because it is not marked virtual, abstract, or override).

So i just declare my own method in my NotContainsAttribute class

```<code>public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
}
</code>```

After i run the program all working like expected but i get warning in compile time that my class hides inherited member, (Warning "NotContainsAttribute" hides inherited member Use the new keyword if hiding was intended.)

But if I use new keyword

```<code>public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationNotContains (this.FormatErrorMessage(metadata.GetDisplayName()), CompareAttribute.FormatPropertyForClientValidation(this.OtherProperty));
            yield break;
        }
</code>```

In such case my method not used, base class method used instead.

I want my method to be used, without new keyword i get it used but why compiler saying that i need to use new keyword if hiding was intended?

I understand that if hiding was intended means that if you want to hide base method and use your method insteard mark it with new keyword but on practice it is really hiding my method.

May be some one may clarify that and is it good practice to declare method with the same name if that method in base class not allowed to be overridden but really you need to override it?

答:
If a method is not marked as virtual then you cannot change what that method does. Using the new keyword will rarely help you because any code that refers to the base class, rather than your class, will still use the base class's implementation.

Here is an explanation of the difference between new and override: Difference between new and override

ContentLicense: CC BY-SA 3.0

Body:
I have base class(CompareAttribute) which implemented IClientValidatable

[AttributeUsage(AttributeTargets.Property)]
public class NotContainsAttribute : CompareAttribute
{
}

I want to override method IEnumerable<ModelClientValidationRule> GetClientValidationRules

but i can't do that because it is not virtual(cannot override inherited member, because it is not marked virtual, abstract, or override).

So i just declare my own method in my NotContainsAttribute class

public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
}

After i run the program all working like expected but i get warning in compile time that my class hides inherited member, (Warning "NotContainsAttribute" hides inherited member Use the new keyword if hiding was intended.)

But if I use new keyword

public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationNotContains (this.FormatErrorMessage(metadata.GetDisplayName()), CompareAttribute.FormatPropertyForClientValidation(this.OtherProperty));
            yield break;
        }

In such case my method not used, base class method used instead.

I want my method to be used, without new keyword i get it used but why compiler saying that i need to use new keyword if hiding was intended?

I understand that if hiding was intended means that if you want to hide base method and use your method insteard mark it with new keyword but on practice it is really hiding my method.

May be some one may clarify that and is it good practice to declare method with the same name if that method in base class not allowed to be overridden but really you need to override it?


问:
RxJs : How to rethrow error from observable
I am new to RxJS. Learning observables and subjects.
I have a very simple login code divided into two files, a) auth.service.ts and b) login.component.ts

Here is login.component.ts

```<code>public login(username: string, password: string): Observable<boolean> {
const headers = { 'content-type': 'application/json' }
const reqBody = {
  "userName": username,
  "password": password
};
const body = JSON.stringify(reqBody);
const subject = new Subject<boolean>();
this.httpClient.post<IAuthToken>(this.apiUrl, body, { 'headers': headers })
  .subscribe(response => {
    if (response) {
      localStorage.setItem(this.accessTokenKey, response.access_token);
      subject.next(true);
    }
    else {
      throwError("Login request failed. Please try again later");
    }
  },
    error => {
      // TODO : Code to show invalid username password
      // this code throws error. Subscribe in the login.component.ts doesnt receive any error.
      throwError(error.error);
    });
return subject.asObservable();
</code>```

}

Here is login.component.ts code

```<code>errorMsg: string;
constructor(
    private authenticationService: AuthService
  ) {  }
async onLogin(): Promise<void> {

        this.authenticationService.login(this.loginForm.value.username,
          this.loginForm.value.password)
          .subscribe((response) => {
            this.errorMsg = null;
            if (response)
                 console.log("logged In");
          },
            error => {
              // TODO : Code to show invalid username password
              // This code doesnt execute, i.e. error is not caught.
              this.errorMsg = error.error;
              console.log(error);
            });
    }
  }
</code>```

I want to throw error for invalid username password from auth.service.ts and catch it in login.component.ts so that can bind the error to UI.
However, the throwError throws error from auth.service.ts, but the error isnt caught in login.component.html

答:
No need to subscribe in service</p>
```<code>public login(username: string, password: string): Observable<boolean> {
    const headers = { 'content-type': 'application/json' }
    const reqBody = {
        "userName": username,
        "password": password
    };
    const body = JSON.stringify(reqBody);
    return this.httpClient.post<IAuthToken>(this.apiUrl, body, { 'headers': headers })
        .pipe(map(response => {
            if (response) {
                localStorage.setItem(this.accessTokenKey, response.access_token);
                return true;
            }
        }))
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to RxJS. Learning observables and subjects.
I have a very simple login code divided into two files, a) auth.service.ts and b) login.component.ts

Here is login.component.ts

public login(username: string, password: string): Observable<boolean> {
const headers = { 'content-type': 'application/json' }
const reqBody = {
  "userName": username,
  "password": password
};
const body = JSON.stringify(reqBody);
const subject = new Subject<boolean>();
this.httpClient.post<IAuthToken>(this.apiUrl, body, { 'headers': headers })
  .subscribe(response => {
    if (response) {
      localStorage.setItem(this.accessTokenKey, response.access_token);
      subject.next(true);
    }
    else {
      throwError("Login request failed. Please try again later");
    }
  },
    error => {
      // TODO : Code to show invalid username password
      // this code throws error. Subscribe in the login.component.ts doesnt receive any error.
      throwError(error.error);
    });
return subject.asObservable();

}

Here is login.component.ts code

errorMsg: string;
constructor(
    private authenticationService: AuthService
  ) {  }
async onLogin(): Promise<void> {

        this.authenticationService.login(this.loginForm.value.username,
          this.loginForm.value.password)
          .subscribe((response) => {
            this.errorMsg = null;
            if (response)
                 console.log("logged In");
          },
            error => {
              // TODO : Code to show invalid username password
              // This code doesnt execute, i.e. error is not caught.
              this.errorMsg = error.error;
              console.log(error);
            });
    }
  }

I want to throw error for invalid username password from auth.service.ts and catch it in login.component.ts so that can bind the error to UI.
However, the throwError throws error from auth.service.ts, but the error isnt caught in login.component.html

Body:
No need to subscribe in service

public login(username: string, password: string): Observable<boolean> {
    const headers = { 'content-type': 'application/json' }
    const reqBody = {
        "userName": username,
        "password": password
    };
    const body = JSON.stringify(reqBody);
    return this.httpClient.post<IAuthToken>(this.apiUrl, body, { 'headers': headers })
        .pipe(map(response => {
            if (response) {
                localStorage.setItem(this.accessTokenKey, response.access_token);
                return true;
            }
        }))
}


问:
QmlProfiler : Plugin initialization failed: Cannot create OpenGL context
I use Qt 6.2.2 in ubuntu 20.04 and I install OpenGL like this:

```<code>sudo apt install libgl1-mesa-dev
</code>```

After I install my graphics card driver (NVDI 470.86) I get this error each time I open QtCreator IDE.

why did this happen and how can I fix this?

I cant compile examples that use qt quick like Qt Quick 3D - Custom Materials Example

QML debugging is enabled. Only use this in a safe environment.
qt.quick3d.general: Unable to find ideal GL version. QGLXContext:
Failed to create dummy context QRhiGles2: Failed to create temporary
context QRhiGles2: Failed to create context Failed to create RHI
(backend 2) Failed to initialize graphics backend for OpenGL.

output pictures:

output from glxinfo | egrep -i version

答:
Had the same problem since this morning. Not sure why this worked (any contribution is appreciated), but I solved it by adding my user to the video group and rebooting:

sudo usermod -a -G video *username*
```

Body:
I use Qt 6.2.2 in ubuntu 20.04 and I install OpenGL like this:

sudo apt install libgl1-mesa-dev

After I install my graphics card driver (NVDI 470.86) I get this error each time I open QtCreator IDE.

why did this happen and how can I fix this?

I cant compile examples that use qt quick like Qt Quick 3D - Custom Materials Example

QML debugging is enabled. Only use this in a safe environment.
qt.quick3d.general: Unable to find ideal GL version. QGLXContext:
Failed to create dummy context QRhiGles2: Failed to create temporary
context QRhiGles2: Failed to create context Failed to create RHI
(backend 2) Failed to initialize graphics backend for OpenGL.

output pictures:

output from glxinfo | egrep -i version


问:
Subset data to contain only label of columns whose names match a condition
I have the following sample data frame:

```<code>M <- c(1, 2)
S <- c(3, 4)
old_df <- data.frame(M, S)
label(old_df$M) <- "My Mathematics Variable"
label(old_df$S) <- "My Science Variable"
</code>```

And I want to filter in order to only have columns that contains "Math" in the label of the columns.

Thanks!

答:
You can use grepl:

old_df[, grepl("Math", label(old_df))]
# My Mathematics Variable
# [1] 1 2
```
<p>data</p>
<pre class="lang-r prettyprint-override"><code>library(Hmisc)
old_df <- structure(list(M = structure(c(1, 2), label = "My Mathematics Variable", class = c("labelled",
"numeric")), S = structure(c(3, 4), label = "My Science Variable", class = c("labelled",
"numeric"))), row.names = c(NA, -2L), class = "data.frame")
</code>```

Body:
I have the following sample data frame:

M <- c(1, 2)
S <- c(3, 4)
old_df <- data.frame(M, S)
label(old_df$M) <- "My Mathematics Variable"
label(old_df$S) <- "My Science Variable"

And I want to filter in order to only have columns that contains "Math" in the label of the columns.

Thanks!

Body:
You can use grepl:

old_df[, grepl("Math", label(old_df))]
# My Mathematics Variable
# [1] 1 2

data

library(Hmisc)
old_df <- structure(list(M = structure(c(1, 2), label = "My Mathematics Variable", class = c("labelled",
"numeric")), S = structure(c(3, 4), label = "My Science Variable", class = c("labelled",
"numeric"))), row.names = c(NA, -2L), class = "data.frame")


问:
Google My Business Requested entity was not found
I'm trying to implement an integration between a ERP system and Google My Business to keep store data in sync.

I have a project in the developer console. I have gained access to the GMB API and is approved by Google to use this API.

I'm using a serviceaccount and have followed the instructions from various guides.

But now I'm stuck.

I'm using the google GMB c# library to connect to GMB. I have a valid .12 file for my service account.

```<code>string MybusinessServiceScope = "https://www.googleapis.com/auth/plus.business.manage";
        String serviceAccountEmail = "myserviceaccount@myapplication-1349.iam.gserviceaccount.com";

        var certificate = new X509Certificate2(_serviceP12File, "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   Scopes = new[] { MybusinessServiceScope },
               }.FromCertificate(certificate));

        return new MybusinessService(new BaseClientService.Initializer()
           {
               HttpClientInitializer = credential,
               ApplicationName = "myapplication-1349",
           });
</code>```

When I try to List, Patch or Create locations I keep getting the same response:

Requested entity was not found. [404]

```<code>Errors [

Message[Requested entity was not found.] Location[ - ] Reason[notFound] Domain[global]

]
</code>```

Any help is appreciated

答: this error occurs when the user doesn't have access to the provided location. (invalid access token or user access has been revoked etc)</p>

Body:
I'm trying to implement an integration between a ERP system and Google My Business to keep store data in sync.

I have a project in the developer console. I have gained access to the GMB API and is approved by Google to use this API.

I'm using a serviceaccount and have followed the instructions from various guides.

But now I'm stuck.

I'm using the google GMB c# library to connect to GMB. I have a valid .12 file for my service account.

string MybusinessServiceScope = "https://www.googleapis.com/auth/plus.business.manage";
        String serviceAccountEmail = "myserviceaccount@myapplication-1349.iam.gserviceaccount.com";

        var certificate = new X509Certificate2(_serviceP12File, "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   Scopes = new[] { MybusinessServiceScope },
               }.FromCertificate(certificate));

        return new MybusinessService(new BaseClientService.Initializer()
           {
               HttpClientInitializer = credential,
               ApplicationName = "myapplication-1349",
           });

When I try to List, Patch or Create locations I keep getting the same response:

Requested entity was not found. [404]

Errors [

Message[Requested entity was not found.] Location[ - ] Reason[notFound] Domain[global]

]

Any help is appreciated


问:
Scraping elements from a Youtube video
I want to take some tags from youtube videos like the title, the number of views etc.I use BeautifulSoup for that but I want to make it faster.Here is my code:</p>

```<code>#for the title
from BeautifulSoup import BeautifulSoup
html = re.findall('content=.*>\n\n',urllib2.urlopen(link).read())
soup = BeautifulSoup(html)
print soup.prettify()

#for the number of views
soup0 = BeautifulSoup(urllib2.urlopen(link).read())
for items in soup0.findAll('strong'):
    if re.match("^[0-9]*$", str(items).strip("<strong>").rstrip("</strong>")):
        viewcount=str(strongs).strip("<strong>").rstrip("</strong>")
</code>```

答:
Use google's youtube api.

Part of their example:

```<code>def PrintEntryDetails(entry):
   print 'Video title: %s' % entry.media.title.text
   print 'Video published on: %s ' % entry.published.text
   print 'Video description: %s' % entry.media.description.text
   print 'Video category: %s' % entry.media.category[0].text
   print 'Video tags: %s' % entry.media.keywords.text
   print 'Video watch page: %s' % entry.media.player.url
   print 'Video flash player URL: %s' % entry.GetSwfUrl()
   print 'Video duration: %s' % entry.media.duration.seconds
</code>```

Title: Scraping elements from a Youtube video

Body:
I want to take some tags from youtube videos like the title, the number of views etc.I use BeautifulSoup for that but I want to make it faster.Here is my code:

#for the title
from BeautifulSoup import BeautifulSoup
html = re.findall('content=.*>\n\n',urllib2.urlopen(link).read())
soup = BeautifulSoup(html)
print soup.prettify()

#for the number of views
soup0 = BeautifulSoup(urllib2.urlopen(link).read())
for items in soup0.findAll('strong'):
    if re.match("^[0-9]*$", str(items).strip("").rstrip("")):
        viewcount=str(strongs).strip("").rstrip("")

Body:
Use google's youtube api.

Part of their example:

def PrintEntryDetails(entry):
   print 'Video title: %s' % entry.media.title.text
   print 'Video published on: %s ' % entry.published.text
   print 'Video description: %s' % entry.media.description.text
   print 'Video category: %s' % entry.media.category[0].text
   print 'Video tags: %s' % entry.media.keywords.text
   print 'Video watch page: %s' % entry.media.player.url
   print 'Video flash player URL: %s' % entry.GetSwfUrl()
   print 'Video duration: %s' % entry.media.duration.seconds


问:
Converting Java map into ordered collection based on map values
Please note: I see that this question appears similar to this one but in that question, they are simply sorting a map. Here I need to extract keys and their values out of a map, sort them and place them, in order into another collection. And that collection must be streamable and present the elements of that stream in the order that the sorting method placed them in.

Java 11 here. I have the following POJO:

```<code>@Data // lombok generates ctor, getters, setters, etc.
public class Answer {
    private String text;
    // ... many other fields here, omitted for brevity
}
</code>```

I have a Map<Answer,Integer> that represents the number of instances for each Answer, for example:

```<code>Map<Answer,Integer> answerCounts = new HashMap<>();
answerCounts.put(answer1, 14); // answer #1 occurs 14 times
answerCounts.put(answer2, 7);
answerCounts.put(answer3, 239);
answerCounts.put(answer4, 7);
answerCounts.put(answer5, 54);
answerCounts.put(answer6, 2);
</code>```

I would like to convert this map into a collection (likely either a List or Set) where the Answer elements are ordered according to their count values in the map. In the case of "ties" (where two map keys have the same count value) then it doesn't really matter what order the Answer elements appear in, so long as they are sorted correctly according to other, non-tying elements.

So using the map example above, I'd like the output of this conversion to be a list/set that provides Answer elements in the following order:

Answer #3 (count = 239)

Answer #5 (count = 54)

Answer #1 (count = 14)

Answer #2 (count = 7)

Answer #4 (count = 7) (<-- #2 and #4 have same count so their respective order doesn't matter to me)

Answer #6 (count = 2)

Any idea how I could accomplish this? The objective is to have a collection that I can then stream over (someCollection.stream()...) and process elements in order of how they appear in the "counts map".

答:
Use a LinkedHashMap instead of a Map. The difference is that the first one has an order, so when you sort it it will remain sorted (until you modify or add new elements)

By the way, you can stream over a Map

```<code>answerCounts.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByValue())
  .forEach(System.out::println);
</code>```

This will sort the Map but in the wrong order, and i can't find a way to reverse it

Body:
Please note: I see that this question appears similar to this one but in that question, they are simply sorting a map. Here I need to extract keys and their values out of a map, sort them and place them, in order into another collection. And that collection must be streamable and present the elements of that stream in the order that the sorting method placed them in.

Java 11 here. I have the following POJO:

@Data // lombok generates ctor, getters, setters, etc.
public class Answer {
    private String text;
    // ... many other fields here, omitted for brevity
}

I have a Map<Answer,Integer> that represents the number of instances for each Answer, for example:

Map<Answer,Integer> answerCounts = new HashMap<>();
answerCounts.put(answer1, 14); // answer #1 occurs 14 times
answerCounts.put(answer2, 7);
answerCounts.put(answer3, 239);
answerCounts.put(answer4, 7);
answerCounts.put(answer5, 54);
answerCounts.put(answer6, 2);

I would like to convert this map into a collection (likely either a List or Set) where the Answer elements are ordered according to their count values in the map. In the case of "ties" (where two map keys have the same count value) then it doesn't really matter what order the Answer elements appear in, so long as they are sorted correctly according to other, non-tying elements.

So using the map example above, I'd like the output of this conversion to be a list/set that provides Answer elements in the following order:

Answer #3 (count = 239)

Answer #5 (count = 54)

Answer #1 (count = 14)

Answer #2 (count = 7)

Answer #4 (count = 7) (<-- #2 and #4 have same count so their respective order doesn't matter to me)

Answer #6 (count = 2)

Any idea how I could accomplish this? The objective is to have a collection that I can then stream over (someCollection.stream()...) and process elements in order of how they appear in the "counts map".

Body:
Use a LinkedHashMap instead of a Map. The difference is that the first one has an order, so when you sort it it will remain sorted (until you modify or add new elements)

By the way, you can stream over a Map

answerCounts.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByValue())
  .forEach(System.out::println);

This will sort the Map but in the wrong order, and i can't find a way to reverse it


问:
Add leading zeros to integer section of filename
I have folders of images with names like HolidaySnapsJune-1.tif , HolidaySnapsMay-12.tif and HolidaySnaps2018-005.tif

I want to add one leading 0 to the integer section of the filename if it is 2 digits long, and I want to add two leading 00s if it is just one digit long.

I have tried variations of

```<code>find . -name '*\_[0-9][0-9].tif' -exec sh -c '
for fpath do
  echo mv "$fpath" "${fpath%/*}/${fpath##*/}"
done' _ {} +
</code>```

But these put the leading zeros in front of the full file name instead of in front of the integer section.

I would love to do this is a bash script which would recursively work on folders so it's important that the difference in names preceeding the '-' is ignored or worked-around.

I'm on Windows and just have access to whatever is built into git-bashso bash, sed, awk etc.

答:
You could use the rename.ul command from linux-utils.

```<code>rename [options] expression replacement file...
</code>```

replaces the first occurence of expression by replacement in all names of files passed to the command.

Assuming your filenames contain exactly one hyphen -, you could simply run both of the following commands in a shell that supports the **/* glob syntax (alternatively, use find with the -exec option or something alike) to recursively rename all files:

```<code>rename.ul -- - -00  **/*-?.tif
rename.ul -- - -0  **/*-??.tif
</code>```

There are several options to rename.ul to prevent you from accidentally renaming unintended files (Watch out! The consequences could be quite drastic):

-v, --verbose
       Show which files were renamed, if any.

-n, --no-act
       Do not make any changes; add --verbose to see what  would
       be made.

-i, --interactive
       Ask before overwriting existing files.
```

So you could either run the commands with the -nv options to perform a dry-run and see what changes the program would make, or add -i to be asked for confirmation each time a file would be renamed.

Body:
I have folders of images with names like HolidaySnapsJune-1.tif , HolidaySnapsMay-12.tif and HolidaySnaps2018-005.tif

I want to add one leading 0 to the integer section of the filename if it is 2 digits long, and I want to add two leading 00s if it is just one digit long.

I have tried variations of

find . -name '*\_[0-9][0-9].tif' -exec sh -c '
for fpath do
  echo mv "$fpath" "${fpath%/*}/${fpath##*/}"
done' _ {} +

But these put the leading zeros in front of the full file name instead of in front of the integer section.

I would love to do this is a bash script which would recursively work on folders so it's important that the difference in names preceeding the '-' is ignored or worked-around.

I'm on Windows and just have access to whatever is built into git-bashso bash, sed, awk etc.

Body:
You could use the rename.ul command from linux-utils.

rename [options] expression replacement file...

replaces the first occurence of expression by replacement in all names of files passed to the command.

Assuming your filenames contain exactly one hyphen -, you could simply run both of the following commands in a shell that supports the **/* glob syntax (alternatively, use find with the -exec option or something alike) to recursively rename all files:

rename.ul -- - -00  **/*-?.tif
rename.ul -- - -0  **/*-??.tif

There are several options to rename.ul to prevent you from accidentally renaming unintended files (Watch out! The consequences could be quite drastic):

-v, --verbose
       Show which files were renamed, if any.

-n, --no-act
       Do not make any changes; add --verbose to see what  would
       be made.

-i, --interactive
       Ask before overwriting existing files.

So you could either run the commands with the -nv options to perform a dry-run and see what changes the program would make, or add -i to be asked for confirmation each time a file would be renamed.


问:
I want to do ternary operation like below code but code is not working fine
When I change f7 value it will perform correctly till second condition but third and fourth condition does not trigger. What can I do please help me it stop on second condition?

```<code>var f7 = 5;
var g7 = (f7 <= 3 ? 100 : (2 <= f7 < 4 ? 75 : (4 <= f7 < 5 ? 60 : (5 <= f7 < 6 ? 40 : 15))));
console.log(g7);
</code>```

答:
thanks @cid my calculations are done
2 <= f7 && f7 < 4
i use above code to do thanks

```<code>var g7 = f7 <= 3 ? 100
: 2 <= f7 && f7 < 4 ? 75
: 4 <= f7 && f7 < 5 ? 60
: 5 <= f7 && f7 < 6 ? 40
: 15;

</code>```

Body:
When I change f7 value it will perform correctly till second condition but third and fourth condition does not trigger. What can I do please help me it stop on second condition?

var f7 = 5;
var g7 = (f7 <= 3 ? 100 : (2 <= f7 < 4 ? 75 : (4 <= f7 < 5 ? 60 : (5 <= f7 < 6 ? 40 : 15))));
console.log(g7);

Body:
thanks @cid my calculations are done
2 <= f7 && f7 < 4
i use above code to do thanks

var g7 = f7 <= 3 ? 100
: 2 <= f7 && f7 < 4 ? 75
: 4 <= f7 && f7 < 5 ? 60
: 5 <= f7 && f7 < 6 ? 40
: 15;


问:
Which GSheet API should I pick to request consent
We have an application that needs to append data to users' designated Gsheet.
They should enter the sheet ID on our app, authorize it and then click export. Our app would then append a new row of data.
We are not clear what is the best or the necessary Oath 2 scope that is appropriate for that.

https://www.googleapis.com/auth/drive.file
or

https://www.googleapis.com/auth/spreadsheets

Any help is appreciated.

答:
What you should do is check the documentation for what ever method you are trying to use.  I am going to guess that you are using Method: spreadsheets.values.update

This method requires one of the following scopes

Which one you pick is up to you.  They will both work. Technically if your not going to be accessing any of the google drive api methods then there's probably no reason to use the drive scope.

You can check the scopes#Sheets documentation for information on exactly what each scope gives you access to.

As you can see the sheets scope gives you access to all sheets a user has, while the drive.file scope will only give you access to files that where created by your app.  Not just sheets.


问:
Telerik MVC Grid: How to use DropDownList in a column?
I have a Telerik MVC grid, in an MVC 3 application with Razor, which is being Ajax-bound. I am now trying to add a drop list column to it, so that users can use it in edit mode, but can't figure out how. The grid displays a list of Products, and I want the drop list to contain a collection of ProductCategories, to which the Product can be associated. I've been at this for hours now and I'm out of ideas. I really hope someone here can help :)

I have been referencing a Telerik demo, which is located here.

I think the part that is hanging me up is in a help view that the demo uses. In the demo, this is called "ClientEmployee(Editor)." In my case, I've placed the helper in a file called  "ProductCategoryDropList.cshtml". In this helper, I'm having a tough time getting the DropDownList to bind correctly. I think this might be because I'm not setting up the BindTo() method with the right data somehow. I've marked this point of confusion in the sample DropDownList Helper code, below, with "SomeCollectionReference," as the first parameter in a "new SelectList()" constructor call. When I try to put "Model" in that spot, I get a NullReferecne exception. When I try to access ViewBag data containing the list, I get a message similar to "the SelectList doesn't have a ProductCategoryID column," or something like that. So, I'm not sure what else to try.

I'm not sure how clear this description of my problem is, but in an effort to be complete, I've included the code that I think is relevant below.

Controller:

```<code>public ActionResult Index()
{
    ViewBag.ProductCategories = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductcategoryName");
    var products = _productService.GetProducts().ToList();
    var presentationModel = _mapper.MapAsList(products);
    return View(presentationModel);
}

//
// GET: /Product/
[GridAction]
public ViewResult _Index()
{
    ViewBag.ProductCategories = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductcategoryName");
    return View(new GridModel<ProductPresentationModel>
                    {
                        Data = _mapper.MapAsList(_productService.GetProducts().ToList())
                    });
}
</code>```

View:

This is a bit long, but I've tried to simplify it by placing "// <--- DropList Here" next to the column that I am trying to work with.

```<code>@model IEnumerable<Models.PresentationModels.ProductPresentationModel>

@(Html.Telerik().Grid(Model).HtmlAttributes(new { style = "width: 100%;" })
        // Give the Grid an HTML id attribute value
        .Name("ProductGrid")
        // Establish the promiry key, to be used for Insert, Update, and Delete commands
        .DataKeys(dataKeys => dataKeys.Add(p => p.ProductID))
        // Add an Insert command to the Grid Toolbar
        .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText))
        // Using Ajax Data Binding to bind data to the grid
        .DataBinding(dataBinding => dataBinding
                // Ajax Binding
                .Ajax()
                    .Select("_Index", "Product")
                    // Home.Insert inserts a new data record
                    .Insert("Create", "Product")
                    // Home.Update updates an existing data record
                    .Update("Edit", "Product")
                    // Home.Delete deletes an existing data record
                    .Delete("Delete", "Product")
        )
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductName).Width(120);
            columns.Bound(p => p.ProductDescription).Width(150);
            columns.Bound(p => p.PricePerMonth).Width(120);
            columns.Bound(p => p.ProductImagePath).Width(150)
            columns.Bound(p => p.ProductActive).Width(120)
                .ClientTemplate("<input type='checkbox' disabled='disabled' name='Active' <#= ProductActive ? checked='checked' : '' #> />");
            columns.Bound(p => p.ProductCategoryName); // <--- DropList Here
            columns.Command(commands =>
            {
                commands.Edit().ButtonType(GridButtonType.Image);
                commands.Delete().ButtonType(GridButtonType.Image);
            });
        })
        .Editable(editing => editing.Mode(GridEditMode.PopUp))
        .ClientEvents(events => events.OnEdit("onEdit"))
        .Pageable()
        .Scrollable()
        .Sortable()
        .Filterable()
)

@section HeadContent {
    <script type="text/javascript">
        function onEdit(e) {
            $(e.form).find('#ProductCategoryName').data('tDropDownList').select(function (dataItem) {
                return dataItem.Text == e.dataItem['ProductCategoryName'];
            });
        }
    </script>
}
</code>```

Model:

```<code>[DisplayName(@"Category Name")]
[UIHint("ProductCategoryDropList"), Required]
[StringLength(255, ErrorMessage = @"Product Category Name cannot be more than 255 characters in length")]
public string ProductCategoryName
{
    get
    {
        string name = string.Empty;

        if (_model.ProductCategory != null)
        {
            name = _model.ProductCategory.ProductCategoryName;
        }

        return name;
    }
    set
    {
        if (_model.ProductCategory != null)
        {
            _model.ProductCategory.ProductCategoryName = value;
        }
    }
}
</code>```

DropList Helper:

```<code>@model Models.PresentationModels.ProductPresentationModel

@(Html.Telerik().DropDownList()
        .Name("ProductCategoryName")
            .BindTo(new SelectList(<SomeCollectionReference>, "ProductCategoryID", "ProductCategoryName"))
)
</code>```

ProductMapper:

```<code>public List<ProductPresentationModel> MapAsList(List<Product> products)
{
    //var categoryList = new SelectList(_productCategoryService.GetProductCategories().ToList(), "ProductCategoryID", "ProductCategoryName");

    var presentationModels = products
            .Select(x => new ProductPresentationModel()
            {
                ProductID = x.ProductID,
                ProductCategoryID = ((x.ProductCategory != null) ? x.ProductCategory.ProductCategoryID : 0),
                ProductCategoryName = ((x.ProductCategory != null) ? x.ProductCategory.ProductCategoryName : String.Empty),
                ProductName = x.ProductName,
                ProductDescription = x.ProductDescription,
                PricePerMonth = x.PricePerMonth,
                ProductImagePath = x.ProductImagePath,
                ProductActive = x.ProductActive,
                ProductCategories = new SelectList(_productCategoryService.GetProductCategories().ToList(), "ProductCategoryID", "ProductCategoryName")//categoryList
            }).ToList();

    return presentationModels;
}
</code>```

答:
I managed to work this out, somewhat, but I still have a question. here's what I changed to get it working:

Created a ViewData object in the controller, like this ...

```<code>public ActionResult Index()
{
    // ViewData object here ...
    ViewData["ProductCategories"] = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductCategoryName");
    var products = _productService.GetProducts().ToList();
    var presentationModel = _mapper.MapAsList(products);
    return View(presentationModel);
}

//
// GET: /Product/
[GridAction]
public ViewResult _Index()
{
    // ViewData object here ...
    ViewData["ProductCategories"] = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductCategoryName");
    return View(new GridModel<ProductPresentationModel>
                    {
                        Data = _mapper.MapAsList(_productService.GetProducts().ToList())
                    });
}
</code>```

Then, I used the ViewData object in the DropDownListHelper, like this ...

```<code>@using System.Collections
@model Models.PresentationModels.ProductPresentationModel

@(Html.Telerik().DropDownList()
        .Name("ProductCategoryName")
        .BindTo(new SelectList((IEnumerable)ViewData["ProductCategories"], "Value", "Text"))
);
</code>```

My question now is ... do I have to use the ViewData object? I'd love to be able to use a property off of my model. But, for some reason my Model is always NULL inside the Helper file. And, if I try to place the DropDownList code inside the Grid creation code, the DropDownList doesn't work at all.

So, do I have any other options?

Body:
I have a Telerik MVC grid, in an MVC 3 application with Razor, which is being Ajax-bound. I am now trying to add a drop list column to it, so that users can use it in edit mode, but can't figure out how. The grid displays a list of Products, and I want the drop list to contain a collection of ProductCategories, to which the Product can be associated. I've been at this for hours now and I'm out of ideas. I really hope someone here can help :)

I have been referencing a Telerik demo, which is located here.

I think the part that is hanging me up is in a help view that the demo uses. In the demo, this is called "ClientEmployee(Editor)." In my case, I've placed the helper in a file called  "ProductCategoryDropList.cshtml". In this helper, I'm having a tough time getting the DropDownList to bind correctly. I think this might be because I'm not setting up the BindTo() method with the right data somehow. I've marked this point of confusion in the sample DropDownList Helper code, below, with "SomeCollectionReference," as the first parameter in a "new SelectList()" constructor call. When I try to put "Model" in that spot, I get a NullReferecne exception. When I try to access ViewBag data containing the list, I get a message similar to "the SelectList doesn't have a ProductCategoryID column," or something like that. So, I'm not sure what else to try.

I'm not sure how clear this description of my problem is, but in an effort to be complete, I've included the code that I think is relevant below.

Controller:

public ActionResult Index()
{
    ViewBag.ProductCategories = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductcategoryName");
    var products = _productService.GetProducts().ToList();
    var presentationModel = _mapper.MapAsList(products);
    return View(presentationModel);
}

//
// GET: /Product/
[GridAction]
public ViewResult _Index()
{
    ViewBag.ProductCategories = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductcategoryName");
    return View(new GridModel<ProductPresentationModel>
                    {
                        Data = _mapper.MapAsList(_productService.GetProducts().ToList())
                    });
}

View:

This is a bit long, but I've tried to simplify it by placing "// <--- DropList Here" next to the column that I am trying to work with.

@model IEnumerable<Models.PresentationModels.ProductPresentationModel>

@(Html.Telerik().Grid(Model).HtmlAttributes(new { style = "width: 100%;" })
        // Give the Grid an HTML id attribute value
        .Name("ProductGrid")
        // Establish the promiry key, to be used for Insert, Update, and Delete commands
        .DataKeys(dataKeys => dataKeys.Add(p => p.ProductID))
        // Add an Insert command to the Grid Toolbar
        .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText))
        // Using Ajax Data Binding to bind data to the grid
        .DataBinding(dataBinding => dataBinding
                // Ajax Binding
                .Ajax()
                    .Select("_Index", "Product")
                    // Home.Insert inserts a new data record
                    .Insert("Create", "Product")
                    // Home.Update updates an existing data record
                    .Update("Edit", "Product")
                    // Home.Delete deletes an existing data record
                    .Delete("Delete", "Product")
        )
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductName).Width(120);
            columns.Bound(p => p.ProductDescription).Width(150);
            columns.Bound(p => p.PricePerMonth).Width(120);
            columns.Bound(p => p.ProductImagePath).Width(150)
            columns.Bound(p => p.ProductActive).Width(120)
                .ClientTemplate("<input type='checkbox' disabled='disabled' name='Active' <#= ProductActive ? checked='checked' : '' #> />");
            columns.Bound(p => p.ProductCategoryName); // <--- DropList Here
            columns.Command(commands =>
            {
                commands.Edit().ButtonType(GridButtonType.Image);
                commands.Delete().ButtonType(GridButtonType.Image);
            });
        })
        .Editable(editing => editing.Mode(GridEditMode.PopUp))
        .ClientEvents(events => events.OnEdit("onEdit"))
        .Pageable()
        .Scrollable()
        .Sortable()
        .Filterable()
)

@section HeadContent {

}

Model:

[DisplayName(@"Category Name")]
[UIHint("ProductCategoryDropList"), Required]
[StringLength(255, ErrorMessage = @"Product Category Name cannot be more than 255 characters in length")]
public string ProductCategoryName
{
    get
    {
        string name = string.Empty;

        if (_model.ProductCategory != null)
        {
            name = _model.ProductCategory.ProductCategoryName;
        }

        return name;
    }
    set
    {
        if (_model.ProductCategory != null)
        {
            _model.ProductCategory.ProductCategoryName = value;
        }
    }
}

DropList Helper:

@model Models.PresentationModels.ProductPresentationModel

@(Html.Telerik().DropDownList()
        .Name("ProductCategoryName")
            .BindTo(new SelectList(<SomeCollectionReference>, "ProductCategoryID", "ProductCategoryName"))
)

ProductMapper:

public List<ProductPresentationModel> MapAsList(List<Product> products)
{
    //var categoryList = new SelectList(_productCategoryService.GetProductCategories().ToList(), "ProductCategoryID", "ProductCategoryName");

    var presentationModels = products
            .Select(x => new ProductPresentationModel()
            {
                ProductID = x.ProductID,
                ProductCategoryID = ((x.ProductCategory != null) ? x.ProductCategory.ProductCategoryID : 0),
                ProductCategoryName = ((x.ProductCategory != null) ? x.ProductCategory.ProductCategoryName : String.Empty),
                ProductName = x.ProductName,
                ProductDescription = x.ProductDescription,
                PricePerMonth = x.PricePerMonth,
                ProductImagePath = x.ProductImagePath,
                ProductActive = x.ProductActive,
                ProductCategories = new SelectList(_productCategoryService.GetProductCategories().ToList(), "ProductCategoryID", "ProductCategoryName")//categoryList
            }).ToList();

    return presentationModels;
}

Body:
I managed to work this out, somewhat, but I still have a question. here's what I changed to get it working:

Created a ViewData object in the controller, like this ...

public ActionResult Index()
{
    // ViewData object here ...
    ViewData["ProductCategories"] = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductCategoryName");
    var products = _productService.GetProducts().ToList();
    var presentationModel = _mapper.MapAsList(products);
    return View(presentationModel);
}

//
// GET: /Product/
[GridAction]
public ViewResult _Index()
{
    // ViewData object here ...
    ViewData["ProductCategories"] = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductCategoryName");
    return View(new GridModel<ProductPresentationModel>
                    {
                        Data = _mapper.MapAsList(_productService.GetProducts().ToList())
                    });
}

Then, I used the ViewData object in the DropDownListHelper, like this ...

@using System.Collections
@model Models.PresentationModels.ProductPresentationModel

@(Html.Telerik().DropDownList()
        .Name("ProductCategoryName")
        .BindTo(new SelectList((IEnumerable)ViewData["ProductCategories"], "Value", "Text"))
);

My question now is ... do I have to use the ViewData object? I'd love to be able to use a property off of my model. But, for some reason my Model is always NULL inside the Helper file. And, if I try to place the DropDownList code inside the Grid creation code, the DropDownList doesn't work at all.

So, do I have any other options?


问:
Java Streams: Find first for multiple filter predicates
I have a Collection<Product> and a Collection<Predicate<Product>>. The Predicates are a simple combination of boolean flags. For example:

```<code>             | isNew | isSoldOut
--------------------------------
predicate 1: | false | false
predicate 2: | false | true
predicate 3: | true  | false
predicate 4: | true  | true
</code>```

I want to find "one of every kind", though I'd like to find the first match for every Predicate within the products Collection.

Currently my code looks like this:

List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();

List<Product> result = predicates.stream()
  .flatMap(predicate -> products.stream().filter(predicate).findFirst().stream())
  .collect(Collectors.toList());
```

But this of course will iterate of the products Collection multiple times, which is not desired, because in my case I have 100000 Products and 64 Predicates and it takes a long time.

In my special case the Predicates are mutually exclusive: If a Predicate returns true, then all other Predicates can be skipped for that particular Product. And because I use findFirst this Predicate then can be skipped for all other Products.

I was wondering if it is possible to iterate over the Product Collection instead, and check every Product only once against all the Predicates.

答:
If I understand correctly, you're looking for something like:

List<Product> results = products.stream()
                        .filter(prod -> predicates.stream()
                                        .anyMatch(pred -> pred.test(prod)))
                        .collect(Collectors.toList());
```

Body:
I have a Collection<Product> and a Collection<Predicate<Product>>. The Predicates are a simple combination of boolean flags. For example:

             | isNew | isSoldOut
--------------------------------
predicate 1: | false | false
predicate 2: | false | true
predicate 3: | true  | false
predicate 4: | true  | true

I want to find "one of every kind", though I'd like to find the first match for every Predicate within the products Collection.

Currently my code looks like this:

List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();

List<Product> result = predicates.stream()
  .flatMap(predicate -> products.stream().filter(predicate).findFirst().stream())
  .collect(Collectors.toList());

But this of course will iterate of the products Collection multiple times, which is not desired, because in my case I have 100000 Products and 64 Predicates and it takes a long time.

In my special case the Predicates are mutually exclusive: If a Predicate returns true, then all other Predicates can be skipped for that particular Product. And because I use findFirst this Predicate then can be skipped for all other Products.

I was wondering if it is possible to iterate over the Product Collection instead, and check every Product only once against all the Predicates.


问:
Angular 13: Delete request to api with some effects
I have an frontend app that I have connected to my backend it works well but when I delete the div with post it disappears unclear, I need to add some effects to it so I can see that the post really disappears in my eyes. I know it's not hard but I'm a newbie in Angular and this is my first frontend app

Delete Post Method:

```<code>deletePost1(id:number){
    this.messageService.delete(id).subscribe(res => {
      this.messages = this.messages.filter(item => item.id !== id);
      console.log('Post deleted successfully!');
    })
  }
</code>```

delete post method from service:

```<code>delete(id: number) {
    return this.httpClient.delete(this.apiURL + 'api/message/' + id, this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
  }
</code>```

答:
You can display a message using the ngx-toaster package

First install it using npm :

```<code>npm install ngx-toastr
</code>```

Then add it to your app.module.ts

```<code>import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import { ToastrService } from 'ngx-toastr';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot({
      tapToDismiss: false,
      autoDismiss: true
    })
  ],
  providers: [
    ToastrService
  ],
  bootstrap: [AppComponent],
  schemas: []
})
export class AppModule { }

</code>```

Then in your component create deletePost() like this :

```<code>constructor(
    private toastr: ToastrService
  ) { }

deletePost1(id:number) {
    this.messageService.delete(id).subscribe(res => {
        this.messages = this.messages.filter(item => item.id !== id);
        this.toastr.success("Post deleted successfully!", 'success', { timeOut: 2500 });

    })
}

</code>```

Body:
I have an frontend app that I have connected to my backend it works well but when I delete the div with post it disappears unclear, I need to add some effects to it so I can see that the post really disappears in my eyes. I know it's not hard but I'm a newbie in Angular and this is my first frontend app

Delete Post Method:

deletePost1(id:number){
    this.messageService.delete(id).subscribe(res => {
      this.messages = this.messages.filter(item => item.id !== id);
      console.log('Post deleted successfully!');
    })
  }

delete post method from service:

delete(id: number) {
    return this.httpClient.delete(this.apiURL + 'api/message/' + id, this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
  }

Body:
You can display a message using the ngx-toaster package

First install it using npm :

npm install ngx-toastr

Then add it to your app.module.ts

import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import { ToastrService } from 'ngx-toastr';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot({
      tapToDismiss: false,
      autoDismiss: true
    })
  ],
  providers: [
    ToastrService
  ],
  bootstrap: [AppComponent],
  schemas: []
})
export class AppModule { }

Then in your component create deletePost() like this :

constructor(
    private toastr: ToastrService
  ) { }

deletePost1(id:number) {
    this.messageService.delete(id).subscribe(res => {
        this.messages = this.messages.filter(item => item.id !== id);
        this.toastr.success("Post deleted successfully!", 'success', { timeOut: 2500 });

    })
}


问:
Gitlab Static Application Security Testing (SAST) fails with permission denied
I am trying to add Static Application Security Testing (SAST) to my ci/cd yaml file.
But when I run it after adding the template Security/SAST.gitlab-ci.yml as instructed in

it fails with this log

```<code>[ERRO] [Find Security Bugs] [2022-01-06T13:20:34Z] ▶ Project couldn't be built: Command couldn't be executed: fork/exec /builds/Hoshani/my-awesome-project/mvnw: permission denied

[FATA] [Find Security Bugs] [2022-01-06T13:20:34Z] ▶ Command couldn't be executed: fork/exec /builds/Hoshani/my-awesome-project/mvnw: permission denied
</code>```

here is the yaml file for your reference

variables:
  MAVEN_OPTS: "-Dhttps.protocols=TLSv1.2 -Dmaven.repo.local=$CI_PROJECT_DIR/.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true"
  MAVEN_CLI_OPTS: "--batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=true -DdeployAtEnd=true"

image: maven:3.8.1

cache:
  paths:
    - .m2/repository

stages:
  - build
  - test
  - deploy

build-job:
  stage: build
  script:
    - mvn clean install

include:
  - template: Security/SAST.gitlab-ci.yml
  - template: Jobs/SAST-IaC.latest.gitlab-ci.yml

unit-test-job:
  stage: test
  script:
    - mvn test
  artifacts:
    when: always
    reports:
      junit:
        - target/surefire-reports/TEST-*.xml
```

any help is appreciated, thanks

答:
As a quick solution, simply adding execution permission on mvnw will fix this.

```<code>chmod a+x mvnw
</code>```

For more details, refer here

Body:
I am trying to add Static Application Security Testing (SAST) to my ci/cd yaml file.
But when I run it after adding the template Security/SAST.gitlab-ci.yml as instructed in

it fails with this log

[ERRO] [Find Security Bugs] [2022-01-06T13:20:34Z] ▶ Project couldn't be built: Command couldn't be executed: fork/exec /builds/Hoshani/my-awesome-project/mvnw: permission denied

[FATA] [Find Security Bugs] [2022-01-06T13:20:34Z] ▶ Command couldn't be executed: fork/exec /builds/Hoshani/my-awesome-project/mvnw: permission denied

here is the yaml file for your reference

variables:
  MAVEN_OPTS: "-Dhttps.protocols=TLSv1.2 -Dmaven.repo.local=$CI_PROJECT_DIR/.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true"
  MAVEN_CLI_OPTS: "--batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=true -DdeployAtEnd=true"

image: maven:3.8.1

cache:
  paths:
    - .m2/repository

stages:
  - build
  - test
  - deploy

build-job:
  stage: build
  script:
    - mvn clean install

include:
  - template: Security/SAST.gitlab-ci.yml
  - template: Jobs/SAST-IaC.latest.gitlab-ci.yml

unit-test-job:
  stage: test
  script:
    - mvn test
  artifacts:
    when: always
    reports:
      junit:
        - target/surefire-reports/TEST-*.xml

any help is appreciated, thanks

Body:
As a quick solution, simply adding execution permission on mvnw will fix this.

chmod a+x mvnw

For more details, refer here


问:
Why am I getting "Unhandled exception: local variable 'pwd' referenced before assignment"?
I'm trying to transfer a schema from my personal machine to RDS via Workbench. I've exported an SQL dump file and am trying to import it into RDS. However, I get the following error:

```<code>Unhandled exception: local variable 'pwd' referenced before assignment

Check the log for more details.
</code>```

The log file has this:

```<code>14:05:01 [WRN][wb_admin_export.py:process_db:277]: Task exited with code 1
14:05:01 [ERR][       pymforms]: Unhandled exception in Python code:
Traceback (most recent call last):
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1334, in _update_progress
    r = self.update_progress()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 913, in update_progress
    self.start()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1323, in start
    password = self.get_mysql_password(self.bad_password_detected)
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 963, in get_mysql_password
    if pwd is None:
UnboundLocalError: local variable 'pwd' referenced before assignment
</code>```

An earlier attempt yielded a little more detail:

```<code>14:00:24 [ERR][wb_admin_export.py:process_db:251]: Error from task: ERROR 1045 (28000): Access denied for user 'admin'@'<some_numbers_I_probably_shouldn't_share!>.skybroadband.com' (using password: YES)

14:00:24 [WRN][wb_admin_export.py:process_db:277]: Task exited with code 1
14:00:24 [ERR][       pymforms]: Unhandled exception in Python code:
Traceback (most recent call last):
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1334, in _update_progress
    r = self.update_progress()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 913, in update_progress
    self.start()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1323, in start
    password = self.get_mysql_password(self.bad_password_detected)
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 963, in get_mysql_password
    if pwd is None:
UnboundLocalError: local variable 'pwd' referenced before assignment
14:00:43 [ERR][wb_admin_utils.py:page_activated:329]: Exception activating the page - 'Label' object has no attribute 'remove_from_parent'Error from task: ERROR 1045 (28000): Access denied for user 'admin'@'<some_numbers_I_probably_shouldn't_share!> (using password: YES)
</code>```

This has confused me somewhat as I'm not using Python to transfer anything - I'm using Workbench. Clearly I have a password issue but what is it exactly and how do I fix it? I'm logged into RDS and can add or remove schemas/tables etc manually so Workbench knows what the correct passwords are...

答:
For me, the error is regarding db privilege:

mysqldump: Got error: 1044: Access denied for user 'myuser'@'%' to database 'mydb' when doing LOCK TABLES
```

You have to uncheck the lock-tables option from the "Advanced Options" available in the top right of the data exporter in MySQL Workbench.

If you're using command to export then add --lock-tables=FALSE flag.

Body:
I'm trying to transfer a schema from my personal machine to RDS via Workbench. I've exported an SQL dump file and am trying to import it into RDS. However, I get the following error:

Unhandled exception: local variable 'pwd' referenced before assignment

Check the log for more details.

The log file has this:

14:05:01 [WRN][wb_admin_export.py:process_db:277]: Task exited with code 1
14:05:01 [ERR][       pymforms]: Unhandled exception in Python code:
Traceback (most recent call last):
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1334, in _update_progress
    r = self.update_progress()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 913, in update_progress
    self.start()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1323, in start
    password = self.get_mysql_password(self.bad_password_detected)
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 963, in get_mysql_password
    if pwd is None:
UnboundLocalError: local variable 'pwd' referenced before assignment

An earlier attempt yielded a little more detail:

14:00:24 [ERR][wb_admin_export.py:process_db:251]: Error from task: ERROR 1045 (28000): Access denied for user 'admin'@'<some_numbers_I_probably_shouldn't_share!>.skybroadband.com' (using password: YES)

14:00:24 [WRN][wb_admin_export.py:process_db:277]: Task exited with code 1
14:00:24 [ERR][       pymforms]: Unhandled exception in Python code:
Traceback (most recent call last):
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1334, in _update_progress
    r = self.update_progress()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 913, in update_progress
    self.start()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1323, in start
    password = self.get_mysql_password(self.bad_password_detected)
  File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 963, in get_mysql_password
    if pwd is None:
UnboundLocalError: local variable 'pwd' referenced before assignment
14:00:43 [ERR][wb_admin_utils.py:page_activated:329]: Exception activating the page - 'Label' object has no attribute 'remove_from_parent'Error from task: ERROR 1045 (28000): Access denied for user 'admin'@'<some_numbers_I_probably_shouldn't_share!> (using password: YES)

This has confused me somewhat as I'm not using Python to transfer anything - I'm using Workbench. Clearly I have a password issue but what is it exactly and how do I fix it? I'm logged into RDS and can add or remove schemas/tables etc manually so Workbench knows what the correct passwords are...

Body:
For me, the error is regarding db privilege:

mysqldump: Got error: 1044: Access denied for user 'myuser'@'%' to database 'mydb' when doing LOCK TABLES

You have to uncheck the lock-tables option from the "Advanced Options" available in the top right of the data exporter in MySQL Workbench.

If you're using command to export then add --lock-tables=FALSE flag.


问:
JPA/Hibernate @OrderBy annotation with boolean row
I want to order by a row "pk" in attributes. But it has a boolean data. The attributes that has pk=true should go first. I just can't write @OrderBy("pk=true"). How can I make it to order by this row?</p>
```<code>public class Entity {

//here are some rows;

@OneToMany
    @JoinColumn(name = "id")
    @OrderBy("pk", "firstName")
    private Collection<Attributes> attributes;
}

public class Attributes {

    @Id
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "pk")
    private Boolean pk;
}
</code>```

答: It will sort false first, since in the database true and false are represented as 1 and 0, respectively</p>

Body:
I want to order by a row "pk" in attributes. But it has a boolean data. The attributes that has pk=true should go first. I just can't write @OrderBy("pk=true"). How can I make it to order by this row?

public class Entity {

//here are some rows;

@OneToMany
    @JoinColumn(name = "id")
    @OrderBy("pk", "firstName")
    private Collection<Attributes> attributes;
}

public class Attributes {

    @Id
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "pk")
    private Boolean pk;
}


答:
Several misconceptions here.

Firstly, throwError is a function which returns an observable that immediately errors. Simply calling it like you do doesn't do anything.

```<code>throwError(error.error); // creates an unused observable
</code>```

Secondly, you're subscribing in the service with some weird glued-together code with a subject. Your service is supposed to just create an observable, and then you subscribe to it in the component. The error would then be caught correctly by default.

```<code>// in service
logIn (username: string, password: string): Observable<boolean> {
  return this.http.post(api, { username, password })
    .pipe(mapTo(true))
}

// in component
onSubmit () {
  this.service.logIn('username', 'p@ssword')
    .subscribe({
      next: () => {
        console.log('Success!')
      },
      error: (error) => {
        console.error(error)
      }
    })
}
</code>```

throwError is usually used in conjuction with catchError when you want to propagate some errors and handle some errors.

```<code>return this.http.post(api, { username, password })
  .pipe(
     catchError((error) => {
       if (canHandleError(error)) {
         // handle...
         return of(false)
       } else {
         return throwError(error)
       }
     }),
  )
</code>```

Title: RxJs : How to rethrow error from observable

Body:
I am new to RxJS. Learning observables and subjects.
I have a very simple login code divided into two files, a) auth.service.ts and b) login.component.ts

Here is login.component.ts

public login(username: string, password: string): Observable<boolean> {
const headers = { 'content-type': 'application/json' }
const reqBody = {
  "userName": username,
  "password": password
};
const body = JSON.stringify(reqBody);
const subject = new Subject<boolean>();
this.httpClient.post<IAuthToken>(this.apiUrl, body, { 'headers': headers })
  .subscribe(response => {
    if (response) {
      localStorage.setItem(this.accessTokenKey, response.access_token);
      subject.next(true);
    }
    else {
      throwError("Login request failed. Please try again later");
    }
  },
    error => {
      // TODO : Code to show invalid username password
      // this code throws error. Subscribe in the login.component.ts doesnt receive any error.
      throwError(error.error);
    });
return subject.asObservable();

}

Here is login.component.ts code

errorMsg: string;
constructor(
    private authenticationService: AuthService
  ) {  }
async onLogin(): Promise<void> {

        this.authenticationService.login(this.loginForm.value.username,
          this.loginForm.value.password)
          .subscribe((response) => {
            this.errorMsg = null;
            if (response)
                 console.log("logged In");
          },
            error => {
              // TODO : Code to show invalid username password
              // This code doesnt execute, i.e. error is not caught.
              this.errorMsg = error.error;
              console.log(error);
            });
    }
  }

I want to throw error for invalid username password from auth.service.ts and catch it in login.component.ts so that can bind the error to UI.
However, the throwError throws error from auth.service.ts, but the error isnt caught in login.component.html

Body:
Several misconceptions here.

Firstly, throwError is a function which returns an observable that immediately errors. Simply calling it like you do doesn't do anything.

throwError(error.error); // creates an unused observable

Secondly, you're subscribing in the service with some weird glued-together code with a subject. Your service is supposed to just create an observable, and then you subscribe to it in the component. The error would then be caught correctly by default.

// in service
logIn (username: string, password: string): Observable<boolean> {
  return this.http.post(api, { username, password })
    .pipe(mapTo(true))
}

// in component
onSubmit () {
  this.service.logIn('username', 'p@ssword')
    .subscribe({
      next: () => {
        console.log('Success!')
      },
      error: (error) => {
        console.error(error)
      }
    })
}

throwError is usually used in conjuction with catchError when you want to propagate some errors and handle some errors.

return this.http.post(api, { username, password })
  .pipe(
     catchError((error) => {
       if (canHandleError(error)) {
         // handle...
         return of(false)
       } else {
         return throwError(error)
       }
     }),
  )


问:
Is there a way to get corresponding index value in a 2nd array using the 1st array as a reference in Javascript?
I am very new to algorithm and programming in general. I may require more explanation than an average fellow. Apologies in advance.

My aim is to Create a function that returns a number, based on the string provided. I have been told that this can be done using loops. I believe my errors lies in the if statement. However, cant seem to figure it out. I would be glad if somebody could help.

```<code>function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}
</code>```

答:
Working Demo :

function getStringNumber(word) {
    let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let i = 0; i < str.length; i++) {
    if (word === str[i]) return int[i];
  }
}

console.log(getStringNumber('nine') ?? 'No word found!');

  ```

Body:
I am very new to algorithm and programming in general. I may require more explanation than an average fellow. Apologies in advance.

My aim is to Create a function that returns a number, based on the string provided. I have been told that this can be done using loops. I believe my errors lies in the if statement. However, cant seem to figure it out. I would be glad if somebody could help.

function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}


问:
is it possible to create a docker image that creates and runs another docker?
I need a machine that runs Kali OS, and builds and runs some docker container.
This was easy using Virtual box.
But it was proved hard (impossible?) on docker.
So - I want to create an image, based on Kali, and then build and run some docker container. is this possible?

I wrote something like this:

```<code>FROM kalilinux/kali-rolling
RUN apt update -y
RUN apt install -y git
RUN apt install -y docker.io
RUN git clone https://something
RUN docker build . -f /something/Dockerfile  -t my_app
CMD docker run my_app
</code>```

答:
A docker is a process (container) running on some environment, most probably on a local docker VM in your case. If you want to build another docker on that VM you need to install docker on it which is probably heavy cumbersome and not advisable.
If you want a Kali image (for some obscure reason) you can use ready made images.
Here

No need to create another docker.

I would suggest you read up and take a docker tutorial.

Body:
I need a machine that runs Kali OS, and builds and runs some docker container.
This was easy using Virtual box.
But it was proved hard (impossible?) on docker.
So - I want to create an image, based on Kali, and then build and run some docker container. is this possible?

I wrote something like this:

FROM kalilinux/kali-rolling
RUN apt update -y
RUN apt install -y git
RUN apt install -y docker.io
RUN git clone https://something
RUN docker build . -f /something/Dockerfile  -t my_app
CMD docker run my_app


问:
Is there a way to get current Google Authenticator 2FA key for a specific account (client-side)
I am searching for a way to obtain the current code in my Google Authenticator app. for a specific account.

Please note that I'm not looking for embedding Google 2FA to any of server-side application - I guess it has been already well-documented.

I am trying to get the same current code shown in my own Google 2FA app. (by providing my Google credientials ofcourse) so I can make my app fully automated even when logging in (to a specific system/website) without asking for the code each time I start the app.

Thanks by now.

UPDATE:
Even if I can't find any answer or simply "there is no way", there is still a way even if it's too ugly.

Running an ios/android simulator (and configure it once by installing the Google Auth app) and simulate the mouse clicks over it and then capturing a screenshot and decoding the code from the image would be much of a work but also can actually work. I'm just trying to find a better way, if there is any.

答:
You could solve this by generating the OTP code locally using a library such as OTP.Net. Simply save the secret locally, and add it to .gitignore if using git.

Then you can make a code on demand like so:

```<code>using OtpNet;
var totp = new Totp(secretKey);
var totpCode = totp.ComputeTotp();
</code>```

Body:
You could solve this by generating the OTP code locally using a library such as OTP.Net. Simply save the secret locally, and add it to .gitignore if using git.

Then you can make a code on demand like so:

using OtpNet;
var totp = new Totp(secretKey);
var totpCode = totp.ComputeTotp();


问:
Getting an PHP enum from dynamic name
I´m trying to create an php 8.1 enum from a dynamic name. Seems not to be possible. So given an enum

```<code>enum Foo {
    case bar;
}
</code>```

The following works of course: Foo::bar While this doesn´t:

```<code>$name = "bar";
Foo::${$name}
</code>```

This results in: Access to undeclared static property App\Console\Commands\Foo::$bar

I tried various tricks here, to no avail. It seems not to be possible to get an enum instance from a dynamic name. My custom and quick workaround looks like this, a static factory:

```<code>/**
 * @throws \Exception
 */
public static function fromName(string $name) : self {

    foreach(Foo::cases() as $enum){
        if($enum->name === $name){
            return $enum;
        }
    }
    throw new \Exception("Not a valid enum name");
}
</code>```

I could put this in a trait and inherit this in all my enums, yes, problem solved.

My question is: am I missing something here? Is it really not possible to instantiate an enum with native php methods? Or am I thinking in the wrong direction?

The pre php8.1 class-as-enum composer packages used to have those convenience methods, see https://github.com/bensampo/laravel-enum
So why is this pretty common case not part of the specification (just curious)?

答:
Could you maybe do something like this?

enum Status {
  case OK;
  case DENIED;
}

$name = "OK";
$reflection = new \ReflectionEnum(Status::class);
if ( $reflection->hasConstant( $name ) ) {
  var_dump($reflection->getConstant( $name ));
}

```

Output: enum(Status::OK)

Title: Getting an PHP enum from dynamic name

Body:
I´m trying to create an php 8.1 enum from a dynamic name. Seems not to be possible. So given an enum

enum Foo {
    case bar;
}

The following works of course: Foo::bar While this doesn´t:

$name = "bar";
Foo::${$name}

This results in: Access to undeclared static property App\Console\Commands\Foo::$bar

I tried various tricks here, to no avail. It seems not to be possible to get an enum instance from a dynamic name. My custom and quick workaround looks like this, a static factory:

/**
 * @throws \Exception
 */
public static function fromName(string $name) : self {

    foreach(Foo::cases() as $enum){
        if($enum->name === $name){
            return $enum;
        }
    }
    throw new \Exception("Not a valid enum name");
}

I could put this in a trait and inherit this in all my enums, yes, problem solved.

My question is: am I missing something here? Is it really not possible to instantiate an enum with native php methods? Or am I thinking in the wrong direction?

The pre php8.1 class-as-enum composer packages used to have those convenience methods, see https://github.com/bensampo/laravel-enum
So why is this pretty common case not part of the specification (just curious)?

Body:
Could you maybe do something like this?

enum Status {
  case OK;
  case DENIED;
}

$name = "OK";
$reflection = new \ReflectionEnum(Status::class);
if ( $reflection->hasConstant( $name ) ) {
  var_dump($reflection->getConstant( $name ));
}

Output: enum(Status::OK)


问:
Looking for a pure-python NxMxZ matrix library
I'm trying to deal with an arbitrary-sized (NxMxZ) 3D matrix in Python, about 50MB of floating point numbers in total. I need to do simple as-efficient-as-possible sum and average calculations across axes and diagonals, but nothing very fancy, and the matrix is dense.

Anyone know if such a library exists? I've found a number of "3D matrix" libraries for python, but they're all for 3D graphics, and are limited to, e.g. 4x4x4 matrices. Normally I'd use Numpy, but I'm on Google AppEngine, and can't use a library that requires C extensions.

答: We just announced a trusted tester program for Python 2.7 support, which includes NumPy. You might want to consider signing up for it.</p>


问:
Creating halo outside the borders of an element in css
I am wondering how to do this in css :

enter image description here

Basically, I can do everything out of it. But I dont manage to recreate the halo surroundering the borders. Could you please advise ? :)

EDIT :

I am quite stuck at making the border with the fading

答:
This effect can be achieved with box-shadows like so:

.box {
  margin: 20px;
  padding: 20px;
  background: lightgreen;
  width: 200px;
}

.halo {
  -webkit-box-shadow: 0px 0px 7px 11px rgba(255,165,28,0.59);
  box-shadow: 0px 0px 7px 11px rgba(255,165,28,0.59);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box halo">Hello There, I am a box, play with my colours to get different results, use the last two pixel values to play with the size and blur.</div></code>```

In order to learn more about box shadows in CSS, you can find its documentation here: https://www.w3schools.com/cssref/css3_pr_box-shadow.asp

Body:
This effect can be achieved with box-shadows like so:

.box {
  margin: 20px;
  padding: 20px;
  background: lightgreen;
  width: 200px;
}

.halo {
  -webkit-box-shadow: 0px 0px 7px 11px rgba(255,165,28,0.59);
  box-shadow: 0px 0px 7px 11px rgba(255,165,28,0.59);
}

<div class="box halo">Hello There, I am a box, play with my colours to get different results, use the last two pixel values to play with the size and blur.</div>

In order to learn more about box shadows in CSS, you can find its documentation here: https://www.w3schools.com/cssref/css3_pr_box-shadow.asp