问:
Spring MVC - Automatically return 204 when rest controller response type is void
I'm trying to have spring automatically return HTTP Status 204 when the controller method response type is void. Ex:

Let's say I have a controller method like this:

```<code>@DeleteMapping(value = "/{heroId}")
public void delete(@PathVariable Long heroId) {
    heroService.delete(heroId);
}
</code>```

I'm looking for a way to automatically return 204 without having to annotate the method with @ResponseStatus(value = HttpStatus.NO_CONTENT).

Is it possible to do this with a handler or AOP or some other facility?

PS. I see this answer, Return HTTP 204 on null with spring @RestController, but does not answer my specific question on how this can be implemented for methods with a void return type. Also, this method should work with a method that has no input arguments.

答:
I was able to implement a solution based on the link provided by Yoshua. I'm not 100% sure on the implementation details, but it's working for me.

This captures the response from all of the controller methods that have a return type of void and changes their HTTP Status to 204.

```<code>import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class NoContentControllerAdvice implements ResponseBodyAdvice<Void> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if(returnType.getParameterType().isAssignableFrom(void.class)) {
            return true;
        }

        return false;
    }

    @Override
    public Void beforeBodyWrite(Void body, MethodParameter returnType, MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(returnType.getParameterType().isAssignableFrom(void.class)) {
            response.setStatusCode(HttpStatus.NO_CONTENT);
        }

        return body;
    }
}
</code>```

Body:
I'm trying to have spring automatically return HTTP Status 204 when the controller method response type is void. Ex:

Let's say I have a controller method like this:

@DeleteMapping(value = "/{heroId}")
public void delete(@PathVariable Long heroId) {
    heroService.delete(heroId);
}

I'm looking for a way to automatically return 204 without having to annotate the method with @ResponseStatus(value = HttpStatus.NO_CONTENT).

Is it possible to do this with a handler or AOP or some other facility?

PS. I see this answer, Return HTTP 204 on null with spring @RestController, but does not answer my specific question on how this can be implemented for methods with a void return type. Also, this method should work with a method that has no input arguments.

Body:
I was able to implement a solution based on the link provided by Yoshua. I'm not 100% sure on the implementation details, but it's working for me.

This captures the response from all of the controller methods that have a return type of void and changes their HTTP Status to 204.

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class NoContentControllerAdvice implements ResponseBodyAdvice<Void> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if(returnType.getParameterType().isAssignableFrom(void.class)) {
            return true;
        }

        return false;
    }

    @Override
    public Void beforeBodyWrite(Void body, MethodParameter returnType, MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(returnType.getParameterType().isAssignableFrom(void.class)) {
            response.setStatusCode(HttpStatus.NO_CONTENT);
        }

        return body;
    }
}


来源: stackexchange

问:
Change opacity using leaflet without plugin
I have a geojson and try change the opacity chaging the button, but it dont work anyway.

Where statesData is my geojson.js, style and onEachFeacture are others functions that I have.

Here is my button:

```<code><span id="image-opacity">0.5</span>
<input type="range" id="sldOpacity" min="0" max="1" step="0.1" value="0.5" />
</code>```

And here is my JS

```<code>$('#sldOpacity').on('change', function(){
  $('#image-opacity').html(this.value);
  geojson.setOpacity(this.value);
});

var geojson = L.geoJson(statesData, {
        style: style,
        onEachFeature: onEachFeature
    }).addTo(map);
</code>```

I tried put opacity: opacity above style: style and create a function opacity() but dont work too. What I have do?

答:
L.GeoJSON does not have a setOpacity method. Use the setStyle method. Also there is no need to use jQuery:

```<code>L.DomEvent.on(L.DomUtil.get('sldOpacity'), 'change', function () {
    L.DomUtil.get('image-opacity').textContent = this.value;
    geojson.setStyle({
        opacity: this.value
    });
});
</code>```

Reference: http://leafletjs.com/reference-1.2.0.html#geojson

ContentLicense: CC BY-SA 3.0

Body:
I have a geojson and try change the opacity chaging the button, but it dont work anyway.

Where statesData is my geojson.js, style and onEachFeacture are others functions that I have.

Here is my button:

0.5
<input type="range" id="sldOpacity" min="0" max="1" step="0.1" value="0.5" />

And here is my JS

$('#sldOpacity').on('change', function(){
  $('#image-opacity').html(this.value);
  geojson.setOpacity(this.value);
});

var geojson = L.geoJson(statesData, {
        style: style,
        onEachFeature: onEachFeature
    }).addTo(map);

I tried put opacity: opacity above style: style and create a function opacity() but dont work too. What I have do?

Body:
L.GeoJSON does not have a setOpacity method. Use the setStyle method. Also there is no need to use jQuery:

L.DomEvent.on(L.DomUtil.get('sldOpacity'), 'change', function () {
    L.DomUtil.get('image-opacity').textContent = this.value;
    geojson.setStyle({
        opacity: this.value
    });
});

Reference: http://leafletjs.com/reference-1.2.0.html#geojson


问:
Trouble with displaying images pulled in from JSON file
I'm still pretty new to ionic and angular, and I'm working on a pokedex app. When I try to display images that I pulled in from a JSON file after setting up the data service, it displays the file path instead of the actual image. I'm not sure what I'm doing wrong. Can anyone help?

Here is a snippet from the JSON file:

{
    "pocketMonsters": [

        {
            "pokemonName": "Bulbasaur",
            "pokedexNumber": "001",
            "description": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger",
            "pokemonImage": ""
        },

        {
            "pokemonName" : "Ivysaur",
            "pokedexNumber" : "002",
            "description" : "",
            "pokemonImage" : ""
        },```
</div>
</div>
</p>

<p>And here's the template. Besides the code that I already have in here, I have also tried <code><img src="pocketMonster.pokemonImage /></code> instead of {{poketMonster.pokemonImage}} and that returned a 404 error in the console.
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-header>
  <ion-navbar>
    <ion-title>
      Pokedex
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      {{pocketMonster.pokemonImage}}
    </ion-item>
   </ion-list>

  <!--<div *ngIf="pocketMonsters.length"></div> -->

</ion-content></code>```

I'll go ahead and include the home component and the data service in case those are needed as well.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { pokemonDataService } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  pocketMonsters = [];
  searchQuery: string = '';

  constructor(public navCtrl: NavController, public dataService: pokemonDataService) {

  }

  ionViewDidLoad() {

           this.dataService.getAllPokemon().then((data) => {

               data.map((pocketMonster) => {

                   this.pocketMonsters = data;
                   return pocketMonster;

               });

               console.log(this.pocketMonsters);
           });

       }

  //ngOnInit(){
    //this.dataService.getAllPokemon()
      //.subscribe(data => {
        //this.pokemonList = data;
    //});
  //}

}```
</div>
</div>
</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>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class pokemonDataService {

    data: any;

    constructor(public http: Http) {

    }

    getAllPokemon() {
      if(this.data){
        return Promise.resolve(this.data);
    }

    return new Promise(resolve => {

        this.http.get('assets/data/pokemon.json').map(res => res.json()).subscribe(data => {
            this.data = data.pocketMonsters;
            resolve(this.data);
        });

    });
      }

}</code>```

答:
If you store data like this way:

```<code>    {
        "pokemonName": "Bulbasaur",
        "pokedexNumber": "001",
        "description": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger",
        "pokemonImage": "<img src='assets/imgs/bulbasaur.png' />"
    },
</code>```

You should use innerHtml to display your image:

```<code><span innerHTML="{{pocketMonster.pokemonImage}}"></span>
</code>```

Hope it helps, but first of all you should pay attention on @bgse answer.

Body:
I'm still pretty new to ionic and angular, and I'm working on a pokedex app. When I try to display images that I pulled in from a JSON file after setting up the data service, it displays the file path instead of the actual image. I'm not sure what I'm doing wrong. Can anyone help?

Here is a snippet from the JSON file:

{
    "pocketMonsters": [

        {
            "pokemonName": "Bulbasaur",
            "pokedexNumber": "001",
            "description": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger",
            "pokemonImage": ""
        },

        {
            "pokemonName" : "Ivysaur",
            "pokedexNumber" : "002",
            "description" : "",
            "pokemonImage" : ""
        },

And here's the template. Besides the code that I already have in here, I have also tried  instead of {{poketMonster.pokemonImage}} and that returned a 404 error in the console.

<ion-header>
  <ion-navbar>
    <ion-title>
      Pokedex
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      {{pocketMonster.pokemonImage}}
    </ion-item>
   </ion-list>

</ion-content>

I'll go ahead and include the home component and the data service in case those are needed as well.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { pokemonDataService } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  pocketMonsters = [];
  searchQuery: string = '';

  constructor(public navCtrl: NavController, public dataService: pokemonDataService) {

  }

  ionViewDidLoad() {

           this.dataService.getAllPokemon().then((data) => {

               data.map((pocketMonster) => {

                   this.pocketMonsters = data;
                   return pocketMonster;

               });

               console.log(this.pocketMonsters);
           });

       }

  //ngOnInit(){
    //this.dataService.getAllPokemon()
      //.subscribe(data => {
        //this.pokemonList = data;
    //});
  //}

}

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class pokemonDataService {

    data: any;

    constructor(public http: Http) {

    }

    getAllPokemon() {
      if(this.data){
        return Promise.resolve(this.data);
    }

    return new Promise(resolve => {

        this.http.get('assets/data/pokemon.json').map(res => res.json()).subscribe(data => {
            this.data = data.pocketMonsters;
            resolve(this.data);
        });

    });
      }

}

Body:
If you store data like this way:

    {
        "pokemonName": "Bulbasaur",
        "pokedexNumber": "001",
        "description": "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger",
        "pokemonImage": "<img src='assets/imgs/bulbasaur.png' />"
    },

You should use innerHtml to display your image:

<span innerHTML="{{pocketMonster.pokemonImage}}"></span>

Hope it helps, but first of all you should pay attention on @bgse answer.


问:
Exculding multiple Nodes RVest
I am scraping newspaper articles and am struggling to figure out how to exclude more than one node. The R help says that :not() accepts a sequence of simple selectors. I tried the following

```<code>zeit_url <- read.html("http://www.zeit.de/wissen/gesundheit/2017-09/aids-hiv-neuinfektionen-europa-virus-gesundheit)

article <- zeit_url %>%
    html_nodes('.article-page>:not(.ad-container, .cardstack)') %>%
    html_text()
</code>```

It does not work to separate the two nodes with a comma. Any suggestions how to correctly specify the sequence of selectors in :not()?

I have spent a lot of time searching for an answer, but I am new to R (and HTML), so I appreciate your patience if this is something obvious.

答:
```<code>library(rvest)
zeit_url <- read_html("http://www.zeit.de/wissen/gesundheit/2017-
            09/aids-hiv-neuinfektionen-europa-virus-gesundheit")

article <- zeit_url %>%
           html_nodes(".article-page>:not(.ad-container):not(.cardstack)") %>%
           html_text()
</code>```

Title: Exculding multiple Nodes RVest

Body:
I am scraping newspaper articles and am struggling to figure out how to exclude more than one node. The R help says that :not() accepts a sequence of simple selectors. I tried the following

zeit_url <- read.html("http://www.zeit.de/wissen/gesundheit/2017-09/aids-hiv-neuinfektionen-europa-virus-gesundheit)

article <- zeit_url %>%
    html_nodes('.article-page>:not(.ad-container, .cardstack)') %>%
    html_text()

It does not work to separate the two nodes with a comma. Any suggestions how to correctly specify the sequence of selectors in :not()?

I have spent a lot of time searching for an answer, but I am new to R (and HTML), so I appreciate your patience if this is something obvious.


问:
Shell script with password in Jenkins
I have created a Jenkins job which executes a shell script. "Unsafe" people can open it and start the job. The job executes a db tool in shell which requires the db password.
The Jenkins instance is run on a computer which can be accessed by "unsafe" people. The job is delegated to a slave which is accessed by "safe" people.

This is a parameterized build, has one parameter: password as Password Parameter.

For the sake of brevity the relevant part of the script is as follows:

```<code>#!/bin/bash +x
dban -u username -p ${password}
</code>```

It runs fine and fails fine if the password is not correct. Echoing the command invoked is disabled by +x as the first line says.

Is this that simple? What else should I consider for safety reasons?

答:
Do you want people to run the build and not have to pass in the parameter of the password?  If so you should checkout setting up a credential for it.

https://support.cloudbees.com/hc/en-us/articles/203802500-Injecting-Secrets-into-Jenkins-Build-Jobs

https://github.com/jenkinsci/credentials-plugin/blob/master/docs/user.adoc

Title: Shell script with password in Jenkins

Body:
I have created a Jenkins job which executes a shell script. "Unsafe" people can open it and start the job. The job executes a db tool in shell which requires the db password.
The Jenkins instance is run on a computer which can be accessed by "unsafe" people. The job is delegated to a slave which is accessed by "safe" people.

This is a parameterized build, has one parameter: password as Password Parameter.

For the sake of brevity the relevant part of the script is as follows:

#!/bin/bash +x
dban -u username -p ${password}

It runs fine and fails fine if the password is not correct. Echoing the command invoked is disabled by +x as the first line says.

Is this that simple? What else should I consider for safety reasons?


问:
Disable save as & open in new tab on an image with css?
I know there is no point to do it, but I want to ask if it is possible to disable right click on an image with only css. </p>

<p>-What I want to do is to disallow naïve users from saving the images, from my WordPress website slider (MetaSlider)</p>

答:
No, you need JavaScript.</p>

```<code>document.addEventListener('contextmenu', event => event.preventDefault());
</code>```

Body:
I know there is no point to do it, but I want to ask if it is possible to disable right click on an image with only css.

-What I want to do is to disallow naïve users from saving the images, from my WordPress website slider (MetaSlider)

Body:
No, you need JavaScript.

document.addEventListener('contextmenu', event => event.preventDefault());


问:
Which programming language Google app engine is most likely to work with next and why?
Their roadmap says their next release will be in March 2009, and that they'll be adding a new 'runtime language'. I'm hoping its either Java or PHP but realy not sure, and would like to know which language is the most probable so i can plan accordingly for a project I plan on hosting with google app engine.

Any ideas?

答:
I'd say Java, if only for the reason Android (or, at least, the SDK) is written in Java and they went to the trouble of writing their own interpreter/VM.

If not Java, then Ruby would be my guess. Not sure why, but it feels like a good fit.

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Click Upvote

OwnerDisplayName: Chris


问:
The request was aborted: Could not create SSL/TLS secure channel
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

```<code>private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}
</code>```

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?

答:
In my case, the service account running the application did not have permission to access the private key. Once I gave this permission, the error went away

mmc

certificates

Expand to personal

select cert

right click

All tasks

Manage private keys

Add the service account user

ContentLicense: CC BY-SA 4.0

Body:
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?


问:
python implemented in assembly
Am just being curious but I would like to know whether python can be implemented in assembly and if not why has it not been done to help for speed issues. forgive my naivete in matters of programming languages.</p>

答: Native code isn't a magic make-it-go-faster operation. The language semantics really dictate quite a bit about how fast (or not) a language is. (For instance, erlang compiled to native code via Hipe is still fairly slow).</p>

Title: python implemented in assembly


问:
Macro to Copy/Paste Data
Here is the code I have. I am trying to find the last populated row in a range. Then copy that data as formulas to the next blank row in the range. Finally copy the last populated row again and paste it to the second to last populated row as values. In a nutshell, move the formulas in the last row/cells down one row and retain that data where it was copied as numbers. So when new data is brought into the file, the formulas recalculate and I do not lose the previous calculated data. Hopefully that makes sense. The below code runs but does not appear to do anything other than to paste the data as values in the existing rows. What am I doing wrong?

```<code>Sub Data Copy()

Dim myLastCell As Range
Set myLastCell = LastCell(Worksheets("YTD Metric Calculator").Range("E7:J76"))

Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row).Copy
Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row + 1).PasteSpecial Paste:=xlPasteFormulas
Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row).Copy
Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row + 1).PasteSpecial Paste:=xlPasteValues
'Retain Yesterday's YTD Metric Data

Function LastCell(r As Range) As Range

Dim LastRow&, lastCol%

On Error Resume Next

With r

LastRow& = .Cells.Find(What:="*", _
  SearchDirection:=xlPrevious, _
  SearchOrder:=xlByRows).Row

lastCol% = .Cells.Find(What:="*", _
  SearchDirection:=xlPrevious, _
  SearchOrder:=xlByColumns).Column

End With

Set LastCell = r.Cells(LastRow&, lastCol%)

End Function
</code>```

VBA Goal

答:
Your LastCell function isn't doing what you think it is doing, because it is determining the row and column within the worksheet of the last used cell in the range, and then using that as an offset from the start of the range.

So if the last used row in E7:J76 was row 10, and the last used column was column I, the cell being returned from your function is cell M16 (i.e. 9 rows below E7, and 8 columns to the right).

Change

```<code>Set LastCell = r.Cells(LastRow&, lastCol%)
</code>```

to be

```<code>Set LastCell = r.Cells(LastRow& - r.Row + 1, lastCol% - r.Column + 1)
</code>```

or to

```<code>Set LastCell = r.Worksheet.Cells(LastRow&, lastCol%)
</code>```

The parts where you are copying the formulas, and then replacing with values, should be something like:

```<code>Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Copy
Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row + 1).Resize(1, 6).PasteSpecial Paste:=xlPasteFormulas
Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Value = _
          Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Value
</code>```

That can be rewritten using a With block to save a few keystrokes:

```<code>With Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6)
    .Copy
    .Offset(1, 0).PasteSpecial Paste:=xlPasteFormulas
    .Value = .Value
End With
</code>```

Title: Macro to Copy/Paste Data

Body:
Here is the code I have. I am trying to find the last populated row in a range. Then copy that data as formulas to the next blank row in the range. Finally copy the last populated row again and paste it to the second to last populated row as values. In a nutshell, move the formulas in the last row/cells down one row and retain that data where it was copied as numbers. So when new data is brought into the file, the formulas recalculate and I do not lose the previous calculated data. Hopefully that makes sense. The below code runs but does not appear to do anything other than to paste the data as values in the existing rows. What am I doing wrong?

Sub Data Copy()

Dim myLastCell As Range
Set myLastCell = LastCell(Worksheets("YTD Metric Calculator").Range("E7:J76"))

Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row).Copy
Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row + 1).PasteSpecial Paste:=xlPasteFormulas
Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row).Copy
Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row + 1).PasteSpecial Paste:=xlPasteValues
'Retain Yesterday's YTD Metric Data

Function LastCell(r As Range) As Range

Dim LastRow&, lastCol%

On Error Resume Next

With r

LastRow& = .Cells.Find(What:="*", _
  SearchDirection:=xlPrevious, _
  SearchOrder:=xlByRows).Row

lastCol% = .Cells.Find(What:="*", _
  SearchDirection:=xlPrevious, _
  SearchOrder:=xlByColumns).Column

End With

Set LastCell = r.Cells(LastRow&, lastCol%)

End Function

VBA Goal

Body:
Your LastCell function isn't doing what you think it is doing, because it is determining the row and column within the worksheet of the last used cell in the range, and then using that as an offset from the start of the range.

So if the last used row in E7:J76 was row 10, and the last used column was column I, the cell being returned from your function is cell M16 (i.e. 9 rows below E7, and 8 columns to the right).

Change

Set LastCell = r.Cells(LastRow&, lastCol%)

to be

Set LastCell = r.Cells(LastRow& - r.Row + 1, lastCol% - r.Column + 1)

or to

Set LastCell = r.Worksheet.Cells(LastRow&, lastCol%)

The parts where you are copying the formulas, and then replacing with values, should be something like:

Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Copy
Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row + 1).Resize(1, 6).PasteSpecial Paste:=xlPasteFormulas
Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Value = _
          Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Value

That can be rewritten using a With block to save a few keystrokes:

With Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6)
    .Copy
    .Offset(1, 0).PasteSpecial Paste:=xlPasteFormulas
    .Value = .Value
End With


问:
Query to extract top records by average grade and name
I am having two tables: Movies and Reviews.

Movies has the following columns : ID, Title, Genre, Duration;

Reviews has ID, Description, Movie_ID ( referencing ID from Movies) and Grade.

I would like to display a top of movies by averages.
(I would want to display the Title of the movie as well as its average grade. )

