问:
Where to keep git submodules inside of a go project?
I want to add a submodule to my go project.

The submodule will contain some .proto files and some go files. I will use protos to generate grpc-gateway files using my Makefile, which will have the same package as the go files in the repo. The repo which contains these protos is not mine, and others are developing it. I won't commit these gateway files generated.

Is there any specific structure for such files in golang projects? Should I keep them in pkg directory?

I have three folders of build, configs, templates currently in my project.

答:
You can keep them in the pkg directory,  maybe at pkg/proto.

The package names for the generated go files will be present in the go_package attribute in the .proto file. For example,

option go_package = "external/api/messages";
```

<p>Then after compilation, the package name inside the go file would be</p>

<pre class="lang-golang prettyprint-override"><code>package messages
</code>```

This is the folder structure

$ tree
.
`-- pkg
    `-- proto
        `-- messages
            |-- messages.pb.go
            `-- messages.proto

```

<p>In order to import it, you'll have to update your <code>go.mod</code> file</p>

```replace external/api v0.0.0 => ./pkg/proto
```

<p>afterwards, you can import it using</p>

```import (
    "external/api/messages"
)
```

Body:
You can keep them in the pkg directory,  maybe at pkg/proto.

The package names for the generated go files will be present in the go_package attribute in the .proto file. For example,

option go_package = "external/api/messages";

Then after compilation, the package name inside the go file would be

package messages

This is the folder structure

$ tree
.
`-- pkg
    `-- proto
        `-- messages
            |-- messages.pb.go
            `-- messages.proto

In order to import it, you'll have to update your go.mod file

replace external/api v0.0.0 => ./pkg/proto

afterwards, you can import it using

import (
    "external/api/messages"
)


来源: stackexchange

问:
How can I get the length of postIds from querying my mongodb am using mongoose
My query returns this

```<code>[ { postIds:
     [ 'https://www.facebook.com/BGISaddis/photos/a.245087592543292/597050737346974/?type=3&__xts__%5B0%5D=68.ARBQb6G1JvudtWmy9B4q_1gU29zEFw6CL6rcyuzJzi6PIlEZsBuc0qOn-YlsWlYif39ANPo22eQZBHvbNid84enU80cZ3K7PAIVB7f7kufQEcsdsYmPXkMUsj_kDgWOrVn6LLAl1SrLjTsaidmaFp1iJNgUwdD2lcXdf6MuPSaMhmm5JhC4_N-fiKTIcgmGwmRs6QmuJqoAMaGthI86M21OTK2VpaJ1_Nnkz8ix5FI4aArPHDKaDNyC_iRJ_wSQJsIOJn66cHCykz00pgW0fJvfCN0vgAAQwtk2uQ_cX3wJU53cuYJkO88ngrZjzH-PBygXCHQmqGnz1Y1zxEjZll6Q&__tn__=-R',
'https://www.facebook.com/BGISaddis/photos/a.154146514970734/154145898304129/?type=3&__xts__%5B0%5D=68.ARDT-LUHFL9tKF7cZH9QVdS66xERPVvnZDNSZecJW5lT4dNnyeDJ_OzGe7s6q3_adeQGlicbBsWv61lKlGfP13QWdQKHfL1RgNHHSxEKphglroMNPGFLEYSx6Fjhh0tLA1xXEYqOAOOQ5fV_AKcIZzj3dRB_IsZAWdxOpxkf--pqkyqbV5vwrgwTA56pJ8ZKWnNMyC2Je-3FG_8EPJiHO2kcWa5QxNfoZgv_Nx7mDRzhkpHlebP4aZfnEaLU-kJQdYlb2S55O5aVSMAPtDw3wJka7-mWPA&__tn__=-R',]
    _id: 5e4bb430878c2365027fda2b } ]
</code>```

This is My code

```<code>async function getPostLinks() {
    const posts = await Post.find().select('postIds')
    console.log(posts.length)
}
</code>```

this code returns undefined

答: Use the .aggregate of mongoose with size aggregation.

ContentLicense: CC BY-SA 4.0

Body:
My query returns this

[ { postIds:
     [ 'https://www.facebook.com/BGISaddis/photos/a.245087592543292/597050737346974/?type=3&__xts__%5B0%5D=68.ARBQb6G1JvudtWmy9B4q_1gU29zEFw6CL6rcyuzJzi6PIlEZsBuc0qOn-YlsWlYif39ANPo22eQZBHvbNid84enU80cZ3K7PAIVB7f7kufQEcsdsYmPXkMUsj_kDgWOrVn6LLAl1SrLjTsaidmaFp1iJNgUwdD2lcXdf6MuPSaMhmm5JhC4_N-fiKTIcgmGwmRs6QmuJqoAMaGthI86M21OTK2VpaJ1_Nnkz8ix5FI4aArPHDKaDNyC_iRJ_wSQJsIOJn66cHCykz00pgW0fJvfCN0vgAAQwtk2uQ_cX3wJU53cuYJkO88ngrZjzH-PBygXCHQmqGnz1Y1zxEjZll6Q&__tn__=-R',
'https://www.facebook.com/BGISaddis/photos/a.154146514970734/154145898304129/?type=3&__xts__%5B0%5D=68.ARDT-LUHFL9tKF7cZH9QVdS66xERPVvnZDNSZecJW5lT4dNnyeDJ_OzGe7s6q3_adeQGlicbBsWv61lKlGfP13QWdQKHfL1RgNHHSxEKphglroMNPGFLEYSx6Fjhh0tLA1xXEYqOAOOQ5fV_AKcIZzj3dRB_IsZAWdxOpxkf--pqkyqbV5vwrgwTA56pJ8ZKWnNMyC2Je-3FG_8EPJiHO2kcWa5QxNfoZgv_Nx7mDRzhkpHlebP4aZfnEaLU-kJQdYlb2S55O5aVSMAPtDw3wJka7-mWPA&__tn__=-R',]
    _id: 5e4bb430878c2365027fda2b } ]

This is My code

async function getPostLinks() {
    const posts = await Post.find().select('postIds')
    console.log(posts.length)
}

this code returns undefined


问:
Flutter compute function not called if parameter is not a primitive?
I tried to send a Map to a compute, but computer is never called. The strange point is if I replace Map with int, it works:

```<code>void A()
{
    var map=Map();
    map["p1"]=90;
    D("before compute");
    var r1 = await compute(p1, 10);
    D("after compute(p1) : $r1");
    var r2 = await compute(p2, map);
    // code never reaches here!
    D("after compute(p2) : $r2");
}

static int p2(Map p)
  {
    return p["p1"]*10;
  }

static int p1(int z)
  {
    return z*10;
  }
</code>```

output is :
after compute(p1) : 100

答:
Flutter compute methods use Isolates and its only transfer (null, num, bool, double, String) types.

https://api.flutter.dev/flutter/dart-isolate/SendPort/send.html

Body:
I tried to send a Map to a compute, but computer is never called. The strange point is if I replace Map with int, it works:

void A()
{
    var map=Map();
    map["p1"]=90;
    D("before compute");
    var r1 = await compute(p1, 10);
    D("after compute(p1) : $r1");
    var r2 = await compute(p2, map);
    // code never reaches here!
    D("after compute(p2) : $r2");
}

static int p2(Map p)
  {
    return p["p1"]*10;
  }

static int p1(int z)
  {
    return z*10;
  }

output is :
after compute(p1) : 100


问:
How to extend and style existing LitElements?
We want to work with components from https://github.com/ing-bank/lion and style them to our needs. Their repo advertises with the components being extensible and minimally styled. However, I cannot seem to figure out how to actually style them. We tried using style element in the parent component, but we cant seem to style these components properly.

Could you give me an example of how to extend a component?

update after answer by @niiyeboah
After a very nice answer by @niiyeboah, I created the following class:

```<code>import {css, customElement} from 'lit-element'
import {LionButton} from '@lion/button'

@customElement('my-custom-button')
class MyCustomButton extends LionButton {
  static get styles() {
    return [
      super.styles,
      css`
        :host {
          background-color: red;
        }
      `,
    ]
  }

  constructor() {
    super()
  }
}

</code>```

However, now it just shows be the button completely unstyled, i.e. only the text. Does anyone know whats happening?

答:
They provide an example of how to extend and style their components on this page.

For tabs, the code will look something like this:

```<code>import { css } from 'lit-element';
import { LionTabs } from '@lion/tabs';

export class MyTabs extends LionTabs {
  static get styles() {
    return [
      super.styles,
      css`
        /* my stylings */
      `
    ];
  }
}

customElements.define('my-tabs', MyTabs);
</code>```

Body:
We want to work with components from https://github.com/ing-bank/lion and style them to our needs. Their repo advertises with the components being extensible and minimally styled. However, I cannot seem to figure out how to actually style them. We tried using style element in the parent component, but we cant seem to style these components properly.

Could you give me an example of how to extend a component?

update after answer by @niiyeboah
After a very nice answer by @niiyeboah, I created the following class:

import {css, customElement} from 'lit-element'
import {LionButton} from '@lion/button'

@customElement('my-custom-button')
class MyCustomButton extends LionButton {
  static get styles() {
    return [
      super.styles,
      css`
        :host {
          background-color: red;
        }
      `,
    ]
  }

  constructor() {
    super()
  }
}

However, now it just shows be the button completely unstyled, i.e. only the text. Does anyone know whats happening?

Body:
They provide an example of how to extend and style their components on this page.

For tabs, the code will look something like this:

import { css } from 'lit-element';
import { LionTabs } from '@lion/tabs';

export class MyTabs extends LionTabs {
  static get styles() {
    return [
      super.styles,
      css`
        /* my stylings */
      `
    ];
  }
}

customElements.define('my-tabs', MyTabs);


问:
Is there a risk that Apple will not accept me as an applied iPhone Developer (with paid membership)?
What does it mean that I have to "apply"? Can day say: "No, we don't like your nose. Do something else!"? Did they do that in the past?

I've been investing now two full months worth about 20.000 USD on learning for iPhone programming, and I didn't apply yet...

答:
Yes they could.  That's the risk behind developing for any tightly locked down environment.

Of course in practice they are unlikely to reject you for no reason.

And you're already taking a gigantic risk by investing $20k into iPhone development.  I can't help wondering if this is a saturated market, although there have been a few well publicised success stories, everybody and his dog are now working on a bejeweled clone, and lets face it, even people who buy iphones are going to be looking a reduction in spending on pointless trivia soon with the market the way it is

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Stephen Pape

OwnerDisplayName: Colin Pickard


问:
Nesting tibbles and performing calculations on each with a group_by
I want to find out what the dominant class of of each id_b is. To calculate it I need to find out the sum of size per class for each id_b. Whichever class is largest is the new dominant class assigned to id_b.

The script below does what I want it to do but it feels quite clunky and over complicated. I've not worked with nested data much before so I'm not sure if I've used the best methods possible Can anyone think of a neater way of achieving the same output in tidyverse or data.table?

Thanks!

```<code>library(tidyverse)

