问:
OpenAndActivateDocument generates ArgumentException
I have to call a function that needs my active document to be close.
Since I can't close an active document I create an empty project and use OpenAndActivateDocument to set the empty project to active. Than I close the first document and call that function, after that I call OpenAndActivateDocument to reopen the first document. When I call OpenAndActivateDocument an ArgumentException is generated: The file is not a Revit document.

I have checked the string filePath before the exception and it is a valid path to a project.

Here is my code:

```<code>try{
 string filePath = mainDoc.PathName;
      string fileName = Path.GetFileNameWithoutExtension(filePath);
      try { mainDoc.Save(); } catch (Exception) { }
      Document placeHolder = uiapp.Application.NewProjectDocument(UnitSystem.Metric);     //Creo un progetto temporaneo vuoto
      if (File.Exists(@"C:\Users\Public\placeholder.rvt")) {
        File.Delete(@"C:\Users\Public\placeholder.rvt");
      }
      placeHolder.SaveAs(@"C:\Users\Public\placeholder.rvt");
      placeHolder = uiapp.OpenAndActivateDocument(placeHolder.PathName).Document;                                //Apro il progetto temporaneo e lo attivo
      mainDoc.Close(false);                                                               //Chiudo il progetto precedente

      if (!Documenta.messageBroker.SCheckInDoc(fileName, DcmRPC.DcmEnum.enumCheckinType.AutoIn, 0)) {   //Faccio il checkin del progetto
        TaskDialog.Show("Errore", "Impossibile effettuare il check in, codice documento: " + fileName);
        return Result.Failed;
      }

      mainDoc = uiapp.OpenAndActivateDocument(filePath).Document;                                            //Riapro il progetto principale
      placeHolder.Close(false);                                                           //Chiudo il progetto temporaneo
      if (File.Exists(@"C:\Users\Public\placeholder.rvt")) {
        File.Delete(@"C:\Users\Public\placeholder.rvt");
      }
    }
    catch (Exception exc) {
      TaskDialog.Show("Errore", exc.ToString());
      message = exc.Message;
      return Result.Failed;
    }
</code>```

答: Solved it. There simply wasn't enough space on the disk.</p>

Body:
I have to call a function that needs my active document to be close.
Since I can't close an active document I create an empty project and use OpenAndActivateDocument to set the empty project to active. Than I close the first document and call that function, after that I call OpenAndActivateDocument to reopen the first document. When I call OpenAndActivateDocument an ArgumentException is generated: The file is not a Revit document.

I have checked the string filePath before the exception and it is a valid path to a project.

Here is my code:

try{
 string filePath = mainDoc.PathName;
      string fileName = Path.GetFileNameWithoutExtension(filePath);
      try { mainDoc.Save(); } catch (Exception) { }
      Document placeHolder = uiapp.Application.NewProjectDocument(UnitSystem.Metric);     //Creo un progetto temporaneo vuoto
      if (File.Exists(@"C:\Users\Public\placeholder.rvt")) {
        File.Delete(@"C:\Users\Public\placeholder.rvt");
      }
      placeHolder.SaveAs(@"C:\Users\Public\placeholder.rvt");
      placeHolder = uiapp.OpenAndActivateDocument(placeHolder.PathName).Document;                                //Apro il progetto temporaneo e lo attivo
      mainDoc.Close(false);                                                               //Chiudo il progetto precedente

      if (!Documenta.messageBroker.SCheckInDoc(fileName, DcmRPC.DcmEnum.enumCheckinType.AutoIn, 0)) {   //Faccio il checkin del progetto
        TaskDialog.Show("Errore", "Impossibile effettuare il check in, codice documento: " + fileName);
        return Result.Failed;
      }

      mainDoc = uiapp.OpenAndActivateDocument(filePath).Document;                                            //Riapro il progetto principale
      placeHolder.Close(false);                                                           //Chiudo il progetto temporaneo
      if (File.Exists(@"C:\Users\Public\placeholder.rvt")) {
        File.Delete(@"C:\Users\Public\placeholder.rvt");
      }
    }
    catch (Exception exc) {
      TaskDialog.Show("Errore", exc.ToString());
      message = exc.Message;
      return Result.Failed;
    }


来源: stackexchange

问:
Laravel - whereHas last relation is = 'manual'
I have a model Lead which 'belongsToMany' Status through lead_has_status table.

What I want is to get all the Leads where the last (current) status of that lead is 'manual'.

I've tried this

```<code>$leads = Lead::whereHas('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

But since the Lead still has it's old statuses linked to it, it returns every Lead that at some point had Status 'manual'. But I only want the Leads where current status is 'manual'. So I want to do something like

```<code>$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

Or

```<code>$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->latest()->first()->where('description', 'LIKE', '%' . $q . '%');
})->get();
</code>```

(I know this it not the way to do it, it's simply to express what I'm trying to do)

I hope the question makes sense, I am super confused right now.

答:
AFAIK there is no built-in eloquent function that gives you this kind of behaviour. If you would like to solve this with SQL only, you would have to look at the other answer using SQL function MAX in a sub-query and add raw queries in your Laravel code (probably a little bit more efficient then rejecting non-matching).

However you can filter your collection after retrieval and reject the elements that doesn't match your criteria.

Assuming the variable $q is of type string and contains a status e.g. "manual", something like this should do the job (code not tested).

```<code>$leads = Lead::whereHas('statuses', function ($query) use ($q) {
    $query->where('description', 'LIKE', '%' . $q . '%');
})
->with('statuses')
->get()
->reject(function($element) use($q) {
    $lastStatus = $element->statuses[count($element->statuses)-1];
    return (strpos($lastStatus->description, $q) === false);
});
</code>```

If you're column description should contain the exact string "manual" I would do it this way instead:

```<code>$leads = Lead::whereHas('statuses', function ($query) {
    $query->where('description', 'manual');
})
->with('statuses')
->get()
->reject(function($element) {
    $lastStatus = $element->statuses[count($element->statuses)-1];
    return $lastStatus->description !== 'manual';
});
</code>```

The whereHas method will not remove any relations like you need. The whereHas method will only say "select the records that have one or more children that matches this criteria", however all of the children records will be accessible, even the once that doesn't matches your criteria, as long as the parent has one that matches.

What you would like to say is "select the records that have one or more children that matches this criteria (whereHas) THEN remove all parents where the last child record does not match the record I am looking for (reject)"

Edit: Updated code using ->with('statuses') for improved performance.

ContentLicense: CC BY-SA 4.0

Body:
I have a model Lead which 'belongsToMany' Status through lead_has_status table.

What I want is to get all the Leads where the last (current) status of that lead is 'manual'.

I've tried this

$leads = Lead::whereHas('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();

But since the Lead still has it's old statuses linked to it, it returns every Lead that at some point had Status 'manual'. But I only want the Leads where current status is 'manual'. So I want to do something like

$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->where('description', 'LIKE', '%' . $q . '%');
})->get();

Or

$leads = Lead::whereLast('statuses', function ($query) use ($q) {
  $query->latest()->first()->where('description', 'LIKE', '%' . $q . '%');
})->get();

(I know this it not the way to do it, it's simply to express what I'm trying to do)

I hope the question makes sense, I am super confused right now.

Body:
AFAIK there is no built-in eloquent function that gives you this kind of behaviour. If you would like to solve this with SQL only, you would have to look at the other answer using SQL function MAX in a sub-query and add raw queries in your Laravel code (probably a little bit more efficient then rejecting non-matching).

However you can filter your collection after retrieval and reject the elements that doesn't match your criteria.

Assuming the variable $q is of type string and contains a status e.g. "manual", something like this should do the job (code not tested).

$leads = Lead::whereHas('statuses', function ($query) use ($q) {
    $query->where('description', 'LIKE', '%' . $q . '%');
})
->with('statuses')
->get()
->reject(function($element) use($q) {
    $lastStatus = $element->statuses[count($element->statuses)-1];
    return (strpos($lastStatus->description, $q) === false);
});

If you're column description should contain the exact string "manual" I would do it this way instead:

$leads = Lead::whereHas('statuses', function ($query) {
    $query->where('description', 'manual');
})
->with('statuses')
->get()
->reject(function($element) {
    $lastStatus = $element->statuses[count($element->statuses)-1];
    return $lastStatus->description !== 'manual';
});

The whereHas method will not remove any relations like you need. The whereHas method will only say "select the records that have one or more children that matches this criteria", however all of the children records will be accessible, even the once that doesn't matches your criteria, as long as the parent has one that matches.

What you would like to say is "select the records that have one or more children that matches this criteria (whereHas) THEN remove all parents where the last child record does not match the record I am looking for (reject)"

Edit: Updated code using ->with('statuses') for improved performance.


问:
How do I limit access to my Netlify Serverless function
I've searched the netlify docs and I can't figure this out.

I have a serverless function located here

```<code>/.netlify/functions/orderCreate
</code>```

But I can hit this in my browser or with curl and it tries to create an order. If an attacker finds out about this function they could create thousands fake orders in my db.

I know I can do some simple checks like make sure it is a HTTP post, or make sure it has some valid session ID but I would really like some type of auth or better security.

Because all requests should come from the a client side react app via an ajax request can I limit it to the same domain or something ?

