问:
Multiple functions for the same path in jax.ws.rs?
Lets say I wanted in implement readonly behaviour on my application (not allowing posts/puts). Could I do this by disabling these types/setting a @POST/@PUT that catches requests on any endpoint? (As opposed to putting a boolean flag on every single post/put in my application</p>

答:
You could add a filter, disallowing all the methods you don't want to support:</p>
```<code>import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;

@Provider
public class AuthorizationRequestFilter implements ContainerRequestFilter {
    private final List<String> disallowed=Arrays.asList("POST","PUT","DELETE","PATCH");

   @Override
   public void filter(ContainerRequestContext requestContext)
                throws IOException {
        if (disallowed.contains(requestContext.getMethod())){
            requestContext.abortWith(Response
                    .status(Response.Status.FORBIDDEN)
                    .entity("User cannot modify the resource.")
                    .build());
        }
    }
}
</code>```

Body:
You could add a filter, disallowing all the methods you don't want to support:

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;

@Provider
public class AuthorizationRequestFilter implements ContainerRequestFilter {
    private final List<String> disallowed=Arrays.asList("POST","PUT","DELETE","PATCH");

   @Override
   public void filter(ContainerRequestContext requestContext)
                throws IOException {
        if (disallowed.contains(requestContext.getMethod())){
            requestContext.abortWith(Response
                    .status(Response.Status.FORBIDDEN)
                    .entity("User cannot modify the resource.")
                    .build());
        }
    }
}


来源: stackexchange

问:
Kubernetespodoperator how to use cmds or cmds and arguments to run multiple commands
I'm using GCP composer to run an algorithm and at the end of the stream I want to run a task that will perform several operations copying and deleting files and folders from a volume to a bucket I'm trying to perform these copying and deleting operations via a kubernetespodoperator. I'm having hardship finding the right way to run several commands using "cmds" I also tried using "cmds" with "arguments".
Here is my KubernetesPodOperator and the cmds and arguments combinations I tried:

```<code>post_algo_run = kubernetes_pod_operator.KubernetesPodOperator(
    task_id="multi-coher-post-operations",
    name="multi-coher-post-operations",
    namespace="default",
    image="google/cloud-sdk:alpine",

    ### doesn't work ###
    cmds=["gsutil", "cp", "/data/splitter-output\*.csv",  "gs://my_bucket/data" , "&" , "gsutil", "rm", "-r", "/input"],
    #Error:
        #[2022-01-27 09:31:38,407] {pod_manager.py:197} INFO - CommandException: Destination URL must name a directory, bucket, or bucket
        #[2022-01-27 09:31:38,408] {pod_manager.py:197} INFO - subdirectory for the multiple source form of the cp command.
    ####################

    ### doesn't work ###
    # cmds=["gsutil", "cp", "/data/splitter-output\*.csv",  "gs://my_bucket/data ;","gsutil", "rm", "-r", "/input"],
        # [2022-01-27 09:34:06,865] {pod_manager.py:197} INFO - CommandException: Destination URL must name a directory, bucket, or bucket
        # [2022-01-27 09:34:06,866] {pod_manager.py:197} INFO - subdirectory for the multiple source form of the cp command.
    ####################

    ### only preform the first command - only copying ###
    # cmds=["bash", "-cx"],
    # arguments=["gsutil cp /data/splitter-output\*.csv gs://my_bucket/data","gsutil rm -r /input"],
        # [2022-01-27 09:36:09,164] {pod_manager.py:197} INFO - + gsutil cp '/data/splitter-output*.csv' gs://my_bucket/data
        # [2022-01-27 09:36:11,200] {pod_manager.py:197} INFO - Copying file:///data/splitter-output\Coherence Results-26-Jan-2022-1025Part1.csv [Content-Type=text/csv]...
        # [2022-01-27 09:36:11,300] {pod_manager.py:197} INFO - / [0 files][    0.0 B/ 93.0 KiB]
        # / [1 files][ 93.0 KiB/ 93.0 KiB]
        # [2022-01-27 09:36:11,302] {pod_manager.py:197} INFO - Operation completed over 1 objects/93.0 KiB.
        # [20   22-01-27 09:36:12,317] {kubernetes_pod.py:459} INFO - Deleting pod: multi-coher-post-operations.d66b4c91c9024bd289171c4d3ce35fdd
    ####################

    volumes=[
        Volume(
            name="nfs-pvc",
            configs={
                "persistentVolumeClaim": {"claimName": "nfs-pvc"}
            },
        )
    ],
    volume_mounts=[
        VolumeMount(
            name="nfs-pvc",
            mount_path="/data/",
            sub_path=None,
            read_only=False,
        )
    ],
)
</code>```

答:
I found a technic for running multiple commands.
First I found the relations between Kubernetespodoperator cmds and arguments properties to Docker's ENTRYPOINT and CMD.

Kubernetespodoperator cmds overwrite the docker original ENTRYPOINT
and Kubernetespodoperator arguments is equivalent to docker's CMD.

And so in order to run multiple commands from the Kubernetespodoperator I've used the following syntax:
I've set the Kubernetespodoperator cmds to run bash with -c:

```<code>cmds=["/bin/bash", "-c"],
</code>```

And I've set the Kubernetespodoperator arguments to run two echo commands separated by &:

```<code>arguments=["echo hello && echo goodbye"],
</code>```

So my Kubernetespodoperator looks like so:

```<code>stajoverflow_test = KubernetesPodOperator(
    task_id="stajoverflow_test",
    name="stajoverflow_test",
    namespace="default",
    image="google/cloud-sdk:alpine",
    cmds=["/bin/bash", "-c"],
    arguments=["echo hello && echo goodbye"],
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using GCP composer to run an algorithm and at the end of the stream I want to run a task that will perform several operations copying and deleting files and folders from a volume to a bucket I'm trying to perform these copying and deleting operations via a kubernetespodoperator. I'm having hardship finding the right way to run several commands using "cmds" I also tried using "cmds" with "arguments".
Here is my KubernetesPodOperator and the cmds and arguments combinations I tried:

post_algo_run = kubernetes_pod_operator.KubernetesPodOperator(
    task_id="multi-coher-post-operations",
    name="multi-coher-post-operations",
    namespace="default",
    image="google/cloud-sdk:alpine",

    ### doesn't work ###
    cmds=["gsutil", "cp", "/data/splitter-output\*.csv",  "gs://my_bucket/data" , "&" , "gsutil", "rm", "-r", "/input"],
    #Error:
        #[2022-01-27 09:31:38,407] {pod_manager.py:197} INFO - CommandException: Destination URL must name a directory, bucket, or bucket
        #[2022-01-27 09:31:38,408] {pod_manager.py:197} INFO - subdirectory for the multiple source form of the cp command.
    ####################

    ### doesn't work ###
    # cmds=["gsutil", "cp", "/data/splitter-output\*.csv",  "gs://my_bucket/data ;","gsutil", "rm", "-r", "/input"],
        # [2022-01-27 09:34:06,865] {pod_manager.py:197} INFO - CommandException: Destination URL must name a directory, bucket, or bucket
        # [2022-01-27 09:34:06,866] {pod_manager.py:197} INFO - subdirectory for the multiple source form of the cp command.
    ####################

    ### only preform the first command - only copying ###
    # cmds=["bash", "-cx"],
    # arguments=["gsutil cp /data/splitter-output\*.csv gs://my_bucket/data","gsutil rm -r /input"],
        # [2022-01-27 09:36:09,164] {pod_manager.py:197} INFO - + gsutil cp '/data/splitter-output*.csv' gs://my_bucket/data
        # [2022-01-27 09:36:11,200] {pod_manager.py:197} INFO - Copying file:///data/splitter-output\Coherence Results-26-Jan-2022-1025Part1.csv [Content-Type=text/csv]...
        # [2022-01-27 09:36:11,300] {pod_manager.py:197} INFO - / [0 files][    0.0 B/ 93.0 KiB]
        # / [1 files][ 93.0 KiB/ 93.0 KiB]
        # [2022-01-27 09:36:11,302] {pod_manager.py:197} INFO - Operation completed over 1 objects/93.0 KiB.
        # [20   22-01-27 09:36:12,317] {kubernetes_pod.py:459} INFO - Deleting pod: multi-coher-post-operations.d66b4c91c9024bd289171c4d3ce35fdd
    ####################

    volumes=[
        Volume(
            name="nfs-pvc",
            configs={
                "persistentVolumeClaim": {"claimName": "nfs-pvc"}
            },
        )
    ],
    volume_mounts=[
        VolumeMount(
            name="nfs-pvc",
            mount_path="/data/",
            sub_path=None,
            read_only=False,
        )
    ],
)

Body:
I found a technic for running multiple commands.
First I found the relations between Kubernetespodoperator cmds and arguments properties to Docker's ENTRYPOINT and CMD.

Kubernetespodoperator cmds overwrite the docker original ENTRYPOINT
and Kubernetespodoperator arguments is equivalent to docker's CMD.

And so in order to run multiple commands from the Kubernetespodoperator I've used the following syntax:
I've set the Kubernetespodoperator cmds to run bash with -c:

cmds=["/bin/bash", "-c"],

And I've set the Kubernetespodoperator arguments to run two echo commands separated by &:

arguments=["echo hello && echo goodbye"],

So my Kubernetespodoperator looks like so:

stajoverflow_test = KubernetesPodOperator(
    task_id="stajoverflow_test",
    name="stajoverflow_test",
    namespace="default",
    image="google/cloud-sdk:alpine",
    cmds=["/bin/bash", "-c"],
    arguments=["echo hello && echo goodbye"],
)


问:
Sending emails via NodeMailer in MERN Stack
I have a question about the whole process, I managed to finish a reset password flow via email, but the emails that I'm sending are going into spam. Do you guys know a way for my emails to go into the inbox and not into the spam folder? Did you ever met this case?</p>

答:
Did you configure the DKIM (DomainKeys Identified Mail) ?

Test the Spammyness of your Emails: https://www.mail-tester.com/


问:
Replace non-specified array values with 0
I want to replace all array values with 0 except work and home.

Input:

```<code>$array = ['work', 'homework', 'home', 'sky', 'door']
</code>```

My coding attempt:

```<code>$a = str_replace("work", "0", $array);
</code>```

Expected output:

```<code>['work', 0, 'home', 0, 0]
</code>```

Also my input data is coming from a user submission and the amount of array elements may be very large.

答:
There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise.  For best maintainability, I recommend separating your list of targeted string as a lookup array.  By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.

Code: (Demo)

```<code>$array = ['work', 'homework', 'home', 'sky', 'door'];

$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);

