问:
AWS Landing Zone - access to core accounts?
How can I access the AWS Landing Zone core accounts after creating an AWS Landing Zone?

This is what I have done so far:

Deploy the AWS Landing Zone based on the AWS Landing Zone initiation template

Let the CodePipeline execute the aws-landing-zone-configuration.zip file

I can see that the shared service, the security and the log archive account has been created and added to the core OU when I look at the AWS Organization in the console

Of course, since I created the accounts, I know the root email address and I can use it to reset the root password, but that is beside the point.

答:
The AWS Landing Zone is deployed into the AWS Organizations account. When you first create the Landing Zone stack from the latest Landing Zone initiation template, you must supply various input parameters, including the primary email addresses for the core accounts that the landing zone creates, namely:

Log Archive account (LoggingAccountEmail)

Security account (SecurityAccountEmail)

Shared Services account (SharedServicesAccountEmail)

From the Landing Zone CloudFormation template for more details:

```<code>Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
    - Label:
        default: Landing Zone Core Account Configuration
      Parameters:
      - SharedServicesAccountEmail
      - LoggingAccountEmail
      - SecurityAccountEmail
      - NestedOUDelimiter
      - CoreOUName
      - NonCoreOUNames
      - SecurityAlertEmail
      - LockStackSetsExecutionRole
      - SubscribeAllChangeEventsEmailToTopic
      - AllChangeEventsEmail
</code>```

When the Security, Log Archive or Shared Services core accounts are created, AWS Organizations initially assigns a password to the root user for each core account that is a minimum of 64 characters long. All characters are randomly generated with no guarantees on the appearance of certain character sets.

You can't retrieve this initial password.

To access the account as the root user for the first time, you must go through the process for password recovery.

See here for more information.

Body:
The AWS Landing Zone is deployed into the AWS Organizations account. When you first create the Landing Zone stack from the latest Landing Zone initiation template, you must supply various input parameters, including the primary email addresses for the core accounts that the landing zone creates, namely:

Log Archive account (LoggingAccountEmail)

Security account (SecurityAccountEmail)

Shared Services account (SharedServicesAccountEmail)

From the Landing Zone CloudFormation template for more details:

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
    - Label:
        default: Landing Zone Core Account Configuration
      Parameters:
      - SharedServicesAccountEmail
      - LoggingAccountEmail
      - SecurityAccountEmail
      - NestedOUDelimiter
      - CoreOUName
      - NonCoreOUNames
      - SecurityAlertEmail
      - LockStackSetsExecutionRole
      - SubscribeAllChangeEventsEmailToTopic
      - AllChangeEventsEmail

When the Security, Log Archive or Shared Services core accounts are created, AWS Organizations initially assigns a password to the root user for each core account that is a minimum of 64 characters long. All characters are randomly generated with no guarantees on the appearance of certain character sets.

You can't retrieve this initial password.

To access the account as the root user for the first time, you must go through the process for password recovery.

See here for more information.


来源: stackexchange

问:
Spring controller is not supporting ServerHttpRequest
I am using ServerHttpRequest as the request parameter in my Rest Controller. But in the response I'm getting error as "No primary or default constructor found for interface org.springframework.http.server.reactive.ServerHttpRequest".

I found one similar question,  but no luck.

Rest Controller

```
@GetMapping(path = "/**")
public Mono &ltResponseEntity&lt String&gt&gt clientRequests(ServerHttpRequest request) {
    Mono&ltResponseEntity&ltString&gt&gt jsonOp =  restServices.getApiResponse();
    return jsonOp;
}
```

Log

```

SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No primary or default constructor found for interface org.springframework.http.server.reactive.ServerHttpRequest] with root cause
java.lang.NoSuchMethodException: org.springframework.http.server.reactive.ServerHttpRequest.()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:216)
    at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:84)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:139)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:126)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:166)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    ```

Pom.xml

```

&ltdependencies&gt
        &ltdependency&gt
            &ltgroupId&gtorg.springframework.boot&lt/groupId&gt
            &ltartifactId&gtspring-boot-starter-webflux&lt/artifactId&gt
            &ltversion&gt${spring-boot.version}&lt/version&gt
            &ltexclusions&gt
                &ltexclusion&gt
                    &ltgroupId&gtorg.springframework.boot&lt/groupId&gt
                    &ltartifactId&gtspring-boot-starter-logging&lt/artifactId&gt
                &lt/exclusion&gt
            &lt/exclusions&gt
        &lt/dependency&gt
        &ltdependency&gt
            &ltgroupId&gtorg.springframework.boot&lt/groupId&gt
            &ltartifactId&gtspring-boot-starter-web&lt/artifactId&gt
            &ltversion&gt${spring-boot.version}&lt/version&gt
            &ltexclusions&gt
                &ltexclusion&gt
                    &ltgroupId&gtorg.springframework.boot&lt/groupId&gt
                    &ltartifactId&gtspring-boot-starter-logging&lt/artifactId&gt
                &lt/exclusion&gt
            &lt/exclusions&gt
        &lt/dependency&gt

        &ltdependency&gt
            &ltgroupId&gtio.projectreactor.netty&lt/groupId&gt
            &ltartifactId&gtreactor-netty&lt/artifactId&gt
            &ltversion&gt${reactor-netty.version}&lt/version&gt
        &lt/dependency&gt
    &lt/dependencies&gt

```

Versions:

```

    &ltspring-boot.version&gt2.1.4.RELEASE&lt/spring-boot.version&gt
    &ltreactor-netty.version&gt0.8.6.RELEASE&lt/reactor-netty.version&gt

```

答:
As explained in the Spring Boot reference documentation on WebFlux, adding both web and webflux starters means that Spring Boot will auto-configure a Spring MVC application.

This argument type cannot be resolved in this case because Spring MVC applications cannot resolve this request type.

ContentLicense: CC BY-SA 4.0

Body:
I am using ServerHttpRequest as the request parameter in my Rest Controller. But in the response I'm getting error as "No primary or default constructor found for interface org.springframework.http.server.reactive.ServerHttpRequest".

I found one similar question,  but no luck.

Rest Controller

@GetMapping(path = "/**")
public Mono &ltResponseEntity&lt String&gt&gt clientRequests(ServerHttpRequest request) {
    Mono&ltResponseEntity&ltString&gt&gt jsonOp =  restServices.getApiResponse();
    return jsonOp;
}

Log

SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No primary or default constructor found for interface org.springframework.http.server.reactive.ServerHttpRequest] with root cause
java.lang.NoSuchMethodException: org.springframework.http.server.reactive.ServerHttpRequest.()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:216)
    at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:84)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:139)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:126)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:166)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

Pom.xml

&ltdependencies&gt
        &ltdependency&gt
            &ltgroupId&gtorg.springframework.boot&lt/groupId&gt
            &ltartifactId&gtspring-boot-starter-webflux&lt/artifactId&gt
            &ltversion&gt${spring-boot.version}&lt/version&gt
            &ltexclusions&gt
                &ltexclusion&gt
                    &ltgroupId&gtorg.springframework.boot&lt/groupId&gt
                    &ltartifactId&gtspring-boot-starter-logging&lt/artifactId&gt
                &lt/exclusion&gt
            &lt/exclusions&gt
        &lt/dependency&gt
        &ltdependency&gt
            &ltgroupId&gtorg.springframework.boot&lt/groupId&gt
            &ltartifactId&gtspring-boot-starter-web&lt/artifactId&gt
            &ltversion&gt${spring-boot.version}&lt/version&gt
            &ltexclusions&gt
                &ltexclusion&gt
                    &ltgroupId&gtorg.springframework.boot&lt/groupId&gt
                    &ltartifactId&gtspring-boot-starter-logging&lt/artifactId&gt
                &lt/exclusion&gt
            &lt/exclusions&gt
        &lt/dependency&gt

        &ltdependency&gt
            &ltgroupId&gtio.projectreactor.netty&lt/groupId&gt
            &ltartifactId&gtreactor-netty&lt/artifactId&gt
            &ltversion&gt${reactor-netty.version}&lt/version&gt
        &lt/dependency&gt
    &lt/dependencies&gt

Versions:

    &ltspring-boot.version&gt2.1.4.RELEASE&lt/spring-boot.version&gt
    &ltreactor-netty.version&gt0.8.6.RELEASE&lt/reactor-netty.version&gt


问:
HttpSession, session.getAttribute(), problem
I have a problem related to Java servlet sessions. I don't understand why the getAttribute() function of the session object is used before setAttribute(); Here is the code:

```<code>Vector buylist=(Vector)session.getAttribute("Register");
if (action.equals("del")) {
String del = request.getParameter("deli");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
}
session.setAttribute("Register", buylist);
</code>```

Thanks.

答: The only explanation I can think of is: first of all you you retrieve the vector, then make the change and after store it back into session object.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a problem related to Java servlet sessions. I don't understand why the getAttribute() function of the session object is used before setAttribute(); Here is the code:

Vector buylist=(Vector)session.getAttribute("Register");
if (action.equals("del")) {
String del = request.getParameter("deli");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
}
session.setAttribute("Register", buylist);

Thanks.