I tried with 2 subqueries : one that would select title and one that would fetch AVG from Reviews ( joined with Movies), but I can not figure out how to feed the result of the SELECT AVG(GRADE)... to the SELECT TITLE FROM MOVIES ... .
Am I trying the right way?

```<code>Movies

ID        TITLE          GENRE       DURATION
1         Movie_name_1   Sci-fi      120
2         Movie_name_2   Comedy      100
3         Movie_name_3   Drama       140
4         Movie_name_4   Sci-fi      105

Reviews
ID        Description    Movie_id      Grade
1         WOW             1             10
2         SUCH            2             9
3         Great           3             9
4         Amazing         2             10
5         Decent          4             7
6         Legendary       2             10
7         Waste           3             4
8         hmmm            1             6
</code>```

Expected Result :

```<code>Movie_name_1           9.50
Movie_name_2           9.25
Movie_name_3           8.25
Movie_name_4           7
</code>```

答:
This should work, just change the FETCH number to however many rows you want to see:

```<code>SELECT Title, AVG(Grade) Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
ORDER BY Grade DESC
FETCH FIRST 5 ROWS ONLY;
</code>```

Edit: More detailed explanation below

The basis of this query is:

```<code>SELECT Title, Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
</code>```

This gets you all of the information you need in a single result set.

Next, you want the average Grade per movie Title

This is accomplished by using the averaging function AVG(), and grouping by Title (since you want the average grade per title after all):

```<code>SELECT Title, AVG(Grade) Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
</code>```

Note: The second Grade in AVG(Grade) Grade is just an alias.  AVG(Grade) doesn't have a column name otherwise, so for simplicity's sake, we are calling the new, averaged column, Grade.

You can also write that as AVG(Grade) as Grade which may be clearer to you.

Next, you want to see the most popular movies first.  We do this with an ORDER BY.  We can reference our averaged Grade column here:

```<code>SELECT Title, AVG(Grade) Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
ORDER BY Grade DESC --Referencing the averaged column, not the main column
</code>```

Last but not least, you mentioned you want to see the top n rows.  We can do this with a FETCH FIRST n ROWS ONLY clause:

```<code>SELECT Title, AVG(Grade) Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
ORDER BY Grade DESC
FETCH FIRST 5 ROWS ONLY;
</code>```

And here is one last version with a different alias name for extra clarity:

```<code>SELECT Title, AVG(Grade) Averaged_Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
ORDER BY Averaged_Grade DESC
FETCH FIRST 5 ROWS ONLY;
</code>```

Body:
I am having two tables: Movies and Reviews.

Movies has the following columns : ID, Title, Genre, Duration;

Reviews has ID, Description, Movie_ID ( referencing ID from Movies) and Grade.

I would like to display a top of movies by averages.
(I would want to display the Title of the movie as well as its average grade. )

I tried with 2 subqueries : one that would select title and one that would fetch AVG from Reviews ( joined with Movies), but I can not figure out how to feed the result of the SELECT AVG(GRADE)... to the SELECT TITLE FROM MOVIES ... .
Am I trying the right way?

Movies

ID        TITLE          GENRE       DURATION
1         Movie_name_1   Sci-fi      120
2         Movie_name_2   Comedy      100
3         Movie_name_3   Drama       140
4         Movie_name_4   Sci-fi      105

Reviews
ID        Description    Movie_id      Grade
1         WOW             1             10
2         SUCH            2             9
3         Great           3             9
4         Amazing         2             10
5         Decent          4             7
6         Legendary       2             10
7         Waste           3             4
8         hmmm            1             6

Expected Result :

Movie_name_1           9.50
Movie_name_2           9.25
Movie_name_3           8.25
Movie_name_4           7

Body:
This should work, just change the FETCH number to however many rows you want to see:

SELECT Title, AVG(Grade) Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
ORDER BY Grade DESC
FETCH FIRST 5 ROWS ONLY;

Edit: More detailed explanation below

The basis of this query is:

SELECT Title, Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID

This gets you all of the information you need in a single result set.

Next, you want the average Grade per movie Title

This is accomplished by using the averaging function AVG(), and grouping by Title (since you want the average grade per title after all):

SELECT Title, AVG(Grade) Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title

Note: The second Grade in AVG(Grade) Grade is just an alias.  AVG(Grade) doesn't have a column name otherwise, so for simplicity's sake, we are calling the new, averaged column, Grade.

You can also write that as AVG(Grade) as Grade which may be clearer to you.

Next, you want to see the most popular movies first.  We do this with an ORDER BY.  We can reference our averaged Grade column here:

SELECT Title, AVG(Grade) Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
ORDER BY Grade DESC --Referencing the averaged column, not the main column

Last but not least, you mentioned you want to see the top n rows.  We can do this with a FETCH FIRST n ROWS ONLY clause:

SELECT Title, AVG(Grade) Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
ORDER BY Grade DESC
FETCH FIRST 5 ROWS ONLY;

And here is one last version with a different alias name for extra clarity:

SELECT Title, AVG(Grade) Averaged_Grade
FROM Movies M
JOIN Reviews R on R.Movie_ID = M.ID
GROUP BY Title
ORDER BY Averaged_Grade DESC
FETCH FIRST 5 ROWS ONLY;


问:
Difference between Boolean(x) and !!x
Using JavaScript, is there any difference between

```<code>Boolean(x)
</code>```

and

```<code>!!x
</code>```

?

答:
They both have the same output, but you have to watch out for the Boolean object vs function. The Boolean constructor (using the new keyword) is not a primitive true or false value. Whereas the !! operator evaluates if an object is truthy/falsey.

Here's a quote from MDN:

Any object of which the value is not undefined or null, including a
  Boolean object whose value is false, evaluates to true when passed to
  a conditional statement.

So the following evaluates to false:

new Boolean(false) === false

but the following evaluates to true:

Boolean(false) === false

Title: Difference between Boolean(x) and !!x

Body:
Using JavaScript, is there any difference between

Boolean(x)

and

!!x

?


问:
Expand all / collapse all lists for class not working
I have a tree list where the user can open or close the branches by clicking. The tree has many levels and sub-levels. I want to be able to collapse all branches (down to the first level) or expand all branches for the class "my-clickable" when the user clicks on the Collapse All or Expand All button.

I can get the individual branches to close or open.  But I can't get them all to open or close at once.

Here is my jsfiddle:
https://jsfiddle.net/dyrh325f/65/

One thing to note is that the Expand All button is being used after an ajax call that populates the entire tree.  I have the 'Expand All' code in the "done" portion of the ajax call, so it applies to the generated html.

I want the user to be able to expand the entire tree out after he has closed one or more nodes.  I've tried several variations of what I have in my jsFiddle.  Nothing seems to work.  What am I doing wrong?

I am a jQuery newbie so - thanks for any and all help!!!

Code:
HTML:

        Expand Tree

```<code><font face="calibri" size="3pt" >
<ul id="tree1" class="mytree">
<li id="theJob" class="my-clickable mytree liParOpen">My Job</li>
<ul id="treeList" class="mytree" name="treeList">
  <li id='0' class='mytree child-click'>Batcher</li>
    <li id='1' class='mytree child-click'>Retriever</li>
    <li id='2' class='my-clickable mytree liParOpen'> TASK 2</li>
    <ul class='mytree'>
      <li id='2a' class='mytree child-click'>Prep1</li>
      <li id='2b' class='mytree child-click'>Prep2</li>
      <li id='2c' class='mytree my-clickable liParOpen'>PREP3</li>
      <ul class='mytree'>
          <li id='2b1' class='mytree child-click'>PREP3a</li>
          <li id='2b2' class='mytree child-click'>PREP3b</li>
      </ul>
    </ul>
    <li id='3' class='mytree child-click' > task 3</li>
    <li id='4' class='my-clickable mytree liParOpen'> TASK 4</li>
    <ul class='mytree'>
      <li id='4a' class='mytree child-click'>Edit1</li>
      <li id='4b' class='mytree child-click'>Edit2</li>
    </ul>
    <li id='5' class='my-clickable mytree liParOpen'> TASK 5</li>
    <ul class='mytree'>
      <li id='5a' class='mytree my-clickable liParOpen'>Del1</li>
      <ul class='mytree'>
        <li id='5a1' class='mytree child-click'>Del1a</li>
        <li id='5a2' class='mytree child-click'>Del1b</li>
      </ul>
      <li id='5b' class='mytree child-click'>Del2</li>
    </ul>
    <li id='6' class='mytree child-click'>DocEjector-3</li>
</ul>
</ul>
</font>
</code>```

Jquery:

```<code>$(document).ready(function(){

  // expand button
  $('#expandTree').on('click', function(event) {
     var all = $('.my-clickable');
     var closed = all.filter('.liParClosed');

     closed.find("ul").each(function(){
        $(this).next('ul').attr("class", "liParOpen");
        $(this).nextAll('ul').toggle();
     });
   }); // end expand button

   // collapse button
   $('#collapseTree').on('click', function(event) {
     var all = $('.my-clickable');
     var open = all.filter('.liParOpen');

     open.find("ul").each(function(){
        $(this).next("ul").attr("class", "liParClosed");
        $(this).nextAll('ul').slideToggle();
     });
   }); // end collapse button

   // this is the top most level parents
   $(".my-clickable").on('click', function(event) {

       var taskId=$(this).closest("li").attr('id');
       var tsk = '#'.concat(taskId);

       if (taskId != "theJob") {
        if ($(tsk).next('ul').length <= 0) {
           $(tsk).toggleClass("liParOpen liParClosed");
               $(tsk).next('ul').slideToggle();
        }
        else {
           //$(event.target).find('ul').toggle();
           $(tsk).toggleClass("liParOpen liParClosed");
               $(tsk).children('li').slideToggle();
               $(tsk).next('ul').slideToggle();
        }
    }  // end if taskId != "theJob"
    else {
       $(tsk).toggleClass("liParOpen liParClosed");
       $(tsk).slideToggle();
    }

    event.cancelBubble=true;
    event.stopPropagation();
});

//2nd level parents
$(".my-clickable").on('click', ".my-clickable", function(event) {
    var taskId=$(this).closest("li").attr('id');
    var tsk = '#'.concat(taskId);

    //$(event.target).find('ul').slideToggle();
    $(tsk).toggleClass("liParOpen liParClosed");

    //event.cancelBubble=true;
    event.stopPropagation();
});

// first level child w/no children (parent=job)
$(".child-click").on('click', function(event) {
    event.stopPropagation();
 });
</code>```

});