foreach ($array as &$v) {
    $v = $lookup[$v] ?? 0;
}

var_export($array);
</code>```

Output:

```<code>array (
  0 => 'work',
  1 => 0,
  2 => 'home',
  3 => 0,
  4 => 0,
)
</code>```

You can very easily, cleanly extend your list of targeted strings by merely extending $keep.

If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)

```<code>var_export(
    array_map(fn($v) => $lookup[$v] ?? 0, $array)
);
</code>```

Body:
I want to replace all array values with 0 except work and home.

Input:

$array = ['work', 'homework', 'home', 'sky', 'door']

My coding attempt:

$a = str_replace("work", "0", $array);

Expected output:

['work', 0, 'home', 0, 0]

Also my input data is coming from a user submission and the amount of array elements may be very large.

Body:
There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise.  For best maintainability, I recommend separating your list of targeted string as a lookup array.  By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.

Code: (Demo)

$array = ['work', 'homework', 'home', 'sky', 'door'];

$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);

foreach ($array as &$v) {
    $v = $lookup[$v] ?? 0;
}

var_export($array);

Output:

array (
  0 => 'work',
  1 => 0,
  2 => 'home',
  3 => 0,
  4 => 0,
)

You can very easily, cleanly extend your list of targeted strings by merely extending $keep.

If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)

var_export(
    array_map(fn($v) => $lookup[$v] ?? 0, $array)
);


问:
Angular + Spring Boot: Forwarding all Angular routes to Angular and all API to the Spring Controllers
I have a Spring Boot app and an Angular app. I want to serve the Angular App from the Spring Boot App. I build the Angular App and moved all files, including the index.html file, into /resources/static/ and just to be sure also to resources/public/. I also put the index.html into resources/templates.
I received 404 when calling any of the angular routes e.g. mywebsite.com/login

Then I added a controller to forward all requests to my Angular App:

```<code>@Controller
public class RedirectToAngularController {

  /**
  * Should redirect all routes to FrontEnd, but doesn't work.
  */
  @RequestMapping({"/", "/login", "/login/**"})
  public String redirectLogin() {
    log.info("Forwarding request to Angular (index.html)");
    return "forward:/index.html";
  }
}
</code>```

IntelliJ gives me a warning for "forward:/index.html" that it can't find the URL:

I still deployed my website and open it at myWebsite.com/login or myWebsite.com/confirm. Instead of my index.html file getting displayed I see forward:/index.html as a string in my browser. So it actually returns the string, not the file
In the logs "Forwarding request to Angular (index.html)" appears, but then it says: Cannot find GET /index.html in the next line.

So I deleted that controller and instead tried to solve this with a ResourceHandler:

```<code>@Configuration
public class WebAdapterConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**/*")
              .addResourceLocations("classpath:/static/")
              .resourceChain(true)
              .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath, Resource location) throws IOException {
                  Resource requestedResource = location.createRelative(resourcePath);

                  return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
                          : new ClassPathResource("/static/index.html");
                }
              });
    registry.setOrder(-1);
  }
}
</code>```

This was described here: Springboot/Angular2 - How to handle HTML5 urls?
and also here: https://keepgrowing.in/java/springboot/make-spring-boot-surrender-routing-control-to-angular/

But this redirects everything! I now get the index file when I open mywebsite.com/login as well as when I make a postman request to my api (e.g. GET mywebsite.com/api/users)

So I tried to narrow it down by replacing registry.addResourceHandler("/**/*") with registry.addResourceHandler("/login") or registry.addResourceHandler("/login/**", "/confirm"). But then only mywebsite.com/login/something and mywebsite.com/confirm retrun the index.html, but all other paths, including the URI for the api methods return 404!

A third approach was to add view controller:

```<code>@Configuration
public class WebAdapterConfig implements WebMvcConfigurer {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("forward:/index.html");
    registry.addViewController("/login/**").setViewName("forward:/index.html");
    registry.addViewController("/confirm").setViewName("forward:/index.html");
  }
}
</code>```

But then I always received 404 for all routes.

I also added spring web MVC to my dependencies, but this didn't seem to change anything.

```<code>dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
}
</code>```

p.s. I don't use tymeleaf as my files are coming from angular. Maybe that's why forward:/ doesn't work?

答:
Narrowing down the ResourceHandler paths was the right approach:

```<code>registry.addResourceHandler(
        "/login/**",
        "/all other Uris of my website"
).addResourceLocations("classpath:/static/")
 .resourceChain(true)
 .addResolver(new PathResourceResolver() {
   @Override
   protected Resource getResource(String resourcePath, Resource location) throws IOException {
              Resource requestedResource = location.createRelative(resourcePath);

              return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
                      : new ClassPathResource("/static/index.html");
            }
          });
</code>```

There was another problem that kept returning 404 for the other URIs, but that had nothing to do with the resourceHandler, but was a problem at our Gateway.

Body:
I have a Spring Boot app and an Angular app. I want to serve the Angular App from the Spring Boot App. I build the Angular App and moved all files, including the index.html file, into /resources/static/ and just to be sure also to resources/public/. I also put the index.html into resources/templates.
I received 404 when calling any of the angular routes e.g. mywebsite.com/login

Then I added a controller to forward all requests to my Angular App:

@Controller
public class RedirectToAngularController {

  /**
  * Should redirect all routes to FrontEnd, but doesn't work.
  */
  @RequestMapping({"/", "/login", "/login/**"})
  public String redirectLogin() {
    log.info("Forwarding request to Angular (index.html)");
    return "forward:/index.html";
  }
}

IntelliJ gives me a warning for "forward:/index.html" that it can't find the URL:

I still deployed my website and open it at myWebsite.com/login or myWebsite.com/confirm. Instead of my index.html file getting displayed I see forward:/index.html as a string in my browser. So it actually returns the string, not the file
In the logs "Forwarding request to Angular (index.html)" appears, but then it says: Cannot find GET /index.html in the next line.

So I deleted that controller and instead tried to solve this with a ResourceHandler:

@Configuration
public class WebAdapterConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**/*")
              .addResourceLocations("classpath:/static/")
              .resourceChain(true)
              .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath, Resource location) throws IOException {
                  Resource requestedResource = location.createRelative(resourcePath);

                  return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
                          : new ClassPathResource("/static/index.html");
                }
              });
    registry.setOrder(-1);
  }
}

This was described here: Springboot/Angular2 - How to handle HTML5 urls?
and also here: https://keepgrowing.in/java/springboot/make-spring-boot-surrender-routing-control-to-angular/

But this redirects everything! I now get the index file when I open mywebsite.com/login as well as when I make a postman request to my api (e.g. GET mywebsite.com/api/users)

So I tried to narrow it down by replacing registry.addResourceHandler("/**/*") with registry.addResourceHandler("/login") or registry.addResourceHandler("/login/**", "/confirm"). But then only mywebsite.com/login/something and mywebsite.com/confirm retrun the index.html, but all other paths, including the URI for the api methods return 404!

A third approach was to add view controller:

@Configuration
public class WebAdapterConfig implements WebMvcConfigurer {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("forward:/index.html");
    registry.addViewController("/login/**").setViewName("forward:/index.html");
    registry.addViewController("/confirm").setViewName("forward:/index.html");
  }
}

But then I always received 404 for all routes.

I also added spring web MVC to my dependencies, but this didn't seem to change anything.

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
}

p.s. I don't use tymeleaf as my files are coming from angular. Maybe that's why forward:/ doesn't work?

Body:
Narrowing down the ResourceHandler paths was the right approach:

registry.addResourceHandler(
        "/login/**",
        "/all other Uris of my website"
).addResourceLocations("classpath:/static/")
 .resourceChain(true)
 .addResolver(new PathResourceResolver() {
   @Override
   protected Resource getResource(String resourcePath, Resource location) throws IOException {
              Resource requestedResource = location.createRelative(resourcePath);

              return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
                      : new ClassPathResource("/static/index.html");
            }
          });

There was another problem that kept returning 404 for the other URIs, but that had nothing to do with the resourceHandler, but was a problem at our Gateway.


问:
Moving average Python using for loop
My code tries to calculate a moving average of a list, but it computes it incorrectly. Here is the code:</p>
```<code>import numpy as np
import matplotlib.pyplot as plt

for i in a:
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)
    display(Mov_Avg)

plt.plot(Mov_Avg)
</code>```

答:
You should loop over the elements of range(len(a)) and not over the elements of a directly.</p>
```<code>import numpy as np
import matplotlib.pyplot as plt

a = np.array([5,3,8,10,2,1,5,1,0,2])
window_size = 2
plt.plot(a)

Mov_Avg = [] #Empty list that will hold the resulting moving averages

for i in range(len(a)):
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)

plt.plot(Mov_Avg)
</code>```

Title: Moving average Python using for loop

Body:
My code tries to calculate a moving average of a list, but it computes it incorrectly. Here is the code:

import numpy as np
import matplotlib.pyplot as plt

for i in a:
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)
    display(Mov_Avg)

plt.plot(Mov_Avg)

Body:
You should loop over the elements of range(len(a)) and not over the elements of a directly.

import numpy as np
import matplotlib.pyplot as plt

a = np.array([5,3,8,10,2,1,5,1,0,2])
window_size = 2
plt.plot(a)

Mov_Avg = [] #Empty list that will hold the resulting moving averages

for i in range(len(a)):
    this_window = a[i : i + window_size]
    window_average = sum(this_window) / window_size
    Mov_Avg.append(window_average)

plt.plot(Mov_Avg)


问:
Not able to create ZIP file through Lambda function
I have small lambda function which donwload files from s3 buckets, create zip of it and upload on S3 bucket again.

My lambda function use .net core3.1.

I can write text file but not create zip file.

Zip File Code in C# (as it deployed in linux system, hence I tried to create zip file in Tmp direcotry)

```<code> ZipFile.CreateFromDirectory(@"/tmp/", "test.zip");
</code>```

Lambda function return below error.

```<code>Error :
  at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode)
   at System.IO.FileStream.OpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync)
   at System.IO.Compression.ZipFile.Open(String archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
   at System.IO.Compression.ZipFile.DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, Nullable`1 compressionLevel, Boolean includeBaseDirectory, Encoding entryNameEncoding)
   at System.IO.Compression.ZipFile.CreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName)
   at XXX.DownloadService.CreateZip(DownloadRequest downloadRequest) in D:\Projects\DownloadService.cs:line 133
</code>```

I don't know what did I wrong. or what is alternative to create zip file if this approach is wrong.

Help me.

Thanks in advance.

答:
I suspect that it is trying to create the Zip file in a read-only directory. The second parameter can include the path of the destination Zip file:

```<code>public static void CreateFromDirectory (string sourceDirectoryName, string destinationArchiveFileName);
</code>```

destinationArchiveFileName: The path of the archive to be created, specified as a relative or absolute path. A relative path is interpreted as relative to the current working directory.

However, in an AWS Lambda function, only the /tmp/ directory can be written to. This might conflict with the fact that you are zipping the entire /tmp/ directory. You might need to put your files in a sub-directory of the /tmp/ directory:

```<code>ZipFile.CreateFromDirectory(@"/tmp/files_to_zip/", "/tmp/test.zip");
</code>```

Body:
I have small lambda function which donwload files from s3 buckets, create zip of it and upload on S3 bucket again.

My lambda function use .net core3.1.

I can write text file but not create zip file.

Zip File Code in C# (as it deployed in linux system, hence I tried to create zip file in Tmp direcotry)

 ZipFile.CreateFromDirectory(@"/tmp/", "test.zip");

Lambda function return below error.

Error :
  at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode)
   at System.IO.FileStream.OpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync)
   at System.IO.Compression.ZipFile.Open(String archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
   at System.IO.Compression.ZipFile.DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, Nullable`1 compressionLevel, Boolean includeBaseDirectory, Encoding entryNameEncoding)
   at System.IO.Compression.ZipFile.CreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName)
   at XXX.DownloadService.CreateZip(DownloadRequest downloadRequest) in D:\Projects\DownloadService.cs:line 133

I don't know what did I wrong. or what is alternative to create zip file if this approach is wrong.

Help me.

Thanks in advance.

Body:
I suspect that it is trying to create the Zip file in a read-only directory. The second parameter can include the path of the destination Zip file:

public static void CreateFromDirectory (string sourceDirectoryName, string destinationArchiveFileName);

destinationArchiveFileName: The path of the archive to be created, specified as a relative or absolute path. A relative path is interpreted as relative to the current working directory.

However, in an AWS Lambda function, only the /tmp/ directory can be written to. This might conflict with the fact that you are zipping the entire /tmp/ directory. You might need to put your files in a sub-directory of the /tmp/ directory:

ZipFile.CreateFromDirectory(@"/tmp/files_to_zip/", "/tmp/test.zip");


问:
how to do in Sequelize where column equal column in another table?
I'm using Sequlize with nodeJS, and I'm doing inner join with multiple tables in Sequelize, but in where condition I cannot find a way to add condition where table1.columnX = table2.column</p>

答:
Something like this:

where: {
  '%included_table1.columnX%': Sequelize.col('column')
}
```

Also, you need to indicate required: true in the include option to get INNER JOIN.

Body:
Something like this:

where: {
  '%included_table1.columnX%': Sequelize.col('column')
}

Also, you need to indicate required: true in the include option to get INNER JOIN.


问:
Galleon: Adding ActiveMQ with CLI on Wildfly 23+ not working
Since Wildfly 23 i have the problem that i cant add the activemq configutration with cli anymore.
Executing /subsystem=messaging-activemq/server=:add return always an error stating that the default security domain "other" is missing (which was removed in version 23).

With the line /subsystem=messaging-activemq/server=default:write-attribute(name=elytron-domain, value=myDomain) i could add another security domain but thats not possible if the above command fails.
Is there a way to get this working? Overriding the default?

答:
Combining both commands did the trick:</p>
```<code>/subsystem=messaging-activemq/server=:add(elytron-domain,myDomain)
</code>```

Body:
Combining both commands did the trick:

/subsystem=messaging-activemq/server=:add(elytron-domain,myDomain)


问:
Modern Command-Line Programming a la Bloomberg Terminal
I want build a financial analysis tool that will feature screen after screen of diverse, dynamic options. The screens will change based on the input from the previous screens. Any single screen can have hundreds of options, most of which will be listed in lists. I think creating my application using a regular gui style will be difficult and slow.

I'd like to build my software in a command-line like environment. I think the closest thing to what I'm going for is a Bloomberg terminal.

Are there any tools, toolkits, environments, etc that I can use to build my app on a totally blank slate that I can constantly change? I need to be able to draw charts and would love as much flexibility in graphics as possible. The folks at Bloomberg somehow do this. Can anyone give me some tips?

I have considered using a browser-based approach but I would much prefer something more native.

If it matters I'd most like to code in Java and/or jRuby.

Thanks!

Please note that regardless of the merits of the approach (per your view), I have a valid technical question.

答:
You'll need to read up on text terminal emulation and ANSI escape codes (for drawing, cursor placement, etc.). See also this.

I would strongly suggest you consider EXEL as that is the UI of choice on Wall Street. I am also not convinced that a GUI would be (grossly) less efficient but GUIs are not the end all be all of user interfaces.  If you believe a text-based virtual terminal approach is best, then go for it!

[edit: See also this open source Java emulator projects]

ContentLicense: CC BY-SA 3.0


问:
Circular Imageview in android
I want circular ImageView in my app. I found some code but this is only round the corner image not to circle. Here is my code. Also check the image.

```<code>   public class CircularImageView extends android.support.v7.widget.AppCompatImageView {

public CircularImageView(Context context) {
    super(context);
}

public CircularImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onDraw(Canvas canvas) {

    Drawable drawable = getDrawable();

    if (drawable == null) {
        return;
    }

    if (getWidth() == 0 || getHeight() == 0) {
        return;
    }
    Bitmap b = ((BitmapDrawable) drawable).getBitmap();
    Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

    int w = getWidth(), h = getHeight();

    Bitmap roundBitmap = getRoundBitmap(bitmap, w);
    canvas.drawBitmap(roundBitmap, 0, 0, null);

}

public static Bitmap getRoundBitmap(Bitmap bmp, int radius) {
    Bitmap sBmp;

    if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
        float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
        float factor = smallest / radius;
        sBmp = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / factor), (int)(bmp.getHeight() / factor), false);
    } else {
        sBmp = bmp;
    }

    Bitmap output = Bitmap.createBitmap(radius, radius,
            Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(output);

    final int color = 0xffa19774;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, radius, radius);

    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(Color.parseColor("#BAB399"));
    canvas.drawCircle(radius / 2 + 0.7f,
            radius / 2 + 0.7f, radius / 2 + 0.1f, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(sBmp, rect, rect, paint);

    return output;
}

 }
</code>```

And Here is xml file

```<code> <com.example.CircularImageView
          android:layout_width="70dp"
          android:layout_height="70dp"
          app:srcCompt="@drawable/dummy />
</code>```

I read many answers on stackoverflow but nothing found according to my requirements. I don't want to use any library I want to create my own code.

I'm new in android can you please let me know want I'm missing in my code.

答:
I use material libraries shapeable image view.

```<code><com.google.android.material.imageview.ShapeableImageView
    app:shapeAppearanceOverlay="@style/ShapeAppearance.App.Image.Circle"
    />
</code>```

Put this code below to styles.xml

```<code><style name="ShapeAppearance.App.Image.Circle" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
    <item name="android:background">@color/transparent</item>
</style>
</code>```

For kotlin developers I suggest coil library it has various animations and crop functions :

```<code>imageView.load("https://www.example.com/image.jpg") {
   crossfade(true)
   placeholder(R.drawable.image)
   transformations(CircleCropTransformation())
}
</code>```

Title: Circular Imageview in android

Body:
I want circular ImageView in my app. I found some code but this is only round the corner image not to circle. Here is my code. Also check the image.

   public class CircularImageView extends android.support.v7.widget.AppCompatImageView {

public CircularImageView(Context context) {
    super(context);
}

public CircularImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onDraw(Canvas canvas) {

    Drawable drawable = getDrawable();

    if (drawable == null) {
        return;
    }

    if (getWidth() == 0 || getHeight() == 0) {
        return;
    }
    Bitmap b = ((BitmapDrawable) drawable).getBitmap();
    Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

    int w = getWidth(), h = getHeight();

    Bitmap roundBitmap = getRoundBitmap(bitmap, w);
    canvas.drawBitmap(roundBitmap, 0, 0, null);

}

public static Bitmap getRoundBitmap(Bitmap bmp, int radius) {
    Bitmap sBmp;

    if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
        float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
        float factor = smallest / radius;
        sBmp = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / factor), (int)(bmp.getHeight() / factor), false);
    } else {
        sBmp = bmp;
    }

    Bitmap output = Bitmap.createBitmap(radius, radius,
            Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(output);

    final int color = 0xffa19774;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, radius, radius);

    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(Color.parseColor("#BAB399"));
    canvas.drawCircle(radius / 2 + 0.7f,
            radius / 2 + 0.7f, radius / 2 + 0.1f, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(sBmp, rect, rect, paint);

    return output;
}

 }

And Here is xml file

 <com.example.CircularImageView
          android:layout_width="70dp"
          android:layout_height="70dp"
          app:srcCompt="@drawable/dummy />

I read many answers on stackoverflow but nothing found according to my requirements. I don't want to use any library I want to create my own code.

I'm new in android can you please let me know want I'm missing in my code.

Body:
I use material libraries shapeable image view.

<com.google.android.material.imageview.ShapeableImageView
    app:shapeAppearanceOverlay="@style/ShapeAppearance.App.Image.Circle"
    />

Put this code below to styles.xml

<style name="ShapeAppearance.App.Image.Circle" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
    <item name="android:background">@color/transparent</item>
</style>

For kotlin developers I suggest coil library it has various animations and crop functions :

imageView.load("https://www.example.com/image.jpg") {
   crossfade(true)
   placeholder(R.drawable.image)
   transformations(CircleCropTransformation())
}


问:
How to use current field in second $match?
Let's say i have 2 collections

```<code>// Post collection:
[
    {
      "_id": "somepost1",
      "author": "firstuser",
      "title": "First post"
    },
    {
      "_id": "somepost2",
      "author": "firstuser",
      "title": "Second post"
    },
    {
      "_id": "somepost3",
      "author": "firstuser",
      "title": "Third post"
    }
]
</code>```
```<code>// User collection:

[
    {
      "_id": "firstuser",
      "nickname": "John",
      "posts": {
        "voted": []
      }
    },
    {
      "_id": "seconduser",
      "nickname": "Bob",
      "posts": {
        "voted": [
          {
            "_id": "somepost1",
            "vote": "1"
          },
          {
            "_id": "somepost3",
            "vote": "-1"
          }
        ]
      }
    }
  ]
</code>```

And i need to get this result:

```<code>[
  {
    "_id": "somepost1",
    "author": {
      "_id": "firstuser",
      "nickname": "John"
    },
    "title": "First post",
    "myvote": "1"
  },
  {
    "_id": "somepost2",
    "author": {
      "_id": "firstuser",
      "nickname": "John"
    },
    "title": "Second post",
    "voted": "0"
  },
  {
    "_id": "somepost3",
    "author": {
      "_id": "firstuser",
      "nickname": "John"
    },
    "title": "Third post",
    "myvote": "-1"
  }
]
</code>```

How can i make a request with aggregation, which will display this output with dynamic _id of elements?
I have problem with using current _id of post in second $match and setting "myvote" to 0 if there are no element in "posts.voted" associated with current post.

Here what i've tried: https://mongoplayground.net/p/v70ZUioVSpQ

```<code>db.post.aggregate([
  {
    $match: {
      author: "firstuser"
    }
  },
  {
    $lookup: {
      from: "user",
      localField: "author",
      foreignField: "_id",
      as: "author"
    }
  },
  {
    $addFields: {
      author: {
        $arrayElemAt: [
          "$author",
          0
        ]
      }
    }
  },
  {
    $lookup: {
      from: "user",
      localField: "_id",
      foreignField: "posts.voted._id",
      as: "Results"
    }
  },
  {
    $unwind: "$Results"
  },
  {
    $unwind: "$Results.posts.voted"
  },
  {
    $match: {
      "Results.posts.voted._id": "ID OF CURRENT POST"
    }
  },
  {
    $project: {
      _id: 1,
      author: {
        _id: 1,
        nickname: 1
      },
      title: 1,
      myvote: "$Results.posts.voted.vote"
    }
  }
])
</code>```

答:
From the $match docs:

The query syntax is identical to the read operation query syntax

The query syntax does not allow usage of document values. which is what you're trying to do.

What we can do is use $expr within the $match stage, this allows us to use aggregation oprerators, thus also giving access to the document values. like so:

```<code>{
    $match: {
        $expr: {
            $eq: ['$Results.posts.voted._id', '$_id'],
        }
    },
},
</code>```

Body:
Let's say i have 2 collections

// Post collection:
[
    {
      "_id": "somepost1",
      "author": "firstuser",
      "title": "First post"
    },
    {
      "_id": "somepost2",
      "author": "firstuser",
      "title": "Second post"
    },
    {
      "_id": "somepost3",
      "author": "firstuser",
      "title": "Third post"
    }
]

// User collection:

[
    {
      "_id": "firstuser",
      "nickname": "John",
      "posts": {
        "voted": []
      }
    },
    {
      "_id": "seconduser",
      "nickname": "Bob",
      "posts": {
        "voted": [
          {
            "_id": "somepost1",
            "vote": "1"
          },
          {
            "_id": "somepost3",
            "vote": "-1"
          }
        ]
      }
    }
  ]

And i need to get this result:

[
  {
    "_id": "somepost1",
    "author": {
      "_id": "firstuser",
      "nickname": "John"
    },
    "title": "First post",
    "myvote": "1"
  },
  {
    "_id": "somepost2",
    "author": {
      "_id": "firstuser",
      "nickname": "John"
    },
    "title": "Second post",
    "voted": "0"
  },
  {
    "_id": "somepost3",
    "author": {
      "_id": "firstuser",
      "nickname": "John"
    },
    "title": "Third post",
    "myvote": "-1"
  }
]

How can i make a request with aggregation, which will display this output with dynamic _id of elements?
I have problem with using current _id of post in second $match and setting "myvote" to 0 if there are no element in "posts.voted" associated with current post.

Here what i've tried: https://mongoplayground.net/p/v70ZUioVSpQ

db.post.aggregate([
  {
    $match: {
      author: "firstuser"
    }
  },
  {
    $lookup: {
      from: "user",
      localField: "author",
      foreignField: "_id",
      as: "author"
    }
  },
  {
    $addFields: {
      author: {
        $arrayElemAt: [
          "$author",
          0
        ]
      }
    }
  },
  {
    $lookup: {
      from: "user",
      localField: "_id",
      foreignField: "posts.voted._id",
      as: "Results"
    }
  },
  {
    $unwind: "$Results"
  },
  {
    $unwind: "$Results.posts.voted"
  },
  {
    $match: {
      "Results.posts.voted._id": "ID OF CURRENT POST"
    }
  },
  {
    $project: {
      _id: 1,
      author: {
        _id: 1,
        nickname: 1
      },
      title: 1,
      myvote: "$Results.posts.voted.vote"
    }
  }
])

Body:
From the $match docs:

The query syntax is identical to the read operation query syntax

The query syntax does not allow usage of document values. which is what you're trying to do.

What we can do is use $expr within the $match stage, this allows us to use aggregation oprerators, thus also giving access to the document values. like so:

{
    $match: {
        $expr: {
            $eq: ['$Results.posts.voted._id', '$_id'],
        }
    },
},


问:
Force Maven to rebuild local dependencies
I have two modules at the same hierarchy level, each a child of the same parent pom.xml: foo (jar) and bar (war). foo is a dependency of bar:

```<code><dependency>
    <groupId>parentArtifact</groupId>
    <artifactId>foo</artifactId>
    <version>1.0</version>
</dependency>
</code>```

When I run mvn install in bar, foo does not get rebuilt. It does if I run a build at the parentArtifact level but I don't want to do it, for speed (there are other modules).

How can I force a rebuild of foo every time a build is run in bar?

答:
Go to the parent level and run

mvn clean install -pl bar -am

This will build bar and all dependencies of bar.

Body:
I have two modules at the same hierarchy level, each a child of the same parent pom.xml: foo (jar) and bar (war). foo is a dependency of bar:

<dependency>
    <groupId>parentArtifact</groupId>
    <artifactId>foo</artifactId>
    <version>1.0</version>
</dependency>

When I run mvn install in bar, foo does not get rebuilt. It does if I run a build at the parentArtifact level but I don't want to do it, for speed (there are other modules).

How can I force a rebuild of foo every time a build is run in bar?


问:
Creating an animation of an app's screenshots?
I am creating a how-to animation of an iphone app. I have got all the screenshots of the app. Wondering what the best tool is to create a short video/animation of these jpgs in your opinion? </p>

答:
Please update the post with the source code as the link no longer works.

Essentially, it's like benhowdle89 said. You can take any jQuery slideshow, adjust the image dimensions to the area inside your iPhone 4 .png, and you're pretty much done.

ContentLicense: CC BY-SA 2.5


问:
ToolbarContent: add a .disabled(Bool) method
I've created a custom ToolbarContent for common buttons, such as Save, Edit, Cancel, etc...

For example:

```<code>
import SwiftUI

public struct SaveToolbarItem: ToolbarContent {
    private let placement: ToolbarItemPlacement
    private let action: () -> Void

    public init(placement: ToolbarItemPlacement = .confirmationAction,
                action: @escaping () -> Void = {}) {
        self.placement = placement
        self.action = action
    }

    public var body: some ToolbarContent {
        ToolbarItem(placement: placement) {
            Button(
                "Save"
            ) {
                action()
            }
        }
    }
}
</code>```

At call site:

```<code>        .toolbar {
            SaveToolbarItem() {
                 // some code for the Action
                presentationMode.wrappedValue.dismiss()
            }
            .disabled(true) // Value of type 'SaveToolbarItem' has no member 'disabled'
        }
</code>```

However, I'm getting the following error while trying to use isDisabled method:

Value of type 'SaveToolbarItem' has no member 'disabled'

How can I mitigate this error? E.g. maybe define disabled only on my custom types of ToolbarContent?

答:
You need to place it inside, like

```<code>public var body: some ToolbarContent {
    ToolbarItem(placement: placement) {
        Button(
            "Save"
        ) {
            action()
        }
        .disabled(true)     // << here !!
    }
}
</code>```

*of course parameter for disabled is expected to be passed in.

Updated: Here is possible approach with built-in disabled modifier.

Tested with Xcode 13.2 / iOS 15.2

```<code>public struct SaveToolbarItem: ToolbarContent {
    private let placement: ToolbarItemPlacement
    private let action: () -> Void

    private var enabled = true

    public init(placement: ToolbarItemPlacement = .confirmationAction,
                action: @escaping () -> Void = {}) {
        self.placement = placement
        self.action = action
    }

    public var body: some ToolbarContent {
        ToolbarItem(placement: placement) {
            Button(
                "Save"
            ) {
                action()
            }
            .disabled(!enabled)
        }
    }

    func disabled(_ flag: Bool) -> Self {
        var newItem = self
        newItem.enabled = !flag
        return newItem
    }
}
</code>```

Body:
I've created a custom ToolbarContent for common buttons, such as Save, Edit, Cancel, etc...

For example:

import SwiftUI

public struct SaveToolbarItem: ToolbarContent {
    private let placement: ToolbarItemPlacement
    private let action: () -> Void

    public init(placement: ToolbarItemPlacement = .confirmationAction,
                action: @escaping () -> Void = {}) {
        self.placement = placement
        self.action = action
    }

    public var body: some ToolbarContent {
        ToolbarItem(placement: placement) {
            Button(
                "Save"
            ) {
                action()
            }
        }
    }
}

At call site:

        .toolbar {
            SaveToolbarItem() {
                 // some code for the Action
                presentationMode.wrappedValue.dismiss()
            }
            .disabled(true) // Value of type 'SaveToolbarItem' has no member 'disabled'
        }

However, I'm getting the following error while trying to use isDisabled method:

Value of type 'SaveToolbarItem' has no member 'disabled'

How can I mitigate this error? E.g. maybe define disabled only on my custom types of ToolbarContent?

Body:
You need to place it inside, like

public var body: some ToolbarContent {
    ToolbarItem(placement: placement) {
        Button(
            "Save"
        ) {
            action()
        }
        .disabled(true)     // << here !!
    }
}

*of course parameter for disabled is expected to be passed in.

Updated: Here is possible approach with built-in disabled modifier.

Tested with Xcode 13.2 / iOS 15.2

public struct SaveToolbarItem: ToolbarContent {
    private let placement: ToolbarItemPlacement
    private let action: () -> Void

    private var enabled = true

    public init(placement: ToolbarItemPlacement = .confirmationAction,
                action: @escaping () -> Void = {}) {
        self.placement = placement
        self.action = action
    }

    public var body: some ToolbarContent {
        ToolbarItem(placement: placement) {
            Button(
                "Save"
            ) {
                action()
            }
            .disabled(!enabled)
        }
    }

    func disabled(_ flag: Bool) -> Self {
        var newItem = self
        newItem.enabled = !flag
        return newItem
    }
}


问:
HTTPError: HTTP Error 403: Forbidden
I making a python script for personal use but it's not working for wikipedia...

This work:

```<code>import urllib2, sys
from bs4 import BeautifulSoup

site = "http://youtube.com"
page = urllib2.urlopen(site)
soup = BeautifulSoup(page)
print soup
</code>```

This not work:

```<code>import urllib2, sys
from bs4 import BeautifulSoup

site= "http://en.wikipedia.org/wiki/StackOverflow"
page = urllib2.urlopen(site)
soup = BeautifulSoup(page)
print soup
</code>```

This is the error:

```<code>Traceback (most recent call last):
  File "C:\Python27\wiki.py", line 5, in <module>
    page = urllib2.urlopen(site)
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 406, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 519, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 444, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 527, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden
</code>```

答:
```<code>from urllib.request import urlopen, Request
from urllib.parse import urlparse
from bs4 import BeautifulSoup as soup

def checkURL(requested_url):
    if not urlparse(requested_url).scheme:
        requested_url = "https://" + requested_url
    return requested_url

def requestAndParse(requested_url):
    requested_url = checkURL(requested_url)
    try:
        # define headers to be provided for request authentication
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
                        'AppleWebKit/537.11 (KHTML, like Gecko) '
                        'Chrome/23.0.1271.64 Safari/537.11',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding': 'none',
            'Accept-Language': 'en-US,en;q=0.8',
            'Connection': 'keep-alive'}
        request_obj = Request(url = requested_url, headers = headers)
        opened_url = urlopen(request_obj)
        page_html = opened_url.read()
        opened_url.close()
        page_soup = soup(page_html, "html.parser")
        return page_soup, requested_url

    except Exception as e:
        print(e)

# Exmaple:
page, url = requestAndParse(url)
</code>```

try out the above code snippet for beautifulsoup page loading.

Title: HTTPError: HTTP Error 403: Forbidden

Body:
I making a python script for personal use but it's not working for wikipedia...

This work:

import urllib2, sys
from bs4 import BeautifulSoup

site = "http://youtube.com"
page = urllib2.urlopen(site)
soup = BeautifulSoup(page)
print soup

This not work:

import urllib2, sys
from bs4 import BeautifulSoup

site= "http://en.wikipedia.org/wiki/StackOverflow"
page = urllib2.urlopen(site)
soup = BeautifulSoup(page)
print soup

This is the error:

Traceback (most recent call last):
  File "C:\Python27\wiki.py", line 5, in <module>
    page = urllib2.urlopen(site)
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 406, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 519, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 444, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 527, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden

Body:
from urllib.request import urlopen, Request
from urllib.parse import urlparse
from bs4 import BeautifulSoup as soup

def checkURL(requested_url):
    if not urlparse(requested_url).scheme:
        requested_url = "https://" + requested_url
    return requested_url

def requestAndParse(requested_url):
    requested_url = checkURL(requested_url)
    try:
        # define headers to be provided for request authentication
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
                        'AppleWebKit/537.11 (KHTML, like Gecko) '
                        'Chrome/23.0.1271.64 Safari/537.11',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding': 'none',
            'Accept-Language': 'en-US,en;q=0.8',
            'Connection': 'keep-alive'}
        request_obj = Request(url = requested_url, headers = headers)
        opened_url = urlopen(request_obj)
        page_html = opened_url.read()
        opened_url.close()
        page_soup = soup(page_html, "html.parser")
        return page_soup, requested_url

    except Exception as e:
        print(e)

# Exmaple:
page, url = requestAndParse(url)

try out the above code snippet for beautifulsoup page loading.


问:
How to randomly reshuffle letters in words
I am trying to make a word scrambler in R. So i have put some words in a collection and tried to use strsplit() to split the letters of each word in the collection.

But I don't understand how to jumble the letters of a word and merge them to one word in R Tool. Does anyone know how can I solve this?

This is what I have done
enter image description here

答:
Here's a one-liner:

```<code>lapply(lapply(strsplit(strings, ""), sample), paste0, collapse = "")
[[1]]
[1] "elfi"

[[2]]
[1] "vleo"

[[3]]
[1] "rmsyyet"
</code>```

Use unlistto get rid of the list:

```<code>unlist(lapply(lapply(strsplit(strings, ""), sample), paste0, collapse = ""))
</code>```

Data:

```<code>strings <- c("life", "love", "mystery")
</code>```

Body:
Here's a one-liner:

lapply(lapply(strsplit(strings, ""), sample), paste0, collapse = "")
[[1]]
[1] "elfi"

[[2]]
[1] "vleo"

[[3]]
[1] "rmsyyet"

Use unlistto get rid of the list:

unlist(lapply(lapply(strsplit(strings, ""), sample), paste0, collapse = ""))

Data:

strings <- c("life", "love", "mystery")


问:
Combine multiple triggers with multiple branches
How can we run github workflows on multiple branches for multiple triggers? Example - How can I run a workflow on pull_request & push on say prod & dev? Refer the code snippet below

on: [push, pull_request]
  branches:
    - 'dev'
    - 'prod'
```
<p>The above isn't allowed. I get the following error -</p>
```Property branches is not allowed.yaml-schema: GitHub Workflow
```

How can I handle this?

答:
You can have multiple events triggering your workflow with subtypes.

Therefore, to achieve what you want (run a workflow on pull_request & push on prod & dev), you would need this implementation:

on:
  push:
    branches:
      - 'dev'
      - 'prod'

  pull_request:
    branches:
      - 'dev'
      - 'prod'
```

The problem in your implementation was that the branches isn't a on subtype in github actions, it's only a pull_request or push subtype.

Body:
How can we run github workflows on multiple branches for multiple triggers? Example - How can I run a workflow on pull_request & push on say prod & dev? Refer the code snippet below

on: [push, pull_request]
  branches:
    - 'dev'
    - 'prod'

The above isn't allowed. I get the following error -

Property branches is not allowed.yaml-schema: GitHub Workflow

How can I handle this?

Body:
You can have multiple events triggering your workflow with subtypes.

Therefore, to achieve what you want (run a workflow on pull_request & push on prod & dev), you would need this implementation:

on:
  push:
    branches:
      - 'dev'
      - 'prod'

  pull_request:
    branches:
      - 'dev'
      - 'prod'

The problem in your implementation was that the branches isn't a on subtype in github actions, it's only a pull_request or push subtype.


问:
Shall I downgrade the installed version of Kotlin plugin in Android Studio?
I am getting a warning as I build an Android Kotlin w/ Jetpack compose app with Android Studio like this:

```<code>Runtime JAR files in the classpath should have the same version. These files were found in the classpath:
.../transformed/jetified-kotlin-stdlib-jdk8-1.5.31.jar (version 1.5)
.../transformed/jetified-kotlin-stdlib-jdk7-1.5.31.jar (version 1.5)
.../transformed/jetified-kotlin-stdlib-1.6.10.jar (version 1.6)
.../transformed/jetified-kotlin-stdlib-common-1.6.10.jar (version 1.6)
</code>```

The Kotlin version I am using with my project is 1.5.31, since It is compatible with Compose compile version 1.0.5.
The Kotlin plugin version installed on Android Studio is 1.6.10

Just for reference I am using Android Studio Bumblebee | 2021.1.1 Patch 1.

Shall I downgrade the plugin Kotlin version on Android Studio from 1.6.10 to 1.5.31?
Or, just ignore the warning? Other solution?

答: This have nothing to do with the plugin version you have installed. Probably some dependency of yours have kotlin 1.6.10 dependency and that's why you hvae this conflict. Try to find out which one using dependency tree - my recommendation is to use gradle scan, you can read about it here. In gradle scan results you can go through all of your dependencies in a tree, like here. You have to find which library is using newer kotlin and then use older version of that library that's targeting your kotlin version

Body:
I am getting a warning as I build an Android Kotlin w/ Jetpack compose app with Android Studio like this:

Runtime JAR files in the classpath should have the same version. These files were found in the classpath:
.../transformed/jetified-kotlin-stdlib-jdk8-1.5.31.jar (version 1.5)
.../transformed/jetified-kotlin-stdlib-jdk7-1.5.31.jar (version 1.5)
.../transformed/jetified-kotlin-stdlib-1.6.10.jar (version 1.6)
.../transformed/jetified-kotlin-stdlib-common-1.6.10.jar (version 1.6)

The Kotlin version I am using with my project is 1.5.31, since It is compatible with Compose compile version 1.0.5.
The Kotlin plugin version installed on Android Studio is 1.6.10

Just for reference I am using Android Studio Bumblebee | 2021.1.1 Patch 1.

Shall I downgrade the plugin Kotlin version on Android Studio from 1.6.10 to 1.5.31?
Or, just ignore the warning? Other solution?


问:
Can I query twice to get more specific value in mongoDB?
For an example, there is a group called "A" which is an array.

And there is another group called "B" which is inside of group "A" also an array.

I want to find and update group "B" elements.

I tried to query chain-like query like in jQuery.

```<code>db.collection.findOne({"group":"A"}).findOne({"society":"B"})
</code>```

something like this..

but this does not work. But main point is that I want to query group elements in group.

Any suggestion on doing this?

If you give me advice especially with PHP implementation, it will be really helpful

答:
Assuming your document looks something like this:

```<code>db.mycol.insert( {
    "_id": 1,
    "group": "A",
    "societies": [
        {"society": "A", "name": "Alpha" },
        {"society": "B", "name": "Beta" }
    ]
} );
</code>```

Then in the Mongo shell, you can retrieve the document you want using a query:

```<code>var group = db.mycol.findOne( { "group": "A" } );
</code>```

And then further filter down on its fields using some client-side JavaScript:

```<code>var societyB = group.societies.filter(function (val) {
    return (val.society == "B");
} );

printjson(societyB);
</code>```

You'd be able to do something similar with the PHP driver.  The key is to perform the action in separate steps: first grab the document you're interested in; then filter and manipulate its fields; then save it back to the database.

Body:
For an example, there is a group called "A" which is an array.

And there is another group called "B" which is inside of group "A" also an array.

I want to find and update group "B" elements.

I tried to query chain-like query like in jQuery.

db.collection.findOne({"group":"A"}).findOne({"society":"B"})

something like this..

but this does not work. But main point is that I want to query group elements in group.

Any suggestion on doing this?

If you give me advice especially with PHP implementation, it will be really helpful

Body:
Assuming your document looks something like this:

db.mycol.insert( {
    "_id": 1,
    "group": "A",
    "societies": [
        {"society": "A", "name": "Alpha" },
        {"society": "B", "name": "Beta" }
    ]
} );

Then in the Mongo shell, you can retrieve the document you want using a query:

var group = db.mycol.findOne( { "group": "A" } );

And then further filter down on its fields using some client-side JavaScript:

var societyB = group.societies.filter(function (val) {
    return (val.society == "B");
} );

printjson(societyB);

You'd be able to do something similar with the PHP driver.  The key is to perform the action in separate steps: first grab the document you're interested in; then filter and manipulate its fields; then save it back to the database.


问:
Give me error validator in undefinded but I used global key in Flutter, how to debug this error

Undefined named parameter error occurred when I used validator function in form text Field

I used the Global key and want to validate my form text field but when using the validator function compiler show the error validator is undefined. My code in a Flutter as follows:

```<code>import 'package:flutter/material.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreen();
}

class _LoginScreen extends State<LoginScreen> {
  //GlobalKey<FormState> formKey = GlobalKey();
  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //child: Text('This is bakwas container'),
        appBar: AppBar(
          title: const Text('Login'),
        ),
        body: Form(
          key: _formKey,
          //validator:(){},
          child: Center(
            child: SizedBox(
              width: MediaQuery.of(context).size.width * .7,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const TextField(
                  // validator: (value) {
                    //   if (value == null || value.isEmpty) {
                    //     return 'Please enter some text';
                    //   }
                    //   return null;
                    // },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                        labelText: 'Email', hintText: 'abc@example.com'),
                  ),
                  //const SizedBox(height: 10,)
                  const TextField(
                    obscureText: true,
                    keyboardType: TextInputType.visiblePassword,
                    decoration: InputDecoration(labelText: 'Password'),
                  ),
                  Container(
                      margin: const EdgeInsets.only(top: 10),
                      child: ElevatedButton(
                          onPressed: () {}, child: const Text('Press IT')))
                ],
              ),
            ),
          ),
        ));
  }
}
</code>```

答:
If you are using TextField your validation should look like below</p>
```<code>class _MyHomeScreenState extends State<MyHomeScreen> {
 final _userEmailController = TextEditingController();
 void errorDialog(String title, String msg) {
 showDialog(
  context: context,
  builder: (_) => AlertDialog(
    title: Text(
      title,
      style: const TextStyle(fontWeight: FontWeight.bold),
    ),
    content: Text(
      msg,
      textAlign: TextAlign.center,
    ),
    actions: [
      TextButton(
        onPressed: () => Navigator.pop(context),
        child: const Text('OK'),
      )
    ],
  ),
 );
}
@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(title: const Text("Test"),),
  body: Column(
    children: [
      TextField(
        controller: _userEmailController,
        decoration: const InputDecoration(
          hintText: 'asdf@gmail.com',
        ),
      ),
      ElevatedButton(
        onPressed: () {
          if (_userEmailController.text.isEmpty) {
            errorDialog('Message', 'User email can not be empty!');
          }
        },
        child: const Text(
          'Login',
          style: TextStyle(fontSize: 18),
        ),
      ),
    ],
  ),
);
}
}
</code>```

Body:
Undefined named parameter error occurred when I used validator function in form text Field

I used the Global key and want to validate my form text field but when using the validator function compiler show the error validator is undefined. My code in a Flutter as follows:

import 'package:flutter/material.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreen();
}

class _LoginScreen extends State<LoginScreen> {
  //GlobalKey<FormState> formKey = GlobalKey();
  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //child: Text('This is bakwas container'),
        appBar: AppBar(
          title: const Text('Login'),
        ),
        body: Form(
          key: _formKey,
          //validator:(){},
          child: Center(
            child: SizedBox(
              width: MediaQuery.of(context).size.width * .7,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const TextField(
                  // validator: (value) {
                    //   if (value == null || value.isEmpty) {
                    //     return 'Please enter some text';
                    //   }
                    //   return null;
                    // },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                        labelText: 'Email', hintText: 'abc@example.com'),
                  ),
                  //const SizedBox(height: 10,)
                  const TextField(
                    obscureText: true,
                    keyboardType: TextInputType.visiblePassword,
                    decoration: InputDecoration(labelText: 'Password'),
                  ),
                  Container(
                      margin: const EdgeInsets.only(top: 10),
                      child: ElevatedButton(
                          onPressed: () {}, child: const Text('Press IT')))
                ],
              ),
            ),
          ),
        ));
  }
}

Body:
If you are using TextField your validation should look like below

class _MyHomeScreenState extends State<MyHomeScreen> {
 final _userEmailController = TextEditingController();
 void errorDialog(String title, String msg) {
 showDialog(
  context: context,
  builder: (_) => AlertDialog(
    title: Text(
      title,
      style: const TextStyle(fontWeight: FontWeight.bold),
    ),
    content: Text(
      msg,
      textAlign: TextAlign.center,
    ),
    actions: [
      TextButton(
        onPressed: () => Navigator.pop(context),
        child: const Text('OK'),
      )
    ],
  ),
 );
}
@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(title: const Text("Test"),),
  body: Column(
    children: [
      TextField(
        controller: _userEmailController,
        decoration: const InputDecoration(
          hintText: 'asdf@gmail.com',
        ),
      ),
      ElevatedButton(
        onPressed: () {
          if (_userEmailController.text.isEmpty) {
            errorDialog('Message', 'User email can not be empty!');
          }
        },
        child: const Text(
          'Login',
          style: TextStyle(fontSize: 18),
        ),
      ),
    ],
  ),
);
}
}


问:
React-query: Show loading spinner while fetching data
Using react-query in new project and having small issue.
Requirement is to show loading spinner on empty page before data is loaded and than after user fetches new results with different query to show spinner above previous results.

First case is pretty easy and well documented:

```<code>  const { isLoading, error, data } = useQuery(["list", query], () =>
    fetch(`https://api/list/${query}`)
  );

  if (isLoading) return <p>Loading...</p>;

  return <div>{data.map((item) => <ListItem key={item.id} item={item}/></div>

</code>```

But, cant figure out second case - because, after query changes react-query doing fetch of new results and data from useQuery is empty as result I get default empty array and in that case falls to that condition - if (isLoading && !data.length )

```<code>  const { isLoading, error, data=[] } = useQuery(["list", query], () =>
    fetch(`https://api/list/${query}`)
  );

  if (isLoading && !data.length ) return <p>Loading...</p>;

  return <div>
    {data.map((item) => <ListItem key={item.id} item={item}/>
    {isLoading && <Spinner/>}
  </div>

</code>```

答:
You can use is isFetching for every time new data is fetched</p>
```<code>const { isFetching, isError, isSuccess, data } = useQuery('key', fnc())
if (isFetching) {
    return <LoaderSpinner />
}
else if (isError) {
    return "error encountered"
}
return (
    { isSuccess && data?.map((item) => <li>{item?.name}</li>)}
)
</code>```

Body:
Using react-query in new project and having small issue.
Requirement is to show loading spinner on empty page before data is loaded and than after user fetches new results with different query to show spinner above previous results.

First case is pretty easy and well documented:

  const { isLoading, error, data } = useQuery(["list", query], () =>
    fetch(`https://api/list/${query}`)
  );

  if (isLoading) return
Loading...
;

  return
{data.map((item) => <ListItem key={item.id} item={item}/>

But, cant figure out second case - because, after query changes react-query doing fetch of new results and data from useQuery is empty as result I get default empty array and in that case falls to that condition - if (isLoading && !data.length )

  const { isLoading, error, data=[] } = useQuery(["list", query], () =>
    fetch(`https://api/list/${query}`)
  );

  if (isLoading && !data.length ) return
Loading...
;

  return

    {data.map((item) => <ListItem key={item.id} item={item}/>
    {isLoading && <Spinner/>}

Body:
You can use is isFetching for every time new data is fetched

const { isFetching, isError, isSuccess, data } = useQuery('key', fnc())
if (isFetching) {
    return <LoaderSpinner />
}
else if (isError) {
    return "error encountered"
}
return (
    { isSuccess && data?.map((item) => <li>{item?.name}</li>)}
)


问:
Kubernetes ingress with backend serviceName regex/wildcard or selector
Hi all we have a Flink application with blue-green deployment which we get using the Flink operator.

Flinkk8soperator for Apache Flink. The operator spins up the following three K8s services after a deployment:

```<code>my-flinkapp-14hdhsr (Top level service)
my-flinkapp-green
my-flinkapp-blue
</code>```

The idea is that one of the two among blue green would be active and would have pods (either blue or green).

And a selector to the the active one would be stored in the top level myflinkapp-14hdhsr service with the selector flink-application-version=blue. Or green. As follows:

```<code>Labels:  flink-app=my-flinkapp
         flink-app-hash=14hdhsr
         flink-application-version=blue
Annotations:       <none>
Selector:          flink-app=my-flinkapp,flink-application-version=blue,flink-deployment-type=jobmanager,
</code>```

I have an ingress defined as follows which I want to use to point to the top level service.

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    nginx.ingress.kubernetes.io/configuration-snippet: |
      proxy_set_header Accept-Encoding "";
      sub_filter '<head>' '<head> <base href="/happy-flink-ui/">';
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/auth-url: "https://$host/oauth2/auth"
    nginx.ingress.kubernetes.io/auth-signin: "https://$host/oauth2/start?rd=$escaped_request_uri"
  name: flink-secure-ingress-my-flink-app
  namespace: happy-flink-flink
spec:
  rules:
    - host: flinkui-myapp.foo.com
      http:
        paths:
          - path: /happy-flink-ui(/|$)(.*)
            backend:
              serviceName: my-flinkapp-14hdhsr // This works but....
              servicePort: 8081
</code>```

The issue I am facing is that the top level service keeps changing the hash at the end as the flink operator changes it at every deployment.. eg. myflinkapp-89hddew  .etc.

So I cannot have a static service name in the ingress definition.

So I am wondering if an ingress can choose a service based on a selector or a regular expression of the service name which can account for the top level app service name plus the hash at the end.

The flink-app-hash (i.e the hash part of the service name - 14hdsr) is also part of the Labels in the top level service. Anyway I could leverage that?

Wondering if default backend could be applied here?

Have folks using Flink operator solved this a different way?

答:
Unfortunately that's not possible OOB to use any kind of regex/wildcards/jsonpath/variables/references inside .backend.serviceName inside Ingres controller.
You are able to use regex only in path: Ingress Path Matching

And its not going to be implemented soon: Allow variable references in backend spec is in the hanged stage.

Would be very interesting to hear any possible solution for this. It was previously discussed on stack, however without any progress: https://stackoverflow.com/a/60810435/9929015

Body:
Hi all we have a Flink application with blue-green deployment which we get using the Flink operator.

Flinkk8soperator for Apache Flink. The operator spins up the following three K8s services after a deployment:

my-flinkapp-14hdhsr (Top level service)
my-flinkapp-green
my-flinkapp-blue

The idea is that one of the two among blue green would be active and would have pods (either blue or green).

And a selector to the the active one would be stored in the top level myflinkapp-14hdhsr service with the selector flink-application-version=blue. Or green. As follows:

Labels:  flink-app=my-flinkapp
         flink-app-hash=14hdhsr
         flink-application-version=blue
Annotations:       <none>
Selector:          flink-app=my-flinkapp,flink-application-version=blue,flink-deployment-type=jobmanager,

I have an ingress defined as follows which I want to use to point to the top level service.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    nginx.ingress.kubernetes.io/configuration-snippet: |
      proxy_set_header Accept-Encoding "";
      sub_filter '' ' <base href="/happy-flink-ui/">';
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/auth-url: "https://$host/oauth2/auth"
    nginx.ingress.kubernetes.io/auth-signin: "https://$host/oauth2/start?rd=$escaped_request_uri"
  name: flink-secure-ingress-my-flink-app
  namespace: happy-flink-flink
spec:
  rules:
    - host: flinkui-myapp.foo.com
      http:
        paths:
          - path: /happy-flink-ui(/|$)(.*)
            backend:
              serviceName: my-flinkapp-14hdhsr // This works but....
              servicePort: 8081

The issue I am facing is that the top level service keeps changing the hash at the end as the flink operator changes it at every deployment.. eg. myflinkapp-89hddew  .etc.

So I cannot have a static service name in the ingress definition.

So I am wondering if an ingress can choose a service based on a selector or a regular expression of the service name which can account for the top level app service name plus the hash at the end.

The flink-app-hash (i.e the hash part of the service name - 14hdsr) is also part of the Labels in the top level service. Anyway I could leverage that?

Wondering if default backend could be applied here?

Have folks using Flink operator solved this a different way?


问:
postgresql manual plpgsql function declaration section not understand
https://www.postgresql.org/docs/14/plpgsql-declarations.html#PLPGSQL-DECLARATION-PARAMETERS

```<code>CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
BEGIN
    RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
END;
$$ LANGUAGE plpgsql;
</code>```

is in_t alias sometable alias name? I try to replicate it by following:

```<code>create function conca_selected_col_emp( in_t public.emp) returns text as $$
    begin
    return in_t.name || in_t.department;
    end;
$$ LANGUAGE plpgsql;
</code>```

Obviously, this will not work...

答:
It should to work:

```<code>create table foo(a varchar, b varchar);

insert into foo values('hello', 'world');

create or replace function fx(arg foo)
returns varchar as $$
begin
   return arg.a || ', ' || arg.b;
end;
$$ language plpgsql;

postgres=# select fx(foo) from foo;
┌──────────────┐
│      fx      │
╞══════════════╡
│ hello, world │
└──────────────┘
(1 row)
</code>```

or alternative syntax:

```<code>postgres=# select foo.fx from foo;
┌──────────────┐
│      fx      │
╞══════════════╡
│ hello, world │
└──────────────┘
(1 row)
</code>```

Body:
https://www.postgresql.org/docs/14/plpgsql-declarations.html#PLPGSQL-DECLARATION-PARAMETERS

CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
BEGIN
    RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
END;
$$ LANGUAGE plpgsql;

is in_t alias sometable alias name? I try to replicate it by following:

create function conca_selected_col_emp( in_t public.emp) returns text as $$
    begin
    return in_t.name || in_t.department;
    end;
$$ LANGUAGE plpgsql;

Obviously, this will not work...

Body:
It should to work:

create table foo(a varchar, b varchar);

insert into foo values('hello', 'world');

create or replace function fx(arg foo)
returns varchar as $$
begin
   return arg.a || ', ' || arg.b;
end;
$$ language plpgsql;

postgres=# select fx(foo) from foo;
┌──────────────┐
│      fx      │
╞══════════════╡
│ hello, world │
└──────────────┘
(1 row)

or alternative syntax:

postgres=# select foo.fx from foo;
┌──────────────┐
│      fx      │
╞══════════════╡
│ hello, world │
└──────────────┘
(1 row)


问:
How to download an encrypted object from S3 and decrypt the same?
I have an encrypted object available on S3.

I would like to download it and decrypt it as well.

The object has been encrypted using CMK/KMS algorithm.

Inspite of seeing a few blogs, the steps to download the encrypted object and decrypt it is not clear. Please help.

答:
There are lot of examples for the service SDKs of how to do this, mainly you need the kms decrypt passing a blob param to decrypt your download data.

For example in Node.js, you will need something like this, passing the buffer for the downloaded s3 file:

```<code>const decryptData = (buffer) => {
    const params = {
        CiphertextBlob: buffer
    }
    return new Promise((resolve, reject) => {
        kms.decrypt(params, (err, data) => {
            if(err) reject(err);
            else resolve(data.Plaintext);
        })
    })
}
</code>```

To do this using the aws cli you can use the following command:

```<code>aws kms decrypt --ciphertext-blob fileb://${ENCRYPTED_S3_FILE} --query Plaintext --output text \
    | base64 --decode
</code>```

Body:
There are lot of examples for the service SDKs of how to do this, mainly you need the kms decrypt passing a blob param to decrypt your download data.

For example in Node.js, you will need something like this, passing the buffer for the downloaded s3 file:

const decryptData = (buffer) => {
    const params = {
        CiphertextBlob: buffer
    }
    return new Promise((resolve, reject) => {
        kms.decrypt(params, (err, data) => {
            if(err) reject(err);
            else resolve(data.Plaintext);
        })
    })
}

To do this using the aws cli you can use the following command:

aws kms decrypt --ciphertext-blob fileb://${ENCRYPTED_S3_FILE} --query Plaintext --output text \
    | base64 --decode


问:
Sitefinity RESTful API Webservice: GET a set of data items of contenttype returns 0 items?
I have a content type "bomeldungs" with 2 items in it.
image

I have set up a RESTful API webservice.
With the GET "API URL HERE" i must get all 2 items in a json format. It must look like this:
image

Calling the API URL in the Postman Application, im getting a successfull 200 OK Status, but in the JSON there are 0 items.
image

How can this happen?

答: Checked permissions? If you’re logged into the browser you’d see items, where you’d be anonymous in postman.</p>


问:
php null replacement function
there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.

i try to write the same function in php, which looks like below:

```<code>function replace_null($value, $replace) {
    if (!isset($value)) {
        return $replace;
    } else {
        return $value;
    }
}

$address = replace_null($data['address'], 'Address is not available.');
</code>```

of course, if $data['address'] is found null, php will stop executing the code and replace_null won't be called.

i'm currently using ternary

```<code>(isset(data['address']) ? data['address'] : 'Address is not available.');
</code>```

but i think replace_null, if it works, will offer a more convenient way.

is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.

thanks in advance.

答:
You could pass the array and the key separately like this:</p>

```<code>function valueOrDefault($array, $key, $default) {
    return isset($array[$key]) ? $array[$key] : $default;
}

$address = valueOrDefault($data, 'address', 'Address is not available.');
</code>```

Title: php null replacement function

Body:
there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.

i try to write the same function in php, which looks like below:

function replace_null($value, $replace) {
    if (!isset($value)) {
        return $replace;
    } else {
        return $value;
    }
}

$address = replace_null($data['address'], 'Address is not available.');

of course, if $data['address'] is found null, php will stop executing the code and replace_null won't be called.

i'm currently using ternary

(isset(data['address']) ? data['address'] : 'Address is not available.');

but i think replace_null, if it works, will offer a more convenient way.

is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.

thanks in advance.

Body:
You could pass the array and the key separately like this:

function valueOrDefault($array, $key, $default) {
    return isset($array[$key]) ? $array[$key] : $default;
}

$address = valueOrDefault($data, 'address', 'Address is not available.');


问:
SFCC Customer Service Center custom actions
I would like to know if somebody already customized the customer service center in SFCC project via custom actions.
I found only this page https://documentation.b2c.commercecloud.salesforce.com/DOC3/topic/com.demandware.dochelp/content/b2c_commerce/topics/customer_service_center/b2c_custom_actions.html

on the documentation.

答: You can find examples of CSC customization here https://github.com/SalesforceCommerceCloud/customer-service-center The Customer Service Center repository contains cartridges to illustrate how Customer Service Center can be customized.</p>


问:
rails plugin installation and upgrades
I have a rails plugin written in v 2.1.1.  When I install it in a 2.2.2 app, it breaks the app.  I'm unable to use polymorphic routes   so something like

```<code><%= link_to @object %>
</code>```

Doesn't work, because it says:
ActionView::TemplateError (undefined method 'polymorphic_path' for #<ActionView::Base:0x1a95c1c>)

If I script/plugin remove the plugin, it's still broken.  So I have a two part question:

What is script/plugin install doing besides just copying the files into vender/plugins.  From the output after installing it, it just looks like it's copying the files over, but clearly something else is going on behind the scenes, because removing it doesn't fix the problem

What do I need to do to update this plugin for rails 2.2.2.  I don't know much about plugins, but I don't see anything that has specific version code in the plugin itself, so I can't figure out what exactly is breaking and what needs to be updated.  Obviously this one is kind of tough to answer without seeing the code, but it's not actually the code in the plugin that's breaking, it's the plugin that is affecting my whole rails config.

Does anyone have experience with upgrading plugins to work for newer versions of rails?

答: Turns out the plugin was overwriting the RouteSet::draw method and just needed to be updated to the 2.2.2 draw code :P</p>

OwnerDisplayName: brad

Title: rails plugin installation and upgrades

Body:
I have a rails plugin written in v 2.1.1.  When I install it in a 2.2.2 app, it breaks the app.  I'm unable to use polymorphic routes   so something like

<%= link_to @object %>

Doesn't work, because it says:
ActionView::TemplateError (undefined method 'polymorphic_path' for #<ActionView::Base:0x1a95c1c>)

If I script/plugin remove the plugin, it's still broken.  So I have a two part question:

What is script/plugin install doing besides just copying the files into vender/plugins.  From the output after installing it, it just looks like it's copying the files over, but clearly something else is going on behind the scenes, because removing it doesn't fix the problem

What do I need to do to update this plugin for rails 2.2.2.  I don't know much about plugins, but I don't see anything that has specific version code in the plugin itself, so I can't figure out what exactly is breaking and what needs to be updated.  Obviously this one is kind of tough to answer without seeing the code, but it's not actually the code in the plugin that's breaking, it's the plugin that is affecting my whole rails config.

Does anyone have experience with upgrading plugins to work for newer versions of rails?


答:
You can use the stringi package if you want:

```<code>> stringi::stri_rand_shuffle(c("hello", "goodbye"))
[1] "oellh"   "deoygob"
</code>```

Title: How to randomly reshuffle letters in words

Body:
I am trying to make a word scrambler in R. So i have put some words in a collection and tried to use strsplit() to split the letters of each word in the collection.

But I don't understand how to jumble the letters of a word and merge them to one word in R Tool. Does anyone know how can I solve this?

This is what I have done
enter image description here

Body:
You can use the stringi package if you want:

> stringi::stri_rand_shuffle(c("hello", "goodbye"))
[1] "oellh"   "deoygob"


问:
Best/suitable algorithm for project slot assignment problem?
I have a requirement where there are multiple projects available with corresponding schedule dates and schedule reviewing dates.

There will be N number of projects available and each project will have a schedule date as part of the deliverable process. The requirement is to assign each project to the earliest available project schedule review slot. Lets say a project is having a schedule date which is tomorrow, i need to find a available review date slot prior to the schedule date and assign the project based on priority level. Maximum I can assign a project to the earliest available slot is 7 days prior to the actual scheduling date of the project.
For example

Project
Complexity
Schedule Date
schedule review slot

1
A
15-02-2022
12-02-2022  09:00 - 10:00

2
B
15-02-2022
12-02-2022  11:00 - 12:00

3
C
15-02-2022
12-02-2022  12:00 - 01:00

4
A
16-02-2022
13-02-2022  09:00 - 10:00

My desired output

Project
Complexity
Schedule Date
schedule review slot

1
A
15-02-2022
12-02-2022  09:00 - 10:00

4
A
16-02-2022
12-02-2022  12:00 - 01:00

2
B
15-02-2022
12-02-2022  11:00 - 12:00

3
C
15-02-2022
13-02-2022  09:00 - 10:00

I am new to algorithm concepts. So could anyone please guide me in this

答:
What you can do is the following:

Sort the projects into groups with equal complexity/priority, so that all projects with priority A are in the same group, all projects with priority B are in the same group and so on.

Sort the projects in each group by their schedule date, so that the projects with the earliest schedule date come first.

Sort the awailable review time slots by time, so that the earliest time slot comes first.

With this input you can go with the following algorithm:

Take the first (earliest) time slot. Let's call it T.

Take the first (earliest) project P from the sorted priority A list.
 If P is scheduled less than 7 days after T, assign it to T, remove T and P from their lists and go to step 1.

Else try the same for the earliest project from the priority B and C lists. If none is scheduled less than 7 days after the T, leave the time slot T unassigned and move back to step 1.


问:
Syntax for outputting raw with 'using'
I'm implementing AuthorizeNet into my site and as per [this posting] I am to use something like:

```<code>@using (Html.BeginSIMForm("http://...", 1.99M, "...", "...", true))
{
    @Html.CheckoutFormInputs(true);
    @Html.Hidden("order_id", "1234");
    <input type = "submit" value = "Pay" />
}
</code>```

the trouble is that the BeginSIMForm method outputs HTML which, of course, gets escaped by Razor, so I need to output raw.

I've tried:

```<code>@Html.Raw(using(html.BeginSIMForm()) { ... })
</code>```

but that's no good.  I can't quite get the syntax right.  is there a way to tell Razor to generate raw output between certain markers?

* update *

I missed something which was in the posting.  what I need to do is wrap the call to .CheckoutFormInputs() like this:

```<code>@Html.Raw(Html.CheckoutFormInputs(true));
</code>```

and that produces the right output... however, the call to .BeginSIMForm() produces output (a form) at the very top of my page and breaks everything.  grr...

答: I've had a look at the source code for their helper.  what garbage.  I recommend anyone wanting to implement this service on Razor not bother downloading it.  I will code the forms by hand.  may come back with some code.</p>

Title: Syntax for outputting raw with 'using'

Body:
I'm implementing AuthorizeNet into my site and as per [this posting] I am to use something like:

@using (Html.BeginSIMForm("http://...", 1.99M, "...", "...", true))
{
    @Html.CheckoutFormInputs(true);
    @Html.Hidden("order_id", "1234");
    <input type = "submit" value = "Pay" />
}

the trouble is that the BeginSIMForm method outputs HTML which, of course, gets escaped by Razor, so I need to output raw.

I've tried:

@Html.Raw(using(html.BeginSIMForm()) { ... })

but that's no good.  I can't quite get the syntax right.  is there a way to tell Razor to generate raw output between certain markers?

* update *

I missed something which was in the posting.  what I need to do is wrap the call to .CheckoutFormInputs() like this:

@Html.Raw(Html.CheckoutFormInputs(true));

and that produces the right output... however, the call to .BeginSIMForm() produces output (a form) at the very top of my page and breaks everything.  grr...


问:
When preprocessing Words in NLP, it changes the assumed numeric values after starting a new kernel
I'm using Anaconda Spyder as the editor( python 3.8),
my code is about to identify the phishing URLs based on NLP. Data was preprocessed using 'One hot representation' technique and trained using LSTM. after the training model gets around 90% accuracy. the problem is when I start a new kernel /after restarting the computer model does not give the accuracy as it gave in training.( problem doesn't occur when I use same kernel which used to train). I found that it is because every time I start a new kernel and preprocess data using 'One hot representation' it assumes different values.

ex- if google.com assumed as google = 1 and com = 2  when I use a new kernel it can be assumed as google = 5 and com = 6. so the model was trained using different values but prediction cannot do best because of value changing.

so is there any technique or technology which I can solve this problem. IF I can assume same value for every time I guess problem can be solved.

code used for preprocessing

```<code>url = 'https://www.google.com'
messages = urlparse(url).netloc  #taking only the domain name from URL

corpus=[]
voc_size = 10000

review = re.sub('[^a-zA-Z]',' ',messages)  #remove none a-z characters
review = review.lower()
review = review.split()
review=' '.join(review)
corpus.append(review)

#assuming numerical values for words

from tensorflow.keras.preprocessing.text import one_hot
onehot_repr=[one_hot(words,voc_size)for words in corpus]
print(onehot_repr)
</code>```

If there is any technique of library that I can surpass this problem It would be helpful.

答:
If you insisted on using tensorflow.keras.preprocessing.text.one_hot object the easiest way is to save/load vocabulary for reuse.

```<code>import pickle
corpus = 'This is a test'.split()
from tensorflow.keras.preprocessing.text import one_hot
onehot_repr=[one_hot(words,20)for words in corpus]
mapping = {c:o for c,o in zip(corpus, onehot_repr)}
print('Before', mapping)
with open('mapping.pkl', 'wb') as fout:
  pickle.dump(mapping, fout)
with open('mapping.pkl', 'rb') as fout:
  mapping = pickle.load(fout)
print('After', mapping)
</code>```

output:

```<code>Before {'This': [3], 'is': [14], 'a': [16], 'test': [13]}
After {'This': [3], 'is': [14], 'a': [16], 'test': [13]}
</code>```

but the more principled way in my opinion is using handy objects like sklearn.preprocessing.OneHotEncoder.

Body:
I'm using Anaconda Spyder as the editor( python 3.8),
my code is about to identify the phishing URLs based on NLP. Data was preprocessed using 'One hot representation' technique and trained using LSTM. after the training model gets around 90% accuracy. the problem is when I start a new kernel /after restarting the computer model does not give the accuracy as it gave in training.( problem doesn't occur when I use same kernel which used to train). I found that it is because every time I start a new kernel and preprocess data using 'One hot representation' it assumes different values.

ex- if google.com assumed as google = 1 and com = 2  when I use a new kernel it can be assumed as google = 5 and com = 6. so the model was trained using different values but prediction cannot do best because of value changing.

so is there any technique or technology which I can solve this problem. IF I can assume same value for every time I guess problem can be solved.

code used for preprocessing

url = 'https://www.google.com'
messages = urlparse(url).netloc  #taking only the domain name from URL

corpus=[]
voc_size = 10000

review = re.sub('[^a-zA-Z]',' ',messages)  #remove none a-z characters
review = review.lower()
review = review.split()
review=' '.join(review)
corpus.append(review)

#assuming numerical values for words

from tensorflow.keras.preprocessing.text import one_hot
onehot_repr=[one_hot(words,voc_size)for words in corpus]
print(onehot_repr)

If there is any technique of library that I can surpass this problem It would be helpful.

Body:
If you insisted on using tensorflow.keras.preprocessing.text.one_hot object the easiest way is to save/load vocabulary for reuse.

import pickle
corpus = 'This is a test'.split()
from tensorflow.keras.preprocessing.text import one_hot
onehot_repr=[one_hot(words,20)for words in corpus]
mapping = {c:o for c,o in zip(corpus, onehot_repr)}
print('Before', mapping)
with open('mapping.pkl', 'wb') as fout:
  pickle.dump(mapping, fout)
with open('mapping.pkl', 'rb') as fout:
  mapping = pickle.load(fout)
print('After', mapping)

output:

Before {'This': [3], 'is': [14], 'a': [16], 'test': [13]}
After {'This': [3], 'is': [14], 'a': [16], 'test': [13]}

but the more principled way in my opinion is using handy objects like sklearn.preprocessing.OneHotEncoder.