问:
Search and Print by Two Conditions using AWK
I have this file:

```<code>         - - - Results from analysis of weight - - -
 Akaike Information Criterion   307019.66 (assuming 2 parameters).
 Bayesian Information Criterion 307036.93

                 Approximate stratum variance decomposition
 Stratum     Degrees-Freedom   Variance      Component Coefficients
 id                 39892.82    490.360         0.7     0.6     1.0
 damid                  0.00    0.00000         0.0     0.0     1.0
 Residual Variance   1546.46    320.979         0.0     0.0     1.0

 Model_Term                             Gamma         Sigma   Sigma/SE   % C
 id                     NRM_V 17633  0.18969       13.480       4.22   0 P
 damid                  NRM_V 17633  0.07644       13.845       2.90   0 P
 ide(damid)             IDV_V 17633  0.00000       32.0979      1.00   0 S
 Residual               SCA_V 12459  1.0000        320.979     27.81   0 P
</code>```

And I Would Like to print the Value of Sigma on id, note there are two id on the file, so I used the condition based on NRM_V too.

I tried this code:

```<code>tac myfile | awk '(/id/ && /NRM_V/){print $5}'
</code>```

but the results printed were:

```<code>13.480
13.845
</code>```

and I need just the first one

答:
Could you please try following, I have added exit function of awk here which will help us to exit from code ASAP whenever first occurrence of condition comes, it will help us to save time too, since its no longer reading whole Input_file.

```<code>awk '(/id/ && /NRM_V/){print $5;exit}' Input_file
</code>```

OR with columns:

```<code>awk '($1=="id" && $2=="NRM_V"){print $5;exit}' Input_file
</code>```

In case you want to read file from last line towards first line and get its first value then try:

```<code>tac Input_file | awk '(/id/ && /NRM_V/){print $5;exit}'
</code>```

OR with columns comparisons:

```<code>tac Input_file | awk '($1=="id" && $2=="NRM_V"){print $5;exit}'
</code>```

Body:
I have this file:

         - - - Results from analysis of weight - - -
 Akaike Information Criterion   307019.66 (assuming 2 parameters).
 Bayesian Information Criterion 307036.93

                 Approximate stratum variance decomposition
 Stratum     Degrees-Freedom   Variance      Component Coefficients
 id                 39892.82    490.360         0.7     0.6     1.0
 damid                  0.00    0.00000         0.0     0.0     1.0
 Residual Variance   1546.46    320.979         0.0     0.0     1.0

 Model_Term                             Gamma         Sigma   Sigma/SE   % C
 id                     NRM_V 17633  0.18969       13.480       4.22   0 P
 damid                  NRM_V 17633  0.07644       13.845       2.90   0 P
 ide(damid)             IDV_V 17633  0.00000       32.0979      1.00   0 S
 Residual               SCA_V 12459  1.0000        320.979     27.81   0 P

And I Would Like to print the Value of Sigma on id, note there are two id on the file, so I used the condition based on NRM_V too.

I tried this code:

tac myfile | awk '(/id/ && /NRM_V/){print $5}'

but the results printed were:

13.480
13.845

and I need just the first one

Body:
Could you please try following, I have added exit function of awk here which will help us to exit from code ASAP whenever first occurrence of condition comes, it will help us to save time too, since its no longer reading whole Input_file.

awk '(/id/ && /NRM_V/){print $5;exit}' Input_file

OR with columns:

awk '($1=="id" && $2=="NRM_V"){print $5;exit}' Input_file

In case you want to read file from last line towards first line and get its first value then try:

tac Input_file | awk '(/id/ && /NRM_V/){print $5;exit}'

OR with columns comparisons:

tac Input_file | awk '($1=="id" && $2=="NRM_V"){print $5;exit}'


来源: stackexchange

问:
Springboot gzip compressing responses having size less than min-response-size configured
I am trying to implement Gzip response compression in my Springboot Rest API

I am using below configuration in my application.properties

```<code># Enable response compression
server.compression.enabled=true

# The comma-separated list of mime types that should be compressed
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json

# Compress the response only if the response size is at least 10KB
server.compression.min-response-size=10240
</code>```

Response compression is happening, but the strange thing is that it is also compression responses having size as low as 1KB or 500B which it should not as server.compression.min-response-size=10240

答:
Are you sure that you are looking at the uncompressed size of the file received, rather than the compressed size actually sent across (as shown in a browsers network tab)?

The web server will check the file size on disc is over the 'server.compression.min-response-size' and compress it if so - this could result in a compressed file being below the value set?

Once the CPU has done the work to compress the file, there is little point then sending the uncompressed version.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement Gzip response compression in my Springboot Rest API

I am using below configuration in my application.properties

# Enable response compression
server.compression.enabled=true

# The comma-separated list of mime types that should be compressed
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json

# Compress the response only if the response size is at least 10KB
server.compression.min-response-size=10240

Response compression is happening, but the strange thing is that it is also compression responses having size as low as 1KB or 500B which it should not as server.compression.min-response-size=10240


问:
Javascript clear content of selectbox
As part of my populating selectbox function I am clearing the contents of the populated select box and then inserting options to a empty box. Although the select box is not being cleared correctly and a lot of options are not removed. I am using the following code to clear the contents of the select box:

```<code>for(var i = 0; i < document.getElementById(selectbox).options.length; i++)
    document.getElementById(selectbox).options[i] = null;
</code>```

Why not all the options are removed from the selectbox?

答:
this example with new generation JavaScript. I do recommend to use.</p>

```<code>[...cbrCenterSelectbox.options].forEach(option => option.remove())
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript clear content of selectbox

Body:
As part of my populating selectbox function I am clearing the contents of the populated select box and then inserting options to a empty box. Although the select box is not being cleared correctly and a lot of options are not removed. I am using the following code to clear the contents of the select box:

for(var i = 0; i < document.getElementById(selectbox).options.length; i++)
    document.getElementById(selectbox).options[i] = null;

Why not all the options are removed from the selectbox?

Body:
this example with new generation JavaScript. I do recommend to use.

[...cbrCenterSelectbox.options].forEach(option => option.remove())


问:
How to concatenate list to int in Python?
When using a list, I saw that I cannot add or subtract the sample I took from the list. For example:

```<code>import random

x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=1 )
print(x + 1)
</code>```

Why I can’t add into the list I created and how can I get around that issue?

答:
The reason you can't concatenate is because the type random.sample is returning is a list of size k=1. If you want to be returning an element of your sequence and add to it, you should be using random.choice. It should read something along the lines of:

```<code>import random
x = random.choice((1,2,3,4,5,6,7,8,9,10,11,12,13))
print(x+1)
</code>```

Body:
When using a list, I saw that I cannot add or subtract the sample I took from the list. For example:

import random

x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=1 )
print(x + 1)

Why I can’t add into the list I created and how can I get around that issue?

Body:
The reason you can't concatenate is because the type random.sample is returning is a list of size k=1. If you want to be returning an element of your sequence and add to it, you should be using random.choice. It should read something along the lines of:

import random
x = random.choice((1,2,3,4,5,6,7,8,9,10,11,12,13))
print(x+1)


问:
Can I alias the dot sourcing command?
I find myself missing the . in dot sourced files and spending a little time getting my footing when switching from C# to PS. Is there a way to alias the . or use a similar command that is more blatantly noticeable?</p>

答:
In short: No, you cannot define an alias for . :

., the (dot-)sourcing operator, is an operator and as such it cannot be the target of an alias (only commands can).

Defining a function is also not an option, because it would itself have to be dot-sourced when called, in order to be able to dot-source other commands (scripts whose definitions to load into the caller's scope).

Title: Can I alias the dot sourcing command?


问:
Can't connect to localhost database from node.js server
Been having a lot of trouble trying to connect to to my localhost database. I've tried using the mysql and mysql-simple node modules but in both cases I just can't get it to connect.

Here's what I used with the 'mysql' module:

```<code>var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  port     : '8000',
  user     : 'uber',
  password : 'pass',
});

connection.connect(function(err) {
      if (err) throw err;

      console.log('Connection Successful');
});

connection.query('USE someDB', function(err) {
  if (err) throw err;

  console.log('Query Successful');
});
</code>```

And here' what I used with the 'mysql-simple' module:

```<code>var database = require('mysql-simple');
database.init('uber', 'pass', 'mysql', 'localhost', 8000);