CSS:

```<code>ul.mytree  li.liParClosed {
    background-color: green;
    fontWeight: normal;
}
ul.mytree  li.liParOpen {
    background-color: cyan;
    fontWeight: normal;
}
.selected{
    border: 3px solid yellow;
    background-color: yellow;
    fontWeight: bold;
}
ul.mytree  liParOpen selected{
    border: 3px solid red;
    background-color: yellow;
    fontWeight: bold;
}
ul.mytree  li selected{
    border: 3px solid red;
    background-color: yellow;
    fontWeight: bold;
}
ul.mytree  li {
    background-color: white;
    fontWeight: normal;
}
ul.mytree  {
    background-color: white;
    fontWeight: normal;
}
</code>```

答:
You almost got it but the toggling of classes "liParClosed" and "liParOpen" wasn't being done right.

Here's a fiddle fixing that issue:

JS Fiddle

Relevant code changes:

```<code>      // expand button
  $('#expandTree').on('click', function(event) {
            var all = $('.my-clickable');
            var closed = all.filter('.liParClosed');

            closed.each(function(){
        $(this).removeClass('liParClosed').addClass('liParOpen');
                $(this).next('ul').slideToggle();
            });
    }); // end expand button

    // collapse button
  $('#collapseTree').on('click', function(event) {
            var all = $('.my-clickable');
            var open = all.filter('.liParOpen');

            open.each(function(){
          $(this).removeClass('liParOpen').addClass('liParClosed');
                $(this).next('ul').slideToggle();
            });
    }); // end collapse button
</code>```

Look at the way the classes are being added/removed. Also, you were
  looking for open.find("ul") BUT open itself had to be looped through as it is a list of open li's.

Hope this helps. :)

Body:
I have a tree list where the user can open or close the branches by clicking. The tree has many levels and sub-levels. I want to be able to collapse all branches (down to the first level) or expand all branches for the class "my-clickable" when the user clicks on the Collapse All or Expand All button.

I can get the individual branches to close or open.  But I can't get them all to open or close at once.

Here is my jsfiddle:
https://jsfiddle.net/dyrh325f/65/

One thing to note is that the Expand All button is being used after an ajax call that populates the entire tree.  I have the 'Expand All' code in the "done" portion of the ajax call, so it applies to the generated html.

I want the user to be able to expand the entire tree out after he has closed one or more nodes.  I've tried several variations of what I have in my jsFiddle.  Nothing seems to work.  What am I doing wrong?

I am a jQuery newbie so - thanks for any and all help!!!

Code:
HTML:

        Expand Tree

My Job

Batcher

Retriever

 TASK 2

Prep1

Prep2

PREP3

PREP3a

PREP3b

 task 3

 TASK 4

Edit1

Edit2

 TASK 5

Del1

Del1a

Del1b

Del2

DocEjector-3

Jquery:

$(document).ready(function(){

  // expand button
  $('#expandTree').on('click', function(event) {
     var all = $('.my-clickable');
     var closed = all.filter('.liParClosed');

     closed.find("ul").each(function(){
        $(this).next('ul').attr("class", "liParOpen");
        $(this).nextAll('ul').toggle();
     });
   }); // end expand button

   // collapse button
   $('#collapseTree').on('click', function(event) {
     var all = $('.my-clickable');
     var open = all.filter('.liParOpen');

     open.find("ul").each(function(){
        $(this).next("ul").attr("class", "liParClosed");
        $(this).nextAll('ul').slideToggle();
     });
   }); // end collapse button

   // this is the top most level parents
   $(".my-clickable").on('click', function(event) {

       var taskId=$(this).closest("li").attr('id');
       var tsk = '#'.concat(taskId);

       if (taskId != "theJob") {
        if ($(tsk).next('ul').length <= 0) {
           $(tsk).toggleClass("liParOpen liParClosed");
               $(tsk).next('ul').slideToggle();
        }
        else {
           //$(event.target).find('ul').toggle();
           $(tsk).toggleClass("liParOpen liParClosed");
               $(tsk).children('li').slideToggle();
               $(tsk).next('ul').slideToggle();
        }
    }  // end if taskId != "theJob"
    else {
       $(tsk).toggleClass("liParOpen liParClosed");
       $(tsk).slideToggle();
    }

    event.cancelBubble=true;
    event.stopPropagation();
});

//2nd level parents
$(".my-clickable").on('click', ".my-clickable", function(event) {
    var taskId=$(this).closest("li").attr('id');
    var tsk = '#'.concat(taskId);

    //$(event.target).find('ul').slideToggle();
    $(tsk).toggleClass("liParOpen liParClosed");

    //event.cancelBubble=true;
    event.stopPropagation();
});

// first level child w/no children (parent=job)
$(".child-click").on('click', function(event) {
    event.stopPropagation();
 });

});

CSS:

ul.mytree  li.liParClosed {
    background-color: green;
    fontWeight: normal;
}
ul.mytree  li.liParOpen {
    background-color: cyan;
    fontWeight: normal;
}
.selected{
    border: 3px solid yellow;
    background-color: yellow;
    fontWeight: bold;
}
ul.mytree  liParOpen selected{
    border: 3px solid red;
    background-color: yellow;
    fontWeight: bold;
}
ul.mytree  li selected{
    border: 3px solid red;
    background-color: yellow;
    fontWeight: bold;
}
ul.mytree  li {
    background-color: white;
    fontWeight: normal;
}
ul.mytree  {
    background-color: white;
    fontWeight: normal;
}

Body:
You almost got it but the toggling of classes "liParClosed" and "liParOpen" wasn't being done right.

Here's a fiddle fixing that issue:

JS Fiddle

Relevant code changes:

      // expand button
  $('#expandTree').on('click', function(event) {
            var all = $('.my-clickable');
            var closed = all.filter('.liParClosed');

            closed.each(function(){
        $(this).removeClass('liParClosed').addClass('liParOpen');
                $(this).next('ul').slideToggle();
            });
    }); // end expand button

    // collapse button
  $('#collapseTree').on('click', function(event) {
            var all = $('.my-clickable');
            var open = all.filter('.liParOpen');

            open.each(function(){
          $(this).removeClass('liParOpen').addClass('liParClosed');
                $(this).next('ul').slideToggle();
            });
    }); // end collapse button

Look at the way the classes are being added/removed. Also, you were
  looking for open.find("ul") BUT open itself had to be looped through as it is a list of open li's.

Hope this helps. :)


问:
Angular directive ng-model working for arrays but not string
The ng-model directive seems to be lacking a reference to the actual object within the JavaScript, but only for string values. Using the list of dictionary objects and looping over the elements with ng-repeat as shown below though, it works.

I can only think that it may be due to returning the array acts like returning a reference to the object, whereas returning the string variable is simply returning the literal string, neutralizing the Angular's ability to do it's two-way data binding and leaving me with a variable that still holds a value of undefined.

Why is my service module below unable to pull the updated value from the view for the variable gitRelease?

In a service module I have this functionality:

```<code>(function () { //start iife

    'use strict';

    angular.module('gms.autoDeploy')
        .factory('AutoDeployService', ["$http", "$q", "$log", "$cookies", "APP_CONFIGS", "SweetAlert", "$timeout", "GridSettingsService", "APP_USER", AutoDeployService]);

    function AutoDeployService($http, $q, $log, $cookies, APP_CONFIGS, $timeout, SweetAlert, GridSettingsService, APP_USER) {

        var tibcoCopyJobs = [];
        var gitRelease = "";

        function addNewTibcoCopyJob() {
            tibcoCopyJobs.push({
                sourceServer: "",
                sourcePath: "",
                destinationServer: "",
                destinationPath: ""
            });
        }

        function getTibcoCopyJobs() { return tibcoCopyJobs; }
        function getGitRelease(){ return gitRelease; }

        function extractFormData() {
            console.log(gitRelease);
            for (var i = 0; i < tibcoCopyJobs.length; i++) {
                console.log(tibcoCopyJobs[i]);
            }
        }

        return {
            addNewTibcoCopyJob:             addNewTibcoCopyJob,
            getTibcoCopyJobs:               getTibcoCopyJobs,
            getGitRelease:                  getGitRelease,
            extractFormData:                extractFormData
        };
    } //end AutoDeployService
}()); //end iife
</code>```

Using it with this controller:

```<code>angular.module("gms.autoDeploy").controller('AutoDeployController', ['$scope', '$compile', 'AutoDeployService',
function ($scope, $compile, AutoDeployService) {

        var model = this;

        init();

        function init() {
            model.tibcoCopyJobs = AutoDeployService.getTibcoCopyJobs();
            model.gitRelease = AutoDeployService.getGitRelease();
        }

        function btn_addNewTibcoCopy() { AutoDeployService.addNewTibcoCopyJob(); }

        function btn_extractFormData() { AutoDeployService.extractFormData(); }

        model.btn_addNewTibcoCopy = btn_addNewTibcoCopy;
        model.btn_extractFormData = btn_extractFormData;
    }
]);
</code>```

To give functionality to this view:

```<code><div ng-controller="AutoDeployController as autoDeploy">
<div class="container-fluid">

<div class="row">
    <div class="col-md-2">
        <input type="text" class="form-control" ng-model="autoDeploy.gitRelease" placeholder="MM-DD-YYYY">
    </div>
</div>

<div class="row">
    <fieldset class="col-md-2" style="margin-bottom: 10px" ng-repeat="item in autoDeploy.tibcoCopyJobs track by $index">
        <legend>Copy</legend>

        <input type="text" class="form-control" placeholder="Source Server..." ng-model="item.sourceServer">
        <br/>
        <input type="text" class="form-control" placeholder="Source Path..." ng-model="item.sourcePath">
        <br/>
        <input type="text" class="form-control" placeholder="Destination Server..." ng-model="item.destinationServer">
        <br/>
        <input type="text" class="form-control" placeholder="Destination Path..." ng-model="item.destinationPath">
    </fieldset>
</div>

<button ng-click="autoDeploy.btn_extractFormData()">extract</button>
<button ng-click="autoDeploy.btn_addNewTibcoCopy()">TIBCO copy</button>
</div>
</div>
</code>```

答:
I think you have explained why in your question. Array is returned by reference, whereas string is just copied by value. But I will try to make it a bit more clear.

