问:
create a dict of dict from a dataframe
i am trying to convert a data-frame to a dict in the below format:

```<code>df
    name   age country state  pincode
0  user1  10.0      in    tn      1.0
1  user2  11.0      us    tx      2.0
2  user3  12.0      eu    fr      3.0
</code>```

```<code>{
   'user1':{'age':10,'country':'in','state':'tn','pincode':1},
   'user2':{'age':11,'country':'us','state':'tx','pincode':2},
   'user3':{'age':12,'country':'eu','state':'fr','pincode':3}
}
</code>```

I am currently doing this by below statement:

```<code>op = {}
for i, row in df.iterrows():
    op[row['name']] = {'age':row['age'],'country':row['country'],'state':row['state'],'pincode':row['pincode']}
</code>```

I want a the solution to work if there are additional columns added to the df. for example telephone number. Since the statement I have written is static it won't give me the additional rows in my output.
Is there a built in method in pandas that does this?

答:
This may not be very readable, but here's a one line dictionary comprehension:</p>

```<code>{k:{a:b for a,b in zip(df.columns.tolist()[1:], v)}
 for k,v in zip(df['name'].to_list(), df.iloc[:,1:].to_numpy().tolist())}
</code>```

Title: create a dict of dict from a dataframe

Body:
i am trying to convert a data-frame to a dict in the below format:

df
    name   age country state  pincode
0  user1  10.0      in    tn      1.0
1  user2  11.0      us    tx      2.0
2  user3  12.0      eu    fr      3.0

{
   'user1':{'age':10,'country':'in','state':'tn','pincode':1},
   'user2':{'age':11,'country':'us','state':'tx','pincode':2},
   'user3':{'age':12,'country':'eu','state':'fr','pincode':3}
}

I am currently doing this by below statement:

op = {}
for i, row in df.iterrows():
    op[row['name']] = {'age':row['age'],'country':row['country'],'state':row['state'],'pincode':row['pincode']}

I want a the solution to work if there are additional columns added to the df. for example telephone number. Since the statement I have written is static it won't give me the additional rows in my output.
Is there a built in method in pandas that does this?

Body:
This may not be very readable, but here's a one line dictionary comprehension:

{k:{a:b for a,b in zip(df.columns.tolist()[1:], v)}
 for k,v in zip(df['name'].to_list(), df.iloc[:,1:].to_numpy().tolist())}


来源: stackexchange

问:
How to benchmark custom interface using google benchmark
since I can't find really good resource or documentation besides what's on the github readme, I'll ask the community here.

Assuming that I have an interface called Base, and multiple derived types.

I want to benchmark a virtual function Foo of all derived types with the same function and the same argument passed to Foo.

For each derived type I want to call Foo multiple times in a single benchmark with varying arguments passed from an std::vector<std::size_t>.

Also some of my constructor of derived types takes extra arguments, how should I deal with it?

The easiest thing to do as I see it, is to use templated benchmark and pass to:

const std::vector<std::size_t> v {1, 2, 4, 8, 16};
BENCHMARK_TEMPLATE(func, Derived1, v);
BENCHMARK_TEMPLATE(func, Derived2, v);
BENCHMARK_TEMPLATE(func, Derived3, v);
...
```

<p>I don't feel this is the correct way to do this since for each derived type with different constructor signature I would need to have different benchmark function which is almost identical to the previous one.</p>

<p>What would be the proper way to benchmark this?</p>

<p>**UPDATE*:
The way I solved this is as follows:</p>

<pre class="lang-cpp prettyprint-override"><code>std::unique_ptr<Base> GetObj(const std::size_t index)
{
    switch(index)
    {
    case 0:
        return std::make_unique<Derived1>(...);
    case 1:
        return std::make_unique<Derived2>(...);
    ...
    }
}

void func(benchmark::State& state)
{
    auto r = state.range();
    auto object = GetObj(r);
    for (auto _ : state)
    {
        ...
    }
}
BENCHMARK(func)->DenseRange(0,5);
</code>```

But what I don't like about it is that the name of the benchmark tests is of the pattern func/0-5 and I would like it to be func/Derived1, func/Derived2 and so on.. any ideas how to achieve that?

答:
Your approach is pretty much correct. If you want to avoid the multiple benchmark functions, move the core of the benchmark to a separate function and call it from each of the per-type ones.  Something like:

static void Benchmark(Base* b, benchmark::State& st) {
  for (auto _ : state) {
    b->DoTheThing()
  }
}

void BM_Foo(benchmark::State& st) {
  Foo f;
  Benchmark(&f, st);
}

BENCHMARK(BM_Foo);
```

<p>If you want to be more sophisticated, you could use the <code>RegisterBenchmark</code> function to register things more flexibly. Something like:</p>

<pre class="lang-cpp prettyprint-override"><code>auto BM_base = [](benchmark::State& st, auto inputs, Base* b) { /* ... */ };

int main(int argc, char**argv) {
  const std::vector<std::size_t> v = {1, 2, 4, 8, 16};
  benchmark::RegisterBenchmark("foo", BM_base, v, new Foo());
  benchmark::Initialize(&argc, argv);
  return benchmark::RunSpecifiedBenchmarks();
}
</code>```

As an aside, should v be set as the Args when the benchmark is registered?

ContentLicense: CC BY-SA 4.0

Body:
since I can't find really good resource or documentation besides what's on the github readme, I'll ask the community here.

Assuming that I have an interface called Base, and multiple derived types.

I want to benchmark a virtual function Foo of all derived types with the same function and the same argument passed to Foo.

For each derived type I want to call Foo multiple times in a single benchmark with varying arguments passed from an std::vector<std::size_t>.

Also some of my constructor of derived types takes extra arguments, how should I deal with it?

The easiest thing to do as I see it, is to use templated benchmark and pass to:

const std::vector<std::size_t> v {1, 2, 4, 8, 16};
BENCHMARK_TEMPLATE(func, Derived1, v);
BENCHMARK_TEMPLATE(func, Derived2, v);
BENCHMARK_TEMPLATE(func, Derived3, v);
...

I don't feel this is the correct way to do this since for each derived type with different constructor signature I would need to have different benchmark function which is almost identical to the previous one.

What would be the proper way to benchmark this?

**UPDATE*:
The way I solved this is as follows:

std::unique_ptr<Base> GetObj(const std::size_t index)
{
    switch(index)
    {
    case 0:
        return std::make_unique<Derived1>(...);
    case 1:
        return std::make_unique<Derived2>(...);
    ...
    }
}

void func(benchmark::State& state)
{
    auto r = state.range();
    auto object = GetObj(r);
    for (auto _ : state)
    {
        ...
    }
}
BENCHMARK(func)->DenseRange(0,5);

But what I don't like about it is that the name of the benchmark tests is of the pattern func/0-5 and I would like it to be func/Derived1, func/Derived2 and so on.. any ideas how to achieve that?

Body:
Your approach is pretty much correct. If you want to avoid the multiple benchmark functions, move the core of the benchmark to a separate function and call it from each of the per-type ones.  Something like:

static void Benchmark(Base* b, benchmark::State& st) {
  for (auto _ : state) {
    b->DoTheThing()
  }
}

void BM_Foo(benchmark::State& st) {
  Foo f;
  Benchmark(&f, st);
}

BENCHMARK(BM_Foo);

If you want to be more sophisticated, you could use the RegisterBenchmark function to register things more flexibly. Something like:

auto BM_base = [](benchmark::State& st, auto inputs, Base* b) { /* ... */ };

int main(int argc, char**argv) {
  const std::vector<std::size_t> v = {1, 2, 4, 8, 16};
  benchmark::RegisterBenchmark("foo", BM_base, v, new Foo());
  benchmark::Initialize(&argc, argv);
  return benchmark::RunSpecifiedBenchmarks();
}

As an aside, should v be set as the Args when the benchmark is registered?


问:
SwiftUI memory leak when referencing property from closure inside Form/NavigationView and swapping views
I have something like this:

struct SomeView: View {
  @ObservedObject var viewModel: SomeViewModel