问:
Subject.subscribe not firing in ngOnInit
I have defined the subject in my service.ts
The onEditItem() in detail.component.ts passes the value of id in .next() and the Subject is subscribed in new.component.ts
But the subscription is not working. Subscription is done in ngOnInit  in new.component.ts

The value of id is successfully passed in onEditItem() but subscription is not working. I've tried doing console.log check inside subscription. But nothing is printed in console.

in details.component.html

```<code><a class="btn btn-primary" (click)="onEditItem()" routerLink="/new">Edit</a>
</code>```

in details.component.ts

```<code>  onEditItem(){this.contactService.startedEditing.next(this.id);}
</code>```

in contactService.ts

```<code>export class ContactService {
  startedEditing =new Subject<number>();
}
</code>```

in new.component.ts

```<code>ngOnInit() {
  this.subscription = this.contactService.startedEditing.subscribe(
    (index: number) => {
      console.log(index);

      this.editedItemIndex = index;
      console.log(this.editedItemIndex);
      this.editMode = true;
      this.editedItem = this.contactService.getContacts(index);

      this.editForm.setValue({
        name: this.editedItem.name,
        address: this.editedItem.address
      })
    }
  );
}
</code>```

I expected that the form which is defined in new.component.html should be initialized with the value from details component but the subscription is not working in ngOnInit.

答:
Subjects need to emit the value in order to the observers to act upon the event.

This means you have to either click on your Div, or switch to a BehaviorSubject, which returns the last value of the stream at subscription.

Body:
I have defined the subject in my service.ts
The onEditItem() in detail.component.ts passes the value of id in .next() and the Subject is subscribed in new.component.ts
But the subscription is not working. Subscription is done in ngOnInit  in new.component.ts

The value of id is successfully passed in onEditItem() but subscription is not working. I've tried doing console.log check inside subscription. But nothing is printed in console.

in details.component.html

Edit

in details.component.ts

  onEditItem(){this.contactService.startedEditing.next(this.id);}

in contactService.ts

export class ContactService {
  startedEditing =new Subject<number>();
}

in new.component.ts

ngOnInit() {
  this.subscription = this.contactService.startedEditing.subscribe(
    (index: number) => {
      console.log(index);

      this.editedItemIndex = index;
      console.log(this.editedItemIndex);
      this.editMode = true;
      this.editedItem = this.contactService.getContacts(index);

      this.editForm.setValue({
        name: this.editedItem.name,
        address: this.editedItem.address
      })
    }
  );
}

I expected that the form which is defined in new.component.html should be initialized with the value from details component but the subscription is not working in ngOnInit.


问:
Execute code after the lack or eventual completion of a CSS transition
I'm trying to execute some code immediately after a CSS transition finishes. The problem is that in certain cases (not determined by me), the transition does not have to occur. How do I know when to expect a transition? I know about the transitionrun and transitionstart events and I tried to use them, but they don't do the job:

function animateIn (elem, action) {
  var expecting = false

  setTimeout(() => {
    console.log('timeout', expecting)
  }, 0)

  window.requestAnimationFrame(() => {
    console.log('raf', expecting)
  })

  elem.addEventListener('transitionrun', () => {
    expecting = true
    console.log('transitionrun')
  })

  elem.addEventListener('transitionstart', () => {
    expecting = true
    console.log('transitionstart')
  })

  elem.addEventListener('transitionend', () => {
    console.log('transitionend')
  })

  action()
}

var elem = document.getElementById('main')
elem.addEventListener('click', () => {
  animateIn(elem, () => {
    elem.classList.remove('is-enter')
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main {
  background: red;
  width: 80px;
  height: 80px;
  transition: background 0.5s ease;
}

#main.is-enter {
  background: blue;
}</code>```

```
</div>
</div>
</p>

<p>As you can see, I want to use the <code>expecting</code> variable to check whether a transition will start after whatever happens in the <code>action</code> function. And that's what I basically want - to check if a certain action (the removal of a class in this case) causes a transition to run.</p>

<p>My idea was to use <code>requestAnimationFrame</code> or <code>setTimeout</code> to wait for a little bit and if <code>transitionrun</code> or <code>transitionstart</code> has fired in the meantime - then a transition is expected, otherwise - it's not.</p>

<p>The problem with that is the fact that both <code>requestAnimationFrame</code> and <code>setTimeout</code> run <em>before</em> <code>transitionrun</code> and <code>transitionstart</code> had the chance to fire (at least in Chrome). So it appears that the transition takes longer to start than one render loop? Why is that?</p>

<p>One workaround is to use an arbitrary timeout that gives the transition enough time to eventually start:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function checkTransition (elem, action) {
  return new Promise ((resolve, reject) => {
    var willTransition = false
    var startHandler = function () {
      willTransition = true
      elem.addEventListener('transitionend', function endHandler () {
        elem.removeEventListener('transitionend', endHandler)
        resolve(true)
      })
    }

    elem.addEventListener('transitionstart', startHandler)

    setTimeout(() => {
      elem.removeEventListener('transitionstart', startHandler)
      if (!willTransition) {
        resolve(false)
      }
    }, 100)

    action()
  })
}

var elem = document.getElementById('main')
elem.addEventListener('click', () => {
  checkTransition(elem, () => {
    elem.classList.remove('is-enter')
  }).then(status => {
    console.log('had transition:', status)
  })
})</code>```

#main {
  background: red;
  width: 80px;
  height: 80px;
  transition: background 0.5s ease;
}

#main.is-enter {
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main" class="is-enter"></div></code>```

When you click the box for the first time, the Promise waits for the transition to finish and resolves with true to signal that a transition has happened. If you click it more times after that, it resolves with false because no transition occurred. That's exactly what I need.

The problem is setTimeout. That 100ms wait is completely arbitrary and very error-prone, I suppose. Is there a better way to capture this? I need some sort of way to fire code immediately after a transitionstart might occur. I was hoping that requestAnimationFrame would do this but it doesn't. Why?

答:
It appears to work in Chrome (latest), Firefox (latest) and IE11 with a double requestAnimationFrame, even for delayed transitions:

function checkTransition (elem, action) {
  return new Promise ((resolve, reject) => {
    var willTransition = false
    var startHandler = function () {
      willTransition = true
      elem.addEventListener('transitionend', function endHandler () {
        elem.removeEventListener('transitionend', endHandler)
        resolve(true)
      })
    }

    elem.addEventListener('transitionrun', startHandler)
    elem.addEventListener('transitionstart', startHandler)

    window.requestAnimationFrame(() => {
      window.requestAnimationFrame(() => {
        elem.removeEventListener('transitionrun', startHandler)
        elem.removeEventListener('transitionstart', startHandler)
        if (!willTransition) {
          resolve(false)
        }
      })
    })

    action()
  })
}

function bind (elem) {
  elem.addEventListener('click', () => {
    checkTransition(elem, () => {
      elem.classList.remove('is-enter')
    }).then(status => {
      console.log('had transition:', status)
    })
  })
}

bind(document.getElementById('main'))
bind(document.getElementById('delayed'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.target {
  display: inline-block;
  width: 80px;
  height: 80px;
  margin-right: 5px;
  background: red;
}

.target.is-enter {
  background: blue;
}

#main {
  transition: background 0.5s ease;
}

#delayed {
  transition: background 0.5s ease 0.4s;
}</code>```

```

I think it's far better than an arbitrary timeout but I still have doubts whether it's reliable. To answer that, I think we need to answer first why one requestAnimationFrame call is not enough in Chrome.

Edit: This trick doesn't seem to work in Chrome on mobile.

Body:
I'm trying to execute some code immediately after a CSS transition finishes. The problem is that in certain cases (not determined by me), the transition does not have to occur. How do I know when to expect a transition? I know about the transitionrun and transitionstart events and I tried to use them, but they don't do the job:

function animateIn (elem, action) {
  var expecting = false

  setTimeout(() => {
    console.log('timeout', expecting)
  }, 0)

  window.requestAnimationFrame(() => {
    console.log('raf', expecting)
  })

  elem.addEventListener('transitionrun', () => {
    expecting = true
    console.log('transitionrun')
  })

  elem.addEventListener('transitionstart', () => {
    expecting = true
    console.log('transitionstart')
  })

  elem.addEventListener('transitionend', () => {
    console.log('transitionend')
  })

  action()
}

var elem = document.getElementById('main')
elem.addEventListener('click', () => {
  animateIn(elem, () => {
    elem.classList.remove('is-enter')
  })
})

#main {
  background: red;
  width: 80px;
  height: 80px;
  transition: background 0.5s ease;
}

#main.is-enter {
  background: blue;
}

As you can see, I want to use the expecting variable to check whether a transition will start after whatever happens in the action function. And that's what I basically want - to check if a certain action (the removal of a class in this case) causes a transition to run.

My idea was to use requestAnimationFrame or setTimeout to wait for a little bit and if transitionrun or transitionstart has fired in the meantime - then a transition is expected, otherwise - it's not.

The problem with that is the fact that both requestAnimationFrame and setTimeout run before transitionrun and transitionstart had the chance to fire (at least in Chrome). So it appears that the transition takes longer to start than one render loop? Why is that?

One workaround is to use an arbitrary timeout that gives the transition enough time to eventually start:

function checkTransition (elem, action) {
  return new Promise ((resolve, reject) => {
    var willTransition = false
    var startHandler = function () {
      willTransition = true
      elem.addEventListener('transitionend', function endHandler () {
        elem.removeEventListener('transitionend', endHandler)
        resolve(true)
      })
    }

    elem.addEventListener('transitionstart', startHandler)

    setTimeout(() => {
      elem.removeEventListener('transitionstart', startHandler)
      if (!willTransition) {
        resolve(false)
      }
    }, 100)

    action()
  })
}

var elem = document.getElementById('main')
elem.addEventListener('click', () => {
  checkTransition(elem, () => {
    elem.classList.remove('is-enter')
  }).then(status => {
    console.log('had transition:', status)
  })
})

#main {
  background: red;
  width: 80px;
  height: 80px;
  transition: background 0.5s ease;
}