database.querySingle('SELECT Host FROM user', function(err, results) {
    if (err) {
        console.log('error fetching some active users: ' + err);
        return;
    }
    log('Query Successful');
    for (var i = 0; i < results.length; i++)
        console.log('got active user ' + results[i]);
}
</code>```

In both cases, when I run my node.js server, it never logs that its connected. I've tried replacing localhost with '127.0.01' and creating a new user to make sure the password is correct, but to no avail. Why isn't it connecting?

Thanks

答: In my case, anything happened, so I solved by generating new GRANTs with a new user for nodejs apps</p>

Body:
Been having a lot of trouble trying to connect to to my localhost database. I've tried using the mysql and mysql-simple node modules but in both cases I just can't get it to connect.

Here's what I used with the 'mysql' module:

var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  port     : '8000',
  user     : 'uber',
  password : 'pass',
});

connection.connect(function(err) {
      if (err) throw err;

      console.log('Connection Successful');
});

connection.query('USE someDB', function(err) {
  if (err) throw err;

  console.log('Query Successful');
});

And here' what I used with the 'mysql-simple' module:

var database = require('mysql-simple');
database.init('uber', 'pass', 'mysql', 'localhost', 8000);

database.querySingle('SELECT Host FROM user', function(err, results) {
    if (err) {
        console.log('error fetching some active users: ' + err);
        return;
    }
    log('Query Successful');
    for (var i = 0; i < results.length; i++)
        console.log('got active user ' + results[i]);
}

In both cases, when I run my node.js server, it never logs that its connected. I've tried replacing localhost with '127.0.01' and creating a new user to make sure the password is correct, but to no avail. Why isn't it connecting?

Thanks


问:
Ionic 4: Setting native http post headers properly
I'm struggling to find the solution to my problem with ionic native http.

I tried the answer to this post, but still i am getting the same error

this is my code

```<code>switchToggle(){

   let url = 'https://io.adafruit.com//api/v2/myusername/feeds/my-feed-id/data/';

   const headers = new Headers();
   headers.set("Content-Type", "application/json")
   headers.set("X-AIO-Key", "PASTED_MY_KEY_HERE");

   let data = {
            "datum":{
              "value" : 1
            }
          };
   this.http.setDataSerializer('json');

   this.http.post(url,data,{headers:headers})
   .then(data => {
       console.log(data);
   }).catch(error => {
     console.log(error)
   });
}
</code>```

and this is the error I am getting

when I try other post request without headers it is working fine. But for this specific API I need to send the request together with the headers.

答:
set your header like this => </p>

```<code>  setHeaders() {
    let headers = new Headers();
    headers.append("X-AIO-Key", "PASTED_MY_KEY_HERE");
    headers.append('Content-Type', 'application/json' );

        const requestOptions = new RequestOptions({ headers: headers });
        return requestOptions;
      }

  switchToggle(): Observable<any>{
          let data = {
            "datum":{
              "value" : 1
            }
          };
         return this.http.post(url, data, this.setHeaders())
       .map(Response => Response.json())
          .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
</code>```

Body:
I'm struggling to find the solution to my problem with ionic native http.

I tried the answer to this post, but still i am getting the same error

this is my code

switchToggle(){

   let url = 'https://io.adafruit.com//api/v2/myusername/feeds/my-feed-id/data/';

   const headers = new Headers();
   headers.set("Content-Type", "application/json")
   headers.set("X-AIO-Key", "PASTED_MY_KEY_HERE");

   let data = {
            "datum":{
              "value" : 1
            }
          };
   this.http.setDataSerializer('json');

   this.http.post(url,data,{headers:headers})
   .then(data => {
       console.log(data);
   }).catch(error => {
     console.log(error)
   });
}

and this is the error I am getting

when I try other post request without headers it is working fine. But for this specific API I need to send the request together with the headers.

Body:
set your header like this =>

  setHeaders() {
    let headers = new Headers();
    headers.append("X-AIO-Key", "PASTED_MY_KEY_HERE");
    headers.append('Content-Type', 'application/json' );

        const requestOptions = new RequestOptions({ headers: headers });
        return requestOptions;
      }

  switchToggle(): Observable<any>{
          let data = {
            "datum":{
              "value" : 1
            }
          };
         return this.http.post(url, data, this.setHeaders())
       .map(Response => Response.json())
          .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }


问:
How do I filter for prices using Satchmo/django?
I'd like to find the minimum and maximum prices for a defined category of products.

I'd also like to be able to do the reverse, i.e, find all products given a defined price range.

The problem is that Satchmo does not have price in it's product model.   How can I solve this problem?

答:
Min/max prices for a category:

```<code>Product.objects.filter(category=some_category).aggregate(Min('price'), Max('price'))
</code>```

Products filtered by price range:

```<code>Product.objects.filter(price__price__range=(5,10))
</code>```

Body:
Min/max prices for a category:

Product.objects.filter(category=some_category).aggregate(Min('price'), Max('price'))

Products filtered by price range:

Product.objects.filter(price__price__range=(5,10))


问:
Java Generic issue: cannot cast Map<K,V> to M extends Map<K, V>
While trying to write some Generic code I faced an issue. Of course, I found some workarounds, but still, why the code below is not working?

```<code>private static <K, U, M extends Map<K, U>>
Supplier<M> mapSupplier() {
    return  HashMap::new;
}
</code>```

This returns

```<code>Error:(25, 17) java: incompatible types: bad return type in lambda expression
    no instance(s) of type variable(s) K,V exist so that java.util.HashMap<K,V> conforms to M
</code>```

Update:
This map supplier is needed for me to create custom map collector:

```<code>public static <E, K, V, M extends Map<K, V>>
Collector<E, ?, M> collectToHashMapWithRandomMerge(BiConsumer<M, E> accumulator) {
    return Collector.of(mapSupplier(),
            accumulator,
            TjiCollectionUtils.randomMapMerger());
}
</code>```

Calling Collector.of with HashMap::new also causes the same compilation error

Ideally, I don't want to create additional method params and just use the following:

```<code>  public static <E, K, V, M extends Map<K, V>>
Collector<E, ?, M> collectToHashMapWithRandomMerge(BiConsumer<M, E> accumulator) {
    return Collector.of(HashMap::new,
            accumulator,
            TjiCollectionUtils.randomMapMerger());
}
</code>```

Answer
I ended up making:

```<code>public static <E, K, V>
Collector<E, ?, Map<K, V>> collectToMapWithRandomMerge(BiConsumer<Map<K, V>, E> accumulator) {
    return Collector.of(HashMap::new,
            accumulator,
            TjiCollectionUtils.randomMapMerger());
}
</code>```

And it's called in the following way:

```<code>MyCollectionUtils.collectToMapWithRandomMerge(
    (Map<String,Integer> m, SomeClassToExtractFrom e) -> ...);
</code>```

答:
M extends Map<K, V> means a specific class that extends Map. HashMap is a class that extends Map, but M could be, say, LinkedHashMap; a HashMap isn't a LinkedHashMap.

You appear already to be given a Supplier<M>, as a parameter:

```<code>public static <E, K, V, M extends Map<K, V>>
Collector<E, ?, M> collectToHashMapWithRandomMerge(Supplier<M> mapSupplier /* HERE */, BiConsumer<M, E> accumulator) {
    return Collector.of(mapSupplier(),
            accumulator,
            TjiCollectionUtils.randomMapMerger());
}
</code>```

So, just use mapSupplier (the parameter) instead of mapSupplier() (the result of invoking the method).

Body:
While trying to write some Generic code I faced an issue. Of course, I found some workarounds, but still, why the code below is not working?

private static <K, U, M extends Map<K, U>>
Supplier<M> mapSupplier() {
    return  HashMap::new;
}

This returns

Error:(25, 17) java: incompatible types: bad return type in lambda expression
    no instance(s) of type variable(s) K,V exist so that java.util.HashMap<K,V> conforms to M

Update:
This map supplier is needed for me to create custom map collector:

public static <E, K, V, M extends Map<K, V>>
Collector<E, ?, M> collectToHashMapWithRandomMerge(BiConsumer<M, E> accumulator) {
    return Collector.of(mapSupplier(),
            accumulator,
            TjiCollectionUtils.randomMapMerger());
}

Calling Collector.of with HashMap::new also causes the same compilation error

Ideally, I don't want to create additional method params and just use the following:

  public static <E, K, V, M extends Map<K, V>>
Collector<E, ?, M> collectToHashMapWithRandomMerge(BiConsumer<M, E> accumulator) {
    return Collector.of(HashMap::new,
            accumulator,
            TjiCollectionUtils.randomMapMerger());
}

Answer
I ended up making:

public static <E, K, V>
Collector<E, ?, Map<K, V>> collectToMapWithRandomMerge(BiConsumer<Map<K, V>, E> accumulator) {
    return Collector.of(HashMap::new,
            accumulator,
            TjiCollectionUtils.randomMapMerger());
}

And it's called in the following way:

MyCollectionUtils.collectToMapWithRandomMerge(
    (Map<String,Integer> m, SomeClassToExtractFrom e) -> ...);

Body:
M extends Map<K, V> means a specific class that extends Map. HashMap is a class that extends Map, but M could be, say, LinkedHashMap; a HashMap isn't a LinkedHashMap.

You appear already to be given a Supplier<M>, as a parameter:

public static <E, K, V, M extends Map<K, V>>
Collector<E, ?, M> collectToHashMapWithRandomMerge(Supplier<M> mapSupplier /* HERE */, BiConsumer<M, E> accumulator) {
    return Collector.of(mapSupplier(),
            accumulator,
            TjiCollectionUtils.randomMapMerger());
}

So, just use mapSupplier (the parameter) instead of mapSupplier() (the result of invoking the method).


问:
Starting VirtualBox VM using Python
How can I start a virtual machine from virtualbox as headless using pyvb modules?

答:
If you use the library pyvbox the task you want to achieve is very simple: </p>

```<code>import virtualbox

vbox = virtualbox.VirtualBox()
machine = vbox.find_machine("you_virtual_machine_name")  ## for example: "ubuntu"
# If you want to run it normally:
proc = machine.launch_vm_process(session, "gui")
# If you want to run it in background:
# proc = machine.launch_vm_process(session, "headless")
proc.wait_for_completion(timeout=-1)
</code>```

Title: Starting VirtualBox VM using Python

Body:
If you use the library pyvbox the task you want to achieve is very simple:

import virtualbox

vbox = virtualbox.VirtualBox()
machine = vbox.find_machine("you_virtual_machine_name")  ## for example: "ubuntu"
# If you want to run it normally:
proc = machine.launch_vm_process(session, "gui")
# If you want to run it in background:
# proc = machine.launch_vm_process(session, "headless")
proc.wait_for_completion(timeout=-1)


问:
Check if at least two elements in an array are greater than zero - JavaScript/Typescript
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

```<code>const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false

</code>```

答:
To avoid wasted effort, you should stop the checking as soon as the condition is met. I think this meets your requirement.

function twoGreaterThanZero(arr) {
    let counter = 0
    for(let x of arr) {
        if(x > 0 && (++counter > 1)) return true
    }
    return false
}

const a = [9, 1, 0]
const b = [0, 0, 0]
const c = [5, 0, 0]

console.log(twoGreaterThanZero(a)) // print true
console.log(twoGreaterThanZero(b)) // print false
console.log(twoGreaterThanZero(c)) // print false```

Body:
Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?

(hypothetical and wrong example using some):

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false


问:
VectorLayer don't toggle visibity, always turned on
I have a VectorLayer with some points generated by the user, configured this way:

var sourcePoint = new VectorSource();
var vectorPoint = new VectorLayer({
    source: sourcePoint,
    style: new Style({
        fill: new Fill({
            color: 'rgba(0, 0, 0, 0.2)'
        }),
        image: new CircleStyle({
            radius: 7,
            fill: new Fill({
                color: '#32ff32'
            })
        })
    }),
    zIndex: 99,
    name: "vectorPoint",
    visible: false
});
```

<p>When the map page opens it loads the user data and populate in sourcePoint. The problem is that this vectorLayer must start with visibity setted to false, but even with the <code>visible: false</code> it starts turned on. </p>

<p>I also tried to toggle this layer visibility with the <code>setVisible()</code> function, which is also not working with this layer. What is strange is that other VectorLayers are working fine as suppose to, starting with visibility set to off and toggling. </p>

<p>Is there any reason why this might be happening? I can't find anyone with a similar problem.</p>

<hr>

<p><strong>Update 17/02/2020</strong></p>

<p>How I`m adding the layer to the map:</p>

<pre class="lang-js prettyprint-override"><code>this.map = new Map({
    layers: [tileBackground, vectorPoint],
    target: document.getElementById('map'),
    view: view
});
</code>```

The basic toggle layers function I'm using

randomFunction(status, layerName) { // Firing as randomFunction(true, 'vectorPoint')
    this.map.getLayers().forEach((layer) => {
        if (layer.get('name') == layerName && layer.get('name') != undefined) {
            if (status == true) {
                layer.setVisible(true);
            } else {
                layer.setVisible(false);
            }
        }
    });
}
```

I can see that the layer is founded after if (layer.get('name') == layerName...

答: Okay, I manage to find the problem. The error in this case is that I had other vector layer for points created with the GPS of the device. When the points are loaded, they populated both of the layers, so when I tried to turn the main point layers off, the other was still active, misleading me to believe that the error was with the method I was using. I'm sorry for the trouble. </p>

Body:
I have a VectorLayer with some points generated by the user, configured this way:

var sourcePoint = new VectorSource();
var vectorPoint = new VectorLayer({
    source: sourcePoint,
    style: new Style({
        fill: new Fill({
            color: 'rgba(0, 0, 0, 0.2)'
        }),
        image: new CircleStyle({
            radius: 7,
            fill: new Fill({
                color: '#32ff32'
            })
        })
    }),
    zIndex: 99,
    name: "vectorPoint",
    visible: false
});

When the map page opens it loads the user data and populate in sourcePoint. The problem is that this vectorLayer must start with visibity setted to false, but even with the visible: false it starts turned on.

I also tried to toggle this layer visibility with the setVisible() function, which is also not working with this layer. What is strange is that other VectorLayers are working fine as suppose to, starting with visibility set to off and toggling.

Is there any reason why this might be happening? I can't find anyone with a similar problem.

Update 17/02/2020

How I`m adding the layer to the map:

this.map = new Map({
    layers: [tileBackground, vectorPoint],
    target: document.getElementById('map'),
    view: view
});

The basic toggle layers function I'm using

randomFunction(status, layerName) { // Firing as randomFunction(true, 'vectorPoint')
    this.map.getLayers().forEach((layer) => {
        if (layer.get('name') == layerName && layer.get('name') != undefined) {
            if (status == true) {
                layer.setVisible(true);
            } else {
                layer.setVisible(false);
            }
        }
    });
}

I can see that the layer is founded after if (layer.get('name') == layerName...


问:
How to use a variable in iosxr_config lines in ansible playbook
I want to use variable in iosxr_config lines in ansible playbook. I have tried the following code.

```<code>- hosts: 116.119.4.1
  connection: local
  vars:
    trapdests: []
  tasks:
    - name: show version
      register: command_out
      iosxr_command:
        commands: "sh ipv4 interface brief | include Loopback0"
    - debug:
        var: command_out.stdout
    - name: trapping the Loopback ip
      register: trapdests
      set_fact:
        trapdests: "{{[item.split()[1]]}}"
      with_items: "{{command_out.stdout_lines}}"
    - debug:
        var: trapdests
#  tasks:
    - name: enable PCEP
      iosxr_config:
        lines:
           - traffic-eng
           - pcc
           - source-address ipv4 "{{item}}"
           - pce address ipv4 100.67.249.67
           - precedence 100
        with_items: "{{trapdests}}"
        parents: segment-routing
</code>```

Basically I want to use the variable at the end of this command---> source-address ipv4 "{{item}}". But I'm getting the following error:

```<code>TASK [enable PCEP] **********************************************************************************************************************************************************************************************
fatal: [116.119.4.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\nThe error appears to have been in '/home/cisco/pcep_enble_test_2.yml': line 20, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n#  tasks:\n    - name: enable PCEP\n      ^ here\n"}
        to retry, use: --limit @/home/cisco/pcep_enble_test_2.retry

PLAY RECAP ******************************************************************************************************************************************************************************************************
116.119.4.1                : ok=5    changed=0    unreachable=0    failed=1
</code>```

Can anybody help me out please. Thanks in advance.

答:
It seems you have a syntax error. With_item have to be on task level:</p>

```<code>- name: enable PCEP
  iosxr_config:
    lines:
      - traffic-eng
      - pcc
      - source-address ipv4 "{{ item }}"
      - pce address ipv4 100.67.249.67
      - precedence 100
    parents: segment-routing
  with_items: "{{ trapdests }}"
</code>```

Body:
I want to use variable in iosxr_config lines in ansible playbook. I have tried the following code.

- hosts: 116.119.4.1
  connection: local
  vars:
    trapdests: []
  tasks:
    - name: show version
      register: command_out
      iosxr_command:
        commands: "sh ipv4 interface brief | include Loopback0"
    - debug:
        var: command_out.stdout
    - name: trapping the Loopback ip
      register: trapdests
      set_fact:
        trapdests: "{{[item.split()[1]]}}"
      with_items: "{{command_out.stdout_lines}}"
    - debug:
        var: trapdests
#  tasks:
    - name: enable PCEP
      iosxr_config:
        lines:
           - traffic-eng
           - pcc
           - source-address ipv4 "{{item}}"
           - pce address ipv4 100.67.249.67
           - precedence 100
        with_items: "{{trapdests}}"
        parents: segment-routing

Basically I want to use the variable at the end of this command---> source-address ipv4 "{{item}}". But I'm getting the following error:

TASK [enable PCEP] **********************************************************************************************************************************************************************************************
fatal: [116.119.4.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\nThe error appears to have been in '/home/cisco/pcep_enble_test_2.yml': line 20, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n#  tasks:\n    - name: enable PCEP\n      ^ here\n"}
        to retry, use: --limit @/home/cisco/pcep_enble_test_2.retry

PLAY RECAP ******************************************************************************************************************************************************************************************************
116.119.4.1                : ok=5    changed=0    unreachable=0    failed=1

Can anybody help me out please. Thanks in advance.

Body:
It seems you have a syntax error. With_item have to be on task level:

- name: enable PCEP
  iosxr_config:
    lines:
      - traffic-eng
      - pcc
      - source-address ipv4 "{{ item }}"
      - pce address ipv4 100.67.249.67
      - precedence 100
    parents: segment-routing
  with_items: "{{ trapdests }}"


答:
This seems to be a common misconception of generics, which is that the callee decides what types the generic parameters are. In fact, the caller does.

Whoever calls mapSupplier gets to decide what K, U and M are. Let's say that I am calling it, and I want K to be Integer, U to be String, and M to be Hashtable<Integer, String>. This is valid because Hashtable implements Map.

```<code>Supplier<Hashtable<Integer, String>> htSupplier = mapSupplier();
Hashtable<Integer, String> ht = htSupplier.get();
</code>```

As the caller, I would expect the above to work, but htSupplier.get, with your implementation, would actually give me a HashMap<Integer, String>, which is an unrelated type to Hashtable (in terms of inheritance hierarchy).

In other words, mapSupplier has single-handedly decided that M should be HashMap<K, U> while also saying that it will work on any M that implements Map<K, U>.

Whenever you see yourself writing a "generic" method that decides what its generic parameters are, that method probably shouldn't have that generic parameter. Therefore, mapSupplier should be probably be rewritten without the M parameter:

```<code>private static <K, U>
Supplier<HashMap<K, U>> mapSupplier() {
    return  HashMap::new;
}
</code>```

EDIT:

Seeing the caller, I think you can either:

remove M from collectToHashMapWithRandomMerge as well, or:

make collectToHashMapWithRandomMerge accept a Supplier<M>, so that its caller can decide the type of map.

Title: Java Generic issue: cannot cast Map<K,V> to M extends Map<K, V>

Body:
This seems to be a common misconception of generics, which is that the callee decides what types the generic parameters are. In fact, the caller does.

Whoever calls mapSupplier gets to decide what K, U and M are. Let's say that I am calling it, and I want K to be Integer, U to be String, and M to be Hashtable<Integer, String>. This is valid because Hashtable implements Map.

Supplier<Hashtable<Integer, String>> htSupplier = mapSupplier();
Hashtable<Integer, String> ht = htSupplier.get();

As the caller, I would expect the above to work, but htSupplier.get, with your implementation, would actually give me a HashMap<Integer, String>, which is an unrelated type to Hashtable (in terms of inheritance hierarchy).

In other words, mapSupplier has single-handedly decided that M should be HashMap<K, U> while also saying that it will work on any M that implements Map<K, U>.

Whenever you see yourself writing a "generic" method that decides what its generic parameters are, that method probably shouldn't have that generic parameter. Therefore, mapSupplier should be probably be rewritten without the M parameter:

private static <K, U>
Supplier<HashMap<K, U>> mapSupplier() {
    return  HashMap::new;
}

EDIT:

Seeing the caller, I think you can either:

remove M from collectToHashMapWithRandomMerge as well, or:

make collectToHashMapWithRandomMerge accept a Supplier<M>, so that its caller can decide the type of map.


问:
C# Registry edit for icon seems not to work
I am using a file called .gfi for my program and decided a custom .ico file would look nice for this.

Using the following code I am successfully setting a reg key.

```<code> RegistryKey key = Registry.ClassesRoot.CreateSubKey(".gfi");
            key.SetValue("DefaultIcon", AppDomain.CurrentDomain.BaseDirectory + "icons\\gfi.ico");
            key.Close();
</code>```

I can see they key when I go to regedit with the fowllowing

(Default) Value not set

DefaultIcon [path to icon file]

The path is correct and everything seems like it should work however the icon is  still not associated with the files.

Any help would be appreciated, thanks.

答:
```<code>Registry.SetValue("DefaultIcon", AppDomain.CurrentDomain.BaseDirectory + @"\icons\gfi.ico");
</code>```

Your code is correct. You won't see it working right away because Explorer should be updated. No need to restart computer, just restart Explorer. You will see that it works.

Body:
I am using a file called .gfi for my program and decided a custom .ico file would look nice for this.

Using the following code I am successfully setting a reg key.

 RegistryKey key = Registry.ClassesRoot.CreateSubKey(".gfi");
            key.SetValue("DefaultIcon", AppDomain.CurrentDomain.BaseDirectory + "icons\\gfi.ico");
            key.Close();

I can see they key when I go to regedit with the fowllowing

(Default) Value not set

DefaultIcon [path to icon file]

The path is correct and everything seems like it should work however the icon is  still not associated with the files.

Any help would be appreciated, thanks.

Body:
Registry.SetValue("DefaultIcon", AppDomain.CurrentDomain.BaseDirectory + @"\icons\gfi.ico");

Your code is correct. You won't see it working right away because Explorer should be updated. No need to restart computer, just restart Explorer. You will see that it works.


问:
Manually decrypting an authorization code throws defuse crypto error
I'm using laravel 6.0 and passport 8.0. I listen for the access token to be created and and am trying to manually decrypt an authorization code like so:

```<code>try {
    $authCodeRaw = request()->input('code');
    $authCode = Crypto::decrypt($authCodeRaw, app('encrypter')->getKey());
} catch (EnvironmentIsBrokenException $e) {

} catch (WrongKeyOrModifiedCiphertextException $e) {

}
</code>```

I'm getting this error:

Symfony\Component\Debug\Exception\FatalThrowableError: Key expected
  for argument 2. String given instead. in file
  /var/www/html/vendor/defuse/php-encryption/src/Crypto.php on line 103

答:
It's expecting a Key object, but you have provided a String as suggested by @misorude.

app('encrypter')->getKey() seems to return a String, hence, you could create a Key object with that:

```<code>$key = \Defuse\Crypto\Key::loadFromAsciiSafeString(
    app('encrypter')->getKey()
);
</code>```

You could now pass the $key to the decrypt method as follows:

```<code>$authCode = Crypto::decrypt($authCodeRaw, $key));
</code>```

Hope it helped you!

Body:
I'm using laravel 6.0 and passport 8.0. I listen for the access token to be created and and am trying to manually decrypt an authorization code like so:

try {
    $authCodeRaw = request()->input('code');
    $authCode = Crypto::decrypt($authCodeRaw, app('encrypter')->getKey());
} catch (EnvironmentIsBrokenException $e) {

} catch (WrongKeyOrModifiedCiphertextException $e) {

}

I'm getting this error:

Symfony\Component\Debug\Exception\FatalThrowableError: Key expected
  for argument 2. String given instead. in file
  /var/www/html/vendor/defuse/php-encryption/src/Crypto.php on line 103

Body:
It's expecting a Key object, but you have provided a String as suggested by @misorude.

app('encrypter')->getKey() seems to return a String, hence, you could create a Key object with that:

$key = \Defuse\Crypto\Key::loadFromAsciiSafeString(
    app('encrypter')->getKey()
);

You could now pass the $key to the decrypt method as follows:

$authCode = Crypto::decrypt($authCodeRaw, $key));

Hope it helped you!


问:
FullCalendar, 4.2 - How to change event class on eventClick function
I'm trying to change the event's CSS class when the event is clicked, but I'm having zero luck. Here's my JS:

```<code>var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
        plugins: [ 'dayGrid', 'timeGrid', 'list' ],
        header: {
            left: 'prevYear,prev,next,nextYear',
            center: 'title',
            right: 'today dayGridMonth,timeGridWeek,timeGridDay,listWeek'
         },
         defaultView: 'dayGridMonth',
         eventLimit: true,
          views: {
             month: {
                eventLimit: 2
             }
         },
        eventClick:function(info){
            var id = info.event.extendedProps.timeslotid;
            $.ajax({
                url: 'index.php?option=com_cases&task=shifts.timeslotform&id='+id,
                type: 'post',
                dataType: 'html',
                async: true,
                success: function(response){
                    if (response) {
                        info.setProp( 'classNames', 'selected' ); // here's where the issue is
                        $('#sbcontent').empty();
                        $('#sbcontent').append(response);
                    }
                }
            });
        },
        events: 'index.php?option=com_cases&task=shifts.buildevents',
        eventTimeFormat: { // like '14:30:00'
            hour: 'numeric',
            minute: '2-digit',
            hour12: true
        }
    });

    calendar.render();
</code>```

I've tried the following, but all result in a JS error similar to: "Uncaught TypeError: info.setProp is not a function".

```<code>1) info.setProp( 'classNames', 'selected' );
2) info.el.setProp( 'classNames', 'selected' );
3) $(this).setProp( 'classNames', 'selected' );
4) $(this).addClass("selected");
</code>```

I've found one similar post, but the accepted answer didn't add or change the class. Instead they just settled for changing the background color of the event. I don't want to do that though. I'd rather add a CSS class to the event.

Similar Post: FullCalendar, how to change event class on eventClick function

Any help appreciated!

答: info.event is the reference to the Event. So you have to do info.event.setProp('yourProp', 'yourValue). Just remember that the classNames attribute is an array, and not a string.

Body:
I'm trying to change the event's CSS class when the event is clicked, but I'm having zero luck. Here's my JS:

var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
        plugins: [ 'dayGrid', 'timeGrid', 'list' ],
        header: {
            left: 'prevYear,prev,next,nextYear',
            center: 'title',
            right: 'today dayGridMonth,timeGridWeek,timeGridDay,listWeek'
         },
         defaultView: 'dayGridMonth',
         eventLimit: true,
          views: {
             month: {
                eventLimit: 2
             }
         },
        eventClick:function(info){
            var id = info.event.extendedProps.timeslotid;
            $.ajax({
                url: 'index.php?option=com_cases&task=shifts.timeslotform&id='+id,
                type: 'post',
                dataType: 'html',
                async: true,
                success: function(response){
                    if (response) {
                        info.setProp( 'classNames', 'selected' ); // here's where the issue is
                        $('#sbcontent').empty();
                        $('#sbcontent').append(response);
                    }
                }
            });
        },
        events: 'index.php?option=com_cases&task=shifts.buildevents',
        eventTimeFormat: { // like '14:30:00'
            hour: 'numeric',
            minute: '2-digit',
            hour12: true
        }
    });

    calendar.render();

I've tried the following, but all result in a JS error similar to: "Uncaught TypeError: info.setProp is not a function".

1) info.setProp( 'classNames', 'selected' );
2) info.el.setProp( 'classNames', 'selected' );
3) $(this).setProp( 'classNames', 'selected' );
4) $(this).addClass("selected");

I've found one similar post, but the accepted answer didn't add or change the class. Instead they just settled for changing the background color of the event. I don't want to do that though. I'd rather add a CSS class to the event.

Similar Post: FullCalendar, how to change event class on eventClick function

Any help appreciated!


问:
Elastic Search Date Range Query
I am new to elastic search and I am struggling with date range query. I have to query the records which fall between some particular dates.The JSON records pushed into elastic search database are as follows:

```<code>                "messageid": "Some message id",
                "subject": "subject",
                "emaildate": "2020-01-01 21:09:24",
                "starttime": "2020-01-02 12:30:00",
                "endtime": "2020-01-02 13:00:00",
                "meetinglocation": "some location",
                "duration": "00:30:00",
                "employeename": "Name",
                "emailid": "abc@xyz.com",
                "employeecode": "141479",
                "username": "username",
                "organizer": "Some name",
                "organizer_email": "cde@xyz.com",