  var body: some View {
     NavigationView { // <- culprit
        Button(action: { self.viewModel.logOut() }) { Text("X").frame(width: 40, height: 40) }
     }
}

class SomeViewModel: ObservableObject {
  func logOut() {
  // changes global state, based on which the views are swapped, so `SomeView` is removed and replaced by a different one
  }
}
```

When the button is pressed, SomeView is closed and a different view is presented. But if I check the memory graph, SomeViewModel is still allocated because self.viewModel.logOut() is called in the Button's action closure and Button is holding the reference to SomeViewModel.

Is there some way around this?

EDIT:
Actually, when not not wrapping the button in NavigationView, there is no leak. As soon as I wrap the button, the leak appears. Wrapping in VStack is working out fine. But wrapping in Form produces the leak again. Seems like the same problem here: SwiftUI - Possible Memory Leak

答:
I found a solution: Make a weak viewModel in your action. It seems that Apple changed the behavior of closures. This means that the NavigationView is storing a strong reference to viewModel. After a couple days of debugging, it finally worked for me.

```<code>Button(action: {
    [weak viewModel] in viewModel?.dismissButtonPressed.send(())
}) {
    Image("crossmark")
        .padding()
        .foregroundColor(Color.white)
    }
}
</code>```

In your problem, this will be solved like this:

```<code>NavigationView {
    [weak viewModel] in Button(action: { viewModel?.logOut() }) {
        Text("X").frame(width: 40, height: 40)
    }
}
</code>```

Tested on the latest Xcode 11.5, with iOS 13.5. Now, after dismissing the view, the viewModel is correctly deallocated.

Body:
I have something like this:

struct SomeView: View {
  @ObservedObject var viewModel: SomeViewModel

  var body: some View {
     NavigationView { // <- culprit
        Button(action: { self.viewModel.logOut() }) { Text("X").frame(width: 40, height: 40) }
     }
}

class SomeViewModel: ObservableObject {
  func logOut() {
  // changes global state, based on which the views are swapped, so `SomeView` is removed and replaced by a different one
  }
}

When the button is pressed, SomeView is closed and a different view is presented. But if I check the memory graph, SomeViewModel is still allocated because self.viewModel.logOut() is called in the Button's action closure and Button is holding the reference to SomeViewModel.

Is there some way around this?

EDIT:
Actually, when not not wrapping the button in NavigationView, there is no leak. As soon as I wrap the button, the leak appears. Wrapping in VStack is working out fine. But wrapping in Form produces the leak again. Seems like the same problem here: SwiftUI - Possible Memory Leak

Body:
I found a solution: Make a weak viewModel in your action. It seems that Apple changed the behavior of closures. This means that the NavigationView is storing a strong reference to viewModel. After a couple days of debugging, it finally worked for me.

Button(action: {
    [weak viewModel] in viewModel?.dismissButtonPressed.send(())
}) {
    Image("crossmark")
        .padding()
        .foregroundColor(Color.white)
    }
}

In your problem, this will be solved like this:

NavigationView {
    [weak viewModel] in Button(action: { viewModel?.logOut() }) {
        Text("X").frame(width: 40, height: 40)
    }
}

Tested on the latest Xcode 11.5, with iOS 13.5. Now, after dismissing the view, the viewModel is correctly deallocated.


问:
Use loop for create multiple columns from another columns in dataframe in R
I have a CSV file with 19 columns and 9 lines about average of rain months from pluviometers and coordinates (LongLat) of them. The columns are averages and the lines are the pluviometers. The CSV file can be acessed here:  https://drive.google.com/file/d/1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4/view?usp=sharing

The aim is create more columns to calculate rainfall factor by months applying a equation from average columns. The rainfall factor for January for each pluviometer (9 lines) will be calculate using column 7, rainfall for february using column 8, march by column 9...

I'm trying this code for each column and it works, but this code can be reduce and made with a loop?

```<code>library(tidyverse)

setwd("C:/scriptsr/R_postos_pluviometricos_interp_FUNCEME/")

#Code
pluviometros <- read.csv("postos_fatorR.csv",
                                 header = T,
                                 sep = ",",
                                 stringsAsFactors = FALSE)

View(pluviometros)