#main.is-enter {
  background: blue;
}

When you click the box for the first time, the Promise waits for the transition to finish and resolves with true to signal that a transition has happened. If you click it more times after that, it resolves with false because no transition occurred. That's exactly what I need.

The problem is setTimeout. That 100ms wait is completely arbitrary and very error-prone, I suppose. Is there a better way to capture this? I need some sort of way to fire code immediately after a transitionstart might occur. I was hoping that requestAnimationFrame would do this but it doesn't. Why?

Body:
It appears to work in Chrome (latest), Firefox (latest) and IE11 with a double requestAnimationFrame, even for delayed transitions:

function checkTransition (elem, action) {
  return new Promise ((resolve, reject) => {
    var willTransition = false
    var startHandler = function () {
      willTransition = true
      elem.addEventListener('transitionend', function endHandler () {
        elem.removeEventListener('transitionend', endHandler)
        resolve(true)
      })
    }

    elem.addEventListener('transitionrun', startHandler)
    elem.addEventListener('transitionstart', startHandler)

    window.requestAnimationFrame(() => {
      window.requestAnimationFrame(() => {
        elem.removeEventListener('transitionrun', startHandler)
        elem.removeEventListener('transitionstart', startHandler)
        if (!willTransition) {
          resolve(false)
        }
      })
    })

    action()
  })
}

function bind (elem) {
  elem.addEventListener('click', () => {
    checkTransition(elem, () => {
      elem.classList.remove('is-enter')
    }).then(status => {
      console.log('had transition:', status)
    })
  })
}

bind(document.getElementById('main'))
bind(document.getElementById('delayed'))

.target {
  display: inline-block;
  width: 80px;
  height: 80px;
  margin-right: 5px;
  background: red;
}

.target.is-enter {
  background: blue;
}

#main {
  transition: background 0.5s ease;
}

#delayed {
  transition: background 0.5s ease 0.4s;
}

<div id="main" class="target is-enter"></div>
<div id="delayed" class="target is-enter"></div>

I think it's far better than an arbitrary timeout but I still have doubts whether it's reliable. To answer that, I think we need to answer first why one requestAnimationFrame call is not enough in Chrome.

Edit: This trick doesn't seem to work in Chrome on mobile.


问:
How to do equivalent of block_reduce on a masked array?
I'm calculating an aggregate value over smaller blocks in a 2D numpy array. I'd like to exclude values 0 from the aggregation operation in an efficient manner (rather than for and if statements).

I'm using skimage.measure.block_reduce and numpy.ma.masked_equal, but it looks like block_reduce ignores the mask.

import numpy as np
import skimage
a = np.array([[2,4,0,12,5,7],[6,0,8,4,3,9]])
zeros_included = skimage.measure.block_reduce(a,(2,2),np.mean)
```

<p>includes 0s and (correctly) produces</p>

<pre class="lang-py prettyprint-override"><code>zeros_included
array([[3., 6., 6.]])
</code>```

I was hoping

masked = np.ma.masked_equal(a,0)
zeros_excluded = skimage.measure.block_reduce(masked,(2,2),np.mean)
```

<p>would do the trick, but still produces</p>

<pre class="lang-py prettyprint-override"><code>zeros_excluded
array([[3., 6., 6.]])
</code>```

The desired result would be:

array([[4., 8., 6.]])
```

I'm looking for a pythonesque way to achieve the correct result, use of skimage is optional. Of course my actual arrays and blocks are much bigger than in this example, hence the need for efficiency.

Thanks for your interest.

答:
You could use np.nanmean, but you'll have to modify original array or create a new one:

```<code>import numpy as np
import skimage

a = np.array([[2,4,0,12,5,7],[6,0,8,4,3,9]])

b = a.astype("float")
b[b==0] = np.nan
zeros_excluded = skimage.measure.block_reduce(b,(2,2), np.nanmean)
zeros_excluded