答:
As Netlify doesn't provide a way to check and specific requests based on origin, you could do it manually from inside your function's code and send a 403 response if the Origin isn't your client-side domain:

```<code>exports.handler = function(event, context, callback) {
    if (event.headers["Origin"] !== "https://whateverisyourdomainname.netlify.com")
        return callback(null, { status: 403 })

    // else, do whatever your function does
}
</code>```

Recent browsers do prevent a user from setting the Origin header himself. However, nothing prevents anyone to craft a curl request and to spoof the Origin header to hit your function. If you wish to really prevent it, you should set-up a proper authentication process to your application.

Body:
I've searched the netlify docs and I can't figure this out.

I have a serverless function located here

/.netlify/functions/orderCreate

But I can hit this in my browser or with curl and it tries to create an order. If an attacker finds out about this function they could create thousands fake orders in my db.

I know I can do some simple checks like make sure it is a HTTP post, or make sure it has some valid session ID but I would really like some type of auth or better security.

Because all requests should come from the a client side react app via an ajax request can I limit it to the same domain or something ?

Body:
As Netlify doesn't provide a way to check and specific requests based on origin, you could do it manually from inside your function's code and send a 403 response if the Origin isn't your client-side domain:

exports.handler = function(event, context, callback) {
    if (event.headers["Origin"] !== "https://whateverisyourdomainname.netlify.com")
        return callback(null, { status: 403 })

    // else, do whatever your function does
}

Recent browsers do prevent a user from setting the Origin header himself. However, nothing prevents anyone to craft a curl request and to spoof the Origin header to hit your function. If you wish to really prevent it, you should set-up a proper authentication process to your application.


问:
How do you run static content for using ( SpringBoot 2.x + weblogic + *.war ) from a classpath an application?
I have a weblogic server that I run into Inlellij Idea for audit work of an application.
I made web-app based on SpringBoot 2.x. I am using Intellij Idea 2019 and there I configure a deploy my webapplication on weblogic 12.x.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.weblogic</groupId>
    <artifactId>weblogic</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>weblogic</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

        <version.apache.maven.plugins>3.8.1</version.apache.maven.plugins>
        <version.mapstruct>1.3.0.Final</version.mapstruct>

        <version.apache.common.lang3>3.9</version.apache.common.lang3>
        <version.apache.commons.text>1.8</version.apache.commons.text>
        <version.apache.commons.beanutils>1.9.4</version.apache.commons.beanutils>
        <version.datasource.proxy>1.6</version.datasource.proxy>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>false</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

```

<p><strong>src/main/webapp/WEB-INF/web.xml</strong></p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

</web-app>
</code>```

src/main/webapp/WEB-INF/weblogic.xml

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app
                      http://xmlns.oracle.com/weblogic/weblogic-web-app/1.9/weblogic-web-app.xsd">

    <wls:weblogic-version>12.2.1.4.0</wls:weblogic-version>
    <wls:context-root>/api</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j.*</wls:package-name>
            <wls:package-name>org.springframework.*</wls:package-name>
            <wls:package-name>javax.persistence.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>

```

<p><strong>src/main/webapp/index.html</strong></p>

<p>When I run weblogic by Intellij Idea I get index.html by url - http://localhost:7001/api</p>

<p>So, It works.</p>

<p>But I need more complex static content and I want to place it into an application classpath.</p>

<p>I made so…</p>

<p><strong>src/main/resources/templates/pages/index.html</strong></p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Weblogic!!!</title>
    <link type="text/css" href="/static/css/style.css" rel="stylesheet"/>
</head>
<body>
<div class="st">
    Hello Weblogic!!!
</div>

</body>
</html>

</code>```

src/main/resources/static/css/style.css

.st{
    color: red;
    font-size: 35px;
}

```

<p>And then…</p>

<p><strong>src/main/java/com/weblogic/weblogic/mvc/config/MyMvcConfig.java</strong></p>

<pre class="lang-java prettyprint-override"><code>package com.weblogic.weblogic.mvc.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler(
                "/static/css/**",
                "/templates/pages/**")
                .addResourceLocations(
                        "classpath:/",
                        "classpath:/static/css/",
                        "classpath:/templates/pages/");
    }
}

</code>```

But I get … Error 500--Internal Server Error
  java.lang.NullPointerException    at
  weblogic.servlet.internal.ServletResponseImpl.sendContentError(ServletResponseImpl.java:738)
    at
  weblogic.servlet.internal.ServletResponseImpl.sendError(ServletResponseImpl.java:796)
    at
  weblogic.servlet.internal.ServletResponseImpl.sendError(ServletResponseImpl.java:713)
    at
  org.springframework.boot.web.servlet.support.ErrorPageFilter$ErrorWrapperResponse.sendErrorIfNecessary(ErrorPageFilter.java:349)
    at
  org.springframework.boot.web.servlet.support.ErrorPageFilter$ErrorWrapperResponse.getWriter(ErrorPageFilter.java:363)
    at
  org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$StaticView.render(ErrorMvcAutoConfiguration.java:227)
    at
  org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
    at
  org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)

who has any ideas how to fix this ?

答:
You must use "template engine" – Thymeleaf. It doesn't work any other way (I would like to use pure (html + bootstrap), but it's not clear how to configure it).

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>web.spring.boot.jar</groupId>
    <artifactId>web-spring-boot-jar</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>web-spring-boot-jar</name>
    <packaging>war</packaging>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

</code>```

The structure of the static resources

src/main/resources/static/css/style.css

src/main/resources/templates/index.html

src/main/resources/templates/pages/login/login.html

*.properties

src/main/resources/application.properties

These settings don't work.

    spring.mvc.servlet.path=/api
    server.servlet.context-path=/api
    server.servlet.contextPath=/api

```

<p>These settings could not be applied. </p>

<ul>
<li><strong>Configuration files</strong> -  *.xml</li>
</ul>

<p>src/main/webapp/WEB-INF/web.xml</p>

<pre class="lang-xml prettyprint-override"><code>   <?xml version="1.0" encoding="UTF-8"?>
   <web-app xmlns="http://java.sun.com/xml/ns/javaee"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
           http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd"
            version="4.0">

   </web-app>
</code>```

If this file is missing, then the deployment occurs with errors ( in the development environment, you can see this in the console).

src/main/webapp/WEB-INF/weblogic.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <wls:weblogic-web-app
            xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            https://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
            http://xmlns.oracle.com/weblogic/weblogic-web-app
            https://xmlns.oracle.com/weblogic/weblogic-web-app/1.9/weblogic-web-app.xsd">

        <wls:context-root>rst</wls:context-root>
        <wls:container-descriptor>
            <wls:prefer-application-packages>
                <wls:package-name>org.slf4j</wls:package-name>
            </wls:prefer-application-packages>
        </wls:container-descriptor>
    </wls:weblogic-web-app>

```

<pre class="lang-xml prettyprint-override"><code>        <wls:context-root>rst</wls:context-root>
</code>```

Here you need to be careful with choosing a name for the root context of the application (for example, if you chose a name for the context - /web, - > there will be an error, since this name is reserved somewhere).

```<code>                             Entry point
</code>```

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan

    public class WebSpringBootJarApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

        public static void main(String[] args) {
            SpringApplication.run(WebSpringBootJarApplication.class, args);
        }

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(WebSpringBootJarApplication.class);
        }

    }

```

<ul>
<li><p>@SpringBootConfiguration</p></li>
<li><p>@EnableAutoConfiguration</p></li>
<li><p>@ComponentScan</p></li>
<li><p>You must have these 3 annotations, otherwise nothing will work.</p>

<p>The documentation says that <strong>@SpringBootConfiguration</strong>, replaces annotations:</p></li>
<li>@Configuration, </li>
<li>@EnableAutoConfiguration </li>
<li>@ComponentScan</li>
</ul>

<p><strong>@SpringBootConfiguration</strong> - indicates that this class provides an application
<strong>SpringBoot</strong></p>

<p>It can also be used as an alternative to the <strong>@Configuration</strong> annotation, because the configuration can be found automatically.</p>

<p><strong>@EnableAutoConfiguration</strong>  - enables automatic configuration of Spring ApplicationContext by scanning class path components and registering beans that match different conditions. </p>

<p>That is, this annotation tries to guess and configure the beans that you may need.</p>

<p>Auto-configuration of classes, usually applied based on classpath
your application and on those beans that you have defined.</p>

<ul>
<li><p>When using the <strong>@SpringBootConfiguration</strong> annotation, the context configuration is enabled automatically and the annotation is added, which will not have any additional effect…
But what I see here is quite different…
Without this annotation, nothing works... That is, we don't get the requested resources.</p></li>
<li><p>@ComponentScan  - Directive configures component scanning for the classes marked with @Configuration.
Provides support in parallel using the configuration described in XML format in the element: <strong></strong></p></li>
</ul>

<p>... But I didn't even specify the packages to scan....</p>

<p>And without specifying this annotation, I also can't access resources... ???</p>

<p>Why is that? I don't know…</p>

<p>What do I need to implement WebApplicationInitializer , - I don't know…</p>

<p>https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-weblogic</p>

<ul>
<li>Contollers</li>
</ul>

<p>src/main/java/web/spring/boot/jar/webspringbootjar/controller/index/IndexController.java</p>

<ul>
<li><p>IndexController</p>