</code>```

I have to query the records which has start time between "2020-01-02 12:30:00" to "2020-01-10 12:30:00". I have written a query like this :

```<code>{
   "query":
      {
        "bool":
           {

              "filter": [
                {
                    "range" : {
                        "starttime": {
                             "gte": "2020-01-02 12:30:00",
                             "lte": "2020-01-10 12:30:00"
                         }
                    }
                }
              ]
           }
      }
}
</code>```

This query is not giving results as expected. I assume that the person who has pushed the data into elastic search database at my office has not set the mapping and Elastic Search is dynamically deciding the data type of "starttime" as "text". Hence I am getting inconsistent results.
I can set the mapping like this :

```<code>PUT /meetings
{
  "mappings": {
    "dynamic": false,
    "properties": {
        .
        .
        .
        .
      "starttime": {
        "type": "date",
        "format":"yyyy-MM-dd HH:mm:ss"
      }
        .
        .
        .
    }
  }
}
</code>```

And the query will work but I am not allowed to do so (office policies). What alternatives do I have so that I can achieve my task.

Update :

I assumed the data type to be "Text" but by default Elastic Search applies both "Text" and "Keyword" so that we can implement both Full Text and Keyword based searches. If it is also set as "Keyword" . Will this benefit me in any case. I do not have access to lots of stuff in the office that's why I am unable to debug the query.I only have the search API for which I have to build the query.

GET /meetings/_mapping output :

```<code>  '
  '
  '
 "starttime" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
  }

    '
    '
    '