When you do

```<code>model.gitRelease = AutoDeployService.getGitRelease();
</code>```

the model object will create property getRelease like this:

```<code>{getRelease: "", ... (more properties from the ctrl)}
</code>```

so whatever you update in the view it will just update the getRelease in the controller.

One possible fix is like what Jags mentioned in the comment.

Or you can make a reference to your service in the ctrl

```<code>var model = this;
model.autoDeployService = AutoDeployService;
</code>```

In your view

```<code><input type="text" class="form-control" ng-model="autoDeploy.autoDeployService.gitRelease" placeholder="MM-DD-YYYY">
</code>```

that should work.

Body:
The ng-model directive seems to be lacking a reference to the actual object within the JavaScript, but only for string values. Using the list of dictionary objects and looping over the elements with ng-repeat as shown below though, it works.

I can only think that it may be due to returning the array acts like returning a reference to the object, whereas returning the string variable is simply returning the literal string, neutralizing the Angular's ability to do it's two-way data binding and leaving me with a variable that still holds a value of undefined.

Why is my service module below unable to pull the updated value from the view for the variable gitRelease?

In a service module I have this functionality:

(function () { //start iife

    'use strict';

    angular.module('gms.autoDeploy')
        .factory('AutoDeployService', ["$http", "$q", "$log", "$cookies", "APP_CONFIGS", "SweetAlert", "$timeout", "GridSettingsService", "APP_USER", AutoDeployService]);

    function AutoDeployService($http, $q, $log, $cookies, APP_CONFIGS, $timeout, SweetAlert, GridSettingsService, APP_USER) {

        var tibcoCopyJobs = [];
        var gitRelease = "";

        function addNewTibcoCopyJob() {
            tibcoCopyJobs.push({
                sourceServer: "",
                sourcePath: "",
                destinationServer: "",
                destinationPath: ""
            });
        }

        function getTibcoCopyJobs() { return tibcoCopyJobs; }
        function getGitRelease(){ return gitRelease; }

        function extractFormData() {
            console.log(gitRelease);
            for (var i = 0; i < tibcoCopyJobs.length; i++) {
                console.log(tibcoCopyJobs[i]);
            }
        }

        return {
            addNewTibcoCopyJob:             addNewTibcoCopyJob,
            getTibcoCopyJobs:               getTibcoCopyJobs,
            getGitRelease:                  getGitRelease,
            extractFormData:                extractFormData
        };
    } //end AutoDeployService
}()); //end iife

Using it with this controller:

angular.module("gms.autoDeploy").controller('AutoDeployController', ['$scope', '$compile', 'AutoDeployService',
function ($scope, $compile, AutoDeployService) {

        var model = this;

        init();

        function init() {
            model.tibcoCopyJobs = AutoDeployService.getTibcoCopyJobs();
            model.gitRelease = AutoDeployService.getGitRelease();
        }

        function btn_addNewTibcoCopy() { AutoDeployService.addNewTibcoCopyJob(); }

        function btn_extractFormData() { AutoDeployService.extractFormData(); }

        model.btn_addNewTibcoCopy = btn_addNewTibcoCopy;
        model.btn_extractFormData = btn_extractFormData;
    }
]);

To give functionality to this view:

        <input type="text" class="form-control" ng-model="autoDeploy.gitRelease" placeholder="MM-DD-YYYY">

    <fieldset class="col-md-2" style="margin-bottom: 10px" ng-repeat="item in autoDeploy.tibcoCopyJobs track by $index">
        <legend>Copy</legend>

        <input type="text" class="form-control" placeholder="Source Server..." ng-model="item.sourceServer">

        <input type="text" class="form-control" placeholder="Source Path..." ng-model="item.sourcePath">

        <input type="text" class="form-control" placeholder="Destination Server..." ng-model="item.destinationServer">

        <input type="text" class="form-control" placeholder="Destination Path..." ng-model="item.destinationPath">
    </fieldset>

<button ng-click="autoDeploy.btn_extractFormData()">extract</button>
<button ng-click="autoDeploy.btn_addNewTibcoCopy()">TIBCO copy</button>

Body:
I think you have explained why in your question. Array is returned by reference, whereas string is just copied by value. But I will try to make it a bit more clear.

When you do

model.gitRelease = AutoDeployService.getGitRelease();

the model object will create property getRelease like this:

{getRelease: "", ... (more properties from the ctrl)}

so whatever you update in the view it will just update the getRelease in the controller.

One possible fix is like what Jags mentioned in the comment.

Or you can make a reference to your service in the ctrl

var model = this;
model.autoDeployService = AutoDeployService;

In your view

<input type="text" class="form-control" ng-model="autoDeploy.autoDeployService.gitRelease" placeholder="MM-DD-YYYY">

that should work.


问:
How can I extract and store and key/value returned by a server response in pharo/smalltalk
In my ZnClient request I get a response from the server which is a HTML format containing key and value that I would like to extract and store for later use. How do I do it in Pharo?

Connectez-vous pour accÃ©der Ã  Tool Platform

   <form method="post" action="." id="login_form"><input type='hidden' name='csrfmiddlewaretoken' value='fLTzkLA7yhy7YKDvohM0PJstFJJCEk2JinfjOyzCe2NA495QKznLgO1wzi64P2S8' />

EmailÂ : <input class="login" id="id_email" maxlength="75" name="email" type="text" required />

PasswordÂ : <input class="login" id="id_password" name="password" type="password" required />

      <button type="submit" class="btn btn-connect pull-right">Connexion</button>
    </form>

```

答:
You can load XMLParserHTML and XPath from the Pharo Catalog. Then this should do the trick:

```<code>| xPath htmlDoc inputs input |

"match inputs with token value of the name attrite"
xPath   := '//input[@name="csrfmiddlewaretoken"]' asXPath.

"parse your html"
htmlDoc := (XMLHTMLParser on: htmlString) parseDocument.

"match all inputs with the token"
inputs  := xPath in: htmlDoc.

"assuming there is only 1 element like that"
input   := inputs first.