# array([[4., 8., 6.]])
</code>```

Body:
I'm calculating an aggregate value over smaller blocks in a 2D numpy array. I'd like to exclude values 0 from the aggregation operation in an efficient manner (rather than for and if statements).

I'm using skimage.measure.block_reduce and numpy.ma.masked_equal, but it looks like block_reduce ignores the mask.

import numpy as np
import skimage
a = np.array([[2,4,0,12,5,7],[6,0,8,4,3,9]])
zeros_included = skimage.measure.block_reduce(a,(2,2),np.mean)

includes 0s and (correctly) produces

zeros_included
array([[3., 6., 6.]])

I was hoping

masked = np.ma.masked_equal(a,0)
zeros_excluded = skimage.measure.block_reduce(masked,(2,2),np.mean)

would do the trick, but still produces

zeros_excluded
array([[3., 6., 6.]])

The desired result would be:

array([[4., 8., 6.]])

I'm looking for a pythonesque way to achieve the correct result, use of skimage is optional. Of course my actual arrays and blocks are much bigger than in this example, hence the need for efficiency.

Thanks for your interest.

Body:
You could use np.nanmean, but you'll have to modify original array or create a new one:

import numpy as np
import skimage

a = np.array([[2,4,0,12,5,7],[6,0,8,4,3,9]])

b = a.astype("float")
b[b==0] = np.nan
zeros_excluded = skimage.measure.block_reduce(b,(2,2), np.nanmean)
zeros_excluded

# array([[4., 8., 6.]])


问:
Find a header, copy a certain range, find a marker and paste it there
I have a piece of code which copies a certain range from Sheet1, searches in Sheet4 for a text called "Marker 1" and pastes the copied range from Sheet1 in Sheet4 beginning in the cell of "Marker 1".

```<code>Sub FindCopyPasteV1()

    Dim FindM1 As Range
    Dim CopyM1 As Range

    With Worksheets("Sheet1").Range("A:DD")

        Set CopyM1 = Sheets("Sheet1").Range("E6:E32")

    End With

    With Worksheets("Sheet4").Range("A:DD")

        Set FindM1 = .Find(What:="Marker 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        CopyM1.Copy FindM1

    End With

End Sub
</code>```

Now I want to change the code so that I can use a Range Object (FindH1) for the selection of the cells which I want to copy from Sheet1.

```<code>Sub FindCopyPasteV2()

    Dim FindH1 As Range
    Dim FindM1 As Range
    Dim CopyM1 As Range

    With Worksheets("Sheet1").Range("A:DD")

        Set FindH1 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        Set CopyM1 = Sheets("Sheet1").Range("FindH1.E32") 'This doesn't work.

         'Instead of Set CopyM1 = Sheets("Sheet1").Range("E6:E32")

    End With

    With Worksheets("Sheet4").Range("A:DD")

        Set FindM1 = .Find(What:="Marker 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        CopyM1.Copy FindM1

    End With

End Sub
</code>```

答:
You can use Resize to reference a range beginning at the found cell: </p>

```<code>Set CopyM1 = FindH1.Resize(howManyRows, howManyCols)
</code>```

Body:
I have a piece of code which copies a certain range from Sheet1, searches in Sheet4 for a text called "Marker 1" and pastes the copied range from Sheet1 in Sheet4 beginning in the cell of "Marker 1".

Sub FindCopyPasteV1()

    Dim FindM1 As Range
    Dim CopyM1 As Range

    With Worksheets("Sheet1").Range("A:DD")

        Set CopyM1 = Sheets("Sheet1").Range("E6:E32")

    End With

    With Worksheets("Sheet4").Range("A:DD")

        Set FindM1 = .Find(What:="Marker 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        CopyM1.Copy FindM1

    End With

End Sub

Now I want to change the code so that I can use a Range Object (FindH1) for the selection of the cells which I want to copy from Sheet1.

Sub FindCopyPasteV2()

    Dim FindH1 As Range
    Dim FindM1 As Range
    Dim CopyM1 As Range

    With Worksheets("Sheet1").Range("A:DD")

        Set FindH1 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        Set CopyM1 = Sheets("Sheet1").Range("FindH1.E32") 'This doesn't work.

         'Instead of Set CopyM1 = Sheets("Sheet1").Range("E6:E32")

    End With

    With Worksheets("Sheet4").Range("A:DD")

        Set FindM1 = .Find(What:="Marker 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        CopyM1.Copy FindM1

    End With

End Sub

Body:
You can use Resize to reference a range beginning at the found cell:

Set CopyM1 = FindH1.Resize(howManyRows, howManyCols)


问:
curl query to check out a document using CMIS
I am trying to checkout a document using the REST-based CMIS protocol, but I get an error from the server (Alfresco).

Am I misusing curl?
Or am I missing something in my request?

```<code>curl --user admin:admin -F "atomentry=@atomentry.xml" http://localhost:8080/alfresco/service/cmis/checkedout
</code>```

With atomentry.xml being:

```<code><?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"
xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
<cmisra:object>
<cmis:properties>
<cmis:propertyId propertyDefinitionId="cmis:objectId">
<cmis:value>workspace://SpacesStore/3e13d089-39cf-48a4-b0b6-773b602bbcc0</cmis:value>
</cmis:propertyId>
</cmis:properties>
</cmisra:object>
</entry>
</code>```

答:
I was wrong with both curl and the XML... here is what worked:

```<code>curl -X POST -uadmin:admin "http://localhost:8080/alfresco/s/cmis/checkedout" -H "Content-Type:application/atom+xml;type=entry;charset=UTF-8" -d @atomentry.xml
</code>```

With atomentry.xml being:

```<code><?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/" xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
<cmisra:object>
<cmis:properties>
<cmis:propertyId propertyDefinitionId="cmis:objectId">
<cmis:value>workspace://SpacesStore/3e13d089-39cf-48a4-b0b6-773b602bbcc0</cmis:value>
</cmis:propertyId>
</cmis:properties>
</cmisra:object>
</entry>
</code>```

Body:
I am trying to checkout a document using the REST-based CMIS protocol, but I get an error from the server (Alfresco).

Am I misusing curl?
Or am I missing something in my request?

curl --user admin:admin -F "atomentry=@atomentry.xml" http://localhost:8080/alfresco/service/cmis/checkedout

With atomentry.xml being:

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"
xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
<cmisra:object>
<cmis:properties>
<cmis:propertyId propertyDefinitionId="cmis:objectId">
<cmis:value>workspace://SpacesStore/3e13d089-39cf-48a4-b0b6-773b602bbcc0</cmis:value>
</cmis:propertyId>
</cmis:properties>
</cmisra:object>
</entry>

Body:
I was wrong with both curl and the XML... here is what worked:

curl -X POST -uadmin:admin "http://localhost:8080/alfresco/s/cmis/checkedout" -H "Content-Type:application/atom+xml;type=entry;charset=UTF-8" -d @atomentry.xml

With atomentry.xml being:

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/" xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
<cmisra:object>
<cmis:properties>
<cmis:propertyId propertyDefinitionId="cmis:objectId">
<cmis:value>workspace://SpacesStore/3e13d089-39cf-48a4-b0b6-773b602bbcc0</cmis:value>
</cmis:propertyId>
</cmis:properties>
</cmisra:object>
</entry>


问:
C++ struct redefinition compiler error
I have created a new .h file with the following contents:

```<code>#include "stdafx.h"
#include <string>
using namespace std;

struct udtCharVec
{
    wstring GraphemeM3;
    wstring GraphemeM2;
};
</code>```

When I want to compile it, the compiler tells me "error C2011: udtCharVec: struct type redefintion".

I did a text search, and I don't have "struct udtCharVec" defined anywhere else.

Does anybody see where I went wrong?

答:
add this macro at the top of the header file</p>

```<code>#pragma once
</code>```

Title: C++ struct redefinition compiler error

Body:
I have created a new .h file with the following contents:

#include "stdafx.h"
#include <string>
using namespace std;

struct udtCharVec
{
    wstring GraphemeM3;
    wstring GraphemeM2;
};

When I want to compile it, the compiler tells me "error C2011: udtCharVec: struct type redefintion".

I did a text search, and I don't have "struct udtCharVec" defined anywhere else.

Does anybody see where I went wrong?

Body:
add this macro at the top of the header file

#pragma once


问:
PHP merge two arrays with same key and output to specific json format
My database has two tables. One is calling out the book info and another is calling image info. I would like to merge these two table data into one JSON. If the img id is matched with the data id, then the image is belongs to this book. I tried to use foreach to loop the book data into array and use another foreach to loop the image data within the book data array, but failed to get the expected result.

Book Table JSON:

```<code>{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller"
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love"
    }
 ]
}
</code>```

Image Table JSON:

```<code>{
"img": [
    {
        "id": 18,
        "url": "image18.png"
    },
    {
        "id": 18,
        "url": "image18b.png"
    },
    {
        "id": 19,
        "url": "image19.png"
    },
    {
        "id": 19,
        "url": "image19b.png"
    },
    {
        "id": 19,
        "url": "image19c.png"
    }
]
}
</code>```

Expected Result:

```<code>{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller",
        "image":[
           {
             "url":"image18"
           },
           {
             "url":"image18b"
           }
         ]
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love",
        "image":[
           {
             "url":"image19"
           },
           {
             "url":"image19b"
           },
           {
             "url":"image19c"
           }
         ]
    }
 ]
 }
</code>```

答:
If you make the data array associative then you only need to loop the image array and add them to the correct subarray in data.

```<code>// This flattens the array and makes it associative
$data = array_column($data['data'], null, 'id');

foreach($img['img'] as $v){
    $data[$v['id']]['image'][] = ['url' => $v['url']];
}
// Add the 'data' again
$final['data'] = array_values($data);

var_dump($final);
echo json_encode($final);
</code>```

https://3v4l.org/736lQ

Body:
My database has two tables. One is calling out the book info and another is calling image info. I would like to merge these two table data into one JSON. If the img id is matched with the data id, then the image is belongs to this book. I tried to use foreach to loop the book data into array and use another foreach to loop the image data within the book data array, but failed to get the expected result.

Book Table JSON:

{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller"
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love"
    }
 ]
}

Image Table JSON:

{
"img": [
    {
        "id": 18,
        "url": "image18.png"
    },
    {
        "id": 18,
        "url": "image18b.png"
    },
    {
        "id": 19,
        "url": "image19.png"
    },
    {
        "id": 19,
        "url": "image19b.png"
    },
    {
        "id": 19,
        "url": "image19c.png"
    }
]
}

Expected Result:

{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller",
        "image":[
           {
             "url":"image18"
           },
           {
             "url":"image18b"
           }
         ]
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love",
        "image":[
           {
             "url":"image19"
           },
           {
             "url":"image19b"
           },
           {
             "url":"image19c"
           }
         ]
    }
 ]
 }

Body:
If you make the data array associative then you only need to loop the image array and add them to the correct subarray in data.

// This flattens the array and makes it associative
$data = array_column($data['data'], null, 'id');

foreach($img['img'] as $v){
    $data[$v['id']]['image'][] = ['url' => $v['url']];
}
// Add the 'data' again
$final['data'] = array_values($data);

var_dump($final);
echo json_encode($final);

https://3v4l.org/736lQ


问:
Can't run my java .exe program. How do I troubleshoot this ? ("A Java exception has occured") and JNI problem
My problem is that I created a Java app that I exported to .jar if I open it in .jar it works perfectly but I'd like to make it an .exe app so I've tried launch4j but if I try to use the .exe file created I get "Error, A JNI error has occured, please check your installation etc..." and "A Java Exception has occured" also I don't know if it's useful but if I try to test the wrapper in Launch4j I get the same messages and this on the log :

```<code>Executing:C:\Users\edena\Documents\CGen.exe
Exception in thread "main" java.lang.UnsupportedClassVersionError: CodeGenerator has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
</code>```

I've already tried to see if the problem was from my Java version but it says it's the latest. Also, I tried deleting metadata in Eclipse and doing the process again but it didn't work

答:
(Posted on behalf of the question author).

I found out how to make it work. I went in my IDE (Eclipse) and right clicked on my project then Properties>Java Compiler then de-checked "Use compliance from execution environment 'JAVA SE-11' on the 'Java BuildPath>I then set the compiler compliance level on 1.4.

Body:
My problem is that I created a Java app that I exported to .jar if I open it in .jar it works perfectly but I'd like to make it an .exe app so I've tried launch4j but if I try to use the .exe file created I get "Error, A JNI error has occured, please check your installation etc..." and "A Java Exception has occured" also I don't know if it's useful but if I try to test the wrapper in Launch4j I get the same messages and this on the log :

Executing:C:\Users\edena\Documents\CGen.exe
Exception in thread "main" java.lang.UnsupportedClassVersionError: CodeGenerator has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

I've already tried to see if the problem was from my Java version but it says it's the latest. Also, I tried deleting metadata in Eclipse and doing the process again but it didn't work


问:
Angular Renderer2 can't add class
addClass method of Renderer doesn't work in case element has class with binding

Some HTML

```

<p>Inside <code>addClassDir</code></p>