<pre class="lang-java prettyprint-override"><code>@Controller
public class IndexController {

    @RequestMapping(value="/", method= RequestMethod.GET)
    public String index() {
        return "index";
    }
}

</code>```

src/main/java/web/spring/boot/jar/webspringbootjar/controller/login/LoginController.java

LoginController

@Controller
public class LoginController {

    @GetMapping(value = {"/log"})
    public ModelAndView showUsersPage() {

        return new ModelAndView("pages/login/login.html");
    }

}

```</li>
</ul>

<p>The creation of an artifact (Intellij Idea)
- Project Structure/Artifacts
- Alt + Insert
- Web Application: Exploded -> From module
 There is the path to the directory with your project will be specified.</p>

<p>You can also configure
- Project Structure/Facets</p>

<p>And then…</p>

<p>Run\Edit Configuration</p>

<p>Here you configure - weblogic…</p>

<p>URL to the app(in my case)
http://localhost:7001/rst/</p>

<p>The same access will be available when you migrate <strong>.*war</strong> from the development environment and deploy it to an external weblogic server. </p>

<p>If you start an external server, you get an error

<p>This means that you need to run <strong>maven</strong> and  it must will make  a *.war-file…</p>

<p><strong>Also It doesn't work...</strong></p>

<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = { ServletContextConfig.class })
public class ServletContextConfig implements WebMvcConfigurer {

    @Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
    webServerFactoryCustomizer() {
        return factory -> factory.setContextPath("/rootweb");
    }

}

</code>```

I suppose we only can use xml-configuration for servlet-context here.

If someone can add something, please specify what is wrong....

Can who has what ideas, about my issues which arose during this messages ....

Body:
I have a weblogic server that I run into Inlellij Idea for audit work of an application.
I made web-app based on SpringBoot 2.x. I am using Intellij Idea 2019 and there I configure a deploy my webapplication on weblogic 12.x.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.weblogic</groupId>
    <artifactId>weblogic</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>weblogic</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

        <version.apache.maven.plugins>3.8.1</version.apache.maven.plugins>
        <version.mapstruct>1.3.0.Final</version.mapstruct>

        <version.apache.common.lang3>3.9</version.apache.common.lang3>
        <version.apache.commons.text>1.8</version.apache.commons.text>
        <version.apache.commons.beanutils>1.9.4</version.apache.commons.beanutils>
        <version.datasource.proxy>1.6</version.datasource.proxy>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>false</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

</web-app>

src/main/webapp/WEB-INF/weblogic.xml

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app
                      http://xmlns.oracle.com/weblogic/weblogic-web-app/1.9/weblogic-web-app.xsd">

    <wls:weblogic-version>12.2.1.4.0</wls:weblogic-version>
    <wls:context-root>/api</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j.*</wls:package-name>
            <wls:package-name>org.springframework.*</wls:package-name>
            <wls:package-name>javax.persistence.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>

src/main/webapp/index.html

When I run weblogic by Intellij Idea I get index.html by url - http://localhost:7001/api

So, It works.

But I need more complex static content and I want to place it into an application classpath.

I made so…

src/main/resources/templates/pages/index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello Weblogic!!!</title>
    <link type="text/css" href="/static/css/style.css" rel="stylesheet"/>

    Hello Weblogic!!!

src/main/resources/static/css/style.css

.st{
    color: red;
    font-size: 35px;
}

And then…

src/main/java/com/weblogic/weblogic/mvc/config/MyMvcConfig.java

package com.weblogic.weblogic.mvc.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler(
                "/static/css/**",
                "/templates/pages/**")
                .addResourceLocations(
                        "classpath:/",
                        "classpath:/static/css/",
                        "classpath:/templates/pages/");
    }
}

But I get … Error 500--Internal Server Error
  java.lang.NullPointerException    at
  weblogic.servlet.internal.ServletResponseImpl.sendContentError(ServletResponseImpl.java:738)
    at
  weblogic.servlet.internal.ServletResponseImpl.sendError(ServletResponseImpl.java:796)
    at
  weblogic.servlet.internal.ServletResponseImpl.sendError(ServletResponseImpl.java:713)
    at
  org.springframework.boot.web.servlet.support.ErrorPageFilter$ErrorWrapperResponse.sendErrorIfNecessary(ErrorPageFilter.java:349)
    at
  org.springframework.boot.web.servlet.support.ErrorPageFilter$ErrorWrapperResponse.getWriter(ErrorPageFilter.java:363)
    at
  org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$StaticView.render(ErrorMvcAutoConfiguration.java:227)
    at
  org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
    at
  org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)

who has any ideas how to fix this ?

Body:
You must use "template engine" – Thymeleaf. It doesn't work any other way (I would like to use pure (html + bootstrap), but it's not clear how to configure it).

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>web.spring.boot.jar</groupId>
    <artifactId>web-spring-boot-jar</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>web-spring-boot-jar</name>
    <packaging>war</packaging>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

The structure of the static resources

src/main/resources/static/css/style.css

src/main/resources/templates/index.html

src/main/resources/templates/pages/login/login.html

*.properties

src/main/resources/application.properties

These settings don't work.

    spring.mvc.servlet.path=/api
    server.servlet.context-path=/api
    server.servlet.contextPath=/api

These settings could not be applied.

Configuration files -  *.xml

src/main/webapp/WEB-INF/web.xml

   <?xml version="1.0" encoding="UTF-8"?>
   <web-app xmlns="http://java.sun.com/xml/ns/javaee"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
           http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd"
            version="4.0">

   </web-app>

If this file is missing, then the deployment occurs with errors ( in the development environment, you can see this in the console).

src/main/webapp/WEB-INF/weblogic.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <wls:weblogic-web-app
            xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            https://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
            http://xmlns.oracle.com/weblogic/weblogic-web-app
            https://xmlns.oracle.com/weblogic/weblogic-web-app/1.9/weblogic-web-app.xsd">

        <wls:context-root>rst</wls:context-root>
        <wls:container-descriptor>
            <wls:prefer-application-packages>
                <wls:package-name>org.slf4j</wls:package-name>
            </wls:prefer-application-packages>
        </wls:container-descriptor>
    </wls:weblogic-web-app>

        <wls:context-root>rst</wls:context-root>

Here you need to be careful with choosing a name for the root context of the application (for example, if you chose a name for the context - /web, - > there will be an error, since this name is reserved somewhere).

                             Entry point

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan

    public class WebSpringBootJarApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

        public static void main(String[] args) {
            SpringApplication.run(WebSpringBootJarApplication.class, args);
        }

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(WebSpringBootJarApplication.class);
        }

    }

@SpringBootConfiguration

@EnableAutoConfiguration

@ComponentScan

You must have these 3 annotations, otherwise nothing will work.

The documentation says that @SpringBootConfiguration, replaces annotations:

@Configuration,

@EnableAutoConfiguration

@ComponentScan

@SpringBootConfiguration - indicates that this class provides an application
SpringBoot

It can also be used as an alternative to the @Configuration annotation, because the configuration can be found automatically.

@EnableAutoConfiguration  - enables automatic configuration of Spring ApplicationContext by scanning class path components and registering beans that match different conditions.

That is, this annotation tries to guess and configure the beans that you may need.

Auto-configuration of classes, usually applied based on classpath
your application and on those beans that you have defined.

When using the @SpringBootConfiguration annotation, the context configuration is enabled automatically and the annotation is added, which will not have any additional effect…
But what I see here is quite different…
Without this annotation, nothing works... That is, we don't get the requested resources.

@ComponentScan  - Directive configures component scanning for the classes marked with @Configuration.
Provides support in parallel using the configuration described in XML format in the element:

... But I didn't even specify the packages to scan....

And without specifying this annotation, I also can't access resources... ???

Why is that? I don't know…

What do I need to implement WebApplicationInitializer , - I don't know…

https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-weblogic

Contollers

src/main/java/web/spring/boot/jar/webspringbootjar/controller/index/IndexController.java

IndexController

@Controller
public class IndexController {

    @RequestMapping(value="/", method= RequestMethod.GET)
    public String index() {
        return "index";
    }
}

src/main/java/web/spring/boot/jar/webspringbootjar/controller/login/LoginController.java

LoginController

@Controller
public class LoginController {

    @GetMapping(value = {"/log"})
    public ModelAndView showUsersPage() {

        return new ModelAndView("pages/login/login.html");
    }

}

The creation of an artifact (Intellij Idea)
- Project Structure/Artifacts
- Alt + Insert
- Web Application: Exploded -> From module
 There is the path to the directory with your project will be specified.

You can also configure
- Project Structure/Facets

And then…

Run\Edit Configuration

Here you configure - weblogic…

URL to the app(in my case)
http://localhost:7001/rst/

The same access will be available when you migrate .*war from the development environment and deploy it to an external weblogic server.

If you start an external server, you get an error

This means that you need to run maven and  it must will make  a *.war-file…

Also It doesn't work...

@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = { ServletContextConfig.class })
public class ServletContextConfig implements WebMvcConfigurer {

    @Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
    webServerFactoryCustomizer() {
        return factory -> factory.setContextPath("/rootweb");
    }

}

I suppose we only can use xml-configuration for servlet-context here.

If someone can add something, please specify what is wrong....

Can who has what ideas, about my issues which arose during this messages ....


问:
How do fread and fwrite distinguish between different data (types) in C?
I am working with a program and C (with Ubuntu and its bash) and using it to manipulate binary data files. First of all, when I use fopen(filename, 'w') it creates a file but without any extension. However, when I use vim filename it opens it up in some binary form.

For this question, when I use fwrite(array, sizeof(some struct), # of structs, filePointer) it writes (which I am not sure how in binary) into the file. When I use fread(anotherArray, sizeof(same struct), same # of structs, anotherFilePointer) it somehow magically knows how to read each struct in binary form and puts it into the array just by knowing its size and how much to read. What happens if I put a decimal value less than the number of structs there are in the # of structs parameter? How would fread know what to read correctly? How does it work in reading data just by looking at the sizes and not knowing what type of data it is?

答:
fwrite writes the bytes of the memory where the object is stored to the output stream and fread reads bytes from the input stream into the memory whose address it gets as an argument. No assumption is made regarding the types and representations of the C objects stored in this memory.

Hence a number of problems can occur:

the representation of basic types can differ from one compiler to another, one machine to another, one OS to another, possibly even depending on compiler switches. Writing the bytes of the memory representation of basic types makes sense only if you know you will be reading the file back into byte-compatible structures.

the mode for accessing the input and output files matters: as you mention, files must be open in binary mode to avoid any translation between memory representation and file contents such as what happens for text files on legacy systems. For example text mode on MS-Windows causes 0A bytes to convert to 0D 0A sequences on output and 0D bytes to be stripped on input, resulting in different contents for isolated 0D bytes in the initial content.

if the C structure contains pointers, the bytes written to the output represent the value of these pointers, not what they point to. Reading these values back into memory is highly likely to create invalid pointers and very unlikely to make any sense.

if the C structure has a flexible array at the end, its contents is not included in the sizeof(T) bytes written by fwrite or read by fread.

the C structure may contain padding between members, causing the output file to contain non  deterministic bytes, which might be a problem in some circumstances.

if the C structure has arrays with only partial meaningful contents, such as char arrays containing C strings, beware that fwrite will write the bytes beyond the null terminator, which should not be meaningful, but might be sensitive information such as password fragments or other meaningful data. Carefully erasing such arrays may avoid this issue, but padding bytes cannot be erased reliably, so this solution is not perfect.

For all the above reasons and other ones, reading/writing binary data is to be reserved to very specific cases where the programmer knows exactly what is happening. For other purposes, saving as text files in human readable form is much preferred.


问:
Streaming frames from the screen, generating a video
If I want to refresh the image I have to keep closing the window to refresh it. Is it possible without keep closing the window?
Here is the code:</p>

```<code>import numpy
import cv2
from PIL import ImageGrab
while True:

    img = ImageGrab.grab(bbox=(765,155,1135,195))
    img_np = numpy.array(img)
    frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
    cv2.imshow("frame",frame)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