</code>```

答: There are ways of parsing text fields as dates at search time but the overhead is impractical... You could, however, keep the starttime as text by default but make it a multi-field and query it using starttime.as_date, for example.

Title: Elastic Search Date Range Query

Body:
I am new to elastic search and I am struggling with date range query. I have to query the records which fall between some particular dates.The JSON records pushed into elastic search database are as follows:

                "messageid": "Some message id",
                "subject": "subject",
                "emaildate": "2020-01-01 21:09:24",
                "starttime": "2020-01-02 12:30:00",
                "endtime": "2020-01-02 13:00:00",
                "meetinglocation": "some location",
                "duration": "00:30:00",
                "employeename": "Name",
                "emailid": "abc@xyz.com",
                "employeecode": "141479",
                "username": "username",
                "organizer": "Some name",
                "organizer_email": "cde@xyz.com",

I have to query the records which has start time between "2020-01-02 12:30:00" to "2020-01-10 12:30:00". I have written a query like this :

{
   "query":
      {
        "bool":
           {

              "filter": [
                {
                    "range" : {
                        "starttime": {
                             "gte": "2020-01-02 12:30:00",
                             "lte": "2020-01-10 12:30:00"
                         }
                    }
                }
              ]
           }
      }
}

This query is not giving results as expected. I assume that the person who has pushed the data into elastic search database at my office has not set the mapping and Elastic Search is dynamically deciding the data type of "starttime" as "text". Hence I am getting inconsistent results.
I can set the mapping like this :

PUT /meetings
{
  "mappings": {
    "dynamic": false,
    "properties": {
        .
        .
        .
        .
      "starttime": {
        "type": "date",
        "format":"yyyy-MM-dd HH:mm:ss"
      }
        .
        .
        .
    }
  }
}

And the query will work but I am not allowed to do so (office policies). What alternatives do I have so that I can achieve my task.

Update :

I assumed the data type to be "Text" but by default Elastic Search applies both "Text" and "Keyword" so that we can implement both Full Text and Keyword based searches. If it is also set as "Keyword" . Will this benefit me in any case. I do not have access to lots of stuff in the office that's why I am unable to debug the query.I only have the search API for which I have to build the query.

GET /meetings/_mapping output :

  '
  '
  '
 "starttime" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
  }

    '
    '
    '


问:
Primefaces Wizard custom back/next button label
i have a question regarding the back/next button label for primefaces wizard. It is possible to customize the navigation button label like the following example:

Button label at step 0 -> Show button label text "Next 1"

Button label at step 1 -> Show button label text "Next 2" and button back label "Back 1"

Button label at step 2 -> Show button label text "Next 3" and button back label "Back 2"

...

Best regards,
Mux

答:
Yes the component has two attributes the nextLabel and backLabel.

https://primefaces.github.io/primefaces/7_0/#/components/wizard?id=attributes

```<code>nextLabel   null    String  Label of next navigation button.
backLabel   null    String  Label of back navigation button.
</code>```

Then do..

```

<p>But since the #component.step is not evaluated on every step you have to do it with JQuery JS code like this following:</p>