<pre class="lang-js prettyprint-override"><code>ngOnInit() {
    this.renderer.addClass(this.elementRef.nativeElement, 'new-class');
}
</code>```

I know that class="my-class-{{smth}}" is a not Angular way, but I don't know how people use my directive. It should work anyway, but it doesn't. What is the most correct way to do it?

答:
Add your Component

```<code>isTrueNewClass = false;
ngOnInit() {
    this.isTrueNewClass = true;
}
</code>```

Adn your template

```<code><some-element [ngClass]="{'new-class new-class2' : isTrueNewClass }">...</some-element>
</code>```

OR

```<code><div class="prevclass1 prevclass2" [ngClass]="{'new-class new-class2' : isTrueNewClass }">...</div>
</code>```

Title: Angular Renderer2 can't add class

Body:
addClass method of Renderer doesn't work in case element has class with binding

Some HTML

Inside addClassDir

ngOnInit() {
    this.renderer.addClass(this.elementRef.nativeElement, 'new-class');
}

I know that class="my-class-{{smth}}" is a not Angular way, but I don't know how people use my directive. It should work anyway, but it doesn't. What is the most correct way to do it?

Body:
Add your Component

isTrueNewClass = false;
ngOnInit() {
    this.isTrueNewClass = true;
}

Adn your template

<some-element [ngClass]="{'new-class new-class2' : isTrueNewClass }">...</some-element>

OR

<div class="prevclass1 prevclass2" [ngClass]="{'new-class new-class2' : isTrueNewClass }">...</div>


问:
Selenium find_elements_ from a tag (xpath or css)
I want to scrape prices with Selenium (Python) from a website (i am a beginner). I recognized that the price is not always in the same html tags and those are the following tags in which is the price stored:

First option:

```<code><strong class="
price
scarcity_color
" data-et-click="">
<b>
€ 999
</b>
</strong>
</code>```

Second option:

```<code><b class="sr_gs_price_total">
€ 999
</b>
</code>```

Third option:

```<code><div class="
totalPrice totalPrice_no-rack-rate entire_row_clickable" data-link="/hotel/de/adlon_berlin.de.html?label=gen173nr-1FCAEoggI46AdIM1gEaDuIAQGYAQe4AQfIAQ_YAQHoAQH4AQuIAgGoAgO4AprH5OYFwAIB&sid=d730f1bbb7d4c57cc4185f54d3c12d41&all_sr_blocks=6096409_97405530_4_2_0&checkin=2019-05-23&checkout=2019-05-24&dest_id=-1829149&dest_type=city&fcpilot=0&group_adults=4&group_children=0&hapos=13&highlighted_blocks=6096409_97405530_4_2_0&hpos=13&req_adults=4&req_children=0&room1=A%2CA%2CA%2CA&sr_order=popularity&srepoch=1558637992&srpvid=95ff85944d0201f3&ucfs=1&from=searchresults#maxotelRoomArea" data-target="_blank">
Preis für 4 Erwachsene
für 1 Nacht:
€ 999
<div class="prd-taxes-and-fees-under-price on-srpage-group blockuid-" data-excl-charges-raw="" data-cur-stage="1"> einschließlich Steuern und Gebühren </div>
</div>
</code>```

Fourth option:

```<code><b class="sr_gs_price_total">
€ 999
</b>
</code>```

Fifth option:

```<code><label class="tpi_price_label tpi_price_label__orange">€ 999</label>
</code>```

I want to just extract the price (number 999). I tried it with css selector, for example with the following code:

```<code>content.find_elements_by_css_selector('.price')
</code>```

But i dont even get this price. How can i access those prices? Thank you!

答:
Get the list of elements with cssSelector and then loop it to get the innerText</p>

```<code>List<WebElement> textInWebElement= driver.findElement(By.xpath("//*[contains(@class,'price')]"));
for(WebElement element : textInWebElement)
{
String innerText= element .getText();

innerText = innerText.replace("€ ", "");

}
</code>```

Body:
I want to scrape prices with Selenium (Python) from a website (i am a beginner). I recognized that the price is not always in the same html tags and those are the following tags in which is the price stored:

First option:

€ 999

Second option:

€ 999

Third option:

<div class="
totalPrice totalPrice_no-rack-rate entire_row_clickable" data-link="/hotel/de/adlon_berlin.de.html?label=gen173nr-1FCAEoggI46AdIM1gEaDuIAQGYAQe4AQfIAQ_YAQHoAQH4AQuIAgGoAgO4AprH5OYFwAIB&sid=d730f1bbb7d4c57cc4185f54d3c12d41&all_sr_blocks=6096409_97405530_4_2_0&checkin=2019-05-23&checkout=2019-05-24&dest_id=-1829149&dest_type=city&fcpilot=0&group_adults=4&group_children=0&hapos=13&highlighted_blocks=6096409_97405530_4_2_0&hpos=13&req_adults=4&req_children=0&room1=A%2CA%2CA%2CA&sr_order=popularity&srepoch=1558637992&srpvid=95ff85944d0201f3&ucfs=1&from=searchresults#maxotelRoomArea" data-target="_blank">
Preis für 4 Erwachsene
für 1 Nacht:
€ 999

 einschließlich Steuern und Gebühren

Fourth option:

€ 999

Fifth option:

€ 999

I want to just extract the price (number 999). I tried it with css selector, for example with the following code:

content.find_elements_by_css_selector('.price')

But i dont even get this price. How can i access those prices? Thank you!

Body:
Get the list of elements with cssSelector and then loop it to get the innerText

List<WebElement> textInWebElement= driver.findElement(By.xpath("//*[contains(@class,'price')]"));
for(WebElement element : textInWebElement)
{
String innerText= element .getText();

innerText = innerText.replace("€&nbsp;", "");

}


答:
You have to change your service

```<code>startedEditing =new Subject<number>();
startedEditing$: Observable<any> = this.startedEditing.asObservable();
</code>```

and

```<code> shareData(data)
  {
    this.startedEditing.next(data)
  }
</code>```

and in your details.component.ts

```<code> onEditItem(){
  this.contactService.shareData(this.id)
  }