pluviometros <- mutate(.data=pluviometros,R.JAN=67.355*((pluviometros[1:nrow(pluviometros),7]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.FEV=67.355*((pluviometros[1:nrow(pluviometros),8]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAR=67.355*((pluviometros[1:nrow(pluviometros),9]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.APR=67.355*((pluviometros[1:nrow(pluviometros),10]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAY=67.355*((pluviometros[1:nrow(pluviometros),11]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUN=67.355*((pluviometros[1:nrow(pluviometros),12]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUL=67.355*((pluviometros[1:nrow(pluviometros),13]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.AGO=67.355*((pluviometros[1:nrow(pluviometros),14]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.SEP=67.355*((pluviometros[1:nrow(pluviometros),15]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.OCT=67.355*((pluviometros[1:nrow(pluviometros),16]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.NOV=67.355*((pluviometros[1:nrow(pluviometros),17]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.DEC=67.355*((pluviometros[1:nrow(pluviometros),18]^2)/pluviometros[1:nrow(pluviometros),19])^0.85
                                       )
View(pluviometros)
</code>```

Body:
I have a CSV file with 19 columns and 9 lines about average of rain months from pluviometers and coordinates (LongLat) of them. The columns are averages and the lines are the pluviometers. The CSV file can be acessed here:  https://drive.google.com/file/d/1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4/view?usp=sharing

The aim is create more columns to calculate rainfall factor by months applying a equation from average columns. The rainfall factor for January for each pluviometer (9 lines) will be calculate using column 7, rainfall for february using column 8, march by column 9...

I'm trying this code for each column and it works, but this code can be reduce and made with a loop?

library(tidyverse)

setwd("C:/scriptsr/R_postos_pluviometricos_interp_FUNCEME/")

#Code
pluviometros <- read.csv("postos_fatorR.csv",
                                 header = T,
                                 sep = ",",
                                 stringsAsFactors = FALSE)

View(pluviometros)

pluviometros <- mutate(.data=pluviometros,R.JAN=67.355*((pluviometros[1:nrow(pluviometros),7]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.FEV=67.355*((pluviometros[1:nrow(pluviometros),8]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAR=67.355*((pluviometros[1:nrow(pluviometros),9]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.APR=67.355*((pluviometros[1:nrow(pluviometros),10]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAY=67.355*((pluviometros[1:nrow(pluviometros),11]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUN=67.355*((pluviometros[1:nrow(pluviometros),12]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUL=67.355*((pluviometros[1:nrow(pluviometros),13]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.AGO=67.355*((pluviometros[1:nrow(pluviometros),14]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.SEP=67.355*((pluviometros[1:nrow(pluviometros),15]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.OCT=67.355*((pluviometros[1:nrow(pluviometros),16]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.NOV=67.355*((pluviometros[1:nrow(pluviometros),17]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.DEC=67.355*((pluviometros[1:nrow(pluviometros),18]^2)/pluviometros[1:nrow(pluviometros),19])^0.85
                                       )
View(pluviometros)

Body:
Adding data.table solution:

library(data.table)

data <- data.table::fread("https://docs.google.com/uc?id=1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4&export=download")

cols <- names(data)[which(names(data) == "JAN"):which(names(data) == "DEC")]

newCols <- paste0("R.", cols)

data[, (newCols) := lapply(.SD, function(x) 67.355* ((x^2) / TOTAL_pa)^0.85), .SDcols=cols]

Result:

> data[, c(cols, newCols), with=F]
       JAN     FEB     MAR     APR    MAY    JUN    JUL   AGO   SEP   OCT   NOV    DEC    R.JAN
1:  85.350 126.923 177.167 177.343 89.050 18.060  7.053 1.573 0.350 1.617 2.637 14.950 492.0292
2:  96.957 130.723 173.343 184.130 89.873 25.780 10.760 0.600 0.933 0.000 0.883 13.970 592.6067
3: 106.153 170.712 212.153 198.241 96.571 35.229 21.071 3.788 1.594 5.447 6.153 16.041 592.2811
4:  89.394 120.876 181.882 149.912 89.094 20.512  8.512 0.294 0.718 2.682 0.747 20.929 543.1993
5: 103.550 107.090 139.940 141.335 66.395 18.960  5.300 0.500 0.000 0.000 3.300 17.500 776.8248
6: 106.171 150.588 167.000 154.859 64.765 18.706  7.412 0.412 3.118 0.353 1.706 25.588 714.3158
7: 102.682 141.729 187.753 176.635 88.529 21.606  3.224 0.000 0.000 0.000 1.471  6.282 651.8239
8:  79.444 103.744 155.481 134.125 53.081 16.188  1.875 0.000 0.000 0.000 0.250  6.825 535.1631
9:  87.113 103.431 128.838 145.919 60.325 25.025  1.375 0.438 0.000 0.000 0.500 11.775 612.9724
       R.FEB    R.MAR    R.APR    R.MAY    R.JUN      R.JUL      R.AGO      R.SEP      R.OCT
1:  965.9696 1702.926 1705.803 528.8379 35.10468  7.0987276 0.55383926 0.04303884 0.58043280
2:  984.8734 1591.193 1763.168 520.8968 62.33945 14.1144143 0.10433719 0.22099416 0.00000000
3: 1328.2870 1921.970 1712.663 504.2925 90.81834 37.9059855 2.04993454 0.47062304 3.80111125
4:  907.2210 1817.094 1308.148 540.1039 44.47834  9.9721478 0.03265318 0.14898636 1.39995758
5:  822.5098 1296.191 1318.234 364.9203 43.34042  4.9640584 0.08970505 0.00000000 0.00000000
6: 1293.9688 1542.759 1356.976 308.2896 37.32912  7.7369606 0.05688601 1.77529109 0.04374185
7: 1127.3785 1818.392 1639.156 506.5652 46.06450  1.8149366 0.00000000 0.00000000 0.00000000
8:  842.4019 1675.845 1303.613 269.6365 35.81053  0.9172431 0.00000000 0.00000000 0.00000000
9:  820.7410 1192.270 1473.296 328.2051 73.54207  0.5301692 0.07582386 0.00000000 0.00000000
        R.NOV     R.DEC
1: 1.33300608 25.458625
2: 0.20124041 21.999656
3: 4.67617546 23.841660
4: 0.15936024 46.026439
5: 2.21840892 37.820963
6: 0.63686082 63.583139
7: 0.47811399  5.641004
8: 0.02984560  8.248154
9: 0.09496179 20.414250


问:
JQuery: each() and this and two sliders
I'm trying to get 2 sliders running on a page. As long as I only use one slide, it's fine, but as soon as I add a second slider only the first works. Tried to solve it with each and $this, but being a novice to jquery I'm missing something.

Note: This slider is built in a way, that it takes the class like "dur-7" and uses it to calculate how long a slide is being shown. This allows in Gutenberg to add a class and such the duration for each individual slide.

Tried the concept of each and this in another example and it worked. Used console.log to see the values coming up.

https://jsfiddle.net/francis_hunger/bzvx6rac/5/

```<code><html>
<div class="wp-block-group fhslide">
  <div class="wp-block-group__inner-container">
    <div class="wp-block-image dur-7"><img src="https://upload.wikimedia.org/wikipedia/commons/5/56/Sequoiadendron_giganteum_at_Kenilworth_Castle.jpg"></div>
    <div class="wp-block-image dur-2"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Baum_im_Sossusvlei.jpg/2560px-Baum_im_Sossusvlei.jpg"></div>
    <div class="wp-block-image dur-9"><img src="https://upload.wikimedia.org/wikipedia/commons/b/bf/Buchenstamm.jpg">       </div>
  </div>
</div>

<hr>

<div class="wp-block-group fhslide">
  <div class="wp-block-group__inner-container">
    <div class="wp-block-image dur-20"><img src="https://upload.wikimedia.org/wikipedia/commons/1/1b/Baumstamm.jpg"></div>
    <div class="wp-block-image dur-20"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Bl%C3%A4tterDurchRinde.jpg/2560px-Bl%C3%A4tterDurchRinde.jpg"></div>
  </div>
</div>

    </div>
    </div>

<script>
jQuery(function() {

if (jQuery('.fhslide').length!==0){

    jQuery.each(jQuery('.fhslide'), function () {

      var theImage = jQuery('.wp-block-image img',this);
      var theWidth = theImage.width(this);

      // INIT
      jQuery ('.wp-block-group__inner-container', this).children().first().addClass('active').css('opacity', '1');
      jQuery ('.wp-block-group__inner-container', this).children().last().addClass('last');

      // First Match
      var lookup = jQuery('.wp-block-group__inner-container',this).children().first().attr('class').match(/dur-[0-9]*/); // Aktuelles Element, Array
      var durStr = '50'; // Standard
            if (!lookup == "") {
                    durStr = lookup[0].substring(4);//  We just need the first position of the array [0], then we match "dur-" and keep the seconds (as a string)
            }
      var durInt = parseInt(durStr)*1000; // string to Milliseconds

    /****** CALL *******/
    var fh_timer = setTimeout(fh_next(this),durInt);

        /****** FH NEXT *******/

        function fh_next() {
            var a = jQuery('.active');
            a.removeClass('active').fadeTo('slow',0).next().fadeTo('slow',1);

             // Last element
                if (a.hasClass('last')) {

            var durStr = a.siblings(":first").attr('class').match(/dur-[0-9]*/)[0].substring(4); // pick the duration of the first element (and go there)
            var durInt = parseInt(durStr)*1000;                                         a.siblings(":first").addClass('active').fadeTo('slow',1); // gehe zum ersten Element
            }

            // All elements
               else {

            var durStr = a.next().attr('class').match(/dur-[0-9]*/)[0].substring(4);
            var durInt = parseInt(durStr)*1000;
                a.next().addClass('active'); // go to next element
               }

            /* Set the duration */
            setTimeout(fh_next, durInt);

        }// fh_next()

    // Maximum height for wrapper
    jQuery('.wp-block-group__inner-container', this).css({
        width: function() {
          return theWidth;
        },
        height: function() {
          return theImage.height();
        },
    });

    // Maximum width for wrapper
    var totalWidth = theImage.length * theWidth;
    jQuery('figure.wp-block-image', this).css({
            width: function() {
              return totalWidth;
            }
    });

    });//each

} //if

});// ready function()

</script>
</html>
</code>```

The expected result would be, that each slider block group with the class "fhslide" works individually. Currently only the first slider runs continuously and the second slider runs once and then no any more.

答:
Issue

You are not assigning this correctly:

    var fh_timer = setTimeout(fh_next(this),durInt); // <---

    function fh_next() {
```

<p>And <code>fh_next</code> does not have arguments.</p>

<h2>Solution</h2>

<p>Bind <code>this</code> when calling:</p>

<pre class="lang-js prettyprint-override"><code>    var fh_timer = setTimeout(() => fh_next.call(this), durInt); // <---

    function fh_next() {
</code>```

Could this be the problem?

Title: JQuery: each() and this and two sliders

Body:
I'm trying to get 2 sliders running on a page. As long as I only use one slide, it's fine, but as soon as I add a second slider only the first works. Tried to solve it with each and $this, but being a novice to jquery I'm missing something.

Note: This slider is built in a way, that it takes the class like "dur-7" and uses it to calculate how long a slide is being shown. This allows in Gutenberg to add a class and such the duration for each individual slide.

Tried the concept of each and this in another example and it worked. Used console.log to see the values coming up.

https://jsfiddle.net/francis_hunger/bzvx6rac/5/

The expected result would be, that each slider block group with the class "fhslide" works individually. Currently only the first slider runs continuously and the second slider runs once and then no any more.

Body:
Issue

You are not assigning this correctly:

    var fh_timer = setTimeout(fh_next(this),durInt); // <---

    function fh_next() {

And fh_next does not have arguments.

Solution

Bind this when calling:

    var fh_timer = setTimeout(() => fh_next.call(this), durInt); // <---

    function fh_next() {

Could this be the problem?


问:
I run my first tomcat and i got an error, what should i do?
enter image description here

I got this problem, when first run tomcat, i knew that the first running have always problem, but i did not found resolve for the windows user.

```<code>Error running 'Unnamed':..port out of range-1
</code>```

what should I do?

答:
Inside your Tomcat installation folder, go to "server.xml" file and change:

from:

```<code><Server port="-1" shutdown="SHUTDOWN">
</code>```

To:

```<code><Server port="8005" shutdown="SHUTDOWN">
</code>```

Body:
enter image description here

I got this problem, when first run tomcat, i knew that the first running have always problem, but i did not found resolve for the windows user.

Error running 'Unnamed':..port out of range-1

what should I do?

Body:
Inside your Tomcat installation folder, go to "server.xml" file and change:

from:

<Server port="-1" shutdown="SHUTDOWN">

To:

<Server port="8005" shutdown="SHUTDOWN">


问:
Calculating co-variance in Python without Numpy or Stats modules
I have been tasked with writing a function in python to calculate the covariance of an array, without using the numpy or statistics module.

I used the below to find the variance:

```<code>def daml_var(x):
    m = x.sum() / len(x)
    var = sum((x-m)**2 for x in x)/len(x)
    return var
</code>```

However I am struggling with the co-variance formula! My below formula returns zero...don't know why. Any takers?

```<code>def daml_cov(x, y):
    m = x.sum() / len(x)
    m2 = y.sum()/len(y)
    xm = sum((x-m) for x in x)
    ym = sum((y-m2) for y in y)
    return xm*ym/len(x)
</code>```

Thanks

答:
You calculate xm (and ym) as the sum of all deviations from the mean. This number will always be zero, by definition of the mean.

Instead, you need to put the product (x - m) * (y - m2) inside the sum, and have the two for loops run in parallel. This can be done with the zip() function.

Also, you shouldn't use x (and y) for both the array and its items.

By the way, if you want to follow the standard convention for the sample variance and covariance, you should divide by len(x) - 1 instead of len(x) in both cases. See the Wikipedia article on the sample covariance.

In summary, this should work:

def daml_cov(x, y):
    m = x.sum() / len(x)
    m2 = y.sum() / len(y)
    return sum([(xi - m) * (yi - m2) for xi, yi in zip(x, y)]) / (len(x) - 1)
```

Body:
I have been tasked with writing a function in python to calculate the covariance of an array, without using the numpy or statistics module.

I used the below to find the variance:

def daml_var(x):
    m = x.sum() / len(x)
    var = sum((x-m)**2 for x in x)/len(x)
    return var

However I am struggling with the co-variance formula! My below formula returns zero...don't know why. Any takers?

def daml_cov(x, y):
    m = x.sum() / len(x)
    m2 = y.sum()/len(y)
    xm = sum((x-m) for x in x)
    ym = sum((y-m2) for y in y)
    return xm*ym/len(x)

Thanks


问:
MySQL - How to filter rows by a hidden rows sub_id
I have two Tables.
in the First are Articles in the Second Members.
I want a query which shows only records with the members_id of a given ID ($_GET['id']) but not the entry with the given ID ($_GET['id'])

the articles table looks like:

```<code>+----+------------+-----------------------+
| id | members_id | ArticleName           |
+----+------------+-----------------------+
|  1 |       1001 | Shirt Nologo          |
|  2 |       1001 | Nike Sneakers         |
|  3 |       1001 | Nike Sneakers for Men |
|  4 |       1031 | Adidas Shirt          |
+----+------------+-----------------------+
</code>```

the members Table looks like:

```<code>+------+---------+
| id   | nick    |
+------+---------+
| 1001 | Member1 |
| 1031 | Member2 |
+------+---------+
</code>```

I want something like:

```<code>+----+------------+-----------------------+
| id | members_id | ArticleName           |
+----+------------+-----------------------+
|  2 |       1001 | Nike Sneakers         |
|  3 |       1001 | Nike Sneakers for Men |
+----+------------+-----------------------+
</code>```

with a query like this:

```<code>//$_GET['id'] == 1
SELECT t1.*,t2.nick
FROM articles t1
    LEFT JOIN members t2 ON t1.members_id=t2.id
WHERE t1.id != '1'
AND t1.members_id = t1.found_id
</code>```

答:
If I understand correctly, you want all ids for a member that has the id value you specify -- but not that particular value.  If so:

```<code>select a.*
from articles a
where exists (select 1
              from articles a2
              where a2.member_id = a.member_id and a2.id = :id
             ) and
      id <> :id
</code>```

Body:
I have two Tables.
in the First are Articles in the Second Members.
I want a query which shows only records with the members_id of a given ID ($_GET['id']) but not the entry with the given ID ($_GET['id'])

the articles table looks like:

+----+------------+-----------------------+
| id | members_id | ArticleName           |
+----+------------+-----------------------+
|  1 |       1001 | Shirt Nologo          |
|  2 |       1001 | Nike Sneakers         |
|  3 |       1001 | Nike Sneakers for Men |
|  4 |       1031 | Adidas Shirt          |
+----+------------+-----------------------+

the members Table looks like:

+------+---------+
| id   | nick    |
+------+---------+
| 1001 | Member1 |
| 1031 | Member2 |
+------+---------+

I want something like:

+----+------------+-----------------------+
| id | members_id | ArticleName           |
+----+------------+-----------------------+
|  2 |       1001 | Nike Sneakers         |
|  3 |       1001 | Nike Sneakers for Men |
+----+------------+-----------------------+

with a query like this:

//$_GET['id'] == 1
SELECT t1.*,t2.nick
FROM articles t1
    LEFT JOIN members t2 ON t1.members_id=t2.id
WHERE t1.id != '1'
AND t1.members_id = t1.found_id

Body:
If I understand correctly, you want all ids for a member that has the id value you specify -- but not that particular value.  If so:

select a.*
from articles a
where exists (select 1
              from articles a2
              where a2.member_id = a.member_id and a2.id = :id
             ) and
      id <> :id


问:
Error in renaming R3 Corda template package
I have cloned the 'Kotlin CorDapp Template' project. I am trying to rename the package from 'com.template' to 'com.new_name' through IntelliJ. Renaming happens, but I get an error while importing the changes - 'can't find resource for bundle java.util.PropertyResourceBundle, key kotlin.gradle.testing.enabled'. Please help.</p>

答:
This looks an error from the IDE.
Somehow it is easy to crash since there are two separate directory requires the same package name.

contracts

workflows

A work-around is to right-click on the net.corda.template on both directories and click refactor to rename it properly.


问:
Iterate over nested JSON objects and append data to variable
i'm pretty new with JS and i'm struggling a little bit with iterating over a nested JSON object.

I need to grab the value of each nested Node_Subtask_Success in history and save that to a variable I can access later.

The dataset is rather large so I won't add it directly into this post, but i've uploaded it to pastebin here: https://pastebin.com/puZ77V0K

What i've tried so far:

```<code>updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    _.each(response.data, function(node) {
                      for(var num in response.data.history) {
                        console.log(num.Node_Subtask_Success)
                      }
                    });
                })
            },
</code>```

But the above just prints undefined 269 times.

答:
The reason behind that is for..in will pick up the property name in that way:

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

What you can do instead:

const history = [
  {
      "id": 539,
      "Node_Cores": 1,
      "Node_Subtask_Success": 856,
  }
];

history.forEach(e => {
   console.log(e.Node_Subtask_Success);
});```
</div>
</div>
</p>
<p>See an example why it was not working:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const history = [
  {
      "id": 539,
      "Node_Cores": 1,
      "Node_Subtask_Success": 856,
  }
];

for (var num in history) {
  console.log({num}); // this return 0
  console.log(num.Node_Subtask_Success); // this one undefined
}</code>```

Body:
i'm pretty new with JS and i'm struggling a little bit with iterating over a nested JSON object.

I need to grab the value of each nested Node_Subtask_Success in history and save that to a variable I can access later.

The dataset is rather large so I won't add it directly into this post, but i've uploaded it to pastebin here: https://pastebin.com/puZ77V0K

What i've tried so far:

updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    _.each(response.data, function(node) {
                      for(var num in response.data.history) {
                        console.log(num.Node_Subtask_Success)
                      }
                    });
                })
            },

But the above just prints undefined 269 times.

Body:
The reason behind that is for..in will pick up the property name in that way:

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

What you can do instead:

const history = [
  {
      "id": 539,
      "Node_Cores": 1,
      "Node_Subtask_Success": 856,
  }
];

history.forEach(e => {
   console.log(e.Node_Subtask_Success);
});

See an example why it was not working:

const history = [
  {
      "id": 539,
      "Node_Cores": 1,
      "Node_Subtask_Success": 856,
  }
];

for (var num in history) {
  console.log({num}); // this return 0
  console.log(num.Node_Subtask_Success); // this one undefined
}


问:
how to compare (1 billion records) data between two kafka streams or Database tables
we are sending data from DB2 (table-1) via CDC to Kafka topics (topic-1).
we need to do reconciliation between DB2 data and Kafka topics.
we have two options -

a) bring down all kafka topic data into DB2 (as table-1-copy) and then do left outer join (between table-1 and table-1-copy) to see the non-matching records, create the delta and push it back into kafka.
problem: Scalability - our data set is about a billion records and i am not sure if DB2 DBA is going to let us run such a huge join operation (that may last easily over 15-20 mins).

b) push DB2 back again into parallel kafka topic (topic-1-copy) and then do some kafka streams based solution to do left outer join between kafka topic-1 and topic-1-copy. I am still wrapping my head around kafka streams and left outer joins.
I am not sure whether (using the windowing system in kafka streams) I will be able to compare the ENTIRE contents of topic-1 with topic-1-copy.

To make matters worse, the topic-1 in kafka is a compact topic,
so when we push the data from DB2 back into Kafka topic-1-copy, we cannot deterministically kick off the kafka topic-compaction cycle to make sure both topic-1 and topic-1-copy are fully compacted before running any sort of compare operation on them.

c) is there any other framework option that we can consider for this ?

The ideal solution has to scale for any size data.

答:
I see no reason why you couldn't do this in either Kafka Streams or KSQL.  Both support table-table joins.  That's assuming the format of the data is supported.

Key compaction won't affect the results as both Streams and KSQL will build the correct final state of joining the two tables. If compaction has run the amount of data that needs processing may be less, but the result will be the same.

For example, in ksqlDB you could import both topics as tables and perform a join and then filter by the topic-1 table being null to find the list of missing rows.

-- example using 0.9 ksqlDB, assuming a INT primary key:

-- create table from main topic:
CREATE TABLE_1
   (ROWKEY INT PRIMARY KEY, <other column defs>)
   WITH (kafka_topic='topic-1', value_format='?');

-- create table from second topic:
CREATE TABLE_2
   (ROWKEY INT PRIMARY KEY, <other column defs>)
   WITH (kafka_topic='topic-1-copy', value_format='?');

-- create a table containing only the missing keys:
CREATE MISSING AS
   SELECT T2.* FROM TABLE_2 T2 LEFT JOIN TABLE_1 T1
   WHERE T1.ROWKEY = null;
```

<p>The benefit of this approach is that the <code>MISSING</code> table of missing rows would automatically update: as you extracted the missing rows from your source DB2 instance and produced them to the <code>topic-1</code> then the rows in the 'MISSING' table would be deleted, i.e. you'd see tombstones being produced to the <code>MISSING</code> topic.</p>

<p>You can even extend this approach to find rows that exist in <code>topic-1</code> that are no longer in the source db:</p>

<pre class="lang-sql prettyprint-override"><code>-- using the same DDL statements for TABLE_1 and TABLE_2 from above

-- perform the join:
CREATE JOINED AS
   SELECT * FROM TABLE_2 T2 FULL OUTER JOIN TABLE_1 T1;

-- detect rows in the DB that aren't in the topic:
CREATE MISSING AS
   SELECT * FROM JOINED
   WHERE T1_ROWKEY = null;

-- detect rows in the topic that aren't in the DB:
CREATE EXTRA AS
   SELECT * FROM JOINED
   WHERE T2_ROWKEY = null;
</code>```

Of course, you'll need to size your cluster accordingly. The bigger your ksqlDB cluster the quicker it will process the data.  It'll also need on-disk capacity to materialize the table.

The maximum amount of parallelization you can get set by the number of partitions on the topics.  If you've only 1 partition, then data will be processed sequentially.  If running with 100 partitions, then you can process the data using 100 CPU cores, assuming you run enough ksqlDB instances. (By default, each ksqlDB node will create 4 stream-processing threads per query, (though you can increase this if the server has more cores!)).

Body:
I see no reason why you couldn't do this in either Kafka Streams or KSQL.  Both support table-table joins.  That's assuming the format of the data is supported.

Key compaction won't affect the results as both Streams and KSQL will build the correct final state of joining the two tables. If compaction has run the amount of data that needs processing may be less, but the result will be the same.

For example, in ksqlDB you could import both topics as tables and perform a join and then filter by the topic-1 table being null to find the list of missing rows.

-- example using 0.9 ksqlDB, assuming a INT primary key:

-- create table from main topic:
CREATE TABLE_1
   (ROWKEY INT PRIMARY KEY, <other column defs>)
   WITH (kafka_topic='topic-1', value_format='?');

-- create table from second topic:
CREATE TABLE_2
   (ROWKEY INT PRIMARY KEY, <other column defs>)
   WITH (kafka_topic='topic-1-copy', value_format='?');

-- create a table containing only the missing keys:
CREATE MISSING AS
   SELECT T2.* FROM TABLE_2 T2 LEFT JOIN TABLE_1 T1
   WHERE T1.ROWKEY = null;

The benefit of this approach is that the MISSING table of missing rows would automatically update: as you extracted the missing rows from your source DB2 instance and produced them to the topic-1 then the rows in the 'MISSING' table would be deleted, i.e. you'd see tombstones being produced to the MISSING topic.

You can even extend this approach to find rows that exist in topic-1 that are no longer in the source db:

-- using the same DDL statements for TABLE_1 and TABLE_2 from above

-- perform the join:
CREATE JOINED AS
   SELECT * FROM TABLE_2 T2 FULL OUTER JOIN TABLE_1 T1;

-- detect rows in the DB that aren't in the topic:
CREATE MISSING AS
   SELECT * FROM JOINED
   WHERE T1_ROWKEY = null;

-- detect rows in the topic that aren't in the DB:
CREATE EXTRA AS
   SELECT * FROM JOINED
   WHERE T2_ROWKEY = null;

Of course, you'll need to size your cluster accordingly. The bigger your ksqlDB cluster the quicker it will process the data.  It'll also need on-disk capacity to materialize the table.

The maximum amount of parallelization you can get set by the number of partitions on the topics.  If you've only 1 partition, then data will be processed sequentially.  If running with 100 partitions, then you can process the data using 100 CPU cores, assuming you run enough ksqlDB instances. (By default, each ksqlDB node will create 4 stream-processing threads per query, (though you can increase this if the server has more cores!)).


问:
Dependencies are not compatible with currently expo package version when running npm start
I recently update npm and now, when I run npm start, This message shows up:

```<code>Some of your project's dependencies are not compatible with currently installed expo package version:
 - @react-native-community/netinfo - expected version range: 5.5.1 - actual version installed: ^5.8.1
</code>```

Does anyone know how can I remove this Warning ?

Thank you!

答:
I was pulling my hair for a similar problem with firebase...

If the expected version was higher than the installed one it would be fixed easily by running "npm install" but not this one, where the expected version is lower than the Installed one.

The fix is to run "expo update" on the project folder.
or yarn upgrade

You can also use the following:

expo install @react-native-community/netinfo@5.8.1

to fix the problem instead of using the big hammer "expo update" :)

Body:
I recently update npm and now, when I run npm start, This message shows up:

Some of your project's dependencies are not compatible with currently installed expo package version:
 - @react-native-community/netinfo - expected version range: 5.5.1 - actual version installed: ^5.8.1

Does anyone know how can I remove this Warning ?

Thank you!


问:
How do you pull a list of images from firebase storage?
I've managed to successfully upload some photos to firebase but I want to download all the images at a certain location

currently I have to do this ugly code:

```<code>const getPhotos = async () => {
    var storage = firebaseApp.storage()
    var gsReference = storage.refFromURL('gs://my-app.appspot.com/')
    for (let i = 1; i < 4; i++) {
        await gsReference
            .child(`${user.id}/${name}/photo${i}.jpg`)
            .getDownloadURL()
            .then((url) => {
                fetch(url).then((res) => {
                    setPhotos((photos) => photos.concat(res.url))
                })
            })
            .catch((error) => {
                console.log('ERROR!', error)
            })
    }
}
</code>```

this relies on all the photos being called photo1.jpg, photo2.jpg etc.

is there a way to just pull them all regardless of what they're called?

答:
Apparently there is Reference.listAll function

const getPhotos = async () => {
    const storage = firebaseApp.storage();
    let reference = storage.refFromURL('gs://my-app.appspot.com/');
    reference = reference.child(`${user.id}/${name}`);

    const {items} = await reference.listAll();
    const urlPromises = items.map(pr => pr.getDownloadURL()
      .then(url => fetch(url))
      .catch(error => error));

    let urls = await Promise.all(urlPromises);
    urls = urls.filter(result => !(result instanceof Error));

    setPhotos(urls);
}
```

Body:
I've managed to successfully upload some photos to firebase but I want to download all the images at a certain location

currently I have to do this ugly code:

const getPhotos = async () => {
    var storage = firebaseApp.storage()
    var gsReference = storage.refFromURL('gs://my-app.appspot.com/')
    for (let i = 1; i < 4; i++) {
        await gsReference
            .child(`${user.id}/${name}/photo${i}.jpg`)
            .getDownloadURL()
            .then((url) => {
                fetch(url).then((res) => {
                    setPhotos((photos) => photos.concat(res.url))
                })
            })
            .catch((error) => {
                console.log('ERROR!', error)
            })
    }
}

this relies on all the photos being called photo1.jpg, photo2.jpg etc.

is there a way to just pull them all regardless of what they're called?


问:
Search $needle in $haystack
I'm using the following to retrieve the script name.

<%
    String pageName = Request.FilePath;
%>

I'd like to be able to check this pageName to see if it contains the value "account".

How do I do this with C#?

答:
Use String.Contains method:</p>

```<code>if (pageName.Contains("account"))
{
    // do something
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Search $needle in $haystack

Body:
Use String.Contains method:

if (pageName.Contains("account"))
{
    // do something
}


问:
How to generate distinct covariance matrices for each class in SAS?
Using SAS I want to generate the covariance matrices for a dataset which contains a binary class, one covariance matrix for class 1 and one covariance matrix for class 2.

```<code>PROC MEANS DATA=my_dataset MAXDEC=2 MEAN STD;
CLASS binary_class;
VAR x1 x2 x3;
RUN;

PROC CORR DATA=my_dataset noprob COV;
CLASS binary_class;
VAR x1 x2 x3;
run;
</code>```

but when I run the second statement I get:

ERROR 180-322: Statement is not valid or it is used out of proper order.

Can someone please help me?

答:
I don't think PROC CORR has a CLASS statement, you want a BY (#2) statement instead, which does require you sort your data ahead of time.

You can add an ODS OUTPUT statement (#1) to store the covariance data to a data set.

```<code>proc sort data=my_dataset;
by binary_class;
run;

ods output cov=cov_by_binary; /*#1*/
proc corr data=my_dataset noprob cov;
by binary_class; /*2*/
var x1-x3;
run;
</code>```

EDIT: In general, a CLASS statement only tells the SAS proc that your variable is categorical, it doesn't necessarily do BY group processing. PROC MEANS is one of the few procs where it can be used somewhat interchangeably.

Body:
Using SAS I want to generate the covariance matrices for a dataset which contains a binary class, one covariance matrix for class 1 and one covariance matrix for class 2.

PROC MEANS DATA=my_dataset MAXDEC=2 MEAN STD;
CLASS binary_class;
VAR x1 x2 x3;
RUN;

PROC CORR DATA=my_dataset noprob COV;
CLASS binary_class;
VAR x1 x2 x3;
run;

but when I run the second statement I get:

ERROR 180-322: Statement is not valid or it is used out of proper order.

Can someone please help me?

Body:
I don't think PROC CORR has a CLASS statement, you want a BY (#2) statement instead, which does require you sort your data ahead of time.

You can add an ODS OUTPUT statement (#1) to store the covariance data to a data set.

proc sort data=my_dataset;
by binary_class;
run;

ods output cov=cov_by_binary; /*#1*/
proc corr data=my_dataset noprob cov;
by binary_class; /*2*/
var x1-x3;
run;

EDIT: In general, a CLASS statement only tells the SAS proc that your variable is categorical, it doesn't necessarily do BY group processing. PROC MEANS is one of the few procs where it can be used somewhat interchangeably.


问:
How to use vw and vh css with React Native
I'm creating a basic login using React Native with a logo and 2 inputs:

```<code>//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image } from 'react-native';

// create a component
class Login extends Component {
    render() {
        const imageURL = require('./images/CircleLogo.png');
        return (
            <View style={styles.container}>
                <View style={styles.loginContainer}>
                    <Image resizeMode="contain" style={styles.logo} source={imageURL} />
                </View>
                <View style={styles.formContainer}>
                    <LoginForm />
                </View>
            </View>
        );
    }
}

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'aliceblue',
    },
    loginContainer:{
        alignItems: 'center',
        flexGrow: 1,
        justifyContent: 'center'
    },
    logo: {
        position: 'absolute',
        width: '70vw',
        height: '70vw',
        maxWidth: 300
    }
});

//make this component available to the app
export default Login;
</code>```

As you can see i am using vw and vh css measurements.

This works on the web, but not on iOS or Android.

Does anyone have a good suggestion for handling vw and vh measurements?

Side Note: It appears react accepts percentages as seen here, which I may revert to. But my question pertains to specifically the vw and vh measurements.

答:
I've browsed through other answers, all that works and simple for new projects. If you desire to make an existing project responsive, I'd recommend using the below package.

https://www.npmjs.com/package/react-native-responsive-view-port

Assume you've already built an app for 1280 x 800 and you wish to make it responsive for all resolutions, then you can achieve it as shown below.

Before

```<code>    <View style={{ width:500 }} ></View>
</code>```

After

```<code>const { vw, vh } = createViewPortConfig({ width : 1280, height : 800 });

<View style={{ width: 500*vw }} ></View>
</code>```

I find this method easier than recalculating all sizes.

Body:
I'm creating a basic login using React Native with a logo and 2 inputs:

//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image } from 'react-native';

// create a component
class Login extends Component {
    render() {
        const imageURL = require('./images/CircleLogo.png');
        return (
            <View style={styles.container}>
                <View style={styles.loginContainer}>
                    <Image resizeMode="contain" style={styles.logo} source={imageURL} />
                </View>
                <View style={styles.formContainer}>
                    <LoginForm />
                </View>
            </View>
        );
    }
}

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'aliceblue',
    },
    loginContainer:{
        alignItems: 'center',
        flexGrow: 1,
        justifyContent: 'center'
    },
    logo: {
        position: 'absolute',
        width: '70vw',
        height: '70vw',
        maxWidth: 300
    }
});

//make this component available to the app
export default Login;

As you can see i am using vw and vh css measurements.

This works on the web, but not on iOS or Android.

Does anyone have a good suggestion for handling vw and vh measurements?

Side Note: It appears react accepts percentages as seen here, which I may revert to. But my question pertains to specifically the vw and vh measurements.

Body:
I've browsed through other answers, all that works and simple for new projects. If you desire to make an existing project responsive, I'd recommend using the below package.

https://www.npmjs.com/package/react-native-responsive-view-port

Assume you've already built an app for 1280 x 800 and you wish to make it responsive for all resolutions, then you can achieve it as shown below.

Before

    <View style={{ width:500 }} ></View>

After

const { vw, vh } = createViewPortConfig({ width : 1280, height : 800 });

<View style={{ width: 500*vw }} ></View>

I find this method easier than recalculating all sizes.


问:
MembershipProvider in .NET 4.0
How can I add the MembershipProvider class to my .NET 4.0 project in VS 2010 B2?

I want to customize a MembershipProvider, but I cannot without adding this class. Please guide me through this process.

答:
On my case, I am using Visual Studio 2019, I need to add both of these:

```<code>System.Web.ApplicationServices
</code>```

and

```<code>System.Configuration
</code>```

In order to build it successfully upon inheriting MembershipProvider to create my own MyMembershipProvider class.

Title: MembershipProvider in .NET 4.0

Body:
On my case, I am using Visual Studio 2019, I need to add both of these:

System.Web.ApplicationServices

and

System.Configuration

In order to build it successfully upon inheriting MembershipProvider to create my own MyMembershipProvider class.


问:
Not able to update the database in hibernate
I am new to hibernate and I am using hibernate 3.0 with MySQL and I want to make the simple database operations like insert update and delete with the database.I am getting the successful results for insert and delete but not able to update the particular field.
I have persistent class named Employee with Fname,Lname,Id and mail with getters and setters.

This is my main method :-

```<code>public static void main(String[] args) {
    Session session = null;
    Random r = new Random();
    try {
        /*
         * This step will read hibernate.cfg.xml
         *
         * and prepare hibernate for use
         */
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        Contact contact = new Contact();
        contact = (Contact) session.get(Contact.class, new Long(1));
        // Create new instance of Contact and set
        // values in it by reading them from form object
        System.out.println("Inserting Record");
        contact.setId(r.nextLong() % 100);
        contact.setFirstName("123anand");
        contact.setLastName("nandurbarkar");
        contact.setEmail("anand_it1990@yahoo.com");
        trx.commit();
        session.update(contact);
</code>```

And this is my conf file :-

```<code>    <hibernate-configuration>
    <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.pool_size">1</property>
 <property name="show_sql">true</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="hibernate.hbm2ddl.auto">update</property>
    <!-- Mapping files -->
 <mapping resource="contact.hbm.xml"/>
 </session-factory>
</hibernate-configuration>
</code>```

Please help if u know how to resolve this issue.
Thanks in Advance...

答:
You cannot change the id of an entity. If you want to see how update of other properties works, try this: </p>

```<code>public static void main(String[] args) {
    Session session = null;
    Random r = new Random();
    try {
        /*
         * This step will read hibernate.cfg.xml
         *
         * and prepare hibernate for use
         */
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        Contact contact = new Contact();

        // Create new instance of Contact and set
        // values in it by reading them from form object
        System.out.println("Inserting Record");
        contact.setId(r.nextLong() % 100);
        contact.setFirstName("123anand");
        contact.setLastName("nandurbarkar");
        contact.setEmail("anand_it1990@yahoo.com");
        // this makes contact persistent. No SQL commands yet
        session.persist(contact);
        // sync the session. Here you get a SQL INSERT
        session.flush();

        // change some properties
        contact.setFirstName("ugo");

        // sync again.Here you get a SQL UPDATE
        session.flush()

        // Now, let's say you want to update an existing instance/record
        // with id = 123
        // retrieve the instance
        Contact c = session.get(Contact.class, new Long(123));
        c.setFirstName("new name");

        // sync the session with the db
        session.flush(); // <- here you get SQL UPDATE

        trx.commit();
</code>```

Body:
I am new to hibernate and I am using hibernate 3.0 with MySQL and I want to make the simple database operations like insert update and delete with the database.I am getting the successful results for insert and delete but not able to update the particular field.
I have persistent class named Employee with Fname,Lname,Id and mail with getters and setters.

This is my main method :-

public static void main(String[] args) {
    Session session = null;
    Random r = new Random();
    try {
        /*
         * This step will read hibernate.cfg.xml
         *
         * and prepare hibernate for use
         */
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        Contact contact = new Contact();
        contact = (Contact) session.get(Contact.class, new Long(1));
        // Create new instance of Contact and set
        // values in it by reading them from form object
        System.out.println("Inserting Record");
        contact.setId(r.nextLong() % 100);
        contact.setFirstName("123anand");
        contact.setLastName("nandurbarkar");
        contact.setEmail("anand_it1990@yahoo.com");
        trx.commit();
        session.update(contact);

And this is my conf file :-

    <hibernate-configuration>
    <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.pool_size">1</property>
 <property name="show_sql">true</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="hibernate.hbm2ddl.auto">update</property>

 <mapping resource="contact.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

Please help if u know how to resolve this issue.
Thanks in Advance...

Body:
You cannot change the id of an entity. If you want to see how update of other properties works, try this:

public static void main(String[] args) {
    Session session = null;
    Random r = new Random();
    try {
        /*
         * This step will read hibernate.cfg.xml
         *
         * and prepare hibernate for use
         */
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        Transaction trx = session.beginTransaction();
        Contact contact = new Contact();

        // Create new instance of Contact and set
        // values in it by reading them from form object
        System.out.println("Inserting Record");
        contact.setId(r.nextLong() % 100);
        contact.setFirstName("123anand");
        contact.setLastName("nandurbarkar");
        contact.setEmail("anand_it1990@yahoo.com");
        // this makes contact persistent. No SQL commands yet
        session.persist(contact);
        // sync the session. Here you get a SQL INSERT
        session.flush();

        // change some properties
        contact.setFirstName("ugo");

        // sync again.Here you get a SQL UPDATE
        session.flush()

        // Now, let's say you want to update an existing instance/record
        // with id = 123
        // retrieve the instance
        Contact c = session.get(Contact.class, new Long(123));
        c.setFirstName("new name");

        // sync the session with the db
        session.flush(); // <- here you get SQL UPDATE

        trx.commit();


问:
Postgres insert data for timestamp with timezone
I have a table with two columns each of type timestamp with time zone. I want to insert data a interval of one hour(from 4 to 5) for current date.
Timezone is GMT
Example - start_date and end_date of type timestamp with time zone.

Today's date is 2020-06-01

I want 2020-06-01T04:00:00Z in start_date and  2020-06-01T05:00:00Z in end_date.

insert into table (start_date,end_date) values (???)

I am trying something like '<<today>>'::date + 'T04:00:00Z' but it gives me error.

答:
According PostgreSQL documnetation + interval can solve this problem like:

```<code>INSERT INTO `table` (`start_date`, `end_date`)
VALUES (
    '<<today>>'::date + interval '4 hour',
    '<<today>>'::date + interval '5 hour'
);
</code>```

Body:
According PostgreSQL documnetation + interval can solve this problem like:

INSERT INTO `table` (`start_date`, `end_date`)
VALUES (
    '<<today>>'::date + interval '4 hour',
    '<<today>>'::date + interval '5 hour'
);


问:
Websocket not able to open the port on Ubuntu
I am using websocket bundle on a symfony based web portal while everything seems to work on localhost things break down when I moved the portal on production server.

On localhost the host i am using is 127.0.0.1 and the port is 8080 so when I moved to the production I had to change the ip to the production ip and I had to then tell ubuntu server to open the port 8080 using the following command

sudo ufw allow 8080/tcp which gave me the output of

```<code>Rule added
Rule added (v6)
</code>```

I then ran the command sudo ufw status to see if the port has been added in firewall and i can see that it is

```<code>To                         Action      From
--                         ------      ----
22                         ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
8080                       ALLOW       Anywhere
8080/tcp                   ALLOW       Anywhere
22 (v6)                    ALLOW       Anywhere (v6)
80/tcp (v6)                ALLOW       Anywhere (v6)
8080 (v6)                  ALLOW       Anywhere (v6)
8080/tcp (v6)              ALLOW       Anywhere (v6)
</code>```

However the error remains

```<code>WebSocket connection to 'ws://111.222.333.44:8080/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
</code>```

I also tried the command telnet 111.222.333.44 8080 and this gives me the following error

```<code>Trying 111.222.333.44...
telnet: connect to address 111.222.333.44: Connection refused
telnet: Unable to connect to remote host
</code>```

So this tells me the port 8080 is not open, what commands do I need to use to open this? I am using Ubuntu 15.10

Any help will be really appreciated.

答:
Try opening port 6001, this is the port that websockets use:</p>

```<code>sudo ufw allow 6001/tcp
</code>```

Body:
I am using websocket bundle on a symfony based web portal while everything seems to work on localhost things break down when I moved the portal on production server.

On localhost the host i am using is 127.0.0.1 and the port is 8080 so when I moved to the production I had to change the ip to the production ip and I had to then tell ubuntu server to open the port 8080 using the following command

sudo ufw allow 8080/tcp which gave me the output of

Rule added
Rule added (v6)

I then ran the command sudo ufw status to see if the port has been added in firewall and i can see that it is

To                         Action      From
--                         ------      ----
22                         ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
8080                       ALLOW       Anywhere
8080/tcp                   ALLOW       Anywhere
22 (v6)                    ALLOW       Anywhere (v6)
80/tcp (v6)                ALLOW       Anywhere (v6)
8080 (v6)                  ALLOW       Anywhere (v6)
8080/tcp (v6)              ALLOW       Anywhere (v6)

However the error remains

WebSocket connection to 'ws://111.222.333.44:8080/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

I also tried the command telnet 111.222.333.44 8080 and this gives me the following error

Trying 111.222.333.44...
telnet: connect to address 111.222.333.44: Connection refused
telnet: Unable to connect to remote host

So this tells me the port 8080 is not open, what commands do I need to use to open this? I am using Ubuntu 15.10

Any help will be really appreciated.

Body:
Try opening port 6001, this is the port that websockets use:

sudo ufw allow 6001/tcp


答:
First of all it seems that you are doing a loop in a loop. _.each (see lodash docs) iterate over an array. You iterate over response.data which is an Object, not an array.

You should iterate over response.data.history instead. Like this

```<code>updateData: function() {
    axios.get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
    .then((response) => {
        _.each(response.data.history, (historyElement) => {
            //your element here
            console.log(historyElement.Node_Subtask_Success)
        });

};
</code>```

Title: Iterate over nested JSON objects and append data to variable

Body:
First of all it seems that you are doing a loop in a loop. _.each (see lodash docs) iterate over an array. You iterate over response.data which is an Object, not an array.

You should iterate over response.data.history instead. Like this

updateData: function() {
    axios.get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
    .then((response) => {
        _.each(response.data.history, (historyElement) => {
            //your element here
            console.log(historyElement.Node_Subtask_Success)
        });

};


问:
Is there a way to code a large array of objects in a much shorter way?
I am doing a personal project in react.js but at this moment I am trying to write clean code. Could exist a way to write shorter this code in two lines? or something like that. I tried to make objects of arrays like

```<code>const apps= {app_name:['Maps','Meet'], position:['0 2323', '0 2323'}
</code>```

but It does not work

const apps = [
  {
    app_name: 'Maps',
    position: '0 -828px'
  },
  {
    app_name: 'Gmail',
    position: '0 -483px'
  },
  {
    app_name: 'Calendar',
    position: '0 -2553px'
  },
  {
    app_name: 'Drive',
    position: '0 -2277px'
  }
];
```

<p>There is not a way to rewrite it in a more shorter way in order to make the map's function works?</p>

<pre class="lang-js prettyprint-override"><code>{apps.map((el, i) =>
    <li className='items'>

            <div className='img_box'>
                <span className='img'
                  style={ { backgroundPosition: el.position } }></span>
            </div>
            <span className='app_name'>{el.app_name}</span>

    </li>
)}

</code>```

答:
An idea would be to write a function that creates the app structure:

function create_app(app_name, position) {
    return ({ app_name, position });
}

const apps = [
    create_app('Maps', '0 -828px'),
    create_app('Gmail', '0 -483px'),
    create_app('Calendar', '0 -2553px'),
    create_app('Drive', '0 -2277px')
];
```

<hr>

<p>Another idea would be to define an object with the app name as key and position as value, but that might be a problem in the long run if you decide later that you want to associate apps with anything other than positions.</p>

<pre class="lang-js prettyprint-override"><code>const app_positions = {
    'Maps': '0 -828px',
    'Gmail': '0 -483px',
    'Calendar': '0 -2553px',
    'Drive': '0 -2277px'
};

{app_positions.keys().map((app_name) =>
    <li className='items'>

            <div className='img_box'>
                <span className='img'
                  style={ { backgroundPosition: app_positions[app_name] } }></span>
            </div>
            <span className='app_name'>{app_name}</span>

    </li>
)}
</code>```

Body:
I am doing a personal project in react.js but at this moment I am trying to write clean code. Could exist a way to write shorter this code in two lines? or something like that. I tried to make objects of arrays like

const apps= {app_name:['Maps','Meet'], position:['0 2323', '0 2323'}

but It does not work

const apps = [
  {
    app_name: 'Maps',
    position: '0 -828px'
  },
  {
    app_name: 'Gmail',
    position: '0 -483px'
  },
  {
    app_name: 'Calendar',
    position: '0 -2553px'
  },
  {
    app_name: 'Drive',
    position: '0 -2277px'
  }
];

There is not a way to rewrite it in a more shorter way in order to make the map's function works?

{apps.map((el, i) =>

            {el.app_name}

)}

Body:
An idea would be to write a function that creates the app structure:

function create_app(app_name, position) {
    return ({ app_name, position });
}

const apps = [
    create_app('Maps', '0 -828px'),
    create_app('Gmail', '0 -483px'),
    create_app('Calendar', '0 -2553px'),
    create_app('Drive', '0 -2277px')
];

Another idea would be to define an object with the app name as key and position as value, but that might be a problem in the long run if you decide later that you want to associate apps with anything other than positions.

const app_positions = {
    'Maps': '0 -828px',
    'Gmail': '0 -483px',
    'Calendar': '0 -2553px',
    'Drive': '0 -2277px'
};

{app_positions.keys().map((app_name) =>
    <li className='items'>
        <a className='link'>
            <div className='img_box'>
                <span className='img'
                  style={ { backgroundPosition: app_positions[app_name] } }></span>
            </div>
            <span className='app_name'>{app_name}</span>
        </a>
    </li>
)}


问:
is there any way to use the SIMILAR TO operator in SQL Server or any other operators like Similar TO operator?
```<code>DELETE FROM TABLE_NAME WHERE COLUMN_NAME SIMILAR TO '%(_100|_200|_300)';
</code>```

Above is a postgresql query.
Need an equivalent SQL Server query.

答:
It looks like you want pattern matching against a regex. In SQL Server you could phrase this as:

```<code>DELETE FROM TABLE_NAME WHERE COLUMN_NAME LIKE '%(_[123]00)';
</code>```

This searches for strings that end with '(_100)' or '(_200)' or '(_300)'.

In am unsure that you really want the parentheses: these are literals, meaning that it will actually search for parentheses in the string. If that's not what you want, then remove them.

Body:
DELETE FROM TABLE_NAME WHERE COLUMN_NAME SIMILAR TO '%(_100|_200|_300)';

Above is a postgresql query.
Need an equivalent SQL Server query.

Body:
It looks like you want pattern matching against a regex. In SQL Server you could phrase this as:

DELETE FROM TABLE_NAME WHERE COLUMN_NAME LIKE '%(_[123]00)';

This searches for strings that end with '(_100)' or '(_200)' or '(_300)'.

In am unsure that you really want the parentheses: these are literals, meaning that it will actually search for parentheses in the string. If that's not what you want, then remove them.


问:
Audio Volume in Apple's speakHere example code
I am trying to increase the volume of my Audio Output using the speakHere example from Apple. The volume is already set to max with :

// set the volume of the queue
    XThrowIfError (AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, 1.0), "set queue volume");

However, the output is directed to the ear-piece speaker, which is not as loud as the bottom-left-speaker on the iPhone. An example of this can be seen nicely in the 'Voice Memos' that comes with the iPhone. They provide a 'Speaker-Button' that toggles between the two speakers. Does anybody have an idea how that is done? What do I need to output my Audio to the bottom speaker?
Any tips, hints, answers will be much appreciated.
Thanks you in advance
Al

答:
You need to set Player to Speaker Mode.

Add this code in AQPlayer.mm:

```<code>OSStatus error;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
error = AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
if (error) printf("couldn't set audio speaker!");
</code>```

Before this code:

```<code>XThrowIfError (AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, 1.0), "set queue volume");
</code>```

I hope it helps.

ContentLicense: CC BY-SA 2.5

Body:
You need to set Player to Speaker Mode.

Add this code in AQPlayer.mm:

OSStatus error;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
error = AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
if (error) printf("couldn't set audio speaker!");

Before this code:

XThrowIfError (AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, 1.0), "set queue volume");

I hope it helps.


问:
HTTP PUT File/BLOB with fetch or XMLHttpRequest
Is it possible to upload a File with fetch? I'm not talking about FormData, but I want to be the file the actual body of the HTTP PUT, and the Content-Type the correct ContentType?

If its not possible with fetch, can it be dont with the XMLHttpRequest? This code isnt working for me (event is a drop event):

```<code>fetch('/foo', {
  method: 'PUT',
  body: event.dataTransfer.files[0],
});
</code>```

Edit:

I'm specifically talking about FILE uploads. This does work if body is a Text, but not if its a FILE/BLOB!

答:
You can just create the form data, something like:

const body = new FormData();
const file = event.dataTransfer.files[0];
body.append('files', file , file.name);

fetch('/foo', {
  method: 'PUT',
  body
});
```

<p>However, if you want to just send the data directly you'll have to change the header and use a <code>Blob</code>:</p>

<pre class="lang-js prettyprint-override"><code>const body = new Blob(event.dataTransfer.files, { type: 'application/octet-stream' });

fetch('/foo', {
  method: 'PUT',
  headers: new Headers({ 'Content-Type': 'application/octet-stream' }),
  body
});
</code>```

Body:
Is it possible to upload a File with fetch? I'm not talking about FormData, but I want to be the file the actual body of the HTTP PUT, and the Content-Type the correct ContentType?

If its not possible with fetch, can it be dont with the XMLHttpRequest? This code isnt working for me (event is a drop event):

fetch('/foo', {
  method: 'PUT',
  body: event.dataTransfer.files[0],
});

Edit:

I'm specifically talking about FILE uploads. This does work if body is a Text, but not if its a FILE/BLOB!

Body:
You can just create the form data, something like:

const body = new FormData();
const file = event.dataTransfer.files[0];
body.append('files', file , file.name);

fetch('/foo', {
  method: 'PUT',
  body
});

However, if you want to just send the data directly you'll have to change the header and use a Blob:

const body = new Blob(event.dataTransfer.files, { type: 'application/octet-stream' });

fetch('/foo', {
  method: 'PUT',
  headers: new Headers({ 'Content-Type': 'application/octet-stream' }),
  body
});


问:
Install plpython on mac with python 2.7
I need to install plpython because I'm getting the error

```<code>could not access file "$libdir/plpython2": No such file or directory
</code>```

when trying to do python manage.py migrate. I have seen different suggestions on how to install this package but none works for me because I need to be using python version 2.7 (some people suggested installing python 3.2) and I cannot run sudo apt-get install ... because I have to be working on a mac.

I have tried running

```<code>CREATE LANGUAGE plpython2u;
</code>```

but I got the error

```<code>ERROR:  could not access file "$libdir/plpython2": No such file or directory
</code>```

Also, I have tried pip/brew install plpython. But no result. Any suggestions?

答:
(macOS Catalina 10.15.5, Homebrew 2.3.0)

The voted solution does not work with recent versions of Homebrew, which does not support options anymore, see https://github.com/Homebrew/homebrew-core/issues/31510.

```<code>> brew reinstall postgresql@9.4 --with-python
...
Error: invalid option: --with-python
</code>```

Fortunately, there is petere / homebrew-postgresql

I first updated the XCode command tools, in order to avoid this error:

```<code>configure: error: header file <perl.h> is required for Perl
</code>```

with

```<code>> sudo rm -rf /Library/Developer/CommandLineTools
> sudo xcode-select --install
</code>```

And then

```<code>> brew tap petere/postgresql
> brew reinstall petere/postgresql/postgresql@9.4
</code>```

brought plpython2 back to life for me.

Title: Install plpython on mac with python 2.7

Body:
I need to install plpython because I'm getting the error

could not access file "$libdir/plpython2": No such file or directory

when trying to do python manage.py migrate. I have seen different suggestions on how to install this package but none works for me because I need to be using python version 2.7 (some people suggested installing python 3.2) and I cannot run sudo apt-get install ... because I have to be working on a mac.

I have tried running

CREATE LANGUAGE plpython2u;

but I got the error

ERROR:  could not access file "$libdir/plpython2": No such file or directory

Also, I have tried pip/brew install plpython. But no result. Any suggestions?

Body:
(macOS Catalina 10.15.5, Homebrew 2.3.0)

The voted solution does not work with recent versions of Homebrew, which does not support options anymore, see https://github.com/Homebrew/homebrew-core/issues/31510.

> brew reinstall postgresql@9.4 --with-python
...
Error: invalid option: --with-python

Fortunately, there is petere / homebrew-postgresql

I first updated the XCode command tools, in order to avoid this error:

configure: error: header file <perl.h> is required for Perl

with

> sudo rm -rf /Library/Developer/CommandLineTools
> sudo xcode-select --install

And then

> brew tap petere/postgresql
> brew reinstall petere/postgresql/postgresql@9.4

brought plpython2 back to life for me.


问:
Run async function in the body of a scaffold
I want to decide what content is displayed in the screen on the basis of a boolean variable called isAdmin. The value for this field is fetched from firestore.

Here's what I got so far:

```<code>Future<bool> isUserAnAdmin() async {
    var snap = await Firestore.instance
        .collection("Users")
        .document(UserSingleton().fireUser.uid)
        .get();
    UserSingleton().user = User.fromJson(snap.data);
    return UserSingleton().user.isAdmin;
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text("hemlp"),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: GestureDetector(
                child: Icon(Icons.exit_to_app),
                onTap: () async => await Auth.logoutUser().then(
                    (value) => Navigator.pushNamed(context, '/SignInPage')),
              ),
            )
          ],
        ),
        body: isUserAnAdmin() == true ? AdminPage() : PatientPage());
  }
</code>```

The problem is that I'm always routed to PatientPage(), irrespective of the value of isAdmin. I suspect that this is happening because it isn't waiting for the value returned by isUserAnAdmin(). I thought I could just await isUserAnAdmin(), but I can't use await in the body of the Scaffold.

I thought I could resolve the issue by doing this:

```<code>body: isUserAnAdmin().then((value) {
          value == true ? AdminPage() : PatientPage();
        })
</code>```

But I get an error that states:

```<code>The argument type 'Future<Null>' can't be assigned to the parameter type 'Widget'.
</code>```

Any idea on how I can resolve this?

答:
In order to use Future, u need to use await. But usually in widget, we use FutureBuilder instead:</p>

```<code> Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text("hemlp"),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: GestureDetector(
                child: Icon(Icons.exit_to_app),
                onTap: () async => await Auth.logoutUser().then(
                    (value) => Navigator.pushNamed(context, '/SignInPage')),
              ),
            )
          ],
        ),
        body: FutureBuilder<bool>(
          future: isUserAnAdmin(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.hasData) {
             if(snapshot.data == true) {
               return AdminPage();
             } else {
               return PatientPage();
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        }
);
  }
</code>```

Body:
I want to decide what content is displayed in the screen on the basis of a boolean variable called isAdmin. The value for this field is fetched from firestore.

Here's what I got so far:

Future<bool> isUserAnAdmin() async {
    var snap = await Firestore.instance
        .collection("Users")
        .document(UserSingleton().fireUser.uid)
        .get();
    UserSingleton().user = User.fromJson(snap.data);
    return UserSingleton().user.isAdmin;
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text("hemlp"),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: GestureDetector(
                child: Icon(Icons.exit_to_app),
                onTap: () async => await Auth.logoutUser().then(
                    (value) => Navigator.pushNamed(context, '/SignInPage')),
              ),
            )
          ],
        ),
        body: isUserAnAdmin() == true ? AdminPage() : PatientPage());
  }

The problem is that I'm always routed to PatientPage(), irrespective of the value of isAdmin. I suspect that this is happening because it isn't waiting for the value returned by isUserAnAdmin(). I thought I could just await isUserAnAdmin(), but I can't use await in the body of the Scaffold.

I thought I could resolve the issue by doing this:

body: isUserAnAdmin().then((value) {
          value == true ? AdminPage() : PatientPage();
        })

But I get an error that states:

The argument type 'Future<Null>' can't be assigned to the parameter type 'Widget'.

Any idea on how I can resolve this?

Body:
In order to use Future, u need to use await. But usually in widget, we use FutureBuilder instead:

 Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text("hemlp"),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: GestureDetector(
                child: Icon(Icons.exit_to_app),
                onTap: () async => await Auth.logoutUser().then(
                    (value) => Navigator.pushNamed(context, '/SignInPage')),
              ),
            )
          ],
        ),
        body: FutureBuilder<bool>(
          future: isUserAnAdmin(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.hasData) {
             if(snapshot.data == true) {
               return AdminPage();
             } else {
               return PatientPage();
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        }
);
  }


问:
How to detect Android OS from a Python script?
I am running a python script in a termux environment on an Android device and I would like to be able to detect that the OS is Android.

The traditional approaches don't work:

```<code>>>> import platform
>>> import sys
>>> print(platform.system())
'Linux'
>>> print(sys.platform)
'linux'
>>> print(platform.release())
'4.14.117-perf+'
>>> print(platform.platform())
'Linux-4.14.117-perf+-aarch64-with-libc'
</code>```

What other ootb options are available?

An apparently useful option is platform.machine() which returns armv8 — this is more than just 'Linux' yet it's just the architecture, and not the OS, and it might return a false positive for example on a raspberry pi or other arm-based systems.

答:
I tried os.uname() without success. So I may suggest using subprocess since uname -o returns b'Android\n'.

Here is a simple check for Android:

```<code>import subprocess
subprocess.check_output(['uname', '-o']).strip() == b'Android'
</code>```

Body:
I am running a python script in a termux environment on an Android device and I would like to be able to detect that the OS is Android.

The traditional approaches don't work:

>>> import platform
>>> import sys
>>> print(platform.system())
'Linux'
>>> print(sys.platform)
'linux'
>>> print(platform.release())
'4.14.117-perf+'
>>> print(platform.platform())
'Linux-4.14.117-perf+-aarch64-with-libc'

What other ootb options are available?

An apparently useful option is platform.machine() which returns armv8 — this is more than just 'Linux' yet it's just the architecture, and not the OS, and it might return a false positive for example on a raspberry pi or other arm-based systems.

Body:
I tried os.uname() without success. So I may suggest using subprocess since uname -o returns b'Android\n'.

Here is a simple check for Android:

import subprocess
subprocess.check_output(['uname', '-o']).strip() == b'Android'