# sample data
set.seed(123)
input <- tibble(id_a = c(letters[seq(1,10)]),
                size = runif(10, min = 10, max = 50),
                class = c("x","x","y","x","y",
                          "y","x","y","x","x"),
                id_b = c("A1","A1","B1","B1","B1",
                         "C1","C1","C1","D1","E1"))
print(input)

</code>```

```<code>   id_a   size class id_b
   <chr> <dbl> <chr> <chr>
 1 a      23.6 x     A1
 2 b      43.6 x     A1
 3 c      23.9 y     B1
 4 d      23.4 x     B1
 5 e      29.1 y     B1
 6 f      45.7 y     C1
 7 g      44.6 x     C1
 8 h      25.6 y     C1
 9 i      41.1 x     D1
10 j      48.4 x     E1
</code>```

```<code># nest input to create a nested tibble for each id_b
input_nest <- input %>% group_by(id_b) %>% nest()

# calculate dominant class
input_nest_dominant <- input_nest %>% mutate(DOMINANT_CLASS = lapply(data, function(x){
  # group each nested tibble by class, and calculate total size. Then find the biggest size and extract
  # the class value
  output <- x %>% group_by(class) %>%
            summarise(total_size = sum(size)) %>%
            top_n(total_size, n = 1) %>%
            pull(class)
  return(output)
} ))

# unnest to end up with a tibble
input_nest_dominant_clean <- input_nest_dominant %>%
                             unnest(cols = c(DOMINANT_CLASS)) %>%
                             select(-data) %>%
                             ungroup()

print(input_nest_dominant_clean)
</code>```

```<code>  id_b  DOMINANT_CLASS
  <chr> <chr>
1 A1    x
2 B1    y
3 C1    y
4 D1    x
5 E1    x
</code>```

答:
You can do just 1 sort, and remove all duplicates. Something like:

```<code>input %>% arrange(desc(size)) %>% filter(!duplicated(id_b)) %>% arrange(id_b)

# A tibble: 5 x 4
  id_a   size class id_b
  <chr> <dbl> <chr> <chr>
1 b      41.5 x     A1
2 e      47.6 y     B1
3 h      45.7 y     C1
4 i      32.1 x     D1
5 j      28.3 x     E1
</code>```

If the order of id_b is not important you can omit the last arrange

Or in base R:

```<code>input = input[order(-input$size),]
input[!duplicated(input$id_b),]
</code>```

Body:
I want to find out what the dominant class of of each id_b is. To calculate it I need to find out the sum of size per class for each id_b. Whichever class is largest is the new dominant class assigned to id_b.

The script below does what I want it to do but it feels quite clunky and over complicated. I've not worked with nested data much before so I'm not sure if I've used the best methods possible Can anyone think of a neater way of achieving the same output in tidyverse or data.table?

Thanks!

library(tidyverse)

# sample data
set.seed(123)
input <- tibble(id_a = c(letters[seq(1,10)]),
                size = runif(10, min = 10, max = 50),
                class = c("x","x","y","x","y",
                          "y","x","y","x","x"),
                id_b = c("A1","A1","B1","B1","B1",
                         "C1","C1","C1","D1","E1"))
print(input)

   id_a   size class id_b
   <chr> <dbl> <chr> <chr>
 1 a      23.6 x     A1
 2 b      43.6 x     A1
 3 c      23.9 y     B1
 4 d      23.4 x     B1
 5 e      29.1 y     B1
 6 f      45.7 y     C1
 7 g      44.6 x     C1
 8 h      25.6 y     C1
 9 i      41.1 x     D1
10 j      48.4 x     E1

# nest input to create a nested tibble for each id_b
input_nest <- input %>% group_by(id_b) %>% nest()

# calculate dominant class
input_nest_dominant <- input_nest %>% mutate(DOMINANT_CLASS = lapply(data, function(x){
  # group each nested tibble by class, and calculate total size. Then find the biggest size and extract
  # the class value
  output <- x %>% group_by(class) %>%
            summarise(total_size = sum(size)) %>%
            top_n(total_size, n = 1) %>%
            pull(class)
  return(output)
} ))

# unnest to end up with a tibble
input_nest_dominant_clean <- input_nest_dominant %>%
                             unnest(cols = c(DOMINANT_CLASS)) %>%
                             select(-data) %>%
                             ungroup()

print(input_nest_dominant_clean)

  id_b  DOMINANT_CLASS
  <chr> <chr>
1 A1    x
2 B1    y
3 C1    y
4 D1    x
5 E1    x

Body:
You can do just 1 sort, and remove all duplicates. Something like:

input %>% arrange(desc(size)) %>% filter(!duplicated(id_b)) %>% arrange(id_b)

# A tibble: 5 x 4
  id_a   size class id_b
  <chr> <dbl> <chr> <chr>
1 b      41.5 x     A1
2 e      47.6 y     B1
3 h      45.7 y     C1
4 i      32.1 x     D1
5 j      28.3 x     E1

If the order of id_b is not important you can omit the last arrange

Or in base R:

input = input[order(-input$size),]
input[!duplicated(input$id_b),]


问:
MAMP Pro 5.6 not available
Is anyone else having problems getting hold of MAMP 5.6?

A colleague of mine downloaded it a few days ago but it is no longer available on their site. The latest version they have is 5.5 yet the only reply I get from their tech support is to try this link which is for 5.7 https://downloads.mamp.info/MAMP-PRO/releases/5.7/MAMP_MAMP_PRO_5.7.pkg

Which itself gives me a 404 error.

Thanks

Gary

答:
At last I have a solution…

"This seems to be a caching problem with cloudflare. I´ve just deleted the cache. If the link still isn´t working, could you please try a different browser?"

All seems to be working now ;-)

Gary

Title: MAMP Pro 5.6 not available


问:
How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
I have some code that uses JAXB API classes which have been provided as a part of the JDK in Java 6/7/8.  When I run the same code with Java 9, at runtime I get errors indicating that JAXB classes can not be found.

The JAXB classes have been provided as a part of the JDK since Java 6, so why can Java 9 no longer find these classes?

答:
You only need 1 dependency:</p>

```<code>dependencies {
    implementation ("jakarta.xml.bind:jakarta.xml.bind-api:2.3.2")
</code>```

Body:
You only need 1 dependency:

dependencies {
    implementation ("jakarta.xml.bind:jakarta.xml.bind-api:2.3.2")


问:
Manipulating array of objects into new array
I have the following array:

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]
```

<p>From the above array I want to create two new arrays, for each day for each product how much was sold. The final array should look like this.</p>

<p>The first value would be a default value call <code>DATE</code> followed by each product name.</p>

```var final = [{
  title: "DATE"
}, {
  title: "PROD1"
}, {
  title: "PROD2"
}, {
  title: "PROD3"
}]
```

<p>I managed to create this by doing the following </p>

```var columns = [{ "title":"DATE" }];

$.each(my_json, function(index, element) {
  columns.push({ "title": element.PRODUCT_NAME })
});
```

<p>The second array should be in this format:</p>

```var data = [
  [ "2020-02-01", 845", "1002" , "45"],
  [ "2020-02-02", "20", "",  "" ],
  [ "2020-02-03", "10", "230",  "" ],
];
```

<p>As you can see, on <code>Feb 1</code> we have a value for all products sold but on <code>Feb 2</code> it's only <code>PROD1</code>. Likewise on <code>Feb 3</code> only <code>PROD2</code> and <code>PROD3</code>. </p>

<p>Each row col should match the first array like bellow</p>

<p><img src="https://i.stack.imgur.com/uegg3.png" alt="enter image description here"></p>

<p>desired output of two arrays as bellow</p>

```         var Array1 = [{title: "DATE"},{title: "PROD1"},{title: "PROD2"},
                      {title: "PROD3"}]

         var Array2 = [
                       [ "2020-02-01", 845", "1002" , "45"],
                       [ "2020-02-02", "20", "",  "" ],
                       [ "2020-02-03", "10", "230",  "" ],
                    ];
```

答:
Please check below code</p>

```<code>
function getDates (json) {
  var dates = [];

  json.forEach(ele => {
    if (!dates.includes(ele.DATE)) {
        dates.push(ele.DATE);
      }
  })

  return dates;
}

function getProducts (json) {
  let products = [];

  json.forEach(ele => {
    if (!products.includes(ele.PRODUCT_NAME)) {
        products.push(ele.PRODUCT_NAME);
      }
  })

  return products;
}

function getColumns (json) {
  let columns = [{ "title":"DATE" }];
  let dates = getDates(json);

  dates.forEach(date => {
    let column = { "title": date };
    columns.push(column);
  });

  return columns;
}

function getQuantityForDate(json, date) {
  let products = getProducts(json);
  let row = new Array(products.length + 1).fill("");
  row[0] = date;

  // Filter full data for a date
  let data = json.filter(ele => ele.DATE === date);

  // Filter product on particular date
  data.forEach(ele => {
    let product_index = products.indexOf(ele.PRODUCT_NAME);
    row[product_index + 1] = ele.PRODUCT_QUANTITY_MT;
  });

  return row;
}

function getFormattedData(json) {
    let grid_data = [];
    let dates = getDates(json);

    dates.forEach(date => {
      grid_data.push(getQuantityForDate(json, date));
    })

    return {
      "columns": getColumns(json),
      "data": grid_data
    }
}

let my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}];

let grid_data = getFormattedData(my_json);
console.log(grid_data.columns)
console.log(grid_data.data)
</code>```

Body:
I have the following array:

var my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}]

From the above array I want to create two new arrays, for each day for each product how much was sold. The final array should look like this.

The first value would be a default value call DATE followed by each product name.

var final = [{
  title: "DATE"
}, {
  title: "PROD1"
}, {
  title: "PROD2"
}, {
  title: "PROD3"
}]

I managed to create this by doing the following

var columns = [{ "title":"DATE" }];

$.each(my_json, function(index, element) {
  columns.push({ "title": element.PRODUCT_NAME })
});

The second array should be in this format:

var data = [
  [ "2020-02-01", 845", "1002" , "45"],
  [ "2020-02-02", "20", "",  "" ],
  [ "2020-02-03", "10", "230",  "" ],
];

As you can see, on Feb 1 we have a value for all products sold but on Feb 2 it's only PROD1. Likewise on Feb 3 only PROD2 and PROD3.

Each row col should match the first array like bellow

desired output of two arrays as bellow

         var Array1 = [{title: "DATE"},{title: "PROD1"},{title: "PROD2"},
                      {title: "PROD3"}]

         var Array2 = [
                       [ "2020-02-01", 845", "1002" , "45"],
                       [ "2020-02-02", "20", "",  "" ],
                       [ "2020-02-03", "10", "230",  "" ],
                    ];

Body:
Please check below code

function getDates (json) {
  var dates = [];

  json.forEach(ele => {
    if (!dates.includes(ele.DATE)) {
        dates.push(ele.DATE);
      }
  })

  return dates;
}

function getProducts (json) {
  let products = [];

  json.forEach(ele => {
    if (!products.includes(ele.PRODUCT_NAME)) {
        products.push(ele.PRODUCT_NAME);
      }
  })

  return products;
}

function getColumns (json) {
  let columns = [{ "title":"DATE" }];
  let dates = getDates(json);

  dates.forEach(date => {
    let column = { "title": date };
    columns.push(column);
  });

  return columns;
}

function getQuantityForDate(json, date) {
  let products = getProducts(json);
  let row = new Array(products.length + 1).fill("");
  row[0] = date;

  // Filter full data for a date
  let data = json.filter(ele => ele.DATE === date);

  // Filter product on particular date
  data.forEach(ele => {
    let product_index = products.indexOf(ele.PRODUCT_NAME);
    row[product_index + 1] = ele.PRODUCT_QUANTITY_MT;
  });

  return row;
}

function getFormattedData(json) {
    let grid_data = [];
    let dates = getDates(json);

    dates.forEach(date => {
      grid_data.push(getQuantityForDate(json, date));
    })

    return {
      "columns": getColumns(json),
      "data": grid_data
    }
}

let my_json = [{
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "845",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "1002",
}, {
  DATE: "2020-02-01",
  PRODUCT_NAME: "PROD3",
  PRODUCT_QUANTITY_MT: "45",
}, {
  DATE: "2020-02-02",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "20",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD1",
  PRODUCT_QUANTITY_MT: "10",
}, {
  DATE: "2020-02-03",
  PRODUCT_NAME: "PROD2",
  PRODUCT_QUANTITY_MT: "230",
}];

let grid_data = getFormattedData(my_json);
console.log(grid_data.columns)
console.log(grid_data.data)


问:
connect-redis not storing session
I've been trying to use connect-redis to use express session store with AWS Elasticache.
The redis server at AWS I used is using Encryption in-transit, encryption at-rest and Redis AUTH token.

i am using Passport with local strategy to authenticate users

This is how it looks in app.js when I configure it:

```<code>const express = require('express'),
  app = express(),
  session = require('express-session'),
  awsHandler = require('./awsHandler'),
  passport = require('passport'),
 ....
 ....

awsHandler.retrieveServiceCredentials('session').then(keys => {
    let secret = keys.session_key;
    let redis_auth = keys.redis_auth;
    const redis = require('redis');
    const redisClient = redis.createClient({
      host: 'master.redis-connect.abcd.efg.cache.amazonaws.com',
      port: REDIS_PORT,
      auth_pass: redis_auth,
      tls: { checkServerIdentity: () => undefined }
    });
    const redisStore = require('connect-redis')(session);

    app.use(session({
      secret: secret,
      resave: false,
      saveUninitialized: false,
      store: new redisStore({
        client: redisClient
      })
    }));
  });
  ....
  ....
  app.use(passport.initialize());
  app.use(passport.session());
</code>```

The thing is I try to connect to my website, and I get no req.session or req.user (when before using SQLite with connect-sqlite3 package, I had req.user after logging in).

I noticed nothing gets stored in redis, when I connect to the Redis Server and type KEYS * there are no keys. However, when I try to set a key in the Redis server hardcoded in app.js with:

redisClient.set('key', 'value')

It IS setting the key and value in the server (when typing KEYS * we can see it there).
So I do successfully establish connection to the redis server with the client library, however, it seems something happens there that I don't configure properly so the sessions gets stored in the Redis.

I am on AWS environment (Elastic Beanstalk, Elasticache).

hank you for reading and helping!

Best regards.

答:
I solved it, it was a problem in my code :
the awsHandler.retrieveServiceCredentials is an async function, and called after couple seconds.
In the flow, it was already initializing everything in the app (initializing passport session, defining routes, starting the node server to listen on port, etc...), and because the retrieveServiceCredentials returned later than that, the order was wrong, and it initialized everything in the app before we used app.use(prodSessionMiddleware), so therefore the session not included in the app.

We set an interval every second, and check a boolean if the 'then' was called, if it was called, we clear the interval and continue with our life :)

Title: connect-redis not storing session

Body:
I've been trying to use connect-redis to use express session store with AWS Elasticache.
The redis server at AWS I used is using Encryption in-transit, encryption at-rest and Redis AUTH token.

i am using Passport with local strategy to authenticate users

This is how it looks in app.js when I configure it:

const express = require('express'),
  app = express(),
  session = require('express-session'),
  awsHandler = require('./awsHandler'),
  passport = require('passport'),
 ....
 ....

awsHandler.retrieveServiceCredentials('session').then(keys => {
    let secret = keys.session_key;
    let redis_auth = keys.redis_auth;
    const redis = require('redis');
    const redisClient = redis.createClient({
      host: 'master.redis-connect.abcd.efg.cache.amazonaws.com',
      port: REDIS_PORT,
      auth_pass: redis_auth,
      tls: { checkServerIdentity: () => undefined }
    });
    const redisStore = require('connect-redis')(session);

    app.use(session({
      secret: secret,
      resave: false,
      saveUninitialized: false,
      store: new redisStore({
        client: redisClient
      })
    }));
  });
  ....
  ....
  app.use(passport.initialize());
  app.use(passport.session());

The thing is I try to connect to my website, and I get no req.session or req.user (when before using SQLite with connect-sqlite3 package, I had req.user after logging in).

I noticed nothing gets stored in redis, when I connect to the Redis Server and type KEYS * there are no keys. However, when I try to set a key in the Redis server hardcoded in app.js with:

redisClient.set('key', 'value')

It IS setting the key and value in the server (when typing KEYS * we can see it there).
So I do successfully establish connection to the redis server with the client library, however, it seems something happens there that I don't configure properly so the sessions gets stored in the Redis.

I am on AWS environment (Elastic Beanstalk, Elasticache).

hank you for reading and helping!

Best regards.


问:
Spring Data Mongo DB: The reply message length 5502322 is less than the maximum message length
Code:

Interface::

```<code>@Query(value = "{'status': {$in: ?0} , 'date':{ $lte: ?1 }}")
List<Blog> findByStatusAndCurrentDateWithOrdering(List<String> status, Date date, Sort order);
</code>```

Calling Class:

findByStatusAndCurrentDateWithOrdering(status, new Date(), Sort.by(Direction.DESC, "date")
```
<p>Error from Application deployed in Azure:</p>
```"status": 500,
    "error": "Internal Server Error",
    "message": "The reply message length 5502322 is less than the maximum message length 4194304; nested exception is com.mongodb.MongoIn
ternalException: The reply message length 5502322 is less than the maximum message length 4194304",
```

The content in MongoDB includes Base64 Image as well as ID, HTML. (and only have 11 or 12 rows)

The Azure Mongo DB version of customer is < 3.2.0. Whereas at local it is > 3.2

What changes could be done in above code to read it in chunks or limit to get it work?

答:
You need to change to this:

```<code>db.blog.aggregate([
    {$match:{"status": {$in: status} , "date":{ $lte: date }}},
    {$sort:{"date":-1}}
],{allowDiskUse:true})
</code>```

Edit:

```<code>import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
...

//Inside your `@Service` class, include:
@Autowired
private MongoTemplate mongotemplate;
...

MatchOperation filter = match(Criteria.where("status").in(status).and("date").lte(date));
SortOperation sort    = sort(Direction.DESC, "date")

Aggregation aggregation = newAggregation(filter, sort)
                             .withOptions(newAggregationOptions()
                             .allowDiskUse(true).build());
AggregationResults<Blog> result = mongoTemplate.aggregate(aggregation, mongoTemplate.getCollection(Blog.class), Blog.class);
List<Blog> blogs = result.getMappedResults();
</code>```

Body:
Code:

Interface::

@Query(value = "{'status': {$in: ?0} , 'date':{ $lte: ?1 }}")
List<Blog> findByStatusAndCurrentDateWithOrdering(List<String> status, Date date, Sort order);

Calling Class:

findByStatusAndCurrentDateWithOrdering(status, new Date(), Sort.by(Direction.DESC, "date")

Error from Application deployed in Azure:

"status": 500,
    "error": "Internal Server Error",
    "message": "The reply message length 5502322 is less than the maximum message length 4194304; nested exception is com.mongodb.MongoIn
ternalException: The reply message length 5502322 is less than the maximum message length 4194304",

The content in MongoDB includes Base64 Image as well as ID, HTML. (and only have 11 or 12 rows)

The Azure Mongo DB version of customer is < 3.2.0. Whereas at local it is > 3.2

What changes could be done in above code to read it in chunks or limit to get it work?

Body:
You need to change to this:

db.blog.aggregate([
    {$match:{"status": {$in: status} , "date":{ $lte: date }}},
    {$sort:{"date":-1}}
],{allowDiskUse:true})

Edit:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
...

//Inside your `@Service` class, include:
@Autowired
private MongoTemplate mongotemplate;
...

MatchOperation filter = match(Criteria.where("status").in(status).and("date").lte(date));
SortOperation sort    = sort(Direction.DESC, "date")

Aggregation aggregation = newAggregation(filter, sort)
                             .withOptions(newAggregationOptions()
                             .allowDiskUse(true).build());
AggregationResults<Blog> result = mongoTemplate.aggregate(aggregation, mongoTemplate.getCollection(Blog.class), Blog.class);
List<Blog> blogs = result.getMappedResults();


问:
Aligning the nav bar
how can i add a refresh button in the nav bar of jq grid.
i tried to add it and the result is shown below. the refresh button goes down the no records  to view line.Please help me to align my refresh button.

thanks,
Devan

答:
Probably you used both viewrecords:true and recordpos:'left' parameters of jqGrid (see the documentation). You can fix the problem with

```<code>$("#pager div.ui-paging-info").css({float:"left"});
</code>```

or

```<code>$("#pager_left table.ui-pg-table").insertAfter($("#pager #pager_right")[0]);
</code>```

or something like this. All depend on how you want the grid pager looks like.

ContentLicense: CC BY-SA 3.0

Title: Aligning the nav bar

Body:
Probably you used both viewrecords:true and recordpos:'left' parameters of jqGrid (see the documentation). You can fix the problem with

$("#pager div.ui-paging-info").css({float:"left"});

or

$("#pager_left table.ui-pg-table").insertAfter($("#pager #pager_right")[0]);

or something like this. All depend on how you want the grid pager looks like.


问:
Copy pasting tables from Excel to word including a line break, but use only Excel VBA
I am working on a file where i have populated a lot of tables in excel using VBA. Following this i want to paste the tables one by one into word. Once i paste a table for some reason, the cursor is stuck at Cell 1 of the first table and when i paste the second table it gets paste into the first cell.

I want to know if there is way to introduce line break or page break following pasting the first table or if i can even move the active cursor to outside of the table.

All the options ive found so far are on word but i dont want to use word. I want to introduce a line break in word after the table using excel VBA.

Can someone help me with this? Is there a way to move the cursor or introduce line break after pasting the table?

The code is as follows:

```<code>WSout.Cells(2, 5).Copy
With myDoc.ActiveWindow.Selection
 .EndOf Unit:=wdStory, Extend:=wdMove
 .TypeParagraph
 '.TypeText (str)
 .TypeParagraph
End With
myDoc.Paragraphs(ba).Range.PasteSpecial xlPasteValues

'For Table 1
ba = 1 + ba

WSout.Range("N1:O22").Copy
myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting

myDoc.Application.Selection.MoveDown Unit:=wdLine, Count:=23

'WordApp.Selection.MoveDown Unit:=wdLine, Count:=23

'For Table 2

ba = 1 + ba

lastrow = "0"
lastcol = "22"

For bb = 2 To WSout.Range("Q" & Rows.Count).End(xlUp).Row

lastrow = 1 + lastrow

Next bb

WSout.Range("Q1", WSout.Cells(lastrow, lastcol)).Copy
myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting
</code>```

答:
You move your selection, but then your second paste repeats the first - so it pastes into exactly the same location. These lines-

```<code>  WSout.Range("Q1", WSout.Cells(lastrow, lastcol)).Copy
  myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting
</code>```

Should be something like

```<code>    WSout.Range("Q1", WSout.Cells(lastrow, lastcol)).Copy
    myDoc.selection.Range.PasteAndFormat wdFormatOriginalFormatting
</code>```

I say something like because I'm on my phone and can't test this

Body:
I am working on a file where i have populated a lot of tables in excel using VBA. Following this i want to paste the tables one by one into word. Once i paste a table for some reason, the cursor is stuck at Cell 1 of the first table and when i paste the second table it gets paste into the first cell.

I want to know if there is way to introduce line break or page break following pasting the first table or if i can even move the active cursor to outside of the table.

All the options ive found so far are on word but i dont want to use word. I want to introduce a line break in word after the table using excel VBA.

Can someone help me with this? Is there a way to move the cursor or introduce line break after pasting the table?

The code is as follows:

WSout.Cells(2, 5).Copy
With myDoc.ActiveWindow.Selection
 .EndOf Unit:=wdStory, Extend:=wdMove
 .TypeParagraph
 '.TypeText (str)
 .TypeParagraph
End With
myDoc.Paragraphs(ba).Range.PasteSpecial xlPasteValues

'For Table 1
ba = 1 + ba

WSout.Range("N1:O22").Copy
myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting

myDoc.Application.Selection.MoveDown Unit:=wdLine, Count:=23

'WordApp.Selection.MoveDown Unit:=wdLine, Count:=23

'For Table 2

ba = 1 + ba

lastrow = "0"
lastcol = "22"

For bb = 2 To WSout.Range("Q" & Rows.Count).End(xlUp).Row

lastrow = 1 + lastrow

Next bb

WSout.Range("Q1", WSout.Cells(lastrow, lastcol)).Copy
myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting

Body:
You move your selection, but then your second paste repeats the first - so it pastes into exactly the same location. These lines-

  WSout.Range("Q1", WSout.Cells(lastrow, lastcol)).Copy
  myDoc.Paragraphs(ba).Range.PasteAndFormat wdFormatOriginalFormatting

Should be something like

    WSout.Range("Q1", WSout.Cells(lastrow, lastcol)).Copy
    myDoc.selection.Range.PasteAndFormat wdFormatOriginalFormatting

I say something like because I'm on my phone and can't test this


问:
Install ODBC driver in Alpine Linux Docker Container
I currently have the following Dockerfile to create my Docker image.

```<code>FROM python:3.6.6-alpine3.8

# Add dependencies for Python packages pandas, numpy and pyodbc
RUN apk add --no-cache curl gcc g++ unixodbc-dev
RUN ln -s /usr/include/locale.h /usr/include/xlocale.h

# Project files
ARG PROJECT_DIR=/srv/scripts
RUN mkdir -p $PROJECT_DIR
WORKDIR $PROJECT_DIR
COPY requirements.txt ./

# Install Python dependencies
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
</code>```

I would like to include various ODBC drivers in this image so that I can use them to connect to different databases from the Python program running in my container.

The Python program is using Pyodbc to connect to databases.

The ODBC drivers I need to install are:

PostgreSQL

MySQL

Ms SQL Server

Teradata

Oracle

Hive

Impala

I wanted to start with PostgreSQL thinking it would be the easiest one but I could not find any package on the Alpine Linux Package manager. Do you have any idea how I should install such a driver?

答: if keeping it lightweight is your concerns, specifically in case of odbc, i recommend using debian:stretch image.</p>

Body:
I currently have the following Dockerfile to create my Docker image.

FROM python:3.6.6-alpine3.8

# Add dependencies for Python packages pandas, numpy and pyodbc
RUN apk add --no-cache curl gcc g++ unixodbc-dev
RUN ln -s /usr/include/locale.h /usr/include/xlocale.h

# Project files
ARG PROJECT_DIR=/srv/scripts
RUN mkdir -p $PROJECT_DIR
WORKDIR $PROJECT_DIR
COPY requirements.txt ./

# Install Python dependencies
RUN pip install --upgrade pip
RUN pip install -r requirements.txt

I would like to include various ODBC drivers in this image so that I can use them to connect to different databases from the Python program running in my container.

The Python program is using Pyodbc to connect to databases.

The ODBC drivers I need to install are:

PostgreSQL

MySQL

Ms SQL Server

Teradata

Oracle

Hive

Impala

I wanted to start with PostgreSQL thinking it would be the easiest one but I could not find any package on the Alpine Linux Package manager. Do you have any idea how I should install such a driver?


问:
Select all non-null column names per row in spark
Suppose I have a dataframe that looks like this:

```<code>+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |
+-----+-----+-----+-----+
|  Y  |null |  Y  |null |
|null |  N  |  N  |null |
|  N  |  Y  |null |  N  |
+-----+-----+-----+-----+
</code>```

I want to add a new column that is a concatenation of the names of all non-null columns for each row.

So, for the example above, it would add a new column

```<code>+--------+
|non-null|
+--------+
| A, C   |
| B, C   |
| A, B, D|
+--------+
</code>```

Is there any easy way to do this? I've tried looking for an anti-coalesce, something that would, if not null, use the supplied name. For example, if there was an anti-coalesce:

```<code>df.withColumn("non-null", antiCoalesce("A", "A,") + antiCoalesce("B", "B,") + antiCoalesce("C", "C,") + antiCoalesce("D", "D"))
</code>```

Alas, there is no such function, but it demonstrates what I am looking for.

答:
What about this approach? You can concat_ws with new columns which are containing the name of column when it is not null.

```<code>val df = Seq(("Y", null, "Y", null),
             (null, "N", "N", null),
             ("N", "Y", null, "N")).toDF("A", "B", "C", "D")

val columns = df.columns
columns.foldLeft(df) {(df, name) => df.withColumn(name + "2", when(!col(name).isNull, lit(name)))}
  .withColumn("non-null", concat_ws(",", columns.map(name => col(name + "2")): _*))
  .drop(columns.map(name => name + "2"): _*)
  .show(false)
</code>```

Then,

```<code>+----+----+----+----+--------+
|A   |B   |C   |D   |non-null|
+----+----+----+----+--------+
|Y   |null|Y   |null|A,C     |
|null|N   |N   |null|B,C     |
|N   |Y   |null|N   |A,B,D   |
+----+----+----+----+--------+
</code>```

Body:
Suppose I have a dataframe that looks like this:

+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |
+-----+-----+-----+-----+
|  Y  |null |  Y  |null |
|null |  N  |  N  |null |
|  N  |  Y  |null |  N  |
+-----+-----+-----+-----+

I want to add a new column that is a concatenation of the names of all non-null columns for each row.

So, for the example above, it would add a new column

+--------+
|non-null|
+--------+
| A, C   |
| B, C   |
| A, B, D|
+--------+

Is there any easy way to do this? I've tried looking for an anti-coalesce, something that would, if not null, use the supplied name. For example, if there was an anti-coalesce:

df.withColumn("non-null", antiCoalesce("A", "A,") + antiCoalesce("B", "B,") + antiCoalesce("C", "C,") + antiCoalesce("D", "D"))

Alas, there is no such function, but it demonstrates what I am looking for.

Body:
What about this approach? You can concat_ws with new columns which are containing the name of column when it is not null.

val df = Seq(("Y", null, "Y", null),
             (null, "N", "N", null),
             ("N", "Y", null, "N")).toDF("A", "B", "C", "D")

val columns = df.columns
columns.foldLeft(df) {(df, name) => df.withColumn(name + "2", when(!col(name).isNull, lit(name)))}
  .withColumn("non-null", concat_ws(",", columns.map(name => col(name + "2")): _*))
  .drop(columns.map(name => name + "2"): _*)
  .show(false)

Then,

+----+----+----+----+--------+
|A   |B   |C   |D   |non-null|
+----+----+----+----+--------+
|Y   |null|Y   |null|A,C     |
|null|N   |N   |null|B,C     |
|N   |Y   |null|N   |A,B,D   |
+----+----+----+----+--------+


问:
DBComparer - Out of bounds when selecting database?
I recently got a new computer and installed all of the programs again that I use every day when developing. When I tried using DBComparer (that I've used for years with no problems) suddenly I keep getting this error (see picture) over and over when I try to select database.

I've read a couple of threads where the answers were only "uninstall" or "use another program".

Solutions I've tried so far:

Uninstall and install again.

Tried both x86 and x64.

Run as admin.

Switched authentication metod.

Double checked the authentication (logged in with the same on SSMS17).

Edit Uninstalled SSMS17 and installed SSMS16.

答:
Installing SQL Server 2014 developer edition worked for me.

The DB Comparer 3.0 needs something that SQL Server 2014 or SSMS 2014 has. It would be nice to know which thing.


问:
How to create table in laravel without created_at and Updated_at column using migration
Can anyone know how to create Table in laravel without created_at and Updated_at Column in table using a migration.
I try this Following code but it's still create created_at and Updated_at column in table:-

Migration Laravel :-

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateNewusersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('newusers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('name');
            $table->string('email', 100)->unique();
            $table->bigInteger('phone_no');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('newusers');
    }
}

</code>```

答:
Add this in your model </p>

```<code>public $timestamps = false;
</code>```

Body:
Can anyone know how to create Table in laravel without created_at and Updated_at Column in table using a migration.
I try this Following code but it's still create created_at and Updated_at column in table:-

Migration Laravel :-

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateNewusersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('newusers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('name');
            $table->string('email', 100)->unique();
            $table->bigInteger('phone_no');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('newusers');
    }
}

Body:
Add this in your model

public $timestamps = false;


问:
Javascript float subtract
I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:

```<code>alert(-0.2-0.1);
</code>```

and the result is -0.30000000000000004. Am I doing something wrong? What do I have to do to get -0.3 ?

答:
No, nothing wrong with your code, most decimal fractions cannot be represented exactly
in binary, use

```<code>number.toFixed(x)
</code>```

Where x is the number of decimals you want and number is the result of the subtraction.

Title: Javascript float subtract

Body:
I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:

alert(-0.2-0.1);

and the result is -0.30000000000000004. Am I doing something wrong? What do I have to do to get -0.3 ?

Body:
No, nothing wrong with your code, most decimal fractions cannot be represented exactly
in binary, use

number.toFixed(x)

Where x is the number of decimals you want and number is the result of the subtraction.


问:
ITMS-90035 Error After Changing Build System to "New Build System" in Xcode
After I change build system from "Legacy Build System" to "New Build System" I started to get below error when trying to upload IPA to Appstore. For both options, I can get success build. What can be the problem?

P.S: My export options plist file is for Distrubition. Therefore, there is no problem with the certificate etc.. (As I mentioned, I can successfully UPLOAD it when build with legacy build system.

What I want to learn is that what can be the reasons for the problem. I'll check all of the reasons of it (e.g naming in files).

ERROR ITMS-90035: "Invalid Signature. A sealed resource is missing or invalid. The file at path [Şans.app/Şans] is not properly signed. Make sure you have signed your application with a distribution certificate, not an ad hoc certificate or a development certificate. Verify that the code signing settings in Xcode are correct at the target level (which override any values at the project level). Additionally, make sure the bundle you are uploading was built using a Release target in Xcode, not a Simulator target. If you are certain your code signing settings are correct, choose "Clean All" in Xcode, delete the "build" directory in the Finder, and rebuild your release target. For more information, please consult https://developer.apple.com/library/ios/documentation/Security/Conceptual/CodeSigningGuide/Introduction/Introduction.html

答:
I got this issue once. The real problem was that some assets were missing, in my case it was some AppIcon sizes. It don't known how it is "build system" related tbh.

Hope it helps


问:
Java API works in reading GMAIL any more?
I have tried different Java(API Based) Programs to read Gmail,  as below with correct Email/Passwords, but I am getting below Exception always. Is java APIs no longer works to read Gmails ?

```<code>import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class CheckingMails {
    public static void check(String host, String storeType, String user, String password) {
        try {
            Properties properties = new Properties();

            properties.put("mail.pop3.host", host);
            properties.put("mail.pop3.port", "995");
            properties.put("mail.pop3.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(properties);

            // create the POP3 store object and connect with the pop server
            Store store = emailSession.getStore("pop3s");

            store.connect(host, user, password);

            // create the folder object and open it
            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            // retrieve the messages from the folder in an array and print it
            Message[] messages = emailFolder.getMessages();
            System.out.println("messages.length---" + messages.length);

            for (int i = 0, n = messages.length; i < n; i++) {
                Message message = messages[i];
                System.out.println("---------------------------------");
                System.out.println("Email Number " + (i + 1));
                System.out.println("Subject: " + message.getSubject());
                System.out.println("From: " + message.getFrom()[0]);
                System.out.println("Text: " + message.getContent().toString());

            }

            // close the store and folder objects
            emailFolder.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        String host = "pop.gmail.com";// change accordingly
        String mailStoreType = "pop3";
        String username = "correctEmailId@gmail.com";// change accordingly
        String password = "CorrectPassword";// change accordingly

        check(host, mailStoreType, username, password);

    }

}
</code>```

Error log:

javax.mail.AuthenticationFailedException: [AUTH] Username and password not accepted. at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209) at javax.mail.Service.connect(Service.java:295) at javax.mail.Service.connect(Service.java:176) at zEmails.CheckingMails.check(CheckingMails.java:31) at zEmails.CheckingMails.main(CheckingMails.java:71)

答:
Thanks Friends and Seshidhar G

Allowing 'low secure app' for the emailID am am able to connect and read Email. Currently I am working on rest of the requirements.

Body:
I have tried different Java(API Based) Programs to read Gmail,  as below with correct Email/Passwords, but I am getting below Exception always. Is java APIs no longer works to read Gmails ?

import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class CheckingMails {
    public static void check(String host, String storeType, String user, String password) {
        try {
            Properties properties = new Properties();

            properties.put("mail.pop3.host", host);
            properties.put("mail.pop3.port", "995");
            properties.put("mail.pop3.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(properties);

            // create the POP3 store object and connect with the pop server
            Store store = emailSession.getStore("pop3s");

            store.connect(host, user, password);

            // create the folder object and open it
            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            // retrieve the messages from the folder in an array and print it
            Message[] messages = emailFolder.getMessages();
            System.out.println("messages.length---" + messages.length);

            for (int i = 0, n = messages.length; i < n; i++) {
                Message message = messages[i];
                System.out.println("---------------------------------");
                System.out.println("Email Number " + (i + 1));
                System.out.println("Subject: " + message.getSubject());
                System.out.println("From: " + message.getFrom()[0]);
                System.out.println("Text: " + message.getContent().toString());

            }

            // close the store and folder objects
            emailFolder.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        String host = "pop.gmail.com";// change accordingly
        String mailStoreType = "pop3";
        String username = "correctEmailId@gmail.com";// change accordingly
        String password = "CorrectPassword";// change accordingly

        check(host, mailStoreType, username, password);

    }

}

Error log:

javax.mail.AuthenticationFailedException: [AUTH] Username and password not accepted. at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209) at javax.mail.Service.connect(Service.java:295) at javax.mail.Service.connect(Service.java:176) at zEmails.CheckingMails.check(CheckingMails.java:31) at zEmails.CheckingMails.main(CheckingMails.java:71)


问:
Calculate z values with data from multiple csv files in pandas
I have 2 DataFrames such as the following.

DataFrame one (df1):This is the file where the daily mean and std(standard deviation) are available with daily mood.

```<code>date    mood      score    count     mean         std       abs
5/1/16  positive  1003.3015 2205    0.45501202  0.1948684  1003.3015
6/1/16  negative  -956.2049 2012    -0.4752509  0.19673153 956.2049
7/1/16  positive  952.049   2095    0.45443866  0.19968715 952.049
8/1/16  neutral    10.021   20       0.50105    0.19613942 10.021
9/1/16  positive  715.7656  1528    0.46843298  0.19674478 715.7656
10/1/16 positive  802.8556  1643    0.48865222  0.20401112 802.8556
</code>```

DataFrame Two (df2): File where I want to get the Z value [df2[score]-df1[mean]]/df1[std] in

```<code>date    score   mood
5/1/16  0.7089  positive
6/1/16  -0.6709 negative
7/1/16  0.564   positive
7/1/16  0.4078  positive
7/1/16  -0.2009 negative
8/1/16  0.0032  neutral
</code>```

So what I want to basically get is the Z value for each of the rows in DataFrame Two. To do that, I have to get the mean and std from df1, subtract the mean from the daily score in df2 and divide the resulting value by the std (standard deviation) in df2. But the issue is df1 contains only one daily mood per date with their mean and std (basically it is an aggregate file) where df2 contains millions of rows and most of the dates have hundreds to thousands of scores with different moods.

Expected Output

```<code>date    score   mood         Zvalue
5/1/16  0.7089  positive    1.30286892
6/1/16  -0.6709 negative    -0.9944977
7/1/16  0.564   positive    0.54866495
7/1/16  0.4078  positive    -0.2335587
7/1/16  -0.2009 negative     0         #because there is no negative mean or std value for this in df1
8/1/16  0.0032  neutral    -2.5382454
</code>```

Having trouble to code it to get expected output. I would really appreciate some help here. If you could put some comments in steps, that would be super helpful.  Many thanks.

Body:
I have 2 DataFrames such as the following.

DataFrame one (df1):This is the file where the daily mean and std(standard deviation) are available with daily mood.

date    mood      score    count     mean         std       abs
5/1/16  positive  1003.3015 2205    0.45501202  0.1948684  1003.3015
6/1/16  negative  -956.2049 2012    -0.4752509  0.19673153 956.2049
7/1/16  positive  952.049   2095    0.45443866  0.19968715 952.049
8/1/16  neutral    10.021   20       0.50105    0.19613942 10.021
9/1/16  positive  715.7656  1528    0.46843298  0.19674478 715.7656
10/1/16 positive  802.8556  1643    0.48865222  0.20401112 802.8556

DataFrame Two (df2): File where I want to get the Z value [df2[score]-df1[mean]]/df1[std] in

date    score   mood
5/1/16  0.7089  positive
6/1/16  -0.6709 negative
7/1/16  0.564   positive
7/1/16  0.4078  positive
7/1/16  -0.2009 negative
8/1/16  0.0032  neutral

So what I want to basically get is the Z value for each of the rows in DataFrame Two. To do that, I have to get the mean and std from df1, subtract the mean from the daily score in df2 and divide the resulting value by the std (standard deviation) in df2. But the issue is df1 contains only one daily mood per date with their mean and std (basically it is an aggregate file) where df2 contains millions of rows and most of the dates have hundreds to thousands of scores with different moods.

Expected Output

date    score   mood         Zvalue
5/1/16  0.7089  positive    1.30286892
6/1/16  -0.6709 negative    -0.9944977
7/1/16  0.564   positive    0.54866495
7/1/16  0.4078  positive    -0.2335587
7/1/16  -0.2009 negative     0         #because there is no negative mean or std value for this in df1
8/1/16  0.0032  neutral    -2.5382454

Having trouble to code it to get expected output. I would really appreciate some help here. If you could put some comments in steps, that would be super helpful.  Many thanks.

Body:
Here is the way with merge usage with parameter how = 'left' for merge df1 and df2 dataframes.

# step 1 set new index and get only mean and std columns from df1
df1['date'] = pd.to_datetime(df1['date'])
df1 = df1.set_index(['date','mood'])[['mean', 'std']]

df1
Out[1]:

                             mean   std
        date    mood
    2016-01-05  positive    0.455012    0.194868
    2016-01-06  negative    -0.475251   0.196732
    2016-01-07  positive    0.454439    0.199687
    2016-01-08  neutral     0.501050    0.196139
    2016-01-09  positive    0.468433    0.196745
    2016-01-10  positive    0.488652    0.204011

# step 2
df2['date'] = pd.to_datetime(df2['date'])
df2
Out[2]:

        date    score   mood
0   2016-01-05  0.7089  positive
1   2016-01-06  -0.6709 negative
2   2016-01-07  0.5640  positive
3   2016-01-07  0.4078  positive
4   2016-01-07  -0.2009 negative
5   2016-01-08  0.0032  neutral

# step 3: merge

df3 = df2.merge(df1, left_on = ['date','mood'], right_index = True, how = 'left')[['date','score','mood','std','mean']]

df3
Out[3]:

              date  score   mood         std        mean
   0    2016-01-05  0.7089  positive    0.194868    0.455012
   1    2016-01-06  -0.6709 negative    0.196732    -0.475251
   2    2016-01-07  0.5640  positive    0.199687    0.454439
   3    2016-01-07  0.4078  positive    0.199687    0.454439
   4    2016-01-07  -0.2009 negative    NaN         NaN
   5    2016-01-08  0.0032  neutral     0.196139    0.501050

df3['Zvalue'] = (df3['score']-df3['mean'])/df3['std']

df3[['date','score','mood','Zvalue']].fillna(0)
Out[4]:

         date   score   mood        Zvalue
0   2016-01-05  0.7089  positive    1.302869
1   2016-01-06  -0.6709 negative    -0.994498
2   2016-01-07  0.5640  positive    0.548665
3   2016-01-07  0.4078  positive    -0.233559
4   2016-01-07  -0.2009 negative    0.000000
5   2016-01-08  0.0032  neutral     -2.538245


问:
Array filter is not returning correct for Zero?

function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));```

I want to return the no. of zero present in the array using filter.

答:
You can use the logic as follows:

```<code>[....].filter(x => x===0).length
</code>```

So your code will be

    function zeroCount(arr){
      return arr.filter(x => x===0).length;
    }

    console.log(zeroCount([2,3,0,5,0,2,0]));```