</code>```

and finally in new.component.ts

```<code>ngOnInit() {
  this.contactService.startedEditing$.subscribe(res=>{
 console.log(res)// you can get the data here
}
</code>```

that's all about it

Title: Subject.subscribe not firing in ngOnInit

Body:
I have defined the subject in my service.ts
The onEditItem() in detail.component.ts passes the value of id in .next() and the Subject is subscribed in new.component.ts
But the subscription is not working. Subscription is done in ngOnInit  in new.component.ts

The value of id is successfully passed in onEditItem() but subscription is not working. I've tried doing console.log check inside subscription. But nothing is printed in console.

in details.component.html

Edit

in details.component.ts

  onEditItem(){this.contactService.startedEditing.next(this.id);}

in contactService.ts

export class ContactService {
  startedEditing =new Subject<number>();
}

in new.component.ts

ngOnInit() {
  this.subscription = this.contactService.startedEditing.subscribe(
    (index: number) => {
      console.log(index);

      this.editedItemIndex = index;
      console.log(this.editedItemIndex);
      this.editMode = true;
      this.editedItem = this.contactService.getContacts(index);

      this.editForm.setValue({
        name: this.editedItem.name,
        address: this.editedItem.address
      })
    }
  );
}

I expected that the form which is defined in new.component.html should be initialized with the value from details component but the subscription is not working in ngOnInit.

Body:
You have to change your service

startedEditing =new Subject<number>();
startedEditing$: Observable<any> = this.startedEditing.asObservable();

and

 shareData(data)
  {
    this.startedEditing.next(data)
  }

and in your details.component.ts

 onEditItem(){
  this.contactService.shareData(this.id)
  }

and finally in new.component.ts

ngOnInit() {
  this.contactService.startedEditing$.subscribe(res=>{
 console.log(res)// you can get the data here
}

that's all about it


问:
How to send mail from a custom UITableViewCell using MFMailComposerViewController
I want to send mail while clicking a button in a custom UITableViewCell using MFMailComposeViewController.

Appreciate if answer is in Objective-C.

答:
Following code in your .h file

#import <MessageUI/MFMailComposeViewController.h>

Give Delegate <MFMailComposeViewControllerDelegate>

Following code in your .m file

```<code>//Where you want to open dialog write below code

if([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
        mailCont.mailComposeDelegate = self; // Required to invoke mailComposeController when send

        [mailCont setSubject:@"Your Subject!"];
        [mailCont setToRecipients:[NSArray arrayWithObject:@"hello@test.com"]];
        [mailCont setMessageBody:@"Your Body" isHTML:NO];

        [self presentViewController:mailCont animated:YES completion:nil];
    }

//Delegate Method

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            //YOUR ACTION
            break;
        case MFMailComposeResultSent:
            //YOUR ACTION
            break;
        case MFMailComposeResultSaved:
            //YOUR ACTION
            break;
        case MFMailComposeResultFailed:
            //YOUR ACTION
            break;
        default:
            break;
    }
}
</code>```

You can dismiss view by this code - [self dismissViewControllerAnimated:YES completion:nil];

Body:
Following code in your .h file

#import <MessageUI/MFMailComposeViewController.h>

Give Delegate <MFMailComposeViewControllerDelegate>

Following code in your .m file

//Where you want to open dialog write below code

if([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
        mailCont.mailComposeDelegate = self; // Required to invoke mailComposeController when send

        [mailCont setSubject:@"Your Subject!"];
        [mailCont setToRecipients:[NSArray arrayWithObject:@"hello@test.com"]];
        [mailCont setMessageBody:@"Your Body" isHTML:NO];

        [self presentViewController:mailCont animated:YES completion:nil];
    }

//Delegate Method

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            //YOUR ACTION
            break;
        case MFMailComposeResultSent:
            //YOUR ACTION
            break;
        case MFMailComposeResultSaved:
            //YOUR ACTION
            break;
        case MFMailComposeResultFailed:
            //YOUR ACTION
            break;
        default:
            break;
    }
}

You can dismiss view by this code - [self dismissViewControllerAnimated:YES completion:nil];


问:
Error when querying using JDBC SQL server connection
I query data using the below code:

```<code>tBPMDataSource = getJndiDataSource("java:/NaNaDS");
tBPMConnection = tBPMDataSource.getConnection();
tBPMStatement=tBPMConnection.createStatement();
if (tBPMDataSource!=null)
{
    tBPMResultSet = tBPMStatement.executeQuery("select OID from ProcessInstance where serialNumber='"+ProcessSerial+"'");
    while (tBPMResultSet.next()) {
        ProcessOID=tBPMResultSet.getString(0);
        }
}
</code>```

And error occured,below is the error log

```<code>   2019-05-27 14:44:07,616 FINE  [com.microsoft.sqlserver.jdbc.SQLServerException] (default task-96) *** SQLException:com.microsoft.sqlserver.jdbc.SQLServerStatement@2b71098e com.microsoft.sqlserver.jdbc.SQLServerException: ̷ӽ 0 ӬԶ׶Χc ̷ӽ 0 ӬԶ׶Χc
</code>```

Can anyone help on ow to find the error code of this exception? I tried to excute the query in sql server and it worked fine. Thx.

答:
in Java column index starts from 1. Try changing this line</p>

```<code>tBPMResultSet.getString(1);
</code>```

Body:
I query data using the below code:

tBPMDataSource = getJndiDataSource("java:/NaNaDS");
tBPMConnection = tBPMDataSource.getConnection();
tBPMStatement=tBPMConnection.createStatement();
if (tBPMDataSource!=null)
{
    tBPMResultSet = tBPMStatement.executeQuery("select OID from ProcessInstance where serialNumber='"+ProcessSerial+"'");
    while (tBPMResultSet.next()) {
        ProcessOID=tBPMResultSet.getString(0);
        }
}

And error occured,below is the error log

   2019-05-27 14:44:07,616 FINE  [com.microsoft.sqlserver.jdbc.SQLServerException] (default task-96) *** SQLException:com.microsoft.sqlserver.jdbc.SQLServerStatement@2b71098e com.microsoft.sqlserver.jdbc.SQLServerException: ̷ӽ 0 ӬԶ׶Χc ̷ӽ 0 ӬԶ׶Χc

Can anyone help on ow to find the error code of this exception? I tried to excute the query in sql server and it worked fine. Thx.

Body:
in Java column index starts from 1. Try changing this line

tBPMResultSet.getString(1);


问:
Make jquery autocomplete not to fill the input value with the label of selected item
Is there any way to make jquery autocomplete plugin only respond to the "select" callback, not to fill the target input with the label value of the selected item after user selection?

I am trying but still no success, waiting for help...

Regards.
Larry

答:
DEMO ON JS FIDDLE

```<code>$('#ac').autocomplete({
    source : ["hello", "how", "do", "you", "do"],
    select: function(event, ui){
        setTimeout(function (){
          $('#ac').val('');
        }, 1000)
    }
})
</code>```

Body:
DEMO ON JS FIDDLE

$('#ac').autocomplete({
    source : ["hello", "how", "do", "you", "do"],
    select: function(event, ui){
        setTimeout(function (){
          $('#ac').val('');
        }, 1000)
    }
})


问:
How can I call facebook SDK in http?
I'm use https and http in parallel.
So I would like to use the javascript sdk to use the user login status(FB.LoginStatus), but when I call sdk from a page that does not use http, I get a cross browsing error.

If I try to use iframe, I get the same error.
Is there a way to get the login status using a javascript sdk on a non-https page?

答:
Short answer, you can not (or at least you should not). More and more browsers are blocking mixed calls. If you start a https request, then further http requests inside the main page will trigger at least a warning to the user. Then some APIs are no longer working on http (for example, the location API used to work on http pages, but it does not work anymore).

Even if you can implement a workaround, you app/site will not be futureproof.

Try to implement https all over your site/app, since there are web-sites that can provide you with free certificates (https://letsencrypt.org/).

Title: How can I call facebook SDK in http?


问:
How to configure docker run correctly via bash
I made a .net core WebApi and added docker to it via visual studio docker support.

Running my container via visual studio Run option works fine.
What I want to do is run this container via batch so that I can access my app without having to run it in visual studio(so that it is always running) but I'm having some difficulties doing this.

For this I'm following this tutorial https://docs.docker.com/engine/examples/dotnetcore/
I have already tried changing my port a million times but without success. I have also searched my question online but could not find anything.

I have also tried removing the sslport from my config in my .net core application but when I do that the application doens't run via docker in visual studio anymore.

The command I'm using to run my image in a countainer is:
docker run -it -d -p 65117:80 apiwithjwt:dev

What I expect is that if I surf to port 65117 I would get to see my webapplication.

When I type: docker container ls. This is what I get to see:
https://imgur.com/a/RQUxowb
On the top you see my container automatically made by visual studio and at the bottom you see the one I created with my command above. As you can see it seems like the port I added is missing something.
My ports are comming from the this setting in the launchsettings.json

```<code>  {
   "iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
  "applicationUrl": "http://localhost:65118",
  "sslPort": 44335
}
},
</code>```

How can I pass the sslPort via my bash command? Or how can I remove the sslPort from my .net core application and still make it run correctly.
Current result: Nothing to see when I surf to the port.

答:
For running image created by VS, you need to build the image with Release mode, refer How to run docker image produced by VS 2017.

You could build your image with command with steps below:

CD to the parent folder of the folder which contains Dockerfile

Run command docker build -f "DockerTest/Dockerfile" -t dockertest:test .

Run command docker run -it -d -p 65119:80 dockertest:test

Body:
I made a .net core WebApi and added docker to it via visual studio docker support.

Running my container via visual studio Run option works fine.
What I want to do is run this container via batch so that I can access my app without having to run it in visual studio(so that it is always running) but I'm having some difficulties doing this.

For this I'm following this tutorial https://docs.docker.com/engine/examples/dotnetcore/
I have already tried changing my port a million times but without success. I have also searched my question online but could not find anything.

I have also tried removing the sslport from my config in my .net core application but when I do that the application doens't run via docker in visual studio anymore.

The command I'm using to run my image in a countainer is:
docker run -it -d -p 65117:80 apiwithjwt:dev

What I expect is that if I surf to port 65117 I would get to see my webapplication.

When I type: docker container ls. This is what I get to see:
https://imgur.com/a/RQUxowb
On the top you see my container automatically made by visual studio and at the bottom you see the one I created with my command above. As you can see it seems like the port I added is missing something.
My ports are comming from the this setting in the launchsettings.json

  {
   "iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
  "applicationUrl": "http://localhost:65118",
  "sslPort": 44335
}
},

How can I pass the sslPort via my bash command? Or how can I remove the sslPort from my .net core application and still make it run correctly.
Current result: Nothing to see when I surf to the port.


问:
SCALA: Error while downloading blobs from an endpoint: Unexpected character '<' at input index 0
I'm using Databricks, writing code with Scala. I download blob files from an endpoint of an API, to which I do not have access otherwise. Sometimes I might get an html response, which should be handled in my code, but I cannot figure out, how.

Download function:

```<code>def dl: (String => String) = { fileUrl: String => {
      val token = getToken();
          val response: HttpResponse[String] = Http(fileUrl)
          .header("Authorization", "Bearer " + token)
          .asString;
      try {
        retry(4){

          if (response.code != 200) {
            throw new javax.xml.ws.http.HTTPException(response.code)
          }
                  response.body;
        }
      } catch {
        case e: javax.xml.ws.http.HTTPException => {
          println("error HTTPException " + e + fileUrl);
          "failed";
        }
      }
    }}
</code>```

In this function, if successful, I return the response.body, which in normal situations is an xml file, but sometimes I get this error, which is why I thought it might be an html response from the endpoint:

```<code>spray.json.JsonParser$ParsingException: Unexpected character '<' at input index 0 (line 1, position 1), expected JSON Value: <html>?
</code>```

Additionally, the response.body will be written to a JSON file, but the error actually comes from the download function.

Could you help me, how to handle this situation?

Thank you a lot in advance!!

答:
Thank you for all the comments, it actually helped me a lot. The error was coming from the function, where I generate a token. This function is called from the download function above, and it returns the token after parsing it as JSON. Sometimes there were time out errors, or an unhandled exception, that I stated above.

So I call the token-generator function (getToken()) outside of the download function (dl()), so instead of generate and parse a new one every time we call the download function, it is generated once, and then use the same token to download an amount of files.

```<code>    val token = getToken();

    def dl: (String => String) = { fileUrl: String => {
          val response: HttpResponse[String] = Http(fileUrl)
          .header("Authorization", "Bearer " + token)
          .asString;
      try {
        retry(4){

          if (response.code != 200) {
            throw new javax.xml.ws.http.HTTPException(response.code)
          }
                  response.body;
        }
      } catch {
        case e: javax.xml.ws.http.HTTPException => {
          println("error HTTPException " + e + fileUrl);
          "failed" + e;
        }
      }
    }}