</code>```

答:
cv2.waitKey(0) waits without timeout, replace it with cv2.waitKey(time_in_msec).

Example for refreshing at about 10Hz:

```<code>import numpy
import cv2
from PIL import ImageGrab

while True:
    img = ImageGrab.grab(bbox=(765,155,1135,195))
    img_np = numpy.array(img)
    frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
    cv2.imshow("frame",frame)
    cv2.waitKey(100)

cv2.destroyAllWindows()
</code>```

See waitKey dcomentation:

imshow

  Displays an image in the specified window.

Note This function should be followed by waitKey function which displays the image for specified milliseconds.

  Otherwise, it won’t display the image.

  For example, waitKey(0) will display the window infinitely until any keypress (it is suitable for image display).

  waitKey(25) will display a frame for 25 ms, after which display will be automatically closed.

Body:
If I want to refresh the image I have to keep closing the window to refresh it. Is it possible without keep closing the window?
Here is the code:

import numpy
import cv2
from PIL import ImageGrab
while True:

    img = ImageGrab.grab(bbox=(765,155,1135,195))
    img_np = numpy.array(img)
    frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
    cv2.imshow("frame",frame)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Body:
cv2.waitKey(0) waits without timeout, replace it with cv2.waitKey(time_in_msec).

Example for refreshing at about 10Hz:

import numpy
import cv2
from PIL import ImageGrab

while True:
    img = ImageGrab.grab(bbox=(765,155,1135,195))
    img_np = numpy.array(img)
    frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
    cv2.imshow("frame",frame)
    cv2.waitKey(100)

cv2.destroyAllWindows()

See waitKey dcomentation:

imshow

  Displays an image in the specified window.

Note This function should be followed by waitKey function which displays the image for specified milliseconds.

  Otherwise, it won’t display the image.

  For example, waitKey(0) will display the window infinitely until any keypress (it is suitable for image display).

  waitKey(25) will display a frame for 25 ms, after which display will be automatically closed.


问:
Scala - Split array within array, extract certain information and apply to case class
```<code>uri:23e6b806-7a39-4836-bae2-f369673defef offset:1
uri:z65e9d4e-a099-41a1-a9fe-3cf74xbb01a4 offset:2
uri:2beff8bf-1019-4265-9da4-30c696397e08 offset:3
uri:3b1df8bb-69f6-4892-a516-523fd285d659 offset:4
uri:4f961415-b847-4d2c-9107-87617671c47b offset:5
uri:015ba25c-c145-456a-bae7-ebe999cb8e0f offset:6
uri:z1f9592f-64d0-443d-ad0d-38c386dd0adb offset:7
</code>```

The above is an arrays of arrays.
Each line is an element in the array however this in itself is an array. I did this by splitting each line on the comma and removing it. What I am trying to do is only extract the uri and offset and apply it to a case class.

case class output2(uri: String, offset: Int)

All I want is the actual values, so each instance of the case class, the uri and offset would be in the below format -

e1af5db7-3aad-4ab0-ac3a-55686fccf6ae

1

I'm trying to find a simple way to do this.

答:
I'd do it this way:</p>

```<code>  case class Output(uri: String, offset: Int)

  val lines = Source
    .fromFile("input")
    .getLines
    .toList

  def parseUri(s: String): Option[String] =
    s.splitAt(s.indexOf(":") + 1)._2 match {
      case "" => None
      case uri => Some(uri)
    }

  def parseOffset(s: String): Option[Int] =
    s.splitAt(s.indexOf(":") + 1)._2 match {
      case "" => None
      case offset => Some(offset.toInt)
    }

  def parseOutput(xs: Array[String]): Option[Output] = for {
    uri <- parseUri(xs(0))
    offset <- parseOffset(xs(1))
  } yield {
    Output(uri, offset)
  }

  lines.map(_.split(" ")).flatMap { x =>
    parseOutput(x)
  }
</code>```

Body:
uri:23e6b806-7a39-4836-bae2-f369673defef offset:1
uri:z65e9d4e-a099-41a1-a9fe-3cf74xbb01a4 offset:2
uri:2beff8bf-1019-4265-9da4-30c696397e08 offset:3
uri:3b1df8bb-69f6-4892-a516-523fd285d659 offset:4
uri:4f961415-b847-4d2c-9107-87617671c47b offset:5
uri:015ba25c-c145-456a-bae7-ebe999cb8e0f offset:6
uri:z1f9592f-64d0-443d-ad0d-38c386dd0adb offset:7

The above is an arrays of arrays.
Each line is an element in the array however this in itself is an array. I did this by splitting each line on the comma and removing it. What I am trying to do is only extract the uri and offset and apply it to a case class.

case class output2(uri: String, offset: Int)

All I want is the actual values, so each instance of the case class, the uri and offset would be in the below format -

e1af5db7-3aad-4ab0-ac3a-55686fccf6ae

1

I'm trying to find a simple way to do this.

Body:
I'd do it this way:

  case class Output(uri: String, offset: Int)

  val lines = Source
    .fromFile("input")
    .getLines
    .toList

  def parseUri(s: String): Option[String] =
    s.splitAt(s.indexOf(":") + 1)._2 match {
      case "" => None
      case uri => Some(uri)
    }

  def parseOffset(s: String): Option[Int] =
    s.splitAt(s.indexOf(":") + 1)._2 match {
      case "" => None
      case offset => Some(offset.toInt)
    }

  def parseOutput(xs: Array[String]): Option[Output] = for {
    uri <- parseUri(xs(0))
    offset <- parseOffset(xs(1))
  } yield {
    Output(uri, offset)
  }

  lines.map(_.split(" ")).flatMap { x =>
    parseOutput(x)
  }


问:
Track local files locally, but ignore them on remote

Context

I want to keep track of the history of a local script in a project root folder using git, but I do not want to push it on remote.

Therefore, this file is now referenced in my .gitignore file, so it is not tracked locally.

But I would like to track it on my local machine (while always keeping the remote without this file).

Ideas

This seemed to be a solution; Track files in local Git repo but ignore in remote but it needs the creation of a subfolder, which I don't want to create for different reasons, and thus keeping all my script files at the root of my folder.

Question

Is there a simple way to do so?

答:
Create new branch without remote tracking

Delete ignored files from .gitignore

Commit local branch

You can set hook to automate commits to local branch

When you commit main branch, you just need to merge this commit to local branch. All changes to local tracked files you should do on local branch.


问:
Merge JSON objects through unique field then print child node data
I have the following JSON:

```<code>data: {
    questions: "[{"id":"vzDDWL3GQvJi","title":"This is question 1","type":"opinion_scale","ref":"data_q1","properties":[]},{"id":"okT0ieWJm74d","title":"This  is question 2","type":"opinion_scale","ref":"data_q2","properties":[]},

    answers: "[{"type":"number","number":2,"field":{"id":"vzDDWL3GQvJi","type":"opinion_scale","ref":"data_q1"}},{"type":"number","number":4,"field":{"id":"okT0ieWJm74d","type":"opinion_scale","ref":"data_q2"}},

    createdDate: "2020-02-14T07:43:02.000000Z"
}
</code>```

A tidy version of the above is:

Question (questions object)

title : "This is question 1"

ref" : "data_q1"

Answer (answers object)

ref" : "data_q1"

number : 2

So, for question 1 (with the ref: data_q1) the number (score) is 2.

What I'm trying to do, is to merge both questions answers together based on ref. I want to do this so that I can get the number. I.e. question and answer for data_q1 is 2.

I have the following:

```<code>// Get questions
var questionData = data.data.questions;
var questions = JSON.parse(questionData);