<pre class="lang-js prettyprint-override"><code>var wizard = PF('wgtWizard');
var stepIndex = wizard.getStepIndex(wizard.currentStep);
wizard.nextNav.find('.ui-button-text').text('Next ' + stepIndex);
wizard.backNav.find('.ui-button-text').text('Back ' + (stepIndex-1));
</code>```

Just execute that JS code on the wizard 'onback' and 'onnext' JS methods.

Body:
Yes the component has two attributes the nextLabel and backLabel.

https://primefaces.github.io/primefaces/7_0/#/components/wizard?id=attributes

nextLabel   null    String  Label of next navigation button.
backLabel   null    String  Label of back navigation button.

Then do..

<p:wizard widgetVar="wgtWizard" nextLabel="Next #{component.step}" backLabel="Back #{component.step}">

But since the #component.step is not evaluated on every step you have to do it with JQuery JS code like this following:

var wizard = PF('wgtWizard');
var stepIndex = wizard.getStepIndex(wizard.currentStep);
wizard.nextNav.find('.ui-button-text').text('Next ' + stepIndex);
wizard.backNav.find('.ui-button-text').text('Back ' + (stepIndex-1));

Just execute that JS code on the wizard 'onback' and 'onnext' JS methods.


问:
How to speed up "for loop" in Python3
Below code is running so slow. I tried using numpy.argwhere instead of "if statement" to speed up the code and I got a pretty efficient result but it's still very slow. I also tried numpy.frompyfunc and numpy.vectorize but I failed. What would you suggest to speed up the code below?

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

time1 = time.time()

n = 1000000
k = 10000

velos = np.linspace(-1000, 1000, n)
line_centers = np.linspace(-1000, 1000, k)
weights = np.random.random_sample(k)
rvs = np.arange(-60, 60, 2)

m = len(rvs)
w = np.arange(10)
M = np.zeros((n, m))
for l, lc in enumerate(line_centers):
    vi = velos - lc

    for j in range(m - 1):
        w = np.argwhere((vi < rvs[j + 1]) & (vi > rvs[j])).T[0]

        M[w, j] = weights[l] * (rvs[j + 1] - vi[w]) / (rvs[j + 1] - rvs[j])
        M[w, j + 1] = weights[l] * (vi[w] - rvs[j]) / (rvs[j + 1] - rvs[j])

time2 = time.time()

print(time2 - time1)
</code>```

EDIT:
The size of the array M  was incorrect. I fixed it.

答:
Of course it is slow, you have two nested loops!  You need to rethink your algorithm using vector operations, as in, no iteration over indices, but implement in terms of index or boolean arrays, and index shifts.

You have not given any background information, so it is incredibly hard for anyone to suggest something meaningful (given the soup of indices in the example).  A few quick suggestions based on quickly gleaning over your example.

An expression like this (rvs[j + 1] - rvs[j]) is easily replaced with numpy.ediff1d.

You seem to be iterating through n in blocks of m, maybe numpy.nditer will be of use.

I have a hunch that your inner loop has an error, are you sure you really mean to iterate over range(m - 1)?  That would mean you are iterating from 0 to m-2 (inclusive), I doubt you meant that.

We can help with more concrete answers if you provide more background information.

Title: How to speed up "for loop" in Python3

Body:
Below code is running so slow. I tried using numpy.argwhere instead of "if statement" to speed up the code and I got a pretty efficient result but it's still very slow. I also tried numpy.frompyfunc and numpy.vectorize but I failed. What would you suggest to speed up the code below?

import numpy as np
import time

time1 = time.time()

n = 1000000
k = 10000

velos = np.linspace(-1000, 1000, n)
line_centers = np.linspace(-1000, 1000, k)
weights = np.random.random_sample(k)
rvs = np.arange(-60, 60, 2)

m = len(rvs)
w = np.arange(10)
M = np.zeros((n, m))
for l, lc in enumerate(line_centers):
    vi = velos - lc

    for j in range(m - 1):
        w = np.argwhere((vi < rvs[j + 1]) & (vi > rvs[j])).T[0]

        M[w, j] = weights[l] * (rvs[j + 1] - vi[w]) / (rvs[j + 1] - rvs[j])
        M[w, j + 1] = weights[l] * (vi[w] - rvs[j]) / (rvs[j + 1] - rvs[j])

time2 = time.time()

print(time2 - time1)

EDIT:
The size of the array M  was incorrect. I fixed it.


问:
Checkerframework replace annotation
I'm new to Checker Framework and I have defined 2 subtyping annotations like this:

```<code>@Target(value={TYPE_USE,TYPE_PARAMETER})
@DefaultQualifierInHierarchy
@SubtypeOf(value={})
public @interface Base{}
</code>```

and

```<code>@Target(value={TYPE_USE,TYPE_PARAMETER})
@SubtypeOf(value=Base.class)
@DefaultFor(value=LOWER_BOUND)
public @interface Sub{}
</code>```

When I use a subtyping checker with these annotations on the following code, it produces an error, because sink() expects a string marked as @Sub, but receives @Base (the default for String s0), which is the expected behaviour.

```<code>public static void main(String args[]) {
    String s0 = "a";
    sink(s0);
}

public static void sink(@Sub String s) {}
</code>```

Now I want to add a third annotation, called for example @ToSub and use it like this:

```<code>public static void main(String args[]) {
    String s0 = "a";
    @ToSub String s1 = s0;
    sink(s1);
}

public static void sink(@Sub String s) {}
</code>```

This third annotation is supposed to turn the current type of s0 (@Base) into its subtype @Sub for the new string s1, so that this code example would not throw an error.

Is this at all possible with Checker Framework?
I could not find a way to accomplish this simply by defining a new annotation, did I miss something? Can this maybe only be accomplished by writing a completely new checker?

答:
You seem to be looking for Java's existing @SuppressWarnings annotation.

More generally, if you want to suppress a warning, see the "Suppressing warnings" chapter of the Checker Framework manual.

Title: Checkerframework replace annotation

Body:
I'm new to Checker Framework and I have defined 2 subtyping annotations like this:

@Target(value={TYPE_USE,TYPE_PARAMETER})
@DefaultQualifierInHierarchy
@SubtypeOf(value={})
public @interface Base{}

and

@Target(value={TYPE_USE,TYPE_PARAMETER})
@SubtypeOf(value=Base.class)
@DefaultFor(value=LOWER_BOUND)
public @interface Sub{}

When I use a subtyping checker with these annotations on the following code, it produces an error, because sink() expects a string marked as @Sub, but receives @Base (the default for String s0), which is the expected behaviour.

public static void main(String args[]) {
    String s0 = "a";
    sink(s0);
}

public static void sink(@Sub String s) {}

Now I want to add a third annotation, called for example @ToSub and use it like this:

public static void main(String args[]) {
    String s0 = "a";
    @ToSub String s1 = s0;
    sink(s1);
}

public static void sink(@Sub String s) {}

This third annotation is supposed to turn the current type of s0 (@Base) into its subtype @Sub for the new string s1, so that this code example would not throw an error.

Is this at all possible with Checker Framework?
I could not find a way to accomplish this simply by defining a new annotation, did I miss something? Can this maybe only be accomplished by writing a completely new checker?


问:
php-ffmpeg installation on apache2
Trying to run PHP-FFMPEG and after install via composer I'm currently getting this.

PHP Fatal error:  Uncaught
  Alchemy\BinaryDriver\Exception\ExecutableNotFoundException:
  Executable not found, proposed : avprobe, ffprobe in
  /var/www/html/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/AbstractBinary.php:159\nStack
  trace:\n#0
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php(48):
  Alchemy\BinaryDriver\AbstractBinary::load(Array, NULL,
  Object(Alchemy\BinaryDriver\Configuration))\n#1
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFProbe.php(226):
  FFMpeg\Driver\FFProbeDriver::create(Object(Alchemy\BinaryDriver\Configuration),
  NULL)\n#2
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFMpeg.php(117):
  FFMpeg\FFProbe::create(Array, NULL,
  Object(Doctrine\Common\Cache\ArrayCache))\n#3
  /var/www/html/starapp/test.php(4): FFMpeg\FFMpeg::create()\n#4
  {main}\n\nNext FFMpeg\Exception\ExecutableNotFoundException: Unable
  to load FFProbe in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php:50\nStack
  trace:\n#0 /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMp in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php
  on line 50

Some people have suggested running the following:

```<code>$ffmpeg = FFMpeg\FFMpeg::create([
    'ffmpeg.binaries' => 'usr/bin/ffmpeg',
    'ffprobe.binaries' => 'usr/bin/ffprobe',
    'timeout' => 3600, 'ffmpeg.threads' => 12
]);
</code>```

However I have no ffmpeg/ffprobe files in usr/bin and can't seem to find them anywhere.

EDIT:

FFMpeg is installed. I rebooted the server and restarted apache2 and now the files are visible. Getting this now:

PHP Fatal error:  Uncaught
  Alchemy\BinaryDriver\Exception\ExecutableNotFoundException:
  Executable not found, proposed : usr/bin/ffprobe in
  /var/www/html/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/AbstractBinary.php:159\nStack
  trace:\n#0
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php(48):
  Alchemy\BinaryDriver\AbstractBinary::load(Array, NULL,
  Object(Alchemy\BinaryDriver\Configuration))\n#1
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFProbe.php(226):
  FFMpeg\Driver\FFProbeDriver::create(Object(Alchemy\BinaryDriver\Configuration),
  NULL)\n#2
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFMpeg.php(117):
  FFMpeg\FFProbe::create(Array, NULL,
  Object(Doctrine\Common\Cache\ArrayCache))\n#3
  /var/www/html/starapp/test.php(11): FFMpeg\FFMpeg::create(Array,
  NULL)\n#4 {main}\n\nNext
  FFMpeg\Exception\ExecutableNotFoundException: Unable to load FFProbe
  in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php:50\nStack
  trace:\n#0 /var/www/html/vendor/php-ffmpeg/php-ffmp in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php
  on line 50

答:
Issue was the paths

```<code>'ffmpeg.binaries' => 'usr/bin/ffmpeg',
'ffprobe.binaries' => 'usr/bin/ffprobe'
</code>```

Whereas:

```<code>'ffmpeg.binaries' => '/usr/bin/ffmpeg',
'ffprobe.binaries' => '/usr/bin/ffprobe'
</code>```

Is working.

Title: php-ffmpeg installation on apache2

Body:
Trying to run PHP-FFMPEG and after install via composer I'm currently getting this.

PHP Fatal error:  Uncaught
  Alchemy\BinaryDriver\Exception\ExecutableNotFoundException:
  Executable not found, proposed : avprobe, ffprobe in
  /var/www/html/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/AbstractBinary.php:159\nStack
  trace:\n#0
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php(48):
  Alchemy\BinaryDriver\AbstractBinary::load(Array, NULL,
  Object(Alchemy\BinaryDriver\Configuration))\n#1
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFProbe.php(226):
  FFMpeg\Driver\FFProbeDriver::create(Object(Alchemy\BinaryDriver\Configuration),
  NULL)\n#2
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFMpeg.php(117):
  FFMpeg\FFProbe::create(Array, NULL,
  Object(Doctrine\Common\Cache\ArrayCache))\n#3
  /var/www/html/starapp/test.php(4): FFMpeg\FFMpeg::create()\n#4
  {main}\n\nNext FFMpeg\Exception\ExecutableNotFoundException: Unable
  to load FFProbe in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php:50\nStack
  trace:\n#0 /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMp in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php
  on line 50

Some people have suggested running the following:

$ffmpeg = FFMpeg\FFMpeg::create([
    'ffmpeg.binaries' => 'usr/bin/ffmpeg',
    'ffprobe.binaries' => 'usr/bin/ffprobe',
    'timeout' => 3600, 'ffmpeg.threads' => 12
]);