</code>```

Another trick, which I will use more often to improve the performance: Handle more exceptions! Spark Scala is able to handle exceptions by itself, but it sometimes improves the performance, if you handle it manually. For example, in my case, next to the HTTPException, I added a JSON parser exception, because scala couldn't handle it.

```<code>case e: spray.json.JsonParser$ParsingException => {
          println("error JsonParser exception " + e );
          "failed" + e;
        }
</code>```

By these modifications I improved the runtime! Before, it was running for 1.5 hours with 100.000 files. After these changes it takes 15-20 minutes!!

Body:
I'm using Databricks, writing code with Scala. I download blob files from an endpoint of an API, to which I do not have access otherwise. Sometimes I might get an html response, which should be handled in my code, but I cannot figure out, how.

Download function:

def dl: (String => String) = { fileUrl: String => {
      val token = getToken();
          val response: HttpResponse[String] = Http(fileUrl)
          .header("Authorization", "Bearer " + token)
          .asString;
      try {
        retry(4){

          if (response.code != 200) {
            throw new javax.xml.ws.http.HTTPException(response.code)
          }
                  response.body;
        }
      } catch {
        case e: javax.xml.ws.http.HTTPException => {
          println("error HTTPException " + e + fileUrl);
          "failed";
        }
      }
    }}

In this function, if successful, I return the response.body, which in normal situations is an xml file, but sometimes I get this error, which is why I thought it might be an html response from the endpoint:

spray.json.JsonParser$ParsingException: Unexpected character '<' at input index 0 (line 1, position 1), expected JSON Value: ?

Additionally, the response.body will be written to a JSON file, but the error actually comes from the download function.

Could you help me, how to handle this situation?

Thank you a lot in advance!!

Body:
Thank you for all the comments, it actually helped me a lot. The error was coming from the function, where I generate a token. This function is called from the download function above, and it returns the token after parsing it as JSON. Sometimes there were time out errors, or an unhandled exception, that I stated above.

So I call the token-generator function (getToken()) outside of the download function (dl()), so instead of generate and parse a new one every time we call the download function, it is generated once, and then use the same token to download an amount of files.

    val token = getToken();

    def dl: (String => String) = { fileUrl: String => {
          val response: HttpResponse[String] = Http(fileUrl)
          .header("Authorization", "Bearer " + token)
          .asString;
      try {
        retry(4){

          if (response.code != 200) {
            throw new javax.xml.ws.http.HTTPException(response.code)
          }
                  response.body;
        }
      } catch {
        case e: javax.xml.ws.http.HTTPException => {
          println("error HTTPException " + e + fileUrl);
          "failed" + e;
        }
      }
    }}

Another trick, which I will use more often to improve the performance: Handle more exceptions! Spark Scala is able to handle exceptions by itself, but it sometimes improves the performance, if you handle it manually. For example, in my case, next to the HTTPException, I added a JSON parser exception, because scala couldn't handle it.

case e: spray.json.JsonParser$ParsingException => {
          println("error JsonParser exception " + e );
          "failed" + e;
        }

By these modifications I improved the runtime! Before, it was running for 1.5 hours with 100.000 files. After these changes it takes 15-20 minutes!!


问:
Share version information in Azure DevOps
I've written a small Android application using Xamarin Android. As the title suggests, I'm using Azure DevOps as CI and Release pipeline. The finally signed APK is published as a GitHub release.

Now I'd like to centralize the version information. At the moment, the Android version information in AndroidManifest.xml and GitHub release version are independent and I have to synchronize them manually.

How can I do this? Obviously, I could do something like:

Centralize version information within a single file

Read file as a build step in Azure DevOps

Pass the extracted information into the Xamarin build step and the GitHub release step.

Is there any built-in approach that comes without this manual ceremony?

答: I'm not sure about a built-in way but there is this extension (Mobile App Tasks for iOS and Android) for Azure DevOps which provides a 'Bump Version' function. There is a blog post and video about it here.</p>


问:
How to fix overflowed issue in Dialog?
I added Dialog, But overflowed on bottow. How to fix like this issue?
return showDialog

```<code> return showDialog(
        //  barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return  Dialog(
            //this right here
            child: Theme(
              data: ThemeData().copyWith(
                inputDecorationTheme: InputDecorationTheme(
                  border: OutlineInputBorder(),
                ), ),
</code>```

Container in child

```<code>              child: Container(
                color: Colors.blueGrey[100],
                height: MediaQuery.of(context).size.height / 2.5,
                width: MediaQuery.of(context).size.width / 1,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
</code>```

first Row

```<code>                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Expanded(child: Text(AppTranslations.of(context).text("minimum_length")),),
                          Text(": 6")
                        ],),
</code>```

others rows same like first row

Padding for gray color Allowed text

```<code>                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: SingleChildScrollView(
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text(
                            AppTranslations.of(context).text("allowed_character"),
                                style: TextStyle(color: Colors.grey[700]),
                              ), ),],),),),
</code>```

OK button

```<code>                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          Expanded(child:
                          FlatButton(
                            child: Text(
                              AppTranslations.of(context).text("ok"),
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                            onPressed: () => Navigator.of(context).pop(),
                          ),),],)],),),),), );
</code>```

答:
For the horizontal overflow add a Expanded parent widget for your Text.

```<code>Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Expanded(
          child: Text(AppTranslations.of(context).text("minimum_length")),
        ),
        Text(": 6")
      ],
    ),