"get the value attribute from the element"
^ input attributeAt: 'value'.
</code>```

Body:
You can load XMLParserHTML and XPath from the Pharo Catalog. Then this should do the trick:

| xPath htmlDoc inputs input |

"match inputs with token value of the name attrite"
xPath   := '//input[@name="csrfmiddlewaretoken"]' asXPath.

"parse your html"
htmlDoc := (XMLHTMLParser on: htmlString) parseDocument.

"match all inputs with the token"
inputs  := xPath in: htmlDoc.

"assuming there is only 1 element like that"
input   := inputs first.

"get the value attribute from the element"
^ input attributeAt: 'value'.


问:
Sort newsgroup-style posts by date, with 'pinned' or 'sticky' posts at the the top. MongoDB
I'm trying to sort posts for a newsgroup-style app so pinned posts show up first, sorted by date newest first, then all other posts show up sorted by date newest first...with the added twist that a post is only sticky for a specified amount of time: while Date.now() is between two midnight-ed dates.

Each document looks like this:

```<code>{
    "_id" : ObjectId("59b6dab93294aebe7d8b480e"),
    "date" : ISODate("2017-11-02T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "First! - Sticky today",
        "author" : "Me",
        "content" : "This post IS sticky on today: 11/12 < 11/13 < 11/18"
    "isSticky" : {
        "begin" : ISODate("2017-11-12T00:00:00.000+0000"),
        "end" : ISODate("2017-11-18T00:00:00.000+0000")
    }
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480f"),
    "date" : ISODate("2017-11-01T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "Second - Sticky today",
        "author" : "Me",
        "content" : "This post IS sticky on today: 11/12 < 11/13 < 11/22"
    "isSticky" : {
        "begin" : ISODate("2017-11-12T00:00:00.000+0000"),
        "end" : ISODate("2017-11-22T00:00:00.000+0000")
    }
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480h"),
    "date" : ISODate("2017-11-10T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "Third",
        "author" : "Me",
        "content" : "Newest NON-sticky post. Never was sticky."
    "isSticky" : {
        ""),
        "")
    }
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b4811"),
    "date" : ISODate("2017-11-09T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "Fourth",
        "author" : "You",
        "content" : "No longer sticky: 11/09 < 11/13 !< 11/11"
    "isSticky" : {
        "begin" : ISODate("2017-11-09T00:00:00.000+0000"),
        "end" : ISODate("2017-11-11T00:00:00.000+0000")
    }
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b4812"),
    "date" : ISODate("2017-11-08T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "Last",
        "author" : "Me",
        "content" : "Never was a sticky post"
    "isSticky" : {
        ""),
        "")
    }
}
</code>```

...For clarity, these documents are already in the same order I would like them to appear once sorted (so my work is done!). I have tried just sorting by isSticky.begin first, then by date,

```<code>{ "isSticky.begin":-1, date: -1 }
</code>```

but that will not work to allow sticky posts to 'expire' and return to their place in the list once they are outside the sticky date range, e.g. the post Titled "Fourth" above. It is also a requirement that a post can be retroactively made sticky at any time or can be set to become sticky in the future...so the sticky date range takes precedence over its creation date and the creation date does not have to equal the beginning of the sticky date range.

I'm still a mongo beginner, so I'm sure there's just some concept in the documentation I haven't grokked yet.

答:
You can use an aggregate pipeline

This way :

```<code>> db.posts.aggregate([{$project: {document: "$$ROOT", "s": {$gte: ["$detail.isSticky.end",  new Date() ] } } }, {$sort: {"s": -1, "date": -1}} , {$replaceRoot: {newRoot: '$document'}}]).pretty()
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480e"),
    "date" : ISODate("2017-11-02T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "First! - Sticky today",
        "author" : "Me",
        "content" : "This post IS sticky on today: 11/12 < 11/13 < 11/18",
        "isSticky" : {
            "begin" : ISODate("2017-11-12T00:00:00Z"),
            "end" : ISODate("2017-11-18T00:00:00Z")
        }
    },
    "s" : true
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480f"),
    "date" : ISODate("2017-11-01T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "Second - Sticky today",
        "author" : "Me",
        "content" : "This post IS sticky on today: 11/12 < 11/13 < 11/22",
        "isSticky" : {
            "begin" : ISODate("2017-11-12T00:00:00Z"),
            "end" : ISODate("2017-11-22T00:00:00Z")
        }
    },
    "s" : true
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480a"),
    "date" : ISODate("2017-11-10T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "Third",
        "author" : "Me",
        "content" : "Newest NON-sticky post. Never was sticky.",
        "isSticky" : {

        }
    },
    "s" : false
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b4811"),
    "date" : ISODate("2017-11-09T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "Fourth",
        "author" : "You",
        "content" : "No longer sticky: 11/09 < 11/13 !< 11/11",
        "isSticky" : {
            "begin" : ISODate("2017-11-09T00:00:00Z"),
            "end" : ISODate("2017-11-11T00:00:00Z")
        }
    },
    "s" : false
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b4812"),
    "date" : ISODate("2017-11-08T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "Last",
        "author" : "Me",
        "content" : "Never was a sticky post",
        "isSticky" : {

        }
    },
    "s" : false
}
</code>```

The $project stage add a "s" field that indicates if the post is stickyand store the document in "document" field.

Then the $sort perform the sort

And $replaceRoot replace the root with the document from the $project stage

Body:
I'm trying to sort posts for a newsgroup-style app so pinned posts show up first, sorted by date newest first, then all other posts show up sorted by date newest first...with the added twist that a post is only sticky for a specified amount of time: while Date.now() is between two midnight-ed dates.

Each document looks like this:

{
    "_id" : ObjectId("59b6dab93294aebe7d8b480e"),
    "date" : ISODate("2017-11-02T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "First! - Sticky today",
        "author" : "Me",
        "content" : "This post IS sticky on today: 11/12 < 11/13 < 11/18"
    "isSticky" : {
        "begin" : ISODate("2017-11-12T00:00:00.000+0000"),
        "end" : ISODate("2017-11-18T00:00:00.000+0000")
    }
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480f"),
    "date" : ISODate("2017-11-01T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "Second - Sticky today",
        "author" : "Me",
        "content" : "This post IS sticky on today: 11/12 < 11/13 < 11/22"
    "isSticky" : {
        "begin" : ISODate("2017-11-12T00:00:00.000+0000"),
        "end" : ISODate("2017-11-22T00:00:00.000+0000")
    }
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480h"),
    "date" : ISODate("2017-11-10T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "Third",
        "author" : "Me",
        "content" : "Newest NON-sticky post. Never was sticky."
    "isSticky" : {
        ""),
        "")
    }
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b4811"),
    "date" : ISODate("2017-11-09T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "Fourth",
        "author" : "You",
        "content" : "No longer sticky: 11/09 < 11/13 !< 11/11"
    "isSticky" : {
        "begin" : ISODate("2017-11-09T00:00:00.000+0000"),
        "end" : ISODate("2017-11-11T00:00:00.000+0000")
    }
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b4812"),
    "date" : ISODate("2017-11-08T00:00:00.000+0000"),
    "type" : "published",
    "detail" : {
        "title" : "Last",
        "author" : "Me",
        "content" : "Never was a sticky post"
    "isSticky" : {
        ""),
        "")
    }
}

...For clarity, these documents are already in the same order I would like them to appear once sorted (so my work is done!). I have tried just sorting by isSticky.begin first, then by date,

{ "isSticky.begin":-1, date: -1 }

but that will not work to allow sticky posts to 'expire' and return to their place in the list once they are outside the sticky date range, e.g. the post Titled "Fourth" above. It is also a requirement that a post can be retroactively made sticky at any time or can be set to become sticky in the future...so the sticky date range takes precedence over its creation date and the creation date does not have to equal the beginning of the sticky date range.

I'm still a mongo beginner, so I'm sure there's just some concept in the documentation I haven't grokked yet.

Body:
You can use an aggregate pipeline

This way :

> db.posts.aggregate([{$project: {document: "$$ROOT", "s": {$gte: ["$detail.isSticky.end",  new Date() ] } } }, {$sort: {"s": -1, "date": -1}} , {$replaceRoot: {newRoot: '$document'}}]).pretty()
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480e"),
    "date" : ISODate("2017-11-02T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "First! - Sticky today",
        "author" : "Me",
        "content" : "This post IS sticky on today: 11/12 < 11/13 < 11/18",
        "isSticky" : {
            "begin" : ISODate("2017-11-12T00:00:00Z"),
            "end" : ISODate("2017-11-18T00:00:00Z")
        }
    },
    "s" : true
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480f"),
    "date" : ISODate("2017-11-01T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "Second - Sticky today",
        "author" : "Me",
        "content" : "This post IS sticky on today: 11/12 < 11/13 < 11/22",
        "isSticky" : {
            "begin" : ISODate("2017-11-12T00:00:00Z"),
            "end" : ISODate("2017-11-22T00:00:00Z")
        }
    },
    "s" : true
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b480a"),
    "date" : ISODate("2017-11-10T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "Third",
        "author" : "Me",
        "content" : "Newest NON-sticky post. Never was sticky.",
        "isSticky" : {

        }
    },
    "s" : false
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b4811"),
    "date" : ISODate("2017-11-09T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "Fourth",
        "author" : "You",
        "content" : "No longer sticky: 11/09 < 11/13 !< 11/11",
        "isSticky" : {
            "begin" : ISODate("2017-11-09T00:00:00Z"),
            "end" : ISODate("2017-11-11T00:00:00Z")
        }
    },
    "s" : false
}
{
    "_id" : ObjectId("59b6dab93294aebe7d8b4812"),
    "date" : ISODate("2017-11-08T00:00:00Z"),
    "type" : "published",
    "detail" : {
        "title" : "Last",
        "author" : "Me",
        "content" : "Never was a sticky post",
        "isSticky" : {

        }
    },
    "s" : false
}

The $project stage add a "s" field that indicates if the post is stickyand store the document in "document" field.

Then the $sort perform the sort

And $replaceRoot replace the root with the document from the $project stage


问:
What tool can generate a blank SRT file with candidate scene changes
I'd like to add subtitles to a video file for which no SRT file exists. Is there any tool that'll automatically scan the audio track of a Video and create a blank SRT file that contains only the time stamps?

I tried VisualSubSync, but the built-in Scan for Scene changes tool apparently only works with existing SRT files.

Basically, I'm looking for an Open Source offline equivalent of GoSubtitle (without the speech recognition feature).

答:
It is a little hard for offline powerful software like that because you need the power of machine learning that the online solutions house.

This can sound a little bold but have you encountered YouTube's automatic captioning service? It has a limited language support but it does an excellent job and for free :) References

(I'm doing a small search now and will update with all alternatives)


问:
How Can I insert System.out.println() in Eclipse with ctrl + space
When i was watching a video about java, a man has inserted System.out.println() immediately to screen. How can i do it. He only Write "S" character...

答: So if you are a mac user, type sysout and try control+space, with control key i mean the one beside fn key in a mac keypad. </p>


问:
Excel VBA Run-time error '424': Object Required when trying to copy TextBox
I'm attempting to copy the contents of a text box from one workbook to another.  I have no problem copying cell values from the first workbook to the 2nd, but I get an object required error when I attempt to copy the text box.  This macro is being run from the workbook containing the data I want copied.  Using Excel 2007 Code:

```<code>Sub UploadData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
    xlo.Worksheets(1).Cells(2, 1) = Range("d4").Value 'Copy cell content (this works fine)
    xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text 'This gives me the object required error
    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub
</code>```

Thanks for any help.

答:
The issue is with this line

```<code> xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text
</code>```

You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.

Hence replace this with

```<code> xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text
</code>```

Body:
I'm attempting to copy the contents of a text box from one workbook to another.  I have no problem copying cell values from the first workbook to the 2nd, but I get an object required error when I attempt to copy the text box.  This macro is being run from the workbook containing the data I want copied.  Using Excel 2007 Code:

Sub UploadData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
    xlo.Worksheets(1).Cells(2, 1) = Range("d4").Value 'Copy cell content (this works fine)
    xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text 'This gives me the object required error
    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

Thanks for any help.

Body:
The issue is with this line

 xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text

You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.

Hence replace this with

 xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text


问:
Cant get data from intlTelInput
Im trying to get extension from intlTelInput plugin on submit, but for some reason it returns empty. Here is an example: https://jsfiddle.net/msfk6top/

And the code:

```<code><link rel="stylesheet" href="https://intl-tel-input.com/node_modules/bootstrap/dist/css/bootstrap.min.css?7">
<link rel="stylesheet" href="https://intl-tel-input.com/node_modules/intl-tel-input/build/css/intlTelInput.css?37">

<form id="my_form">
    <input name="phone" type="tel" id="phone" class="form-control">
    <input type="submit">
</form>

<!-- use old jquery so demo works in IE -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://intl-tel-input.com/node_modules/intl-tel-input/build/js/intlTelInput.js?60"></script>

<script>
    $("#phone").intlTelInput();

    $("#my_form").submit(function () {
        alert($("#phone").intlTelInput("getExtension"));
    });