However I have no ffmpeg/ffprobe files in usr/bin and can't seem to find them anywhere.

EDIT:

FFMpeg is installed. I rebooted the server and restarted apache2 and now the files are visible. Getting this now:

PHP Fatal error:  Uncaught
  Alchemy\BinaryDriver\Exception\ExecutableNotFoundException:
  Executable not found, proposed : usr/bin/ffprobe in
  /var/www/html/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/AbstractBinary.php:159\nStack
  trace:\n#0
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php(48):
  Alchemy\BinaryDriver\AbstractBinary::load(Array, NULL,
  Object(Alchemy\BinaryDriver\Configuration))\n#1
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFProbe.php(226):
  FFMpeg\Driver\FFProbeDriver::create(Object(Alchemy\BinaryDriver\Configuration),
  NULL)\n#2
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/FFMpeg.php(117):
  FFMpeg\FFProbe::create(Array, NULL,
  Object(Doctrine\Common\Cache\ArrayCache))\n#3
  /var/www/html/starapp/test.php(11): FFMpeg\FFMpeg::create(Array,
  NULL)\n#4 {main}\n\nNext
  FFMpeg\Exception\ExecutableNotFoundException: Unable to load FFProbe
  in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php:50\nStack
  trace:\n#0 /var/www/html/vendor/php-ffmpeg/php-ffmp in
  /var/www/html/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Driver/FFProbeDriver.php
  on line 50

Body:
Issue was the paths

'ffmpeg.binaries' => 'usr/bin/ffmpeg',
'ffprobe.binaries' => 'usr/bin/ffprobe'

Whereas:

'ffmpeg.binaries' => '/usr/bin/ffmpeg',
'ffprobe.binaries' => '/usr/bin/ffprobe'

Is working.


问:
Material-ui Grid Responsive Direction Column Width doesn't work
I have read the Material UI Grid List and Flexbox/FlexGrow property, which I understand, and it works correctly if I don't specify a direction. I am trying to set up a Grid with Vertical orientation. Looks like when we assign the align-center property, the width is not what we specify. Example: (style)

```<code>const styles = () => ({
    root: {
        flexGrow: 1,
    },

    paper: {
        margin: '10px'
    },

    textField: {
        width: '100%',
        marginTop: '10px',
        marginLeft: '10px'
    },

    gridBorder: {
        borderColor: 'transparent',
        borderWidth: 'thin',
        borderStyle: 'dotted',
        borderRadius: '12px'
    }
});
</code>```

Render Method:

```<code><div id='registration'>
    <Grid container spacing={4} direction='column' className={classes.root}>
        <Grid item xl={4} lg={4} xs={12}>
            <TextField required label="Email" id='' className={classes.textField}  onChange={this.handleChange}  />
        </Grid>
        <Grid item xl={4} lg={4} xs={12}>
            <TextField required label="Password" id='' className={classes.textField}  onChange={this.handleChange}  />
        </Grid>
    </Grid>
</div>
</code>```

It looks like this:. It seems correct, but as soon as I set align-items property, it goes beyond my understanding. So when I inject the following line:

```<code><Grid container spacing={4} direction='column' className={classes.root} alignItems='center'>
</code>```

It starts looking like this: I read various threads here and none of the thread talked about the direction. Can someone please help me understand this? Why the width reduces as soon as I set it to center? What I am missing?

Update:
I am able to fix it with a workaround. But I will really like to be able to align it to center without using this workaround. I added a fake grid before the original grid, to make it look like it is in center. The code is:

```<code><Grid container direction='row'>
    <Grid item xs={1} xl={4} lg={4}>
        <Grid container direction='column' className={[classes.root, 'same-row', 'background-test'].join(' ')}>
            <Grid item>Fake Grid</Grid>
        </Grid>
    </Grid>
    <Grid item  xs={1} xl={4} lg={4}>
        <Grid container direction='column' className={[classes.root, 'same-row'].join(' ')}>
            <Grid item>
                <TextField required label="Email" id='' className={classes.textField}  onChange={this.handleChange}  />
            </Grid>
            <Grid item>
                <TextField required label="Password" id='' className={classes.textField}  onChange={this.handleChange}  />
            </Grid>
        </Grid>
    </Grid>
</Grid>
</code>```

and the result is:. But still doesn't answer my question, that why aligning to center will reduce the width.

答:
Using breakpoints is not supported for column grids:

https://material-ui.com/components/grid/#direction-column-column-reverse

Body:
I have read the Material UI Grid List and Flexbox/FlexGrow property, which I understand, and it works correctly if I don't specify a direction. I am trying to set up a Grid with Vertical orientation. Looks like when we assign the align-center property, the width is not what we specify. Example: (style)

const styles = () => ({
    root: {
        flexGrow: 1,
    },

    paper: {
        margin: '10px'
    },

    textField: {
        width: '100%',
        marginTop: '10px',
        marginLeft: '10px'
    },

    gridBorder: {
        borderColor: 'transparent',
        borderWidth: 'thin',
        borderStyle: 'dotted',
        borderRadius: '12px'
    }
});

Render Method:

    <Grid container spacing={4} direction='column' className={classes.root}>
        <Grid item xl={4} lg={4} xs={12}>
            <TextField required label="Email" id='' className={classes.textField}  onChange={this.handleChange}  />
        </Grid>
        <Grid item xl={4} lg={4} xs={12}>
            <TextField required label="Password" id='' className={classes.textField}  onChange={this.handleChange}  />
        </Grid>
    </Grid>

It looks like this:. It seems correct, but as soon as I set align-items property, it goes beyond my understanding. So when I inject the following line:

<Grid container spacing={4} direction='column' className={classes.root} alignItems='center'>

It starts looking like this: I read various threads here and none of the thread talked about the direction. Can someone please help me understand this? Why the width reduces as soon as I set it to center? What I am missing?

Update:
I am able to fix it with a workaround. But I will really like to be able to align it to center without using this workaround. I added a fake grid before the original grid, to make it look like it is in center. The code is:

<Grid container direction='row'>
    <Grid item xs={1} xl={4} lg={4}>
        <Grid container direction='column' className={[classes.root, 'same-row', 'background-test'].join(' ')}>
            <Grid item>Fake Grid</Grid>
        </Grid>
    </Grid>
    <Grid item  xs={1} xl={4} lg={4}>
        <Grid container direction='column' className={[classes.root, 'same-row'].join(' ')}>
            <Grid item>
                <TextField required label="Email" id='' className={classes.textField}  onChange={this.handleChange}  />
            </Grid>
            <Grid item>
                <TextField required label="Password" id='' className={classes.textField}  onChange={this.handleChange}  />
            </Grid>
        </Grid>
    </Grid>
</Grid>

and the result is:. But still doesn't answer my question, that why aligning to center will reduce the width.


问:
ORACLE SQL How to use custom function iside insert cte
I am trying to use function inside insert SQL, but I am getting error   ORA-32034. Looks like that I couldn't access this function in the cte.
Maybe someone can help? </p>

```<code>    insert into table1 (

    Field1,
    Field2,
    Field3
 )

   with

function STR_country(in_str  VARCHAR2) return char is out_str char(2);
    begin
          out_str :='';
          if    SUBSTR(in_str,1,1)= 'A'  then out_str :='AT';
          elsif SUBSTR(in_str,1,1)= 'D'  then out_str :='DE';
          elsif SUBSTR(in_str,1,2)= 'CH' then out_str :='CH';
          elsif SUBSTR(in_str,1,2)= 'CZ' then out_str :='CZ';
          elsif SUBSTR(in_str,1,1)= 'H'  then out_str :='HU';
          else  out_str := ' ';
         end if;
          return out_str   ;
   end;

help_select_transactions1 as
(select distinct

    master.reference,
   f.start_date,
   f.end_date,
   f.Branch_NO,
   f.seq,
   master.SOURCEAPPLICATIONCODE,
   f.PAYRECIND,
   f.NOSTRODDAINDICATOR,
   f.PAYMENTVALUEDATE,
   f.PAYMENTCURRENCY,
   f.PAYMENTAMOUNT,
  STR_country(customer1.address3)   as customer_country,
   STR_country(customer2.address3)   as customer_country2)
</code>```

答:
If the query containing the PL/SQL declaration section is not the top
  level query, the top-level query must include the WITH_PLSQL hint.
  Without this hint, the statement will fail to compile

This says documentation. So in this case you will probably need:

```<code>insert /*+ WITH_PLSQL*/ into table1 (Field1, Field2, ...
</code>```

dbfiddle with similiar table

Body:
I am trying to use function inside insert SQL, but I am getting error   ORA-32034. Looks like that I couldn't access this function in the cte.
Maybe someone can help?

    insert into table1 (

    Field1,
    Field2,
    Field3
 )

   with

function STR_country(in_str  VARCHAR2) return char is out_str char(2);
    begin
          out_str :='';
          if    SUBSTR(in_str,1,1)= 'A'  then out_str :='AT';
          elsif SUBSTR(in_str,1,1)= 'D'  then out_str :='DE';
          elsif SUBSTR(in_str,1,2)= 'CH' then out_str :='CH';
          elsif SUBSTR(in_str,1,2)= 'CZ' then out_str :='CZ';
          elsif SUBSTR(in_str,1,1)= 'H'  then out_str :='HU';
          else  out_str := ' ';
         end if;
          return out_str   ;
   end;

help_select_transactions1 as
(select distinct

    master.reference,
   f.start_date,
   f.end_date,
   f.Branch_NO,
   f.seq,
   master.SOURCEAPPLICATIONCODE,
   f.PAYRECIND,
   f.NOSTRODDAINDICATOR,
   f.PAYMENTVALUEDATE,
   f.PAYMENTCURRENCY,
   f.PAYMENTAMOUNT,
  STR_country(customer1.address3)   as customer_country,
   STR_country(customer2.address3)   as customer_country2)

Body:
If the query containing the PL/SQL declaration section is not the top
  level query, the top-level query must include the WITH_PLSQL hint.
  Without this hint, the statement will fail to compile

This says documentation. So in this case you will probably need:

insert /*+ WITH_PLSQL*/ into table1 (Field1, Field2, ...

dbfiddle with similiar table


问:
Why does an IP header need to have source address?
What is the use of source address in IP header? Isn't network layer only concerned with forwarding packets to the destination address using the routing table?</p>

答:
Indeed the packet would be sent to the destination and routed correctly even without its original source address. You would not be able to leave the source address field empty as it will change the length of the header, at least you need to have some IP address. This field must be exactly 32 bits long for IPv4 (RFC791) and 128 bits for IPv6 (RFC8200) so no zero-length fields are allowed.

Whether the packet reaches its destination depends on the infrastructure in between. It is absolutely possible that the destination receives the packet, provided that there is no some firewall or other filter to drop the packet if it sees it as illegal, which some firewalls do.

To answer why it is needed, usually in two way communication you need to mention where the receiver should send the response.

In case you don't want to get a response then you might not care if the receiver knows the source address of the packet or not. In that case you can spoof the true source address and send the packet with any address you want, as long as you don't divert from the protocol specification.

However this would be an exception rather than the rule. Thus most protocols are designed to be used for (or at least to support) two way communication and the source address field is built into their specification.


问:
Facebook API: Get fans of / people who like a page
I'd like to get a list of users who like a certain page or a fan of it.

The FB API documentation states that you can only get the count of the fans of a certain page using the social graph, but not a list of the fans.

A discussion here Retrieve Facebook Fan Names suggests that one could use an FQL query like SELECT user_id FROM like WHERE object_id="YOUR PAGE ID" to get the number of people who liked the page, but for the same page, it gives an empty response "{}".

So I was wondering if anyone has an idea if this can be done.

答:
I created small tool called luster for downloading list of "likers" and "followers" of your Facebook page.

After download and unpack archive for your platform you can run it from terminal as

```<code>luster fans my-page-name
</code>```

Where my-page-name is string identifier of your Facebook page.

You will be asked for email and password to your Facebook account. Note that this account need to have one of available page roles. Even Analyst is enough.

After while you should receive output similar to following

```<code>TIME,KIND,ID,NAME,LINK
1581665652,Like,111111111,John Doe,https://www.facebook.com/111111111
1581663355,Like,222222222,Kal Peterson,https://www.facebook.com/222222222
1581661970,Follow,333333333,Nikol Kus,https://www.facebook.com/333333333
</code>```

This tool is based on reading table which can be found in Settings -> People and Other Pages section of your Facebook page.

Be aware that there is some limit up to 7k results from
Facebook side. I tested it on two pages with more than 20k of fans and
didn't get more then 7k results.

See https://github.com/zladovan/luster for details.

Body:
I created small tool called luster for downloading list of "likers" and "followers" of your Facebook page.

After download and unpack archive for your platform you can run it from terminal as

luster fans my-page-name

Where my-page-name is string identifier of your Facebook page.

You will be asked for email and password to your Facebook account. Note that this account need to have one of available page roles. Even Analyst is enough.

After while you should receive output similar to following

TIME,KIND,ID,NAME,LINK
1581665652,Like,111111111,John Doe,https://www.facebook.com/111111111
1581663355,Like,222222222,Kal Peterson,https://www.facebook.com/222222222
1581661970,Follow,333333333,Nikol Kus,https://www.facebook.com/333333333

This tool is based on reading table which can be found in Settings -> People and Other Pages section of your Facebook page.

Be aware that there is some limit up to 7k results from
Facebook side. I tested it on two pages with more than 20k of fans and
didn't get more then 7k results.

See https://github.com/zladovan/luster for details.


问:
Can layoutIfNeeded be called only once per loading the view - e.g. viewDidLoad?
A view's height in my view controller needs to change as the user interacts with the application. Sometimes the view needs to be larger in height and other times it needs to be shorter depending on the number of options a user has.

I have implemented a method to change the height depending on the state of the view, and I call this method in viewDidLoad to set the initial state, and I recall the method whenever the state changes.

However, the only time the view actually updates the layout is from the call in viewDidLoad. All other calls of my method do not update the view.

```<code>func updateContainerViewHeight(constant: CGFloat) {
    print("lets update")
    baseView.heightAnchor.constraint(equalToConstant: constant).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: constant).isActive = true
    self.view.setNeedsLayout()

    UIView.animate(withDuration: 0.25) {
        self.view.layoutIfNeeded()
    }
}
</code>```

FYI print("let's update") is printing in the console.

答:
As here

```<code>baseView.heightAnchor.constraint(equalToConstant: constant).isActive = true
containerView.heightAnchor.constraint(equalToConstant: constant).isActive = true
</code>```

every call adds new constraints which will cause conflicts , so create

1-

```<code>var baseCon,containCon:NSLayoutConstraint!
</code>```

2-

```<code>baseCon = baseView.heightAnchor.constraint(equalToConstant: constant)
baseCon.isActive = true
containCon = containerView.heightAnchor.constraint(equalToConstant: constant)
containCo.isActive = true
</code>```

3- Then play with constant

```<code>baseCon.constant = ////
</code>```

Body:
A view's height in my view controller needs to change as the user interacts with the application. Sometimes the view needs to be larger in height and other times it needs to be shorter depending on the number of options a user has.

I have implemented a method to change the height depending on the state of the view, and I call this method in viewDidLoad to set the initial state, and I recall the method whenever the state changes.

However, the only time the view actually updates the layout is from the call in viewDidLoad. All other calls of my method do not update the view.

func updateContainerViewHeight(constant: CGFloat) {
    print("lets update")
    baseView.heightAnchor.constraint(equalToConstant: constant).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: constant).isActive = true
    self.view.setNeedsLayout()

    UIView.animate(withDuration: 0.25) {
        self.view.layoutIfNeeded()
    }
}

FYI print("let's update") is printing in the console.

Body:
As here

baseView.heightAnchor.constraint(equalToConstant: constant).isActive = true
containerView.heightAnchor.constraint(equalToConstant: constant).isActive = true

every call adds new constraints which will cause conflicts , so create

1-

var baseCon,containCon:NSLayoutConstraint!

2-

baseCon = baseView.heightAnchor.constraint(equalToConstant: constant)
baseCon.isActive = true
containCon = containerView.heightAnchor.constraint(equalToConstant: constant)
containCo.isActive = true

3- Then play with constant

baseCon.constant = ////


问:
Showing a single value from api call TextBlock (MVVM)
I have been stuck on this for a few hours now. I am using the IGDB api for the application I'm building. So, I'm trying to get the ListBox I have to show the Game Title, cover and Developer. I've managed to get all of them to show up in the list with no issues but the main issue comes in when I just want to show a single developer within the list, the list is showing all companies involved plus the developer because the API returns an array of Involved Companies and within those Involved Companies the developer body returns a Boolean value to say which one is the developer. I can see it in my head, if developer is true then show the developer and remove the other involved companies. Here is an image of what is showing up when I run my query:

Query Image

I have outlined it in red. From that list all I would need is Bungie since they're the developers. So in my view I have a ListBox and a ListView nested within it:

BrowseGamesView

```<code><ListBox ItemsSource="{Binding Games}"
             Width="390"
             Height="500"
             Grid.Row="4">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Border Grid.Column="0"
                            Grid.Row="0"
                            Grid.RowSpan="2"
                            Margin="0 0 10 0">
                        <Image Source="{Binding cover.image_id, Converter={StaticResource stringToImage}}"
                               Stretch="Fill"
                               Height="70"
                               Width="60"/>
                    </Border>
                    <TextBlock Text="{Binding name}"
                               FontWeight="Bold"
                               Grid.Column="1"
                               Grid.Row="0"/>
                    <ListView Grid.Column="1"
                              Grid.Row="1"
                              ItemsSource="{Binding involved_companies}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding company.name}"/>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</code>```

Within my ViewModel I have a method for making the query and also holds the ObservableCollection (Games).

BrowseGamesViewModel

```<code>public ObservableCollection<Game> Games { get; set; }

public async void MakeQuery()
        {
            var games = await IGDBHelper.GetGames(Query);

            Games.Clear();
            foreach(var game in games)
            {
                Games.Add(game);
            }
        }
</code>```

In my Helper class I get the games

IGDBHelper

```<code>public static async Task<List<Game>> GetGames(string query)
        {
            List<Game> games = new List<Game>();

            string myJson = "search \"{0}\"; fields name, cover.url, cover.image_id, involved_companies.developer, involved_companies.company.name; limit 500;";

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("user-key", "key hidden");

                var response = await client.PostAsync(BASE_URL_GAMES, new StringContent(string.Format(myJson, query), Encoding.UTF8, "application/json"));

                var responseString = await response.Content.ReadAsStringAsync();

                games = JsonConvert.DeserializeObject<List<Game>>(responseString);
            }

            return games;
        }
</code>```

And all of models are concrete classes for the Json

```<code>public class Game
    {
        public int id { get; set; }
        public Cover cover { get; set; }
        public List<InvolvedCompany> involved_companies { get; set; }
        public string name { get; set; }
    }

public class InvolvedCompany
    {
        public int id { get; set; }
        public Company company { get; set; }
        public bool developer { get; set; }
    }

public class Company
    {
        public int id { get; set; }
        public string name { get; set; }
    }

public class Cover
{
    public int id { get; set; }
    public string image_id { get; set; }
    public string url { get; set; }
}
</code>```

So, to reiterate, I need to somehow just show the developers name by removing the rest of the involved companies from the list. I have tried several things from converters to trying it in the converter class and each time I get exceptions for null.

答:
First, I would suggest to name your properties in PascalCase.
Now for your problem, I suggest to filter the companies by developer property and assign a new list of involving companies to the game before adding it to the list.

```<code>foreach(var game in games)
  {
     game.involved_companies = game.involved_companies.Where(e => e.developer == true).Tolist();
     Games.Add(game);
  }
</code>```

Not tested but I believe this should work.

Body:
I have been stuck on this for a few hours now. I am using the IGDB api for the application I'm building. So, I'm trying to get the ListBox I have to show the Game Title, cover and Developer. I've managed to get all of them to show up in the list with no issues but the main issue comes in when I just want to show a single developer within the list, the list is showing all companies involved plus the developer because the API returns an array of Involved Companies and within those Involved Companies the developer body returns a Boolean value to say which one is the developer. I can see it in my head, if developer is true then show the developer and remove the other involved companies. Here is an image of what is showing up when I run my query:

Query Image

I have outlined it in red. From that list all I would need is Bungie since they're the developers. So in my view I have a ListBox and a ListView nested within it:

BrowseGamesView

<ListBox ItemsSource="{Binding Games}"
             Width="390"
             Height="500"
             Grid.Row="4">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Border Grid.Column="0"
                            Grid.Row="0"
                            Grid.RowSpan="2"
                            Margin="0 0 10 0">
                        <Image Source="{Binding cover.image_id, Converter={StaticResource stringToImage}}"
                               Stretch="Fill"
                               Height="70"
                               Width="60"/>
                    </Border>
                    <TextBlock Text="{Binding name}"
                               FontWeight="Bold"
                               Grid.Column="1"
                               Grid.Row="0"/>
                    <ListView Grid.Column="1"
                              Grid.Row="1"
                              ItemsSource="{Binding involved_companies}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding company.name}"/>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Within my ViewModel I have a method for making the query and also holds the ObservableCollection (Games).

BrowseGamesViewModel

public ObservableCollection<Game> Games { get; set; }

public async void MakeQuery()
        {
            var games = await IGDBHelper.GetGames(Query);

            Games.Clear();
            foreach(var game in games)
            {
                Games.Add(game);
            }
        }

In my Helper class I get the games

IGDBHelper