The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and .length() will get the length of that array here.

Body:
function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));

I want to return the no. of zero present in the array using filter.

Body:
You can use the logic as follows:

[....].filter(x => x===0).length

So your code will be

    function zeroCount(arr){
      return arr.filter(x => x===0).length;
    }

    console.log(zeroCount([2,3,0,5,0,2,0]));

The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and .length() will get the length of that array here.


问:
nestjs, GRPC server and micro services architecture
I've started a new project with nestjs with microservices, but it's my first microservices project and i don't' have enough knowledge.
During my documentation study, I can't find a way to use a microservice with grpc and HTTP at the same time.

In my architecture, I have got a few microservices that have to serve REST API for the client but have also to serve grpc request for "internal" purpose, is that a right decision?

答:
It is not correct to say "I can't find a way to use a microservice with grpc and HTTP at the same time" since GRPC uses HTTP. GRPC is not a protocol, it is a way to serialize messages, by exposing HTTP endpoints you have the possibility to choose between different alternatives such as XML; REST/JSON or GRPC.

Normally following the "hexagonal architecture" philosophy (https://en.wikipedia.org/wiki/Hexagonal_architecture_(software)) you should be able to separate the logic from the adapters and your project can implement multiple adapters for the same logic, for example one adapter in HTTP/REST and another in HTTP/GRPC. On the other hand, a way to avoid having to implement multiple ports is to always choose HTTP/GRPC and use Envoy as a proxy between HTTP/REST and HTTP/GRPC (see https://grpc.io/docs/tutorials/basic/web/) but final solution depends on many factors


问:
Request goes through each line in dictionary: how to fix
```<code>geomap = {
    "UK": ["London", "Manchester", "Liverpool"],
    "Czech Republic": ["Prague", "Brno", "Ostrava"],
    "Slovak Republic": ["Bratislava", "Košice"],
    "USA": ["Washington", "New York", "Detroit"],
    "Germany": ["Berlin", "Hamburg", "Munich"]
}

search = input("Tell me city and I'll tell you country: ")

for country, cities in geomap.items():
  if search in cities:
    print(search, "found in", country)
  else:
    print(search, "not found")
</code>```

outcome:

```<code>London found in UK
London not found
London not found
London not found
London not found
</code>```

Looks like it goes through each line in geomap dictionary. Do you have some ideas how to fix this? Thank you!

desired outcome:

```<code>London -> London found in UK (when IN dictionary)
Paris -> Paris not found (when not)
</code>```

and no extra sentences

答:
I adding break in the found in if statement will resolve the issue.</p>

```<code>for country, cities in geomap.items():
    if search in cities:
        print(search, "found in", country)
        break
    else:
        print(search, "not found")
</code>```

Body:
geomap = {
    "UK": ["London", "Manchester", "Liverpool"],
    "Czech Republic": ["Prague", "Brno", "Ostrava"],
    "Slovak Republic": ["Bratislava", "Košice"],
    "USA": ["Washington", "New York", "Detroit"],
    "Germany": ["Berlin", "Hamburg", "Munich"]
}

search = input("Tell me city and I'll tell you country: ")

for country, cities in geomap.items():
  if search in cities:
    print(search, "found in", country)
  else:
    print(search, "not found")

outcome:

London found in UK
London not found
London not found
London not found
London not found

Looks like it goes through each line in geomap dictionary. Do you have some ideas how to fix this? Thank you!

desired outcome:

London -> London found in UK (when IN dictionary)
Paris -> Paris not found (when not)

and no extra sentences

Body:
I adding break in the found in if statement will resolve the issue.

for country, cities in geomap.items():
    if search in cities:
        print(search, "found in", country)
        break
    else:
        print(search, "not found")


问:
Vue router - on refreshing browser window logs out my admin user
I have a router.beforeEach method that works perfectly when going through vue router but refreshing the page logs me back out

```<code>router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.isAdmin)) {
        if (store.getters.isAdmin) {
            next();
            return;
        }

        next('/dashboard');

    } else {
        next();
    }
});
</code>```

So even if my admin status is "admin" I still get redirected to dashboard. Any ideas why!

EDIT:

This is how I am loggin in the user and storing their session/token

```<code>import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

// set up our api end point
var get_url = window.location;
var base_url = get_url .protocol + '//' + get_url.host;
const api_base = base_url + '/api/v1';

export default new Vuex.Store({
    state: {
        status: false,
        token: localStorage.getItem('token') || '',
        user: {}
    },
    mutations: {
      auth_request(state){
        state.status = 'loading';
      },
      auth_success(state, {token, user}) {
        state.status = 'success';
        state.token = token;
        state.user = user;
      },
      auth_error(state){
        state.status = 'error';
      },
      logout(state){
        state.status = '';
        state.token = '';
      },
      set_user(state, user) {
        state.user = user;
      }
    },
    actions: {
      login({commit}, user){
        return new Promise((resolve, reject) => {
          commit('auth_request');
          axios({url: api_base + '/login', data: user, method: 'post' })
          .then(resp => {
            const token = resp.data.data;
            localStorage.setItem('token', token);
            axios.defaults.headers.common['Authorization'] = token;
            commit('auth_success', {token, token});
            resolve(resp);
          })
          .catch(err => {
            commit('auth_error');
            localStorage.removeItem('token');
            reject(err);
          });
        });
      },
    },
    getters : {
      isLoggedIn: state => !!state.token,
      authStatus: state => state.status,
      getUser: state => state.user,
      isAdmin: state => state.user.admin
    }

  });
</code>```

So I am storing the token in localStorage - I am not sure if the local storage is actually working as I don't know how to see my local storage contents (though imagine this is easy to find out).

答:
I'll make some assumptions about your app since I don't know the details, but here's my take.

When your app is initially loaded (i.e. on page refresh), the Vuex state is set to the initial values, which means the user is not logged in. The user has to go through the login process that your app provides, and then the Vuex state is updated with information about the logged in user.

If you refresh the page, your Vuex state is lost and you have to go through the login process again.

If you want to persist data across page reloads, you have to store some data on the client side (typically in LocalStorage). How this is done exactly can vary from app to app since it depends on how you have implemented logged in sessions; are you storing the session in a cookie, or are you using an auth token that you send with each request?

When the app is initially loaded, one of the first things it should do is check if there is a logged in session stored, and if so attempt to authenticate it to make sure it is still valid and retrieve from the server up-to-date information about that session (i.e. information about the logged in user). At minimum, you could store the user object in LocalStorage after logging in and then retrieve it when the app loads.

This is a big topic and I can't give you a succinct answer here, but I've given you some things to think about so you can research this topic further.

Body:
I have a router.beforeEach method that works perfectly when going through vue router but refreshing the page logs me back out

router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.isAdmin)) {
        if (store.getters.isAdmin) {
            next();
            return;
        }

        next('/dashboard');

    } else {
        next();
    }
});