// get answers
var answerData = data.data.answers;
var answers = JSON.parse(answerData);
</code>```

What I've tried:

```<code>var answersInfo = answers.map( function(order) {
if( answers.ref === "RefIDHere"){
     var info = { "number": answers.number}
     return info;
 }
});
console.log(answersInfo);
</code>```

However, the issue with the above is, in answers.ref ===, I don't know what to pass because the questions and answers haven't been mapped together yet.

答:
1) Build an answer_number object which has ref as key and value as number from data.answers.

2) Use map over data.questions and add the number value from above.
Hope this helps.

const data = {
  questions: [
    {
      id: "vzDDWL3GQvJi",
      title: "This is question 1",
      type: "opinion_scale",
      ref: "data_q1",
      properties: []
    },
    {
      id: "okT0ieWJm74d",
      title: "This  is question 2",
      type: "opinion_scale",
      ref: "data_q2",
      properties: []
    }
  ],
  answers: [
    {
      type: "number",
      number: 2,
      field: { id: "vzDDWL3GQvJi", type: "opinion_scale", ref: "data_q1" }
    },
    {
      type: "number",
      number: 4,
      field: { id: "okT0ieWJm74d", type: "opinion_scale", ref: "data_q2" }
    }
  ],
  createdDate: "2020-02-14T07:43:02.000000Z"
};

const answers_number = data.answers.reduce(
  (acc, curr) => Object.assign(acc, { [curr.field.ref]: curr.number }),
  {}
);

const questions_count = data.questions.map(que => ({
  ...que,
  number: answers_number[que.ref]
}));

console.log(questions_count);```

Body:
I have the following JSON:

data: {
    questions: "[{"id":"vzDDWL3GQvJi","title":"This is question 1","type":"opinion_scale","ref":"data_q1","properties":[]},{"id":"okT0ieWJm74d","title":"This  is question 2","type":"opinion_scale","ref":"data_q2","properties":[]},

    answers: "[{"type":"number","number":2,"field":{"id":"vzDDWL3GQvJi","type":"opinion_scale","ref":"data_q1"}},{"type":"number","number":4,"field":{"id":"okT0ieWJm74d","type":"opinion_scale","ref":"data_q2"}},

    createdDate: "2020-02-14T07:43:02.000000Z"
}

A tidy version of the above is:

Question (questions object)

title : "This is question 1"

ref" : "data_q1"

Answer (answers object)

ref" : "data_q1"

number : 2

So, for question 1 (with the ref: data_q1) the number (score) is 2.

What I'm trying to do, is to merge both questions answers together based on ref. I want to do this so that I can get the number. I.e. question and answer for data_q1 is 2.

I have the following:

// Get questions
var questionData = data.data.questions;
var questions = JSON.parse(questionData);

// get answers
var answerData = data.data.answers;
var answers = JSON.parse(answerData);

What I've tried:

var answersInfo = answers.map( function(order) {
if( answers.ref === "RefIDHere"){
     var info = { "number": answers.number}
     return info;
 }
});
console.log(answersInfo);

However, the issue with the above is, in answers.ref ===, I don't know what to pass because the questions and answers haven't been mapped together yet.


问:
Cross component communication with angular 2+ (any child to any parent)
I have been working on web application in Angular 2+. and i have following situation

```<code>component A
  |
  component B
    |
    component C
      |
      component D   //click on button -> call apis and return value to component A's variable
</code>```

In component D there is button if user click on that we need to call rest API and that API's result should be show in component A.

Business case : Consider that component A is your top header which contain point count and form component D user do some task and based on that task i need to increment that points.

I can achieve this functionality with broadcast service in angular Subject<BroadcastEvent> (after api return value create broadcast and in component A i am listing that event ) but i am not sure that if there is a better way to do this stuff.
Or i can't use same service in both component because I need to assign value in variable as well as in show in DOM. If i need only DOM element to be updated than service can resolve my problem but i also need in components variable.

答:
if you call your api in a method of ComponentB you can use

@viewchild(ComponentA)ComponentA:ComponentA

in your ComponentB and Assignment result api from ComponentB to variable or array of ComponentA.
for example You define a array in ComponentA and:

ComponentA

```<code>export class componentA {
    points = [];
}
</code>```

ComponentB

```<code>import { HttpClient } from '@angular/common/http';
import { ComponentA } from '{{ComponentA_PATH}}/ComponentA';

export class ComponentB {
    @viewchild(ComponentA) componentARef: ComponentA;

    constructor(private httpClient: HttpClient)

    GetPoints() {
    this.httpClient.get(your url).subscribe(
      result=>{
        componentARef.points.push(result);
              }
               }
}
</code>```

but this way is not bestway you should create a sevice and pass data bettween components like the above answer but this is also a way i hope i have been able to help.

Body:
I have been working on web application in Angular 2+. and i have following situation

component A
  |
  component B
    |
    component C
      |
      component D   //click on button -> call apis and return value to component A's variable

In component D there is button if user click on that we need to call rest API and that API's result should be show in component A.

Business case : Consider that component A is your top header which contain point count and form component D user do some task and based on that task i need to increment that points.

I can achieve this functionality with broadcast service in angular Subject<BroadcastEvent> (after api return value create broadcast and in component A i am listing that event ) but i am not sure that if there is a better way to do this stuff.
Or i can't use same service in both component because I need to assign value in variable as well as in show in DOM. If i need only DOM element to be updated than service can resolve my problem but i also need in components variable.

Body:
if you call your api in a method of ComponentB you can use

@viewchild(ComponentA)ComponentA:ComponentA

in your ComponentB and Assignment result api from ComponentB to variable or array of ComponentA.
for example You define a array in ComponentA and:

ComponentA

export class componentA {
    points = [];
}

ComponentB

import { HttpClient } from '@angular/common/http';
import { ComponentA } from '{{ComponentA_PATH}}/ComponentA';

export class ComponentB {
    @viewchild(ComponentA) componentARef: ComponentA;

    constructor(private httpClient: HttpClient)

    GetPoints() {
    this.httpClient.get(your url).subscribe(
      result=>{
        componentARef.points.push(result);
              }
               }
}

but this way is not bestway you should create a sevice and pass data bettween components like the above answer but this is also a way i hope i have been able to help.


问:
Append multi-values return to func argument
Is it possible to compact this operation?

a, b := obtain2Values()
c = ":)"

process3Values(a, b, c)
```

<p><strong>into something like this</strong>? (I know this doesn't precisely work, but I'm looking for an alternative, if it exists)</p>

<pre class="lang-go prettyprint-override"><code>process3Values(obtain2Values(), ":)")
</code>```

答:
This works:

```<code>package main

import "fmt"

func obtain2Values() (int, int) {
        return 1, 2
}

func process3Values(a, b int, c string){
    fmt.Printf("%v %v %v\n", a, b, c)
}

func main() {
    a, b := obtain2Values()
    process3Values(a, b,":)")
    // process3Values(obtain2Values(), ":)")
}
</code>```

process3Values(obtain2Values(), ":)") does not work:

```<code>./prog.go:16:16: not enough arguments in call to process3Values
./prog.go:16:30: multiple-value obtain2Values() in single-value context
</code>```

Body:
Is it possible to compact this operation?

a, b := obtain2Values()
c = ":)"

process3Values(a, b, c)

into something like this? (I know this doesn't precisely work, but I'm looking for an alternative, if it exists)

process3Values(obtain2Values(), ":)")

Body:
This works:

package main

import "fmt"

func obtain2Values() (int, int) {
        return 1, 2
}

func process3Values(a, b int, c string){
    fmt.Printf("%v %v %v\n", a, b, c)
}

func main() {
    a, b := obtain2Values()
    process3Values(a, b,":)")
    // process3Values(obtain2Values(), ":)")
}

process3Values(obtain2Values(), ":)") does not work:

./prog.go:16:16: not enough arguments in call to process3Values
./prog.go:16:30: multiple-value obtain2Values() in single-value context


问:
node js request-promise, retry request on error
so I have a chain of request that are sent, and once catch at the end, the problem is if I have an error i wanna retry that specific request that caught the error, I know one solution to this would be to add a catch at the end off all the request i send, and when it catches an error it retries that request, but that would lead to too many catch statements, I just want one catch statement at the end that when it catches an error it retrys the specific request </p>

```<code>rp.get('https://www.off---white.com/en-us/api/products/' + variant, options2)
    .then((data) => {
     // doo stuff with request
        return rp.post('https://www.off---white.com/en-us/api/bags/' + bagId + '/items', options2)
    })

    .then((data) => {
    // doo stuff with request
    })

    .catch((error) => {

    })
</code>```

答:
First of all, you will need to design your rp.get() function in a way such that somehow whenever there is an error, the error object must have an identifier (stored as type key) as of from which request the error is propagated, then on a conditional basis, you can handle the error in a single catch() block accordingly.

```<code>const rpWrapper = (type) => { //add other required params
  rp.get() //pass required params
    .then( (res) => result )
    .catch( (err) =>  { throw { type, err }) }
}
</code>```

Then, modify your original code to something like,

```<code>rpWrapper.get('https://www.off---white.com/en-us/api/products/' + variant, options2)
.then((data) => {
 // doo stuff with request
    return rpWrapper.post('https://www.off---white.com/en-us/api/bags/' + bagId + '/items', options2)
})
.then((data) => {
// doo stuff with request
})
.catch((error) => {
   if(error.type === "request1") { //handle error on first req }
   if(error.type === "request2") { //handle error second req }
})
</code>```

Body:
so I have a chain of request that are sent, and once catch at the end, the problem is if I have an error i wanna retry that specific request that caught the error, I know one solution to this would be to add a catch at the end off all the request i send, and when it catches an error it retries that request, but that would lead to too many catch statements, I just want one catch statement at the end that when it catches an error it retrys the specific request

rp.get('https://www.off---white.com/en-us/api/products/' + variant, options2)
    .then((data) => {
     // doo stuff with request
        return rp.post('https://www.off---white.com/en-us/api/bags/' + bagId + '/items', options2)
    })