</script>
</code>```

Any idea why its not returning the chosen extension?

答:
You need to specify the utilsScript option when initializing the plugin in order for getExtension to work.

In your plunker, do:

```<code>$("#phone").intlTelInput({utilsScript:'https://intl-tel-input.com/node_modules/intl-tel-input/build/js/utils.js'});
</code>```

utilsScript should be the path to the utils.js script that is included with the intl-tel-input plugin.

Title: Cant get data from intlTelInput

Body:
Im trying to get extension from intlTelInput plugin on submit, but for some reason it returns empty. Here is an example: https://jsfiddle.net/msfk6top/

And the code:

<link rel="stylesheet" href="https://intl-tel-input.com/node_modules/bootstrap/dist/css/bootstrap.min.css?7">
<link rel="stylesheet" href="https://intl-tel-input.com/node_modules/intl-tel-input/build/css/intlTelInput.css?37">

<form id="my_form">
    <input name="phone" type="tel" id="phone" class="form-control">
    <input type="submit">
</form>

Any idea why its not returning the chosen extension?

Body:
You need to specify the utilsScript option when initializing the plugin in order for getExtension to work.

In your plunker, do:

$("#phone").intlTelInput({utilsScript:'https://intl-tel-input.com/node_modules/intl-tel-input/build/js/utils.js'});

utilsScript should be the path to the utils.js script that is included with the intl-tel-input plugin.


问:
NHibernate: Updates in one session don't get reflected in another open session
This is a WPF app. I use one session per presenter. The user navigates from one presenter to another but usually no more than 2 levels deep:

Open Presenter1 (Session1) -> Displays a list of entities

Navigate to Presenter2 (Session2) (Presenter1 and Session1 are still alive)

Presenter2 (Session2) -> Edits an entity

Navigate back to Presenter1. Session2 is closed and changes are persisted in the database

Presenter1 reloads list of entities but the change made in step 3 is not there

How can I solve this scenario?

答:
This happens because the Session includes what is commonly referred to as the first-level cache. It simply contains all entities the Session has "seen" during it's lifespan, in order to avoid re-fetching them from the database.

You can use session.Clear() to clear the session before making any queries. If you do this in your presenter after each navigation action, you should be OK.

Another approach is to define a SessionManager class that manages your Session so the two presenters share their Session. This might be the best solution, if you can find some way to define the lifespan of one Session (I wouldn't recommend keeping the same Session around for the entire program execution).


问:
Jenkins SVN Revision Mismatch
I'm seeing some odd behavior in our Jenkins setup.

We have a typical 3 environment setup:

Dev, Test, Prod,

Jenkins is configured to build all of them.

Dev is configured to poll an SVN repository every 15 minutes and do a build if there has been an update.

Test has been configured with this option: "This project builds a Subversion feature branch", builds using the last successful Dev build code, and is manually triggered.

The problem is this: Dev builds fine. Test, however, doesn't build using the correct SVN revision the first time. After checking the console output, I see where it brings down the correct revision to the workspace, it's set to do a fresh checkout each time and merges the changes in. But, when I look at the generated command line, as the project is built using Maven, the svn revision passed to the command is actually the second to last successful build instead of the last.

The svn revision is being passed using Jenkin's SVN_REVISION variable, which is somehow getting reset to the old value. I've scoured the documentation and done a lot of Googling, and I just can't determine if the problem is a bug in the Subversion module (2.6), Jenkins (1.642.4), or if it's the way the Test build is configured. I've checked the SVN and Jenkins server times and verified they're in sync, so it's not a time related issue. When Test is built a second time, it picks up the correct version.

I'm not a Jenkins expert, so maybe I'm overlooking something, but there's no obvious (to me) cause for the issue and any ideas are welcome.

Thanks.

答: Ok, issue solved. Turns out the test build wasn't using the dev code base directly. Instead, Test was building a feature branch AND doing a code rebase pre-build. For whatever reason, the rebase was being done but the build wasn't picking up the changes. So, I changed the Dev build to produce a tag in SVN after a successful build and then changed the repository location to point to the newly tagged Dev code. Viola, no more issues with changes not being included.</p>

Title: Jenkins SVN Revision Mismatch


问:
How do I make a Spinner's "disabled" state look disabled?
When I disable my Spinner it looks almost exactly like it did prior to being disabled, i.e.

Before

After

It is disabled and so functionally everything is fine but I'd like it to look disabled. This question appears to have been asked around the traps (here and here for instance) but the closest anyone's come to an answer is this, which appears incomplete and I don't understand anyway?!?

Romain said it was to be fixed in Froyo onwards but I'm using Honeycomb and as you can see from the screenshots, it doesn't appear to work. Any advice would be appreciated.

答:
I've tried the following, and it's working as expected for me:</p>

```<code>_userMembership.setEnabled(false);
_userMembership.setClickable(false);
_userMembership.setAlpha((float)0.7);
_userMembership.setBackgroundColor(Color.GRAY);
</code>```

Body:
I've tried the following, and it's working as expected for me:

_userMembership.setEnabled(false);
_userMembership.setClickable(false);
_userMembership.setAlpha((float)0.7);
_userMembership.setBackgroundColor(Color.GRAY);


问:
Automatically import data into SQL Server
I am trying to import data from a .CSV file into SQL Server automatically. For example, if I have a set of .CSV files in a folder, I want the data from those .CSV files to be imported into SQL Server automatically, every time I add a new .CSV file to that folder.

答: If you want it to be truly automatic, you will need to go beyond SQL.  Otherwise, scheduling a load from the csv to your database would require a simple SSIS package.  Then you can go and schedule a job using SQL Server Agent to import the data daily, weekly, hourly, etc.</p>


问:
Camel Route is running infinitely to move JMS message
I am trying to move the message from a queue1(Dead Letter queue) to queue2 in active MQ at periodic interval of 5 minutes using Camel router. I am using below code to achieve this :-

```<code>    public class MessageRouteBuilder extends RouteBuilder {

    private static final Logger LOG =
            LoggerFactory.getLogger(MessageRouteBuilder.class);

    /*
     * (non-Javadoc)
     *
     * @see org.apache.camel.builder.RouteBuilder#configure()
     */
    @Override
    public void configure() throws Exception {
        LOG.info("Routing of camel is started");
        CronScheduledRoutePolicy startPolicy = new CronScheduledRoutePolicy();
        startPolicy.setRouteStartTime("0 0/5 * * * ?");

        from(
            "jms:queue:DLQ.Consumer.OUTDOCS.VirtualTopic.queue1")
                .routeId("DLQMessageMoverID").routePolicy(startPolicy)
                .noAutoStartup()
                .to("jms:queue:Consumer.OUTDOCS.VirtualTopic.queue1");
        LOG.info("Routing of camel is done");

    }

}

@Startup
@Singleton
public class ScheduledMessageDLQConsumer {

    @Inject
    private MessagingUtil msgUtil;

    @Inject
    private MessageRouteBuilder builder;