So even if my admin status is "admin" I still get redirected to dashboard. Any ideas why!

EDIT:

This is how I am loggin in the user and storing their session/token

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

// set up our api end point
var get_url = window.location;
var base_url = get_url .protocol + '//' + get_url.host;
const api_base = base_url + '/api/v1';

export default new Vuex.Store({
    state: {
        status: false,
        token: localStorage.getItem('token') || '',
        user: {}
    },
    mutations: {
      auth_request(state){
        state.status = 'loading';
      },
      auth_success(state, {token, user}) {
        state.status = 'success';
        state.token = token;
        state.user = user;
      },
      auth_error(state){
        state.status = 'error';
      },
      logout(state){
        state.status = '';
        state.token = '';
      },
      set_user(state, user) {
        state.user = user;
      }
    },
    actions: {
      login({commit}, user){
        return new Promise((resolve, reject) => {
          commit('auth_request');
          axios({url: api_base + '/login', data: user, method: 'post' })
          .then(resp => {
            const token = resp.data.data;
            localStorage.setItem('token', token);
            axios.defaults.headers.common['Authorization'] = token;
            commit('auth_success', {token, token});
            resolve(resp);
          })
          .catch(err => {
            commit('auth_error');
            localStorage.removeItem('token');
            reject(err);
          });
        });
      },
    },
    getters : {
      isLoggedIn: state => !!state.token,
      authStatus: state => state.status,
      getUser: state => state.user,
      isAdmin: state => state.user.admin
    }

  });