</code>```

And for the vertical overflow add SingleChildScrollView parent for your Column

```<code>   Padding(
          padding: const EdgeInsets.all(8.0),
          child: SingleChildScrollView( child : Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[ ...
</code>```

Title: How to fix overflowed issue in Dialog?

Body:
I added Dialog, But overflowed on bottow. How to fix like this issue?
return showDialog

 return showDialog(
        //  barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return  Dialog(
            //this right here
            child: Theme(
              data: ThemeData().copyWith(
                inputDecorationTheme: InputDecorationTheme(
                  border: OutlineInputBorder(),
                ), ),

Container in child

              child: Container(
                color: Colors.blueGrey[100],
                height: MediaQuery.of(context).size.height / 2.5,
                width: MediaQuery.of(context).size.width / 1,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[

first Row

                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Expanded(child: Text(AppTranslations.of(context).text("minimum_length")),),
                          Text(": 6")
                        ],),

others rows same like first row

Padding for gray color Allowed text

                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: SingleChildScrollView(
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text(
                            AppTranslations.of(context).text("allowed_character"),
                                style: TextStyle(color: Colors.grey[700]),
                              ), ),],),),),

OK button

                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          Expanded(child:
                          FlatButton(
                            child: Text(
                              AppTranslations.of(context).text("ok"),
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                            onPressed: () => Navigator.of(context).pop(),
                          ),),],)],),),),), );

Body:
For the horizontal overflow add a Expanded parent widget for your Text.

Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Expanded(
          child: Text(AppTranslations.of(context).text("minimum_length")),
        ),
        Text(": 6")
      ],
    ),

And for the vertical overflow add SingleChildScrollView parent for your Column

   Padding(
          padding: const EdgeInsets.all(8.0),
          child: SingleChildScrollView( child : Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[ ...


问:
Retrieve records based on Date
I have a date column in my table.
Is there any way in mysql to retrieve record based on date excluding the time part?

I have tried appending * but does not seems to work.

SELECT * FROM myTable where filterDate="2010-08-01 *"

Is there any way to do it like this rather then filtering it by using between?

Thanks.

答:
Try this </p>

```<code>SELECT DATE_FORMAT(filterDate , '%d-%m-%Y') AS new_date FROM table_name WHERE
DATE_FORMAT(filterDate , '%d-%m-%Y') = '2010-08-01'
</code>```

Title: Retrieve records based on Date

Body:
Try this

SELECT DATE_FORMAT(filterDate , '%d-%m-%Y') AS new_date FROM table_name WHERE
DATE_FORMAT(filterDate , '%d-%m-%Y') = '2010-08-01'


问:
Passing bean field to th:field in Thymeleaf fragment
I'm trying to refactor our Thymeleaf code that have a lot of copy-paste. The general idea is we have something like this:

```<code><form th:object="${createForm}">
  <div><input type="text" th:field="*{first}"/> <!-- some boilerplate code --></div>
  <div><input type="text" th:field="*{second}"/> <!-- some boilerplate code --></div>
  <div><input type="text" th:field="*{third}"/> <!-- some boilerplate code --></div>
  <div><input type="text" th:field="*{fourth}"/> <!-- some boilerplate code --></div>
 </form>
</code>```

and I want to refactor the fragment

```<code>  <input type="text" th:field="*{first}"/> <!-- some boilerplate code -->
</code>```

to a separate file as it is a lot of copy paste (there is quite some HTML in the boilerplate code section).

My first approach was to do something like this:

```<code><form th:object="${createForm}">
  <div th:replace="fragments/input :: input(*{first}" />
  <div th:replace="fragments/input :: input(*{second}" />
  <div th:replace="fragments/input :: input(*{third}" />
  <div th:replace="fragments/input :: input(*{fourth}" />
 </form>
</code>```

and then have a fragments/input.html file

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
</head>
<body>
<div th:fragment="input(field)">
    <input th:field="${field}"/> <!-- some boilerplate code -->
</div>
</body>
</html>
</code>```

But, once compiled/deployed, I get error

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'field' available as request attribute

Anyone an idea how to solve this? The question is to reduce code copy-paste while retaining the benefit of having th:field.

I also tried use th:with like this

```<code><div th:width="field=*{first}" th:replace="fragments/smallslider :: input()" />
</code>```

and fragment

```<code><div th:fragment="input()">
    <input th:field="${field}"/> <!-- some boilerplate code -->
</div>
</code>```

but that did neither produce error nor generate HTML.

答:
I solved this in similar way as @Wilson did.

Fragment:

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
    <div th:fragment="input(fieldName)">
        <input th:field="*{__${fieldName}__}" type="text">
    </div>
</body>
</html>
</code>```

Calling:

```<code><form th:object="${createForm}">
    <div th:replace="fragments/input :: input('first')" />
    <div th:replace="fragments/input :: input('second')" />
    <div th:replace="fragments/input :: input('third')" />
    <div th:replace="fragments/input :: input('fourth')" />
</form>
</code>```

Body:
I'm trying to refactor our Thymeleaf code that have a lot of copy-paste. The general idea is we have something like this:

<form th:object="${createForm}">

<input type="text" th:field="*{first}"/>

<input type="text" th:field="*{second}"/>

<input type="text" th:field="*{third}"/>

<input type="text" th:field="*{fourth}"/>

 </form>

and I want to refactor the fragment

  <input type="text" th:field="*{first}"/>

to a separate file as it is a lot of copy paste (there is quite some HTML in the boilerplate code section).

My first approach was to do something like this:

<form th:object="${createForm}">

 </form>

and then have a fragments/input.html file

<!DOCTYPE html>

    <meta charset="UTF-8"/>

    <input th:field="${field}"/>

But, once compiled/deployed, I get error

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'field' available as request attribute

Anyone an idea how to solve this? The question is to reduce code copy-paste while retaining the benefit of having th:field.

I also tried use th:with like this

and fragment

    <input th:field="${field}"/>

but that did neither produce error nor generate HTML.

Body:
I solved this in similar way as @Wilson did.

Fragment:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
    <div th:fragment="input(fieldName)">
        <input th:field="*{__${fieldName}__}" type="text">
    </div>
</body>
</html>

Calling:

<form th:object="${createForm}">
    <div th:replace="fragments/input :: input('first')" />
    <div th:replace="fragments/input :: input('second')" />
    <div th:replace="fragments/input :: input('third')" />
    <div th:replace="fragments/input :: input('fourth')" />
</form>


问:
Laravel Docker Container not connecting to local mysql
I have an issue connecting to mysql running in the local machine in my DockerFile i have mentioned

```<code>FROM php:7
RUN apt-get update -y && apt-get install -y openssl zip unzip git
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN docker-php-ext-install pdo mbstring pdo_mysql
WORKDIR /home
COPY . /home
RUN composer install --ignore-platform-reqs

CMD php artisan serve --host=0.0.0.0 --port=8081
EXPOSE 8081
</code>```

and this in my .env configuration

```<code>DB_HOST=localhost
DB_DATABASE=databasename
DB_USERNAME=root
DB_PASSWORD=testpassword
</code>```

I have very less clue about where it is failing. Do i need to install mysql for Docker container also?

答:
I see two options -

Use the private IP of your docker host i.e where mysql server is running.

Use the host network mode while running container in case you want to use localhost.

docker container --net=host ...

Body:
I have an issue connecting to mysql running in the local machine in my DockerFile i have mentioned

FROM php:7
RUN apt-get update -y && apt-get install -y openssl zip unzip git
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN docker-php-ext-install pdo mbstring pdo_mysql
WORKDIR /home
COPY . /home
RUN composer install --ignore-platform-reqs

CMD php artisan serve --host=0.0.0.0 --port=8081
EXPOSE 8081

and this in my .env configuration

DB_HOST=localhost
DB_DATABASE=databasename
DB_USERNAME=root
DB_PASSWORD=testpassword

I have very less clue about where it is failing. Do i need to install mysql for Docker container also?


问:
How do I fetch the generated foreign key created in MySQL to be used in Insert Function
I am running the following PHP, as I want to insert data from a form into 2 tables: EventLocation and Events (EventLocationID is the foreign key in the table Events).
First I run an INSERT query to insert into EventLocation. As EventLocationID is auto-incremented, it generates the next ID without me having to enter anything. My question is how should I fetch this unique ID to be used in the next INSERT query to insert into events?

Note that the first query inserts fine, but the second query gives me an error

PHP:

```<code><?php
require '../dbh.inc.php';
$Event_Name = $_POST['Event_Name'];
$Event_Date = $_POST['Event_Date'];
$Street_1 = $_POST['Street_1'];
$Street_2 = $_POST['Street_2'];
$City = $_POST['City'];
$Start_Time = $_POST['Start_Time'];
$End_Time = $_POST['End_Time'];
$Zipcode = $_POST['Zipcode'];

$query = "INSERT INTO EventLocation (Street_1, Street_2, City, Zipcode) VALUES ('$Street_1', '$Street_2', '$City', '$Zipcode')";
$queryexecution = mysqli_query($conn, $query);

if(!$queryexecution){
  echo "damn, there was an error inserting into Event Location";
}
else {
  echo "Event Location was added!";
}

$querytwo = "SELECT EventLocationID from EventLocation where Street_1 = '$Street_1';";
$querytwoexecution = mysqli_query($conn, $querytwo);
while ($displayname = mysqli_fetch_assoc($querytwoexecution)){
     echo "<h1>".$displayname['EventLocationID']."</h1>";
}

$secinsert = "INSERT INTO events (Event_Name, Event_Date, Start_Time, End_Time, EventLocationID) VALUES ('$Event_Name','$Event_Date','$Start_Time','$End_Time', '$displayname')";
$secqueryexecution = mysqli_query($conn, $secinsert);
if(!$secqueryexecution){
  echo "damn, there was an error inserting into Events";
}
else {
  echo "Event data was added!";
}
 ?>
</code>```

I am curious to know if I could just use an Inner Join function to make it more efficient; I tried before but to no success?

答:
You can just use mysqli_insert_id:

```<code>$displayname = mysqli_insert_id($link);
</code>```

this will fetch the last auto_incremented id value from the current connection.

Body:
I am running the following PHP, as I want to insert data from a form into 2 tables: EventLocation and Events (EventLocationID is the foreign key in the table Events).
First I run an INSERT query to insert into EventLocation. As EventLocationID is auto-incremented, it generates the next ID without me having to enter anything. My question is how should I fetch this unique ID to be used in the next INSERT query to insert into events?

Note that the first query inserts fine, but the second query gives me an error

PHP:

<?php
require '../dbh.inc.php';
$Event_Name = $_POST['Event_Name'];
$Event_Date = $_POST['Event_Date'];
$Street_1 = $_POST['Street_1'];
$Street_2 = $_POST['Street_2'];
$City = $_POST['City'];
$Start_Time = $_POST['Start_Time'];
$End_Time = $_POST['End_Time'];
$Zipcode = $_POST['Zipcode'];

$query = "INSERT INTO EventLocation (Street_1, Street_2, City, Zipcode) VALUES ('$Street_1', '$Street_2', '$City', '$Zipcode')";
$queryexecution = mysqli_query($conn, $query);

if(!$queryexecution){
  echo "damn, there was an error inserting into Event Location";
}
else {
  echo "Event Location was added!";
}

$querytwo = "SELECT EventLocationID from EventLocation where Street_1 = '$Street_1';";
$querytwoexecution = mysqli_query($conn, $querytwo);
while ($displayname = mysqli_fetch_assoc($querytwoexecution)){
     echo "
".$displayname['EventLocationID']."
";
}

$secinsert = "INSERT INTO events (Event_Name, Event_Date, Start_Time, End_Time, EventLocationID) VALUES ('$Event_Name','$Event_Date','$Start_Time','$End_Time', '$displayname')";
$secqueryexecution = mysqli_query($conn, $secinsert);
if(!$secqueryexecution){
  echo "damn, there was an error inserting into Events";
}
else {
  echo "Event data was added!";
}
 ?>

I am curious to know if I could just use an Inner Join function to make it more efficient; I tried before but to no success?

Body:
You can just use mysqli_insert_id:

$displayname = mysqli_insert_id($link);

this will fetch the last auto_incremented id value from the current connection.