    .then((data) => {
    // doo stuff with request
    })

    .catch((error) => {

    })

Body:
First of all, you will need to design your rp.get() function in a way such that somehow whenever there is an error, the error object must have an identifier (stored as type key) as of from which request the error is propagated, then on a conditional basis, you can handle the error in a single catch() block accordingly.

const rpWrapper = (type) => { //add other required params
  rp.get() //pass required params
    .then( (res) => result )
    .catch( (err) =>  { throw { type, err }) }
}

Then, modify your original code to something like,

rpWrapper.get('https://www.off---white.com/en-us/api/products/' + variant, options2)
.then((data) => {
 // doo stuff with request
    return rpWrapper.post('https://www.off---white.com/en-us/api/bags/' + bagId + '/items', options2)
})
.then((data) => {
// doo stuff with request
})
.catch((error) => {
   if(error.type === "request1") { //handle error on first req }
   if(error.type === "request2") { //handle error second req }
})


问:
The connection to the server xxxx:6443 was refused - did you specify the right host or port?
I follow this to install kubernetes on my cloud.
When I run command kubectl get nodes I get this error:

```<code>The connection to the server localhost:6443 was refused - did you specify the right host or port?
</code>```

How can I fix this?

答: Verify if there are any proxies set like "http_proxy" or "https_proxy", mostly we set it as environment variables. If yes, then remove the proxies and it should work for you.</p>

Body:
I follow this to install kubernetes on my cloud.
When I run command kubectl get nodes I get this error:

The connection to the server localhost:6443 was refused - did you specify the right host or port?

How can I fix this?


问:
How to make a method do nothing in junit integration test?
I have a mail service and controller which I want to test together but I don't want to send an email when the test is run. I tried using @Autowire on the mail sender in the test class to make it's method doNothing but it failed since it's not a mock. I can't really make it a @Mock since I'm not calling the controller method but rather making an actual request with import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; Here are the classes:

```<code>public class EmailControllerTest extends AbstractMvcTest {
    private static final String CONTROLLER_URL = "/api/emails";

    @Test
    @Sql({DbScripts.EMAILS, DbScripts.IDENTITY_NUMBER_TYPES, DbScripts.SUBJECTS, DbScripts.USERS})
    public void sendVerificationCodeToEmailStandardTest() throws Exception {
        EmailWrapperDto dto = new EmailWrapperDto();
        dto.setEmail("test@gmail.com");

        MockHttpServletRequestBuilder request = put(CONTROLLER_URL + "/verify");
        request.content(getRequestBodyFromObject(dto));

        mockMvc.perform(request).andExpect(status().isOk());
    }
}
</code>```

```<code>@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = EServicesWebBackendApplication.class)
@ActiveProfiles(ApplicationConstants.SPRING_PROFILE_TEST)
public abstract class AbstractMvcTest {
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private ObjectMapper objectMapper;

    private H2TestDatabaseCleaner dbCleaner = new H2TestDatabaseCleaner();

    @Autowired
    private SessionFactory sessionFactory;

    protected MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = setupMockMvcBuilder(MockMvcBuilders.webAppContextSetup(webApplicationContext), true).build();
    }

    protected DefaultMockMvcBuilder setupMockMvcBuilder(DefaultMockMvcBuilder builder, boolean withCsrf) {
        MockHttpServletRequestBuilder mockServletRequestBuilder = MockMvcRequestBuilders.get("/");

        return builder.defaultRequest(mockServletRequestBuilder.contentType(MediaType.APPLICATION_JSON)
                .header("X-Requested-With", "XMLHttpRequest"));
    }

    protected String getRequestBodyFromObject(Object objectToConvertToJson) throws JsonProcessingException {
        return objectMapper.writeValueAsString(objectToConvertToJson);
    }

    @After
    public void teardown() {
        dbCleaner.clean(sessionFactory);
    }
}
</code>```

```<code>@Service
public class EmailService {
    private static final int TWENTY_FOUR_HOURS_IN_MINUTES = 1440;

    @Autowired
    private MailSender mailSender;

    @Autowired
    private GenericRepository genericRepository;

    @Transactional
    public void sendVerificationCode(String email) {
        User user = genericRepository.findByIdOrElseThrowException(User.class, 11);
        String token = UUID.randomUUID().toString();
        VerificationToken verificationToken = new VerificationToken();
        verificationToken.setToken(token);
        verificationToken.setUser(user);
        verificationToken.setExpirationDate(calculateExpiryDate(TWENTY_FOUR_HOURS_IN_MINUTES));
        genericRepository.save(verificationToken);

        String subject = "Registration Confirmation";

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(email);
        mailMessage.setFrom("test@gmail.com");
        mailMessage.setSubject(subject);
        mailMessage.setText(token);
        mailSender.send(mailMessage);
    }

    private Date calculateExpiryDate(int expiryTimeInMinutes) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Timestamp(cal.getTime().getTime()));
        cal.add(Calendar.MINUTE, expiryTimeInMinutes);
        return new Date(cal.getTime().getTime());
    }
}
</code>```

答:
If you use spring's Mockito features you should be able to use the @MockBean annotation like so:

public class EmailControllerTest extends AbstractMvcTest {
   ...

   @MockBean
   private MailSender mailSender;

   ...
}
```

<p>and then define the (optional, doing nothing is mockito's default behaviour for void method stubs) <code>doNothing</code> action:</p>

```Mockito.doNothing().when(mailSender).send(Mockito.any(SimpleMailMessage.class));
```

<p>This can be useful if you want to use an <code>ArgumentCaptor</code> in a mocked void method:</p>

```ArgumentCaptor<SimpleMailMessage> valueCapture = ArgumentCaptor.forClass(SimpleMailMessage.class);
Mockito.doNothing().when(mailSender)
    .send(Mockito.any(SimpleMailMessage.class), valueCapture.capture());
```

see for reference: https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html

https://www.baeldung.com/mockito-void-methods

Body:
I have a mail service and controller which I want to test together but I don't want to send an email when the test is run. I tried using @Autowire on the mail sender in the test class to make it's method doNothing but it failed since it's not a mock. I can't really make it a @Mock since I'm not calling the controller method but rather making an actual request with import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; Here are the classes:

public class EmailControllerTest extends AbstractMvcTest {
    private static final String CONTROLLER_URL = "/api/emails";

    @Test
    @Sql({DbScripts.EMAILS, DbScripts.IDENTITY_NUMBER_TYPES, DbScripts.SUBJECTS, DbScripts.USERS})
    public void sendVerificationCodeToEmailStandardTest() throws Exception {
        EmailWrapperDto dto = new EmailWrapperDto();
        dto.setEmail("test@gmail.com");

        MockHttpServletRequestBuilder request = put(CONTROLLER_URL + "/verify");
        request.content(getRequestBodyFromObject(dto));

        mockMvc.perform(request).andExpect(status().isOk());
    }
}

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = EServicesWebBackendApplication.class)
@ActiveProfiles(ApplicationConstants.SPRING_PROFILE_TEST)
public abstract class AbstractMvcTest {
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private ObjectMapper objectMapper;

    private H2TestDatabaseCleaner dbCleaner = new H2TestDatabaseCleaner();

    @Autowired
    private SessionFactory sessionFactory;

    protected MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = setupMockMvcBuilder(MockMvcBuilders.webAppContextSetup(webApplicationContext), true).build();
    }

    protected DefaultMockMvcBuilder setupMockMvcBuilder(DefaultMockMvcBuilder builder, boolean withCsrf) {
        MockHttpServletRequestBuilder mockServletRequestBuilder = MockMvcRequestBuilders.get("/");

        return builder.defaultRequest(mockServletRequestBuilder.contentType(MediaType.APPLICATION_JSON)
                .header("X-Requested-With", "XMLHttpRequest"));
    }

    protected String getRequestBodyFromObject(Object objectToConvertToJson) throws JsonProcessingException {
        return objectMapper.writeValueAsString(objectToConvertToJson);
    }

    @After
    public void teardown() {
        dbCleaner.clean(sessionFactory);
    }
}

@Service
public class EmailService {
    private static final int TWENTY_FOUR_HOURS_IN_MINUTES = 1440;

    @Autowired
    private MailSender mailSender;

    @Autowired
    private GenericRepository genericRepository;

    @Transactional
    public void sendVerificationCode(String email) {
        User user = genericRepository.findByIdOrElseThrowException(User.class, 11);
        String token = UUID.randomUUID().toString();
        VerificationToken verificationToken = new VerificationToken();
        verificationToken.setToken(token);
        verificationToken.setUser(user);
        verificationToken.setExpirationDate(calculateExpiryDate(TWENTY_FOUR_HOURS_IN_MINUTES));
        genericRepository.save(verificationToken);

        String subject = "Registration Confirmation";

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(email);
        mailMessage.setFrom("test@gmail.com");
        mailMessage.setSubject(subject);
        mailMessage.setText(token);
        mailSender.send(mailMessage);
    }

    private Date calculateExpiryDate(int expiryTimeInMinutes) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Timestamp(cal.getTime().getTime()));
        cal.add(Calendar.MINUTE, expiryTimeInMinutes);
        return new Date(cal.getTime().getTime());
    }
}

Body:
If you use spring's Mockito features you should be able to use the @MockBean annotation like so:

public class EmailControllerTest extends AbstractMvcTest {
   ...

   @MockBean
   private MailSender mailSender;

   ...
}

and then define the (optional, doing nothing is mockito's default behaviour for void method stubs) doNothing action:

Mockito.doNothing().when(mailSender).send(Mockito.any(SimpleMailMessage.class));

This can be useful if you want to use an ArgumentCaptor in a mocked void method:

ArgumentCaptor<SimpleMailMessage> valueCapture = ArgumentCaptor.forClass(SimpleMailMessage.class);
Mockito.doNothing().when(mailSender)
    .send(Mockito.any(SimpleMailMessage.class), valueCapture.capture());

see for reference: https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html

https://www.baeldung.com/mockito-void-methods


问:
Is there a way to turn slack messages into gitlab issues?
I'm looking for a way to get messages from our customer support channel on Slack turned into issues in Gitlab as they come in. Is that possible?</p>

答:
You could enable the New issue via mail feature to allow issues to be created using emails.

You could then use a solution proposed here to send emails from Slack to the email address that creates issues within Gitlab.


问:
Select last Order state from Orders
I have tables:

orders:

```<code>id_order    id_customer
1           1
2           2
3           1
</code>```

orders_history

```<code>id_history  id_order    id_order_state    date_add
1           1           1                 2010-01-01 00:00:00
2           1           2                 2010-01-02 00:00:00
3           1           3                 2010-01-03 00:00:00
4           2           2                 2010-05-01 00:00:00
5           2           3                 2011-05-02 00:00:00
6           3           1                 2011-05-03 00:00:00
7           3           2                 2011-06-01 00:00:00
</code>```

order_state

```<code>id_order_state    name
1                 New
2                 Sent
3                 Rejected
4                 ...
</code>```

How to get all order_id's where last id_order_state of that order (by last I mean this with MAX(id_history) or MAX(date_add)) is not equal 1 or 3?

答:
I think what he's after is what orders are complete... ie their final status, not those that are exclusive of the 1 and 3 specifically.  The first pre-query should be the max ID regardless of the status code

```<code>select
      orders.*
   from
      ( select oh.id_order,
               max( oh.id_history ) LastID_HistoryPerOrder
           from
               orders_history oh
           group by
               oh.id_order ) PreQuery
      join orders_history oh2
         on PreQuery.ID_Order = oh2.id_order
         AND PreQuery.LastID_HistoryPerOrder = oh2.id_history
         AND NOT OH2.id_order_state IN (1, 3)   <<== THIS ELIMINATES 1's & 3's from result set
      join Orders                               <<= NOW, anything left after above ^ is joined to orders
         on PreQuery.ID_Order = Orders.ID_Order
</code>```

Just to re-show YOUR data... I've marked the last SEQUENCE (ID_History) per ORDER... This is what the PREQUERY is going to return...

```<code>id_history  id_order    id_order_state    date_add
  1           1          1                2010-01-01 00:00:00
  2           1          2                2010-01-02 00:00:00
**3           1          3                2010-01-03 00:00:00

  4           2          2                2010-05-01 00:00:00
**5           2          3                2011-05-02 00:00:00

  6           3          1                2011-05-03 00:00:00
**7           3          2                2011-06-01 00:00:00
</code>```

The "PreQuery" will result with the following subset

```<code>ID_Order   LastID_HistoryPerOrder (ID_History)
1          3  (state=3)  THIS ONE WILL BE SKIPPED IN FINAL RESULT
2          5  (state=3)  THIS ONE WILL BE SKIPPED IN FINAL RESULT
3          7  (state=2)
</code>```

Now, the result of this is then re-joined back to order history on just these two elements... yet adds the criteria to EXCLUDE the 1,3 entries for "order state".

In this case,

```<code>   1 would be rejected as its state = 3 (sequence #3),
   2 would be rejected since its last history is state = 3 (sequence #5).
   3 would be INCLUDED since its state = 2 (sequence #7)
</code>```

Finally, all that joined to the orders will result with ONE ID, and nicely match up with the orders table on the Order_ID alone and get the desired results.

ContentLicense: CC BY-SA 3.0

Title: Select last Order state from Orders

Body:
I have tables:

orders:

id_order    id_customer
1           1
2           2
3           1

orders_history

id_history  id_order    id_order_state    date_add
1           1           1                 2010-01-01 00:00:00
2           1           2                 2010-01-02 00:00:00
3           1           3                 2010-01-03 00:00:00
4           2           2                 2010-05-01 00:00:00
5           2           3                 2011-05-02 00:00:00
6           3           1                 2011-05-03 00:00:00
7           3           2                 2011-06-01 00:00:00

order_state

id_order_state    name
1                 New
2                 Sent
3                 Rejected
4                 ...

How to get all order_id's where last id_order_state of that order (by last I mean this with MAX(id_history) or MAX(date_add)) is not equal 1 or 3?

Body:
I think what he's after is what orders are complete... ie their final status, not those that are exclusive of the 1 and 3 specifically.  The first pre-query should be the max ID regardless of the status code

select
      orders.*
   from
      ( select oh.id_order,
               max( oh.id_history ) LastID_HistoryPerOrder
           from
               orders_history oh
           group by
               oh.id_order ) PreQuery
      join orders_history oh2
         on PreQuery.ID_Order = oh2.id_order
         AND PreQuery.LastID_HistoryPerOrder = oh2.id_history
         AND NOT OH2.id_order_state IN (1, 3)   <<== THIS ELIMINATES 1's & 3's from result set
      join Orders                               <<= NOW, anything left after above ^ is joined to orders
         on PreQuery.ID_Order = Orders.ID_Order

Just to re-show YOUR data... I've marked the last SEQUENCE (ID_History) per ORDER... This is what the PREQUERY is going to return...

id_history  id_order    id_order_state    date_add
  1           1          1                2010-01-01 00:00:00
  2           1          2                2010-01-02 00:00:00
**3           1          3                2010-01-03 00:00:00

  4           2          2                2010-05-01 00:00:00
**5           2          3                2011-05-02 00:00:00

  6           3          1                2011-05-03 00:00:00
**7           3          2                2011-06-01 00:00:00

The "PreQuery" will result with the following subset

ID_Order   LastID_HistoryPerOrder (ID_History)
1          3  (state=3)  THIS ONE WILL BE SKIPPED IN FINAL RESULT
2          5  (state=3)  THIS ONE WILL BE SKIPPED IN FINAL RESULT
3          7  (state=2)

Now, the result of this is then re-joined back to order history on just these two elements... yet adds the criteria to EXCLUDE the 1,3 entries for "order state".

In this case,

   1 would be rejected as its state = 3 (sequence #3),
   2 would be rejected since its last history is state = 3 (sequence #5).
   3 would be INCLUDED since its state = 2 (sequence #7)

Finally, all that joined to the orders will result with ONE ID, and nicely match up with the orders table on the Order_ID alone and get the desired results.


问:
Chrome sources not showing a file that was generated from Typescript and has a source map
I have a file that is dynamically loaded by sapui5 as a controller. I have altered my code so that I can leverage Typescript for Intellisense and fault detection.

My JS file is successfully created, and runs correctly in Chrome. The DevTools/Sources/Network window does not list my 'FinalAssembly.controller.js' file, nor does it list the similarly named 'FinalAssembly.controller.ts' file.

I have found that if I remove the '//# sourceMapURL=' line from the bottom of my file, Chrome will eventually list my JS file.

I had read that use of the '//# sourceURL=' line at the top of my file would cause my file to be listed, but it wasn't, further, I read that use of this directive should allow me to vary the name that is displayed in the Sources list, it doesn't. It appears that Chrome is ignoring this directive.

As of today, Chrome indicates that it is up to date at version 66. I have read lots of articles and Github issues over the last 4 hours that indicate that Source Maps tend to be problematic and can fail in some versions of Chrome.

The map file itself works in Internet Explorer, but I can't really see myself developing with that.

Has anybody debugged JS with a Source Map in Chrome 66? Can anybody suggest how I can debug my map file usage in Chrome?

I have placed a very simple test created via VSCode (tsc.exe) at my website: http://www.ia.uk.com/TypescriptTest/default.htm - on my Chrome 66 this one doesn't seem to download the map file at all (Fiddler didn't see any request for that). Doesn't show any TS view of the code. This is not a dynamically loaded library as per my original problem, but does show that there is a problem.

答:
Make sure your Angular app is up.

If your Angular app is not up, then you can't see the .ts file in Chrome. So you need to first run the Angular app.


问:
How are these called? literals, captions, labels or properties?
Instead of hardcoding text in the UI we use placeholders with keys which get replaced by the actual text. This also helps localisation of the application.

example Java properties file:

```<code>about=About
contact=Contact Us
</code>```

These could also be found in the database or in XML files etc

How are these called?

literals?

captions?

labels?

properties?

I'm looking for a general and language agnostic term.

Edit: Adding all the suggested terms from answers:

translatable strings

resource strings

Resource Properties

localization

Culture Variant UI Fields

Locales

Locales Strings

messages

message placeholders

I don't know why but it kind of saddens and confuses me that there isn't a single solid term to describe this thing. And in one way or another it exists in all languages and frameworks.

答:
The mentioned items are termed as "Resource Strings". Resource strings can be further classifed into localized strings.

Consider the following example :-

When the culture is US-en (US English )
A constant named WELCOME in US English can refer to "Welcome" in the resource string.

When the culture is FR-fr ( France French )

The same constant WELCOME shall refer to "Bonjour" in the resource string. Obviously you have to correlate the WELCOME constant to "Bonjour" . As a side note, there are a wide variety of tools available for translation of entire projects in different locales .

P.S. I am not a French expert , so forgive me I was wrong in the translation of Welcome to Bonjour .:-)

Body:
Instead of hardcoding text in the UI we use placeholders with keys which get replaced by the actual text. This also helps localisation of the application.

example Java properties file:

about=About
contact=Contact Us

These could also be found in the database or in XML files etc

How are these called?

literals?

captions?

labels?

properties?

I'm looking for a general and language agnostic term.

Edit: Adding all the suggested terms from answers:

translatable strings

resource strings

Resource Properties

localization

Culture Variant UI Fields

Locales

Locales Strings

messages

message placeholders

I don't know why but it kind of saddens and confuses me that there isn't a single solid term to describe this thing. And in one way or another it exists in all languages and frameworks.


问:
What are the risks in storing data in session?
I've heard of cross-site scripting and that people can access cookies and devious ways. So I was hoping that someone could answer a few questions around these. I want to take the example of storing something in session the purest way, but using a CMS like Drupal. Let's say we have this:

```<code>$data = $fancyWebService->getSuperSecureDataThatOnlyTheCurrentlyLoggedInUserCanSee();
$_SESSION['basic_variable'] = $data;
</code>```

Should the user now travel from mysite.com, to devious-site.com, is there any way that someone can get the data from "basic_variable", just by knowing that the variable is called that?

Is there any way that the current user can see a print out of the $_SERVER variable and actually see all the contents stored in it?

I read somewhere that data in the session or in cookies should be "encrypted". In the above example, I'm fairly sure the data is being stored in the session, and that this session is secure. Is this the case, or is it only secure if HTTPS is enabled?

Drupal stores some info in cookies, if you choose to use cookies as apposed to "session", how does that affect the above?

UPDATE

With regards to question 2. I mean, if I type the following in a php file:

```<code>print '```';
print_r($_SESSION);
die();
```

(or just vardump the session variable)...

I end up with all the info I have stored there, unencrypted. My question is, is there any way a user can somehow find a way to get access to the session variable (other than through me exposing it) that would make it a bad idea to leave values unencrypted?

答:
Yes, you can store data in a session.However, you have to minimise the vulnerable
data and store only minimal info so that you can identify the user for example,
by id number, eventually it will work. Overall, using session data is not
recommended.</p>

Body:
I've heard of cross-site scripting and that people can access cookies and devious ways. So I was hoping that someone could answer a few questions around these. I want to take the example of storing something in session the purest way, but using a CMS like Drupal. Let's say we have this:

$data = $fancyWebService->getSuperSecureDataThatOnlyTheCurrentlyLoggedInUserCanSee();
$_SESSION['basic_variable'] = $data;

Should the user now travel from mysite.com, to devious-site.com, is there any way that someone can get the data from "basic_variable", just by knowing that the variable is called that?

Is there any way that the current user can see a print out of the $_SERVER variable and actually see all the contents stored in it?

I read somewhere that data in the session or in cookies should be "encrypted". In the above example, I'm fairly sure the data is being stored in the session, and that this session is secure. Is this the case, or is it only secure if HTTPS is enabled?

Drupal stores some info in cookies, if you choose to use cookies as apposed to "session", how does that affect the above?

UPDATE

With regards to question 2. I mean, if I type the following in a php file:

print '
';
print_r($_SESSION);
die();

(or just vardump the session variable)...

I end up with all the info I have stored there, unencrypted. My question is, is there any way a user can somehow find a way to get access to the session variable (other than through me exposing it) that would make it a bad idea to leave values unencrypted?


问:
Get directory name with grep and remove it
please is there any simple way how can I get NAME output only from lines, where DATE < 5 days ago and then call other command called rm on these lines with NAME as argument?

I have the following output from mega-ls path/ -l (mega.nz) command:

```<code>FLAGS VERS    SIZE            DATE       NAME
d---    -          - 06Feb2020 05:00:01 bk_20200206050000
d---    -          - 07Feb2020 05:00:01 bk_20200207050000
d---    -          - 08Feb2020 05:00:01 bk_20200208050000
d---    -          - 09Feb2020 05:00:01 bk_20200209050000
d---    -          - 10Feb2020 05:00:01 bk_20200210050000
d---    -          - 11Feb2020 05:00:01 bk_20200211050000
</code>```

I tried grep, sort and other ways e.g. mega-ls path/ -l | head -n 5 but I don't know how to search these lines based on the date.

Thank you a lot.

答:
I try find simple way for you request ;)

```<code>mega-ls path/ -l | head -n 5 | tr -s ' ' | cut -d ' ' -f6 | grep -v -e '^$' | grep '^bk_20200206.*' | xargs rm -f
</code>```

Part 1 : This is you command (returned folders list by extra data)

mega-ls path/ -l | head -n 5

Part 2 : Try to remove extra space in your part 1 result

tr -s ' '

Part 3 : Try to use cut command to delimit result part 2 and return Name Folders column

cut -d ' ' -f6

Part 4 : Try to remove Empty lines from result part 3 (result of header line)

grep -v -e '^$'

Part 5 : This your request for search folders name by date yyyymmdd format example : 20200206 (replace 20200206 to your real date need)

grep '^bk_20200206.*'

Part 6 : (Very Important!!) If you need to delete result folders use this part (Very Important!!)

xargs rm -f

Best Regards

Body:
please is there any simple way how can I get NAME output only from lines, where DATE < 5 days ago and then call other command called rm on these lines with NAME as argument?

I have the following output from mega-ls path/ -l (mega.nz) command:

FLAGS VERS    SIZE            DATE       NAME
d---    -          - 06Feb2020 05:00:01 bk_20200206050000
d---    -          - 07Feb2020 05:00:01 bk_20200207050000
d---    -          - 08Feb2020 05:00:01 bk_20200208050000
d---    -          - 09Feb2020 05:00:01 bk_20200209050000
d---    -          - 10Feb2020 05:00:01 bk_20200210050000
d---    -          - 11Feb2020 05:00:01 bk_20200211050000

I tried grep, sort and other ways e.g. mega-ls path/ -l | head -n 5 but I don't know how to search these lines based on the date.

Thank you a lot.

Body:
I try find simple way for you request ;)

mega-ls path/ -l | head -n 5 | tr -s ' ' | cut -d ' ' -f6 | grep -v -e '^$' | grep '^bk_20200206.*' | xargs rm -f

Part 1 : This is you command (returned folders list by extra data)

mega-ls path/ -l | head -n 5

Part 2 : Try to remove extra space in your part 1 result

tr -s ' '

Part 3 : Try to use cut command to delimit result part 2 and return Name Folders column

cut -d ' ' -f6

Part 4 : Try to remove Empty lines from result part 3 (result of header line)

grep -v -e '^$'

Part 5 : This your request for search folders name by date yyyymmdd format example : 20200206 (replace 20200206 to your real date need)

grep '^bk_20200206.*'

Part 6 : (Very Important!!) If you need to delete result folders use this part (Very Important!!)

xargs rm -f

Best Regards