So I am storing the token in localStorage - I am not sure if the local storage is actually working as I don't know how to see my local storage contents (though imagine this is easy to find out).


问:
Regex strip all html tags excluding
 &
I am relatively new to regex but my aim is to strip all html tags from a string excluding
s and  tags with the class='user'. I want to user this regex to clean unwanted html garbage from contentedittable fields.

Hope one of you regex masters can help...

Here is an example to test on: http://gskinner.com/RegExr/?2tpai

I think I'm close, but the closing tag of the a class='user' is currently still being selected as garbage when it is required.

答:
How about:

```<code><?php
$new_content = strip_tags($content, '<a><br>');
</code>```

This would allow all br and all a-elements. Unforutantely in this function you don't have the possibility to allow/disallow element-properties like your class="user". This functions allways allows/disallows the specified elements with all properties.

Title:
Regex strip all html tags excluding
 &

Body:
How about:

<?php
$new_content = strip_tags($content, '<a><br>');

This would allow all br and all a-elements. Unforutantely in this function you don't have the possibility to allow/disallow element-properties like your class="user". This functions allways allows/disallows the specified elements with all properties.


问:
How to initialize List<T> in Kotlin?
I see Kotlin has a List<out E> collection and I was wondering about different ways to initialize one. In Java, I could write:

```<code>List<String> geeks = Arrays.asList("Fowler", "Beck", "Evans");
</code>```

How can I achieve the same in Kotlin?

答:
In this way, you can initialize the List in Kotlin</p>

```<code>val alphabates : List<String> = listOf("a", "b", "c")
</code>```

Title: How to initialize List<T> in Kotlin?

Body:
I see Kotlin has a List<out E> collection and I was wondering about different ways to initialize one. In Java, I could write:

List<String> geeks = Arrays.asList("Fowler", "Beck", "Evans");

How can I achieve the same in Kotlin?

Body:
In this way, you can initialize the List in Kotlin

val alphabates : List<String> = listOf("a", "b", "c")


问:
How to perform set-like operations in pandas?
I need to fill a column with values, that are present in a set and not present in any other columns.

initial df

```<code>    c0  c1  c2  c3  c4  c5
0   4   5   6   3   2   1
1   1   5   4   0   2   3
2   5   6   4   0   1   3
3   5   4   6   2   0   1
4   5   6   4   0   1   3
5   0   1   4   5   6   2
</code>```

I need df['c6'] column that is a set-like difference operation product between a set of set([0,1,2,3,4,5,6]) and each row of df

so that the result df is

```<code>    c0  c1  c2  c3  c4  c5   c6
0   4   5   6   3   2   1    0
1   1   5   4   0   2   3    6
2   5   6   4   0   1   3    2
3   5   4   6   2   0   1    3
4   5   6   4   0   1   3    2
5   0   1   4   5   6   2    3
</code>```

Thank you!

答:
Slightly different approach:

```<code>df['c6'] = sum(range(7)) - df.sum(axis=1)
</code>```

or if you want to be more verbose:

```<code>df['c6'] = sum([0,1,2,3,4,5,6]) - df.sum(axis=1)
</code>```

Body:
I need to fill a column with values, that are present in a set and not present in any other columns.

initial df

    c0  c1  c2  c3  c4  c5
0   4   5   6   3   2   1
1   1   5   4   0   2   3
2   5   6   4   0   1   3
3   5   4   6   2   0   1
4   5   6   4   0   1   3
5   0   1   4   5   6   2

I need df['c6'] column that is a set-like difference operation product between a set of set([0,1,2,3,4,5,6]) and each row of df

so that the result df is

    c0  c1  c2  c3  c4  c5   c6
0   4   5   6   3   2   1    0
1   1   5   4   0   2   3    6
2   5   6   4   0   1   3    2
3   5   4   6   2   0   1    3
4   5   6   4   0   1   3    2
5   0   1   4   5   6   2    3

Thank you!

Body:
Slightly different approach:

df['c6'] = sum(range(7)) - df.sum(axis=1)

or if you want to be more verbose:

df['c6'] = sum([0,1,2,3,4,5,6]) - df.sum(axis=1)


问:
Stop PyYaml from converting a yaml item to list
I am trying to load the following yaml:

yaml_string = """
key:
- [HELLO]
- another string
- another
"""
yaml.safe_load(yaml_string) # returns {"key": [["HELLLO"], "another_string", "another"}
```

<p>and the result is a list containing the HELLO string. I wan to load this a string value that is </p>

<pre class="lang-py prettyprint-override"><code>type(yaml.save_load(yaml_string).get("key")[0])
<class 'str'>
</code>```

Since yaml describes some sort of commnads that are formatted this way, it is necessary to be read as strings and not as sequences. Basically I want to be able to read strings that start and end with brackets. As explained to the comment underneath, unfortunatelly it is not possible to add " since the yaml files were created by a Java app using Jackson which didn't have a problem turning yaml into an object and treating entries that start and end with brackets as strings.  The files are to many for users to start adding quotes.

Is this possible?

EDIT: Added a more complete example

答:
The [] syntax is part of the YAML syntax. If you created this with a program and those are supposed to be strings, the program you used did not implement YAML correctly, as the strings would have to be quoted.

You can try out the following experimental perl script to add quotes around [...]. This relies on the assumption that your documents do not use flow style sequences that should be real sequences. Also it might not work for all cases.

It will definitely not work if the string only has an opening [ but not a closing one.

#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;

use YAML::LibYAML::API::XS;

my $yaml = <<'EOM';
key:
- [HELLO]
- another string
- another
- [HELLO2]
EOM

my @lines = split /(?<=\n)/, $yaml;

my @events;
YAML::LibYAML::API::XS::parse_string_events($yaml, \@events);
while (my $event = shift @events) {
    if ($event->{name} eq 'sequence_start_event' and $event->{style} == 2) {
        my $start = $event->{start};
        my $line = $start->{line};
        my $column = $start->{column};
        # Add single quote before [
        substr($lines[ $line ], $column, 0) = "'";
        # find the next matching `]`
        while (my $event = shift @events) {
            if ($event->{name} eq 'sequence_end_event') {
                my $end = $event->{end};
                my $line = $end->{line};
                # Add single quote after ]
                # add 1 because we modified the line already and added one char
                my $column = $end->{column} + 1;
                substr($lines[ $line ], $column, 0) = "'";
                last;
            }
        }
    }
}

$yaml = join '', @lines;
say $yaml;
```

<p>You might be able to do the same with Python if you have an interface to the libyaml API.</p>

<p>Output:</p>

```key:
- '[HELLO]'
- another string
- another
- '[HELLO2]'
```

Body:
I am trying to load the following yaml:

yaml_string = """
key:
- [HELLO]
- another string
- another
"""
yaml.safe_load(yaml_string) # returns {"key": [["HELLLO"], "another_string", "another"}

and the result is a list containing the HELLO string. I wan to load this a string value that is

type(yaml.save_load(yaml_string).get("key")[0])
<class 'str'>

Since yaml describes some sort of commnads that are formatted this way, it is necessary to be read as strings and not as sequences. Basically I want to be able to read strings that start and end with brackets. As explained to the comment underneath, unfortunatelly it is not possible to add " since the yaml files were created by a Java app using Jackson which didn't have a problem turning yaml into an object and treating entries that start and end with brackets as strings.  The files are to many for users to start adding quotes.

Is this possible?

EDIT: Added a more complete example

Body:
The [] syntax is part of the YAML syntax. If you created this with a program and those are supposed to be strings, the program you used did not implement YAML correctly, as the strings would have to be quoted.

You can try out the following experimental perl script to add quotes around [...]. This relies on the assumption that your documents do not use flow style sequences that should be real sequences. Also it might not work for all cases.

It will definitely not work if the string only has an opening [ but not a closing one.

#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;

use YAML::LibYAML::API::XS;

my $yaml = <<'EOM';
key:
- [HELLO]
- another string
- another
- [HELLO2]
EOM

my @lines = split /(?<=\n)/, $yaml;

my @events;
YAML::LibYAML::API::XS::parse_string_events($yaml, \@events);
while (my $event = shift @events) {
    if ($event->{name} eq 'sequence_start_event' and $event->{style} == 2) {
        my $start = $event->{start};
        my $line = $start->{line};
        my $column = $start->{column};
        # Add single quote before [
        substr($lines[ $line ], $column, 0) = "'";
        # find the next matching `]`
        while (my $event = shift @events) {
            if ($event->{name} eq 'sequence_end_event') {
                my $end = $event->{end};
                my $line = $end->{line};
                # Add single quote after ]
                # add 1 because we modified the line already and added one char
                my $column = $end->{column} + 1;
                substr($lines[ $line ], $column, 0) = "'";
                last;
            }
        }
    }
}

$yaml = join '', @lines;
say $yaml;

You might be able to do the same with Python if you have an interface to the libyaml API.

Output:

key:
- '[HELLO]'
- another string
- another
- '[HELLO2]'


问:
How to contact flask-restful api from react native app?
i am new to backend dev. I try to developp a flask restful api. I followed the documentation and made the suggested minimal api, that is just returning a jsonified dict. With postman, curl and in the browser, no problem, the api is running and responds to my requests.

From my react native app however, i always get a Netwrok Error.

I tried lots of things:

- multiple IP addresses for the flask serveur

- differents ways to use axios

- different os : win10, ubuntu

- different endpoints : /, /api, /test

- different ways of writing the api (flask-restful class, flask app functions ...)

- manips from web documentations : dev mode of my device, chrome dev tools (port forwarding)

- i asked a react native developper to check my client-side code, nothing wrong according to him,

precisions :

- python code runs under a conda virtual env

- appli runs under node js and expo

- container folders of my app and my api are at the same level

- the flask server does not respond 404 or whatever, it does not respond at all, the error returned in react native is a network error

- depending on url, the network errors occurs immediately or after a 2 minutes delay

- flask shows requests and status when called by postman, curl, chrome, but does not react when i press my buttons from the react native app

Here is (one of) my python code:

```<code>from flask import (Flask, jsonify)
# from flask_restful import Resource, Api
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route("/api", methods=["GET"])
def get():
    return jsonify(hello='bouh !')

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)
</code>```

and here is the clientside code:

```<code>import React, {Component} from 'react';
import { View, Button } from 'react-native';
import axios from 'axios';