    private static final Logger LOG =
            LoggerFactory.getLogger(ScheduledMessageDLQConsumer.class);
    @PostConstruct
    public void init() {
        LOG.info("camel Scheduling scheduled started");
        CamelContext camelContext = new DefaultCamelContext();
        ConnectionFactory connectionFactory = msgUtil.getAMQConnectionFactory();
        camelContext.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

        try {
            camelContext.addRoutes(builder);
            camelContext.start();
            LOG.info("Camel scheduling completed");
        } catch (Exception e) {
            // TODO Auto-generated catch block

            LOG.error("Error in registering camel route builder", e);
        }

        LOG.info(" camel Scheduling scheduled completed");
    }

}
</code>```

Problem here is that:- Camel routing gets enabled after 5 minutes. It moves the message from DLQ (DLQ.Consumer.OUTDOCS.VirtualTopic.queue1) to queue1 (Consumer.OUTDOCS.VirtualTopic.queue1). But if message is poison , it again comes back to DLQ and again routing moves the message from DLQ to normal queue and this process keeps on running infinitely.

My requirement is that routing should move the message once only from DLQ to queue after every 5 minutes ? if poison message comes, it should check after 5 minutes only.

答:
Firstly, your whole idea looks as bad design. Reprocessing and redelivery should be handled on consumer or broker, without any obscure periodical "DLQMessageMover". If you have application consuming from OUTDOCS.VirtualTopic.queue1 under control, rethink your concepts of error handling.

BTW simple combination of maximumRedeliveries=-1 and redeliveryDelay=300000 on consumer connection would have same affect as all code, you have written in this question.

Secondly, you need idempotent consumer with correlation key on header with name JMSCorrelationID. This process every correlation id only once. When using MemoryIdempotentRepository, it gets cleared on route restart, so message is processed again, which fits to your requirement.

I have created small example, to show how it works. In your case, there will be no mocking of JMSCorrelationID header and jms component instead of timer.

```<code>public class IdempotentConsumerRouteBuilder extends RouteBuilder {
private final IdempotentRepository idempotentRepository = new MemoryIdempotentRepository();
private final List<String> mockCorrelationIds = Arrays.asList("id0","id0","id0","id1","id2","id0","id4","id0","id6","id7");

public void configure() {
    CronScheduledRoutePolicy startPolicy = new CronScheduledRoutePolicy();
    startPolicy.setRouteStopTime("0 0/5 * * * ?");
    startPolicy.setRouteStartTime("0 0/5 * * * ?");

    from("timer:jms?period=100")
            .routePolicy(startPolicy)
            .process(e -> e.getIn().setHeader(
                    "JMSCorrelationID", //Mock JMSCorrelationID to work with timer as it is jms component
                    mockCorrelationIds.get(e.getProperty("CamelTimerCounter", Integer.class)%10))
            )
            .idempotentConsumer(header("JMSCorrelationID"), idempotentRepository)
            .log("correlationId is ${header.JMSCorrelationID}")
            .to(("log:done?level=OFF"))
            .end();

}}
</code>```

And output of this code:

```<code>[artzScheduler-camel-1_Worker-3] DefaultCamelContext            INFO  Route: route1 started and consuming from: timer://jms?period=100
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id0
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id1
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id2
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id4
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id6
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id7
[artzScheduler-camel-1_Worker-6] DefaultShutdownStrategy        INFO  Starting to graceful shutdown 1 routes (timeout 10000 milliseconds)
[el-1) thread #5 - ShutdownTask] DefaultShutdownStrategy        INFO  Route: route1 shutdown complete, was consuming from: timer://jms?period=100
[artzScheduler-camel-1_Worker-6] DefaultShutdownStrategy        INFO  Graceful shutdown of 1 routes completed in 0 seconds
[artzScheduler-camel-1_Worker-6] DefaultCamelContext            INFO  Route: route1 is stopped, was consuming from: timer://jms?period=100
[artzScheduler-camel-1_Worker-8] ScheduledRoutePolicy           WARN  Route is not in a started/suspended state and cannot be stopped. The current route state is Stopped
[artzScheduler-camel-1_Worker-7] DefaultCamelContext            INFO  Route: route1 started and consuming from: timer://jms?period=100
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id0
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id1
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id2
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id4
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id6
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id7
[rtzScheduler-camel-1_Worker-10] DefaultShutdownStrategy        INFO  Starting to graceful shutdown 1 routes (timeout 10000 milliseconds)
</code>```

Body:
I am trying to move the message from a queue1(Dead Letter queue) to queue2 in active MQ at periodic interval of 5 minutes using Camel router. I am using below code to achieve this :-

    public class MessageRouteBuilder extends RouteBuilder {

    private static final Logger LOG =
            LoggerFactory.getLogger(MessageRouteBuilder.class);

    /*
     * (non-Javadoc)
     *
     * @see org.apache.camel.builder.RouteBuilder#configure()
     */
    @Override
    public void configure() throws Exception {
        LOG.info("Routing of camel is started");
        CronScheduledRoutePolicy startPolicy = new CronScheduledRoutePolicy();
        startPolicy.setRouteStartTime("0 0/5 * * * ?");

        from(
            "jms:queue:DLQ.Consumer.OUTDOCS.VirtualTopic.queue1")
                .routeId("DLQMessageMoverID").routePolicy(startPolicy)
                .noAutoStartup()
                .to("jms:queue:Consumer.OUTDOCS.VirtualTopic.queue1");
        LOG.info("Routing of camel is done");

    }

}

@Startup
@Singleton
public class ScheduledMessageDLQConsumer {

    @Inject
    private MessagingUtil msgUtil;

    @Inject
    private MessageRouteBuilder builder;

    private static final Logger LOG =
            LoggerFactory.getLogger(ScheduledMessageDLQConsumer.class);
    @PostConstruct
    public void init() {
        LOG.info("camel Scheduling scheduled started");
        CamelContext camelContext = new DefaultCamelContext();
        ConnectionFactory connectionFactory = msgUtil.getAMQConnectionFactory();
        camelContext.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

        try {
            camelContext.addRoutes(builder);
            camelContext.start();
            LOG.info("Camel scheduling completed");
        } catch (Exception e) {
            // TODO Auto-generated catch block

            LOG.error("Error in registering camel route builder", e);
        }

        LOG.info(" camel Scheduling scheduled completed");
    }

}

Problem here is that:- Camel routing gets enabled after 5 minutes. It moves the message from DLQ (DLQ.Consumer.OUTDOCS.VirtualTopic.queue1) to queue1 (Consumer.OUTDOCS.VirtualTopic.queue1). But if message is poison , it again comes back to DLQ and again routing moves the message from DLQ to normal queue and this process keeps on running infinitely.

My requirement is that routing should move the message once only from DLQ to queue after every 5 minutes ? if poison message comes, it should check after 5 minutes only.

Body:
Firstly, your whole idea looks as bad design. Reprocessing and redelivery should be handled on consumer or broker, without any obscure periodical "DLQMessageMover". If you have application consuming from OUTDOCS.VirtualTopic.queue1 under control, rethink your concepts of error handling.

BTW simple combination of maximumRedeliveries=-1 and redeliveryDelay=300000 on consumer connection would have same affect as all code, you have written in this question.

Secondly, you need idempotent consumer with correlation key on header with name JMSCorrelationID. This process every correlation id only once. When using MemoryIdempotentRepository, it gets cleared on route restart, so message is processed again, which fits to your requirement.

I have created small example, to show how it works. In your case, there will be no mocking of JMSCorrelationID header and jms component instead of timer.

public class IdempotentConsumerRouteBuilder extends RouteBuilder {
private final IdempotentRepository idempotentRepository = new MemoryIdempotentRepository();
private final List<String> mockCorrelationIds = Arrays.asList("id0","id0","id0","id1","id2","id0","id4","id0","id6","id7");

public void configure() {
    CronScheduledRoutePolicy startPolicy = new CronScheduledRoutePolicy();
    startPolicy.setRouteStopTime("0 0/5 * * * ?");
    startPolicy.setRouteStartTime("0 0/5 * * * ?");

    from("timer:jms?period=100")
            .routePolicy(startPolicy)
            .process(e -> e.getIn().setHeader(
                    "JMSCorrelationID", //Mock JMSCorrelationID to work with timer as it is jms component
                    mockCorrelationIds.get(e.getProperty("CamelTimerCounter", Integer.class)%10))
            )
            .idempotentConsumer(header("JMSCorrelationID"), idempotentRepository)
            .log("correlationId is ${header.JMSCorrelationID}")
            .to(("log:done?level=OFF"))
            .end();

}}

And output of this code:

[artzScheduler-camel-1_Worker-3] DefaultCamelContext            INFO  Route: route1 started and consuming from: timer://jms?period=100
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id0
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id1
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id2
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id4
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id6
[mel-1) thread #4 - timer://jms] route1                         INFO  correlationId is id7
[artzScheduler-camel-1_Worker-6] DefaultShutdownStrategy        INFO  Starting to graceful shutdown 1 routes (timeout 10000 milliseconds)
[el-1) thread #5 - ShutdownTask] DefaultShutdownStrategy        INFO  Route: route1 shutdown complete, was consuming from: timer://jms?period=100
[artzScheduler-camel-1_Worker-6] DefaultShutdownStrategy        INFO  Graceful shutdown of 1 routes completed in 0 seconds
[artzScheduler-camel-1_Worker-6] DefaultCamelContext            INFO  Route: route1 is stopped, was consuming from: timer://jms?period=100
[artzScheduler-camel-1_Worker-8] ScheduledRoutePolicy           WARN  Route is not in a started/suspended state and cannot be stopped. The current route state is Stopped
[artzScheduler-camel-1_Worker-7] DefaultCamelContext            INFO  Route: route1 started and consuming from: timer://jms?period=100
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id0
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id1
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id2
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id4
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id6
[mel-1) thread #6 - timer://jms] route1                         INFO  correlationId is id7
[rtzScheduler-camel-1_Worker-10] DefaultShutdownStrategy        INFO  Starting to graceful shutdown 1 routes (timeout 10000 milliseconds)


问:
React Native : Changing Label based on Picker selection
I am trying to create a very simple input screen containing inputs, labels and a picker.

The app that I am trying to build contain a picker, two numeric inputs and two labels (existing side by side along with the input elements) as shown below

When the user makes a selection in the picker (can choose either "Metric" or "Imperial"), the labels (B1 & B2) beside the inputs should also change accordingly as {B1: "Kg", B2: "Cm"} or {B1: "Inches", B2: "Lbs"}

What are some design pattern/strategies to achieve this ?.

Looks like a simple problem but I have run out of ideas as to how change the label based on the selection of picker.

I have thought of creating two different Modals M1 and M2 with visibility toggling but I am not sure that the solution is elegant :(

Would appreciate any tips or guidelines as to how this problem (changing a  label based on picker selection) is solved.

答:
I strongly advise you to try creating code yourself first by following the react documentation.

These are some steps to help you get started:

Set an event handler on the picker.

In this handler you set the state to be either metric or imperial.

After that you can render based on state values.

A change in state will re-render components so the label will change automatically.


问:
Removing rows where the number of interest is below cut-off (Perl)
I have files with several columns that contain text in the following format “number/number:zero,number_of_interest”. Example: “1/1:0,13”.

I need to remove rows if the number of interest is less than 20 in any of the columns.
I prefer to use egrep and not to read in the file but not sure how to evaluate the number of interest in each column in a single statement.

I’m also removing rows that contain SVLEN=-1 or SVLEN=-2 and it seems to be working well with egrep:

```<code>$cmd2 = `egrep -v 'SVLEN=-1;|SVLEN=-2;' $my_vcf > $my_new_vcf`; print $cmd1;
</code>```

I've tried the following but it did not work:

```<code>my $cmd2 = `egrep -v 'SVLEN=-1;|SVLEN=-2;|(\,(\d+) < 20)' $my_vcf > $my_new_vcf`; print $cmd2;
</code>```

Thank you.

答:
egrep is the wrong tool for this purpose as it can't do math within its regular expression.
Because you already have a Perl script you are better off using Perl commands to achieve your goal.

Unfortunately you have to open and read the file line by line to do so, but that is exactly what egrep does. How else could it judge the lines?

```<code>#!/usr/bin/env perl

use strict;
use warnings;
use List::Util;

sub filter_lines
{
    my $in_filename  = shift;
    my $out_filename = shift;
    open( my $fhin,  '<', $in_filename )  or die "cannot open $in_filename: $!\n";
    open( my $fhout, '>', $out_filename ) or die "cannot open $out_filename: $!\n";
    while ( my $line = <$fhin> ) {

        next if ( $line =~ /SVLEN=-1;|SVLEN=-2;/ );
        if ( my @numbers_of_interest = ( $line =~ m/\d+\/\d+:0,(\d+)/g ) ) {
            next unless List::Util::min(@numbers_of_interest) < 20;
        }

        print $fhout $line;

    }
    close($fhin);
    close($fhout);
}

filter_lines( $my_vcf, $my_new_vcf );
</code>```

Because I have no exact input line the pattern for the @numbers_of_interest might be a bit inaccurate and need improvement. There's also much room for optimization in case this code turns out to be slow.

Body:
I have files with several columns that contain text in the following format “number/number:zero,number_of_interest”. Example: “1/1:0,13”.

I need to remove rows if the number of interest is less than 20 in any of the columns.
I prefer to use egrep and not to read in the file but not sure how to evaluate the number of interest in each column in a single statement.

I’m also removing rows that contain SVLEN=-1 or SVLEN=-2 and it seems to be working well with egrep:

$cmd2 = `egrep -v 'SVLEN=-1;|SVLEN=-2;' $my_vcf > $my_new_vcf`; print $cmd1;

I've tried the following but it did not work:

my $cmd2 = `egrep -v 'SVLEN=-1;|SVLEN=-2;|(\,(\d+) < 20)' $my_vcf > $my_new_vcf`; print $cmd2;

Thank you.

Body:
egrep is the wrong tool for this purpose as it can't do math within its regular expression.
Because you already have a Perl script you are better off using Perl commands to achieve your goal.

Unfortunately you have to open and read the file line by line to do so, but that is exactly what egrep does. How else could it judge the lines?

#!/usr/bin/env perl

use strict;
use warnings;
use List::Util;

sub filter_lines
{
    my $in_filename  = shift;
    my $out_filename = shift;
    open( my $fhin,  '<', $in_filename )  or die "cannot open $in_filename: $!\n";
    open( my $fhout, '>', $out_filename ) or die "cannot open $out_filename: $!\n";
    while ( my $line = <$fhin> ) {

        next if ( $line =~ /SVLEN=-1;|SVLEN=-2;/ );
        if ( my @numbers_of_interest = ( $line =~ m/\d+\/\d+:0,(\d+)/g ) ) {
            next unless List::Util::min(@numbers_of_interest) < 20;
        }

        print $fhout $line;

    }
    close($fhin);
    close($fhout);
}

filter_lines( $my_vcf, $my_new_vcf );

Because I have no exact input line the pattern for the @numbers_of_interest might be a bit inaccurate and need improvement. There's also much room for optimization in case this code turns out to be slow.