public static async Task<List<Game>> GetGames(string query)
        {
            List<Game> games = new List<Game>();

            string myJson = "search \"{0}\"; fields name, cover.url, cover.image_id, involved_companies.developer, involved_companies.company.name; limit 500;";

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("user-key", "key hidden");

                var response = await client.PostAsync(BASE_URL_GAMES, new StringContent(string.Format(myJson, query), Encoding.UTF8, "application/json"));

                var responseString = await response.Content.ReadAsStringAsync();

                games = JsonConvert.DeserializeObject<List<Game>>(responseString);
            }

            return games;
        }

And all of models are concrete classes for the Json

public class Game
    {
        public int id { get; set; }
        public Cover cover { get; set; }
        public List<InvolvedCompany> involved_companies { get; set; }
        public string name { get; set; }
    }

public class InvolvedCompany
    {
        public int id { get; set; }
        public Company company { get; set; }
        public bool developer { get; set; }
    }

public class Company
    {
        public int id { get; set; }
        public string name { get; set; }
    }

public class Cover
{
    public int id { get; set; }
    public string image_id { get; set; }
    public string url { get; set; }
}

So, to reiterate, I need to somehow just show the developers name by removing the rest of the involved companies from the list. I have tried several things from converters to trying it in the converter class and each time I get exceptions for null.

Body:
First, I would suggest to name your properties in PascalCase.
Now for your problem, I suggest to filter the companies by developer property and assign a new list of involving companies to the game before adding it to the list.

foreach(var game in games)
  {
     game.involved_companies = game.involved_companies.Where(e => e.developer == true).Tolist();
     Games.Add(game);
  }

Not tested but I believe this should work.


问:
Restructure Date in R
I have dataset like:

```<code> CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4
</code>```

Actual data set is much bigger. I want to convert all the DATE's in 01-JAN-19 format.
I tried with:

```<code>a <- as.Date(df$DATE, format = "%d-%b-%y")
b <- as.Date(df$DATE, format = "%d-%m-%y")
a[is.na(a)] <- b[!is.na(b)]
df$ <- a
</code>```

But it's taking time & giving result in 2019-01-01 format. Even I tried with:

```<code>df$DATE <- format(as.Date(df$DATE, format = c("%d-%b-%y", "%d-%m-%y")), "%d-%b-%y")
</code>```

It's giving the desired result but it's filling alternate NA values in DATE column like:

```<code> CODE    NAME    DATE      HOUR
  1       Ab    01-JAN-19    1
  1       Ab    NA           2
  1       Ab    03-JAN-19    3
  1       Ab    NA           4
  2       Xy    NA           1
  2       Xy    02-JAN-19    2
  2       Xy    NA           3
  2       Xy    04-JAN-19    4
</code>```

I think it's because of format = c("%d-%b-%y", "%d-%m-%y"). How can I convert all DATE's into 01-JAN-19 format.

答:
Hi I would try something like this

```<code>df$DATE = format(as.Date(df$DATE, format = ifelse(grepl(paste0(letters[1:26],collapse = '|'), df$DATE, ignore.case = TRUE), "%d-%b-%y", "%d-%m-%y")), format = "%d-%b-%y")
</code>```

Hope this helps

Test

```<code># ifelse
format(as.Date(df$DATE, format = ifelse(grepl(paste0(letters[1:26],collapse = '|'), df$DATE, ignore.case = TRUE), "%d-%b-%y", "%d-%m-%y")), format = "%d-%b-%Y")
[1] "01-Jan-2019" "02-Jan-2019" "03-Jan-2019" "04-Jan-2019" "01-Jan-2019"
[6] "02-Jan-2019" "03-Jan-2019" "04-Jan-2019"

# lubridate
format(lubridate::parse_date_time(df$DATE, c('dmy','dby')), '%d-%b-%Y')
[1] "01-Jan-2019" "02-Jan-2019" "03-Jan-2019" "04-Jan-2019" "01-Jan-2019"
[6] "02-Jan-2019" "03-Jan-2019" "04-Jan-2019"
</code>```

Title: Restructure Date in R

Body:
I have dataset like:

 CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4

Actual data set is much bigger. I want to convert all the DATE's in 01-JAN-19 format.
I tried with:

a <- as.Date(df$DATE, format = "%d-%b-%y")
b <- as.Date(df$DATE, format = "%d-%m-%y")
a[is.na(a)] <- b[!is.na(b)]
df$ <- a

But it's taking time & giving result in 2019-01-01 format. Even I tried with:

df$DATE <- format(as.Date(df$DATE, format = c("%d-%b-%y", "%d-%m-%y")), "%d-%b-%y")

It's giving the desired result but it's filling alternate NA values in DATE column like:

 CODE    NAME    DATE      HOUR
  1       Ab    01-JAN-19    1
  1       Ab    NA           2
  1       Ab    03-JAN-19    3
  1       Ab    NA           4
  2       Xy    NA           1
  2       Xy    02-JAN-19    2
  2       Xy    NA           3
  2       Xy    04-JAN-19    4

I think it's because of format = c("%d-%b-%y", "%d-%m-%y"). How can I convert all DATE's into 01-JAN-19 format.

Body:
Hi I would try something like this

df$DATE = format(as.Date(df$DATE, format = ifelse(grepl(paste0(letters[1:26],collapse = '|'), df$DATE, ignore.case = TRUE), "%d-%b-%y", "%d-%m-%y")), format = "%d-%b-%y")

Hope this helps

Test

# ifelse
format(as.Date(df$DATE, format = ifelse(grepl(paste0(letters[1:26],collapse = '|'), df$DATE, ignore.case = TRUE), "%d-%b-%y", "%d-%m-%y")), format = "%d-%b-%Y")
[1] "01-Jan-2019" "02-Jan-2019" "03-Jan-2019" "04-Jan-2019" "01-Jan-2019"
[6] "02-Jan-2019" "03-Jan-2019" "04-Jan-2019"

# lubridate
format(lubridate::parse_date_time(df$DATE, c('dmy','dby')), '%d-%b-%Y')
[1] "01-Jan-2019" "02-Jan-2019" "03-Jan-2019" "04-Jan-2019" "01-Jan-2019"
[6] "02-Jan-2019" "03-Jan-2019" "04-Jan-2019"


问:
non-repeating column in postgresql
my query is like that:

```<code>SELECT o.id, o.title, oc.category_id,
(SELECT name from categories c where c.id = oc.category_id)
FROM objects o
LEFT JOIN object_categories oc ON oc.object_id = o.id
WHERE type_id = 17
</code>```

it returns me table like at the image

I want to return non-repeating category name. Can anyone help me?

答:
In Postgres, you can use distinct on:

```<code>SELECT DISTINCT ON(c.id)
    o.id,
    o.title,
    oc.category_id,
    c.name,
    count(*) over(partition by o.id) cnt
FROM objects o
LEFT JOIN object_categories oc ON oc.object_id = o.id
LEFT JOIN categories c ON c.c.id = oc.category_id
WHERE type_id = 17
ORDER BY c.id, o.id
</code>```

When a category appears in than one record, this selects only the one that has the smallest object id.

I used the category id rather than the name to identify duplicates - you can use the category name instead, if that matters to you.

Note that I converted the inline subquery on categories to a regular join, since I find it more readable.

Title: non-repeating column in postgresql

Body:
my query is like that:

SELECT o.id, o.title, oc.category_id,
(SELECT name from categories c where c.id = oc.category_id)
FROM objects o
LEFT JOIN object_categories oc ON oc.object_id = o.id
WHERE type_id = 17

it returns me table like at the image

I want to return non-repeating category name. Can anyone help me?

Body:
In Postgres, you can use distinct on:

SELECT DISTINCT ON(c.id)
    o.id,
    o.title,
    oc.category_id,
    c.name,
    count(*) over(partition by o.id) cnt
FROM objects o
LEFT JOIN object_categories oc ON oc.object_id = o.id
LEFT JOIN categories c ON c.c.id = oc.category_id
WHERE type_id = 17
ORDER BY c.id, o.id

When a category appears in than one record, this selects only the one that has the smallest object id.

I used the category id rather than the name to identify duplicates - you can use the category name instead, if that matters to you.

Note that I converted the inline subquery on categories to a regular join, since I find it more readable.


问:
WebSocket.close is broken in Chrome?
According to the WebSocket Draft-76 spec, Wocket.close is supposed to do the following:

"To close the connection cleanly, a frame consisting of just a 0xFF byte followed by a 0×00 byte is sent from one peer to ask that the other peer close the connection."

But, after a few tests, I don’t think that Chrome is doing anything when closed is called. I’m curious if I’m doing something wrong or if it’s a known bug.

答: i know this topic is really old, but I noticed that Chrome is the only browser, which doesnt send 0xff00 at socket close command... instead it closes its socket conn on browser side, so if I notice, that a "chrome" user is offline, if i failt to receive data from that socket. Just my two cents :)</p>

ContentLicense: CC BY-SA 2.5

Title: WebSocket.close is broken in Chrome?


问:
Pandas: row comparisons by group based on a condition across 2 columns
I want to do row comparisons by group based on a condition across 2 columns. This condition
is: (col1(i)-col1(j))*(col2(i)-col2(j)) <= 0, where we are comparing every row i with row j in columns col1 and col2. If the condition is satisfied for all row comparisons in the group, then set true for that group, else false.

```<code>data = {'group':['A', 'A', 'A', 'B', 'B', 'B'],
                 'col1':[1, 2, 3, 2, 3, 1], 'col2':[4, 3, 2, 2, 3, 1]}
df = pd.DataFrame(data)
df
</code>```

with output

```<code>A True
B False
</code>```

答:
You can use shift for comparision with next row along  with groupby+all for checking if all items in the group is True:

```<code>cond=((df['col1']-df['col1'].shift(-1))*(df['col2']-df['col2'].shift(-1))<=0)&(df['group']==df['group'].shift(-1))
cond.groupby(df['group']).all()
</code>```

```<code>group
A     True
B    False
dtype: bool
</code>```

Body:
I want to do row comparisons by group based on a condition across 2 columns. This condition
is: (col1(i)-col1(j))*(col2(i)-col2(j)) <= 0, where we are comparing every row i with row j in columns col1 and col2. If the condition is satisfied for all row comparisons in the group, then set true for that group, else false.

data = {'group':['A', 'A', 'A', 'B', 'B', 'B'],
                 'col1':[1, 2, 3, 2, 3, 1], 'col2':[4, 3, 2, 2, 3, 1]}
df = pd.DataFrame(data)
df

with output

A True
B False

Body:
You can use shift for comparision with next row along  with groupby+all for checking if all items in the group is True:

cond=((df['col1']-df['col1'].shift(-1))*(df['col2']-df['col2'].shift(-1))<=0)&(df['group']==df['group'].shift(-1))
cond.groupby(df['group']).all()

group
A     True
B    False
dtype: bool


答:
To do that you can use the DISTINCT ON expression:
https://www.postgresql.org/docs/9.0/sql-select.html#SQL-DISTINCT</p>

Title: non-repeating column in postgresql