import { sharedStyles } from '../../SHARED/_shared';

var url = "http://192.168.1.16:5000/api";

export default class PrevCommune extends Component {
    constructor(props){
        super(props);
        this.navigation=this.props.navigation;
    };

    getAxios=()=>{
        axios.get(`${url}`).then((response)=>{
            console.log("succes axios :",response);
        }).catch((error)=>{
            console.log("fail axios :", error);
        });
    };

    getFetch=()=>{
        fetch(url).then((response)=>{
            console.log("succes fetch :",response)
        }).catch((error)=>{
            console.log("fail fetch :",error)
        })
    }

    render(){
        return (
            <View style={sharedStyles.mainContainer}>
                <Button onPress={()=>this.getAxios()} title={"get axios"}></Button>

                <Button onPress={()=>this.getFetch()} title={"get fetch"}></Button>
            </View>
        );
    };
};
</code>```

And the lines returned by requests:

```<code>fail axios : [Error: Network Error]
fail fetch : [TypeError: Network request failed]
</code>```

I saw lots of tutos, videos, articles on flask api but i didn't find where i am wrong. Please tell me if you have any ideas ! I think both client and server codes are ok, the problem seems to be that my requests are blocked by something.

答: Solved : the probleme was my firewall ... thank you ricardo for the CORS doc =)</p>

Body:
i am new to backend dev. I try to developp a flask restful api. I followed the documentation and made the suggested minimal api, that is just returning a jsonified dict. With postman, curl and in the browser, no problem, the api is running and responds to my requests.

From my react native app however, i always get a Netwrok Error.

I tried lots of things:

- multiple IP addresses for the flask serveur

- differents ways to use axios

- different os : win10, ubuntu

- different endpoints : /, /api, /test

- different ways of writing the api (flask-restful class, flask app functions ...)

- manips from web documentations : dev mode of my device, chrome dev tools (port forwarding)

- i asked a react native developper to check my client-side code, nothing wrong according to him,

precisions :

- python code runs under a conda virtual env

- appli runs under node js and expo

- container folders of my app and my api are at the same level

- the flask server does not respond 404 or whatever, it does not respond at all, the error returned in react native is a network error

- depending on url, the network errors occurs immediately or after a 2 minutes delay

- flask shows requests and status when called by postman, curl, chrome, but does not react when i press my buttons from the react native app

Here is (one of) my python code:

from flask import (Flask, jsonify)
# from flask_restful import Resource, Api
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route("/api", methods=["GET"])
def get():
    return jsonify(hello='bouh !')

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)

and here is the clientside code:

import React, {Component} from 'react';
import { View, Button } from 'react-native';
import axios from 'axios';

import { sharedStyles } from '../../SHARED/_shared';

var url = "http://192.168.1.16:5000/api";

export default class PrevCommune extends Component {
    constructor(props){
        super(props);
        this.navigation=this.props.navigation;
    };

    getAxios=()=>{
        axios.get(`${url}`).then((response)=>{
            console.log("succes axios :",response);
        }).catch((error)=>{
            console.log("fail axios :", error);
        });
    };

    getFetch=()=>{
        fetch(url).then((response)=>{
            console.log("succes fetch :",response)
        }).catch((error)=>{
            console.log("fail fetch :",error)
        })
    }

    render(){
        return (
            <View style={sharedStyles.mainContainer}>
                <Button onPress={()=>this.getAxios()} title={"get axios"}></Button>

                <Button onPress={()=>this.getFetch()} title={"get fetch"}></Button>
            </View>
        );
    };
};

And the lines returned by requests:

fail axios : [Error: Network Error]
fail fetch : [TypeError: Network request failed]

I saw lots of tutos, videos, articles on flask api but i didn't find where i am wrong. Please tell me if you have any ideas ! I think both client and server codes are ok, the problem seems to be that my requests are blocked by something.


答:
For filtering, you need to return a boolean like value, like a truthy or falsy value.

A better approach is to count zero values directly.

function zeroCount(arr) {
    return arr.reduce((s, v) => s + !v, 0);
}

console.log(zeroCount([2, 3, 0, 5, 0, 2, 0]));```

Title: Array filter is not returning correct for Zero?


问:
Typescript bundling with Rollup and rollup-plugin-typescript2 gone bad
I'm trying to extract small part of monorepo to web client library and running into some unexpected hurdles, in here.
So, quite straight forward rollup config, like this:

```<code>import resolve from "rollup-plugin-node-resolve";
import typescript from "rollup-plugin-typescript2";
import sourceMaps from 'rollup-plugin-sourcemaps';

export default {
    input: "../main.ts",
    output: {
        file: './bundle/rollup-bundle.js',
        format: 'iife',
        name: 'WebClient',
        sourcemap: true
    },
    plugins: [
        typescript(),
        resolve({browser: true, mainFields: ['module']}),
        sourceMaps(),
    ]
};
</code>```

Produces:

../main.ts → ./bundle/rollup-bundle.js...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
..\main.ts (3:32)
1: [...]
2:
3: export const createClient = (url: string) => new ClientImpl([...]);
                                   ^
Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
```

It just looks like rollup-plugin-typescript2 doesn't do it's job of transpiling typescript and that just seems way too basic to not to work. I'm confused!

Thanks in advance!

答:
It appears that rollupis possibly built with idea, that it will be always located in project root, in mind. And once I attempted to place web client builder as a separate app in it's dedicated folder with it's dedicated tsconfig and rollup.config it all gone mad with no clear indications on why that was taking place.
Only obvious indication is that rollup-plugin-typescript2 isn't capable to transpile (it's not even attempting to) any *.ts files located in higher folders and it took hell of a time to find this out.

Body:
I'm trying to extract small part of monorepo to web client library and running into some unexpected hurdles, in here.
So, quite straight forward rollup config, like this:

import resolve from "rollup-plugin-node-resolve";
import typescript from "rollup-plugin-typescript2";
import sourceMaps from 'rollup-plugin-sourcemaps';

export default {
    input: "../main.ts",
    output: {
        file: './bundle/rollup-bundle.js',
        format: 'iife',
        name: 'WebClient',
        sourcemap: true
    },
    plugins: [
        typescript(),
        resolve({browser: true, mainFields: ['module']}),
        sourceMaps(),
    ]
};

Produces:

../main.ts → ./bundle/rollup-bundle.js...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
..\main.ts (3:32)
1: [...]
2:
3: export const createClient = (url: string) => new ClientImpl([...]);
                                   ^
Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)

It just looks like rollup-plugin-typescript2 doesn't do it's job of transpiling typescript and that just seems way too basic to not to work. I'm confused!

Thanks in advance!


问:
How variable gets created and destroy in python?
If we create 2 variables a followed by b, then how these variable gets destroy in python heap.
We want to understand the memory management done by python interpreter.</p>

答:
Simply putting, Python memory manager counts references to the existing variables and if reference count is equal to zero, garbage collector automatically de-allocates the space for that variable.

I'd recommend following resources to better understand the flow:

https://realpython.com/python-memory-management/

https://docs.python.org/3/c-api/memory.html


问:
Using SAS Token with Azure ServiceBus
I am using new Azure ServiceBus SDK which is .NET Standard 2.0 and I am finding it difficult to use SAS Token. Previously, it used to be MessagingFactory but in new SDK it's not there. ServiceBusConnectionStringBuilder has SAS Token but it also expects a connectionString.

Basically, I want to Send and Receive using SAS Policy (Send rule for Sending and Receive rule for Receiving) and SAS token created from connection string of these policies.

I am able to generate SAS Token but cannot find a way to create QueueClient using this token.

答:
I ended up using following override of ServiceBusConnectionStringBuilder that uses a SharedAccess Signature:

```<code>public ServiceBusConnectionStringBuilder (string endpoint, string entityPath, string sharedAccessSignature);
</code>```

Based on this, here's the code I wrote. This first generates a SAS token using RootManagedAccessKey that is valid for an hour and then uses that token to send a message to a queue.

using System;
using System.Text;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Primitives;

namespace SO60273377
{
    class Program
    {
        static void Main(string[] args)
        {
            var endpoint = "sb://<namespace>.servicebus.windows.net/";
            var queueName = "test";
            var keyName = "RootManageSharedAccessKey";
            var keyValue = "<key>";
            var validityDuration = TimeSpan.FromHours(1);

            TokenScope tokenScope = TokenScope.Entity;

            var provider = (SharedAccessSignatureTokenProvider) TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, keyValue, validityDuration, tokenScope);

            var token = provider.GetTokenAsync(endpoint+queueName, validityDuration).GetAwaiter().GetResult();
            var sasToken = token.TokenValue;
            Console.WriteLine("SAS Token: " + sasToken);
            var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(endpoint, queueName, sasToken);
            QueueClient client = new QueueClient(serviceBusConnectionStringBuilder, ReceiveMode.PeekLock);
            client.SendAsync(new Message(Encoding.UTF8.GetBytes("This is a test"))).GetAwaiter().GetResult();

            Console.WriteLine("Press any key to continue");
            Console.ReadLine();
        }
    }
}
```

Title: Using SAS Token with Azure ServiceBus

Body:
I ended up using following override of ServiceBusConnectionStringBuilder that uses a SharedAccess Signature:

public ServiceBusConnectionStringBuilder (string endpoint, string entityPath, string sharedAccessSignature);

Based on this, here's the code I wrote. This first generates a SAS token using RootManagedAccessKey that is valid for an hour and then uses that token to send a message to a queue.

using System;
using System.Text;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Primitives;

namespace SO60273377
{
    class Program
    {
        static void Main(string[] args)
        {
            var endpoint = "sb://<namespace>.servicebus.windows.net/";
            var queueName = "test";
            var keyName = "RootManageSharedAccessKey";
            var keyValue = "<key>";
            var validityDuration = TimeSpan.FromHours(1);

            TokenScope tokenScope = TokenScope.Entity;

            var provider = (SharedAccessSignatureTokenProvider) TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, keyValue, validityDuration, tokenScope);

            var token = provider.GetTokenAsync(endpoint+queueName, validityDuration).GetAwaiter().GetResult();
            var sasToken = token.TokenValue;
            Console.WriteLine("SAS Token: " + sasToken);
            var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(endpoint, queueName, sasToken);
            QueueClient client = new QueueClient(serviceBusConnectionStringBuilder, ReceiveMode.PeekLock);
            client.SendAsync(new Message(Encoding.UTF8.GetBytes("This is a test"))).GetAwaiter().GetResult();

            Console.WriteLine("Press any key to continue");
            Console.ReadLine();
        }
    }
}