问:
Multiple geom_smooth at differing thresholds
I would like to make a plot that has multiple geom_smooth(method="loess") lines for differing thresholds, but I'm having some issues.

Specifically, I want a geom_smooth() line for the all points >1 standard deviation (SD) or < -1 SD (which includes -/+2SD), one for <-2SD and >2SD, and one with all the points together. However, I'm running into an issue where it is only doing the smooth for the data within each category (i.e. greater than 1 SD but less than 2 SD.

I have made some toy data here:

```<code>#test data
a <- c(rnorm(10000, mean=0, sd = 1))
b <- c(rnorm(10000, mean=0, sd = 1))

test <- as.data.frame(cbind(a,b))

test3$Thresholds <- cut(test$a, breaks = c(-Inf,-2*sd(test$a),-sd(test$a),0,sd(test$a), 2*sd(test$a), Inf),
                                 labels = c("2_SD+", "1_SD", "0_SD","0_SD", "1_SD", "2_SD+"))

plot <- ggplot(test3, aes(x=b, y=a, color=Thresholds, alpha = 0.25, legend = F)) + geom_point() + geom_smooth(method="loess")
</code>```

This creates the following plot:

Does anyone have any suggestions?

答:
If you want smoothing done for different quantities of x and y you have to manipulate the data component...

library(ggplot2)
library(dplyr)

#test data
a <- c(rnorm(10000, mean=0, sd = 1))
b <- c(rnorm(10000, mean=0, sd = 1))

test <- as.data.frame(cbind(a,b))

test$Thresholds <- cut(test$a, breaks = c(-Inf,-2*sd(test$a),-sd(test$a),0,sd(test$a), 2*sd(test$a), Inf),
                        labels = c("2_SD+", "1_SD", "0_SD","0_SD", "1_SD", "2_SD+"))

ggplot(test, aes(x=b, y=a)) +
geom_point() +
  # just 2
  geom_smooth(data = test %>% filter(Thresholds == "2_SD+"), method="loess") +
  # 1 and 2
  geom_smooth(data = test %>% filter(Thresholds == "1_SD" | Thresholds == "2_SD+" ),  method="loess", color = "yellow") +
  #all
  geom_smooth(data = test,  method="loess", color = "red")
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'
```

Body:
I would like to make a plot that has multiple geom_smooth(method="loess") lines for differing thresholds, but I'm having some issues.

Specifically, I want a geom_smooth() line for the all points >1 standard deviation (SD) or < -1 SD (which includes -/+2SD), one for <-2SD and >2SD, and one with all the points together. However, I'm running into an issue where it is only doing the smooth for the data within each category (i.e. greater than 1 SD but less than 2 SD.

I have made some toy data here:

#test data
a <- c(rnorm(10000, mean=0, sd = 1))
b <- c(rnorm(10000, mean=0, sd = 1))

test <- as.data.frame(cbind(a,b))

test3$Thresholds <- cut(test$a, breaks = c(-Inf,-2*sd(test$a),-sd(test$a),0,sd(test$a), 2*sd(test$a), Inf),
                                 labels = c("2_SD+", "1_SD", "0_SD","0_SD", "1_SD", "2_SD+"))

plot <- ggplot(test3, aes(x=b, y=a, color=Thresholds, alpha = 0.25, legend = F)) + geom_point() + geom_smooth(method="loess")

This creates the following plot:

Does anyone have any suggestions?


来源: stackexchange

问:
Parsing & Filtering JSON data from API into C# application
My goal is to retrieve JSON data from "The virus tracker" API and parse it into a label. This is for my IB personal project so I just started learning c#. Fount this old code and tried fixing it, it worked with basic GET API's but it doesn't work with the one I'm using. (English not my main language)

POSTMAN RESPONSE

```<code>{
   "results": [
      {
         "total_cases": 5954607,
         "total_recovered": 2622507,
         "total_unresolved": 2255875,
         "total_deaths": 363208,
         "total_new_cases_today": 53700,
         "total_new_deaths_today": 1659,
         "total_active_cases": 45257,
         "total_serious_cases": 2698001,
         "total_affected_countries": 213,
         "source": {
            "url": "https://thevirustracker.com/"
         }
      }
   ],
   "stat": "ok"
}
</code>```

C# CODE

```<code>//Creating Client connection
        RestClient restClient = new RestClient("https://thevirustracker.com/free-api?global=stats");

        //Creating request to get data from server
        RestRequest restRequest = new RestRequest("total_cases", Method.GET);

        // Executing request to server and checking server response to the it
        IRestResponse restResponse = restClient.Execute(restRequest);

        // Extracting output data from received response
        string response = restResponse.Content;

        // Parsing JSON content into element-node JObject
        var jObject = JObject.Parse(restResponse.Content);

        //Extracting Node element using Getvalue method
        string cases = jObject.GetValue("total_cases").ToString();
        label1.Text = (cases);
</code>```

ERROR

```<code>An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
</code>```

My final goal with this code is that label1 says "5954607"

Remember that I'm really new to this so if you can explain the changes you made to the code ill really appreciate it.

答:
You're not using RestRequest correctly or initialized the RestClient wrongly.

If that url you used in the RestClient is the whole url then you don't need a "resource" in the RestRequest.

Due to that mistake you got an HTML response indicated by the error

Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

The value of restResponse.Content probably starts with <html and that is not  valid JSON.

The Json payload is a bit more complex then you coded for. The results object holds an array with an object that has your stat property.

Putting these fixes together gives you this code.

```<code>RestClient restClient = new RestClient("https://thevirustracker.com/free-api?global=stats");

//Creating request to get data from server
RestRequest restRequest = new RestRequest(null, DataFormat.Json);

// Executing request to server and checking server response to the it
IRestResponse restResponse = restClient.Execute(restRequest);

// Extracting output data from received response
string response = restResponse.Content;

// Parsing JSON content into element-node JObject
var jObject = JObject.Parse(restResponse.Content);

//Extracting
// the object has a results property
// that is an array with one item (zero-based)
// on index 0 there is an object
// that has a property total_cases
string cases = (string) jObject["results"][0]["total_cases"];
label1.Text = (cases);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My goal is to retrieve JSON data from "The virus tracker" API and parse it into a label. This is for my IB personal project so I just started learning c#. Fount this old code and tried fixing it, it worked with basic GET API's but it doesn't work with the one I'm using. (English not my main language)

POSTMAN RESPONSE

{
   "results": [
      {
         "total_cases": 5954607,
         "total_recovered": 2622507,
         "total_unresolved": 2255875,
         "total_deaths": 363208,
         "total_new_cases_today": 53700,
         "total_new_deaths_today": 1659,
         "total_active_cases": 45257,
         "total_serious_cases": 2698001,
         "total_affected_countries": 213,
         "source": {
            "url": "https://thevirustracker.com/"
         }
      }
   ],
   "stat": "ok"
}

C# CODE

//Creating Client connection
        RestClient restClient = new RestClient("https://thevirustracker.com/free-api?global=stats");

        //Creating request to get data from server
        RestRequest restRequest = new RestRequest("total_cases", Method.GET);

        // Executing request to server and checking server response to the it
        IRestResponse restResponse = restClient.Execute(restRequest);

        // Extracting output data from received response
        string response = restResponse.Content;

        // Parsing JSON content into element-node JObject
        var jObject = JObject.Parse(restResponse.Content);

        //Extracting Node element using Getvalue method
        string cases = jObject.GetValue("total_cases").ToString();
        label1.Text = (cases);

ERROR

An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

My final goal with this code is that label1 says "5954607"

Remember that I'm really new to this so if you can explain the changes you made to the code ill really appreciate it.

Body:
You're not using RestRequest correctly or initialized the RestClient wrongly.

If that url you used in the RestClient is the whole url then you don't need a "resource" in the RestRequest.

Due to that mistake you got an HTML response indicated by the error

Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

The value of restResponse.Content probably starts with <html and that is not  valid JSON.

The Json payload is a bit more complex then you coded for. The results object holds an array with an object that has your stat property.

Putting these fixes together gives you this code.

RestClient restClient = new RestClient("https://thevirustracker.com/free-api?global=stats");

//Creating request to get data from server
RestRequest restRequest = new RestRequest(null, DataFormat.Json);

// Executing request to server and checking server response to the it
IRestResponse restResponse = restClient.Execute(restRequest);

// Extracting output data from received response
string response = restResponse.Content;

// Parsing JSON content into element-node JObject
var jObject = JObject.Parse(restResponse.Content);

//Extracting
// the object has a results property
// that is an array with one item (zero-based)
// on index 0 there is an object
// that has a property total_cases
string cases = (string) jObject["results"][0]["total_cases"];
label1.Text = (cases);


问:
header file and standard library
I am new to programming. learning C as of now. I understand that header file only contains the declarations and function prototypes, not the functions themselves. Am I correct?

I understand that Library is a single file that contains different object codes. Are these object codes necessarily written only in C language or other languages can also be used to generate such object codes?

On linking, does the entire library file get attached to the executable or just the object codes declared in the header file?

答:
The header file usually contains just declarations and prototypes, but in modern C it can contain "static inline" functions along with their definitions.  (And in C++, it is common for template classes to have their implementations in the header file, but do not worry about that for now...)

Objects in a library can be written in any language; as long as they obey "C linkage" (essentially, calling and naming conventions at the assembly level) they can call and be called from C functions.  It is not uncommon for a few performance-critical library functions to be written in assembly language, for instance.

The answer to your last question depends on the linker.  I believe GNU ld includes all of the functions from all .o files any of whose functions is referenced, but to be honest, I am not even sure.  Most libraries you link against are "shared libraries" anyway, which means the answer to your question does not even matter.  (Actually, it does not matter much in general, as the OS will only load pages from disk when they are actually accessed.  So the size of your executable on disk and the amount of RAM it takes while running can be very, very different.)

ContentLicense: CC BY-SA 3.0

Title: header file and standard library


问:
What does the term 'binding' mean in JS?
Please clarify for me what the term binding means in JavaScript. I've started to read the book 'Eloquent JS' and there are lots of occurrences of this word. Does it just mean variable? Here are few examples from the book:

So if you know that the property you are interested in is called color, you say value.color. If you want to extract the property named by the value held in the binding i, you say value[i].Property names are strings. They can be any string, but the dot notation works only with names that look like valid binding names.

Bindings can also be changeable or constant, but this is separate from the way their values behave. Even though number values don’t change, you can use a let binding to keep track of a changing number by changing the value the binding points at. Similarly, though a const binding to an object can itself not be changed and will continue to point at the same object, the contents of that object might change.

答:
Binding is a general term to mean that your symbol or variable points to some location in memory. This is also illustrating the principle in JavaScript that even when you declare an object using const, you can still manipulate the properties of that object. Only the reference to the object itself cannot be redefined.

So you can't say myObj = {greeting: "Hello Stack Overflow"} and then myObj = someOtherObj. But you can say myObj.greeting = "Beep Boop"


答:
The attempt you made uses data.table but you don't refer to data.table. Have you done library(data.table) before ?

I think it should rather be :

```<code>df_joined = df_bestquotes[df_transactions, on=.(day, time), roll = TRUE]
</code>```

But I cannot test without the objects. Does it work ? roll="nearest" doesn't give you the previous best quotes but the nearest.

EDIT : Thanks for the objects, I checked, that works for me :

```<code>library(data.table)
dfb <- fread("df_bestquotes.csv", dec=",")
dft <- fread("df_transactions.csv", dec = ",")
dfb[, c("day2", "time2") := .(day,time)] # duplicated to keep track of the best quotes days
joinedDf <- dfb [dft, on=.(day, time), roll = +Inf]
</code>```

It puts NA when there is no best quotes for the day. If you want to roll across days, I suggest you create a unique measure of time. I don't know exactly what time is. Considering the units of time is seconds :

```<code>dfb[, uniqueTime := day + time/(60*60*24)]
dft[, uniqueTime := day + time/(60*60*24)]
joinedDf <- dfb [dft, on=.(uniqueTime), roll = +Inf]
</code>```

This works even if time is not seconds, only the ranking is important in this case.

Title: Merge two data frames in R by the closest default options, not by excess

Body:
i have two dataframes:

df_bestquotes

df_transactions

df_transactions:

day time        vol price   buy ask     bid
1   43688,08    100 195,8   1   195,8   195,74
1   56357,34    20  192,87  1   192,87  192,86
1   57576,14    14  192,48  -1  192,48  192,46
2   50468,29    3   193,83  1   193,86  193,77
2   56107,54    11  194,17  -1  194,2   194,16
7   42549,66    100 188,81  -1  188,85  188,78
7   42724,38    200 188,62  -1  188,66  188,61
7   48924,66    5   189,59  -1  189,62  189,59
8   48950,14    52  187,66  -1  187,7   187,66
9   36242,86    89  186,61  1   186,62  186,56
9   53910,46    1   189,81  -1  189,87  189,81
10  47041,94    15  187,87  -1  187,88  187,86
13  34380,73    87  187,29  -1  187,42  187,27
13  36037,18    100 188,94  1   188,95  188,94
14  46644,64    100 189,29  -1  189,34  189,29
14  57571,12    52  190,03  1   190,03  190
15  36418,71    45  192,07  1   192,07  192,04
15  37223,77    100 191,09  -1  191,07  191,06
17  37245,59    100 186,45  -1  186,47  186,45
23  34200,39    50  189,29  -1  189,29  189,27
24  40294,73    60  193,52  -1  193,54  193,5
29  52813,68    5   202,99  -1  203,01  202,99
29  55279,13    93  203,97  -1  203,98  203,9
30  51356,91    68  204,41  -1  204,45  204,4
30  53530,24    40  204,14  -1  204,18  204,14

df_bestquotes:

day time       best_ask best_bid
1   51384,613   31,78   31,75
1   56593,74    31,6    31,55
3   40568,217   31,36   31,32
7   39169,237   31,34   31,28
8   44715,713   31,2    31,17
8   53730,707   31,24   31,19
8   55851,75    31,17   31,14
10  49376,267   31,06   30,99
16  48610,483   30,75   30,66
16  57360,917   30,66   30,64
17  53130,717   30,39   30,32
20  46353,133   30,72   30,63
23  46429,67    29,7    29,64
24  37627,727   29,81   29,63
24  46354,647   29,92   29,77
24  53863,69    30,04   29,93
24  53889,923   30,03   29,95
24  59047,223   29,99   29,2
28  39086,407   30,87   30,83
28  41828,703   30,87   30,8
28  50489,367   30,99   30,87
29  54264,467   30,97   30,85
30  34365,95    31,21   30,99
30  39844,357   31,06   31
30  57550,523   31,18   31,15

For each record of the df_transactions, from the day and time, I need to find the best_ask and the best_bid that was just before that moment, and incorporate this information to df_transactions.

df_joined: df_transactions + df_bestquotes

day time        vol price   buy ask     bid     best_ask   best_bid
1   43688,08    100 195,8   1   195,8   195,74
1   56357,34    20  192,87  1   192,87  192,86
1   57576,14    14  192,48  -1  192,48  192,46
2   50468,29    3   193,83  1   193,86  193,77
2   56107,54    11  194,17  -1  194,2   194,16
7   42549,66    100 188,81  -1  188,85  188,78
7   42724,38    200 188,62  -1  188,66  188,61
7   48924,66    5   189,59  -1  189,62  189,59
8   48950,14    52  187,66  -1  187,7   187,66
9   36242,86    89  186,61  1   186,62  186,56
9   53910,46    1   189,81  -1  189,87  189,81
10  47041,94    15  187,87  -1  187,88  187,86
13  34380,73    87  187,29  -1  187,42  187,27
13  36037,18    100 188,94  1   188,95  188,94
14  46644,64    100 189,29  -1  189,34  189,29
14  57571,12    52  190,03  1   190,03  190
15  36418,71    45  192,07  1   192,07  192,04
15  37223,77    100 191,09  -1  191,07  191,06
17  37245,59    100 186,45  -1  186,47  186,45
23  34200,39    50  189,29  -1  189,29  189,27
24  40294,73    60  193,52  -1  193,54  193,5
29  52813,68    5   202,99  -1  203,01  202,99
29  55279,13    93  203,97  -1  203,98  203,9
30  51356,91    68  204,41  -1  204,45  204,4
30  53530,24    40  204,14  -1  204,18  204,14

I have tried with the next code, but it doesn't work:

library(data.table)
df_joined = df_bestquotes[df_transactions, on="time", roll = "nearest"]

Here are the real files with a lot more records, the ones I put before are an example of only 25 records.

df_transactions_original

df_bestquotes_original

And my code in R:

matching.R

Any suggestions on how to get it? Thanks a lot, guys.

Body:
The attempt you made uses data.table but you don't refer to data.table. Have you done library(data.table) before ?

I think it should rather be :

df_joined = df_bestquotes[df_transactions, on=.(day, time), roll = TRUE]

But I cannot test without the objects. Does it work ? roll="nearest" doesn't give you the previous best quotes but the nearest.

EDIT : Thanks for the objects, I checked, that works for me :

library(data.table)
dfb <- fread("df_bestquotes.csv", dec=",")
dft <- fread("df_transactions.csv", dec = ",")
dfb[, c("day2", "time2") := .(day,time)] # duplicated to keep track of the best quotes days
joinedDf <- dfb [dft, on=.(day, time), roll = +Inf]

It puts NA when there is no best quotes for the day. If you want to roll across days, I suggest you create a unique measure of time. I don't know exactly what time is. Considering the units of time is seconds :

dfb[, uniqueTime := day + time/(60*60*24)]
dft[, uniqueTime := day + time/(60*60*24)]
joinedDf <- dfb [dft, on=.(uniqueTime), roll = +Inf]

This works even if time is not seconds, only the ranking is important in this case.


问:
Django cache does not get refreshed
I've added a simple caching to my web application and when I delete or add new object the cache does not get refreshed after the peroid of time (2 minutes) that I've set.

It looks like it froze. When I restart my application then it gets refreshed.

I tried it on memached and locmemcache.

```<code>INDEX_LIST_CACHE_KEY = "index_list_cache_key"

class IndexView(BaseView):
    queryset = Advert.objects.all().select_related('category', 'location')[:25]
    template_name = "adverts/category_view.html"

    def get_queryset(self):
        queryset = cache.get(INDEX_LIST_CACHE_KEY)
        if queryset is None:
            queryset = self.queryset
            cache.set(INDEX_LIST_CACHE_KEY, queryset, 2 * 60)
        return queryset
</code>```

Why caching behaves like that in this project?

Edit - settings.py:

for locmemcache

```<code>CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'oglos-cache'
    }
}
</code>```

for memcached

```<code>CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}
</code>```

答:
I had the same problem, I resolved it by forcing django to not cache my view: </p>

```<code>from django.views.decorators.cache import cache_page
urlpatterns = [
    path('some_path', cache_page(0)(views.MyViewList.as_view()), name='view-list')
]
</code>```

Title: Django cache does not get refreshed

Body:
I've added a simple caching to my web application and when I delete or add new object the cache does not get refreshed after the peroid of time (2 minutes) that I've set.

It looks like it froze. When I restart my application then it gets refreshed.

I tried it on memached and locmemcache.

INDEX_LIST_CACHE_KEY = "index_list_cache_key"

class IndexView(BaseView):
    queryset = Advert.objects.all().select_related('category', 'location')[:25]
    template_name = "adverts/category_view.html"

    def get_queryset(self):
        queryset = cache.get(INDEX_LIST_CACHE_KEY)
        if queryset is None:
            queryset = self.queryset
            cache.set(INDEX_LIST_CACHE_KEY, queryset, 2 * 60)
        return queryset

Why caching behaves like that in this project?

Edit - settings.py:

for locmemcache

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'oglos-cache'
    }
}

for memcached

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

Body:
I had the same problem, I resolved it by forcing django to not cache my view:

from django.views.decorators.cache import cache_page
urlpatterns = [
    path('some_path', cache_page(0)(views.MyViewList.as_view()), name='view-list')
]


问:
Reading txt file in java, program skipping the first line
My program is skipping the first line of my .txt file. Here is where my code is supposed to read from the .txt file.

static int getPints(int[] pints) throws IOException {
    Scanner inputFile = new Scanner(new File("BloodInFile.txt"));
    int count = 0;
    while (inputFile.hasNext()) {
        pints[count] = inputFile.nextInt();
        count++;
    }
    return pints[count];
}
```

<p>It should be reading 7 integers, but I only get 6 of them to be read.
The rest of the code works, but I am not sure how to get it to read the first integer.</p>

<p>This is the rest of my code:</p>

<pre class="lang-java prettyprint-override"><code>static int getPints(int[] pints) throws IOException {
    Scanner inputFile = new Scanner(new File("BloodInFile.txt"));
    int count = 0;
    while (inputFile.hasNext()) {
        pints[count] = inputFile.nextInt();
        count++;
    }
    inputFile.close();
    return pints[count];
}

static double getAverage(int pints[], int MAX_HOURS) {
    int counter;
    double totalPints = 1;
    double averagePints;
    for (counter = 1; counter < MAX_HOURS - 1; counter++) {
        System.out.println("pints:" + pints[counter]);
        totalPints = totalPints + pints[counter];
    }
    averagePints = totalPints / (MAX_HOURS - 2);
    System.out.println("Total pints: " + totalPints);
    return averagePints;
}

static double getHigh(int pints[], int MAX_HOURS) {
    int index = 1;
    double highest = pints[index];
    for (index = 1; index < MAX_HOURS - 1; index++) {
        if (pints[index] > highest) {
            highest = pints[index];
        }
    }
    return highest;
}

static double getLow(int pints[], int MAX_HOURS) {
    int index = 1;
    double lowest = pints[index];
    for (index = 1; index < MAX_HOURS - 1; index++) {
        if (pints[index] < lowest) {
            lowest = pints[index];
        }
    }
    return lowest;
}
</code>```

答:
I did it once just like this, maybe that works for you too    </p>

```<code>public static List<String> get16TeamsFromTxt() throws IOException {
    Path currentRelativePath = Paths.get("");
    String s1 = currentRelativePath.toAbsolutePath().normalize().toString();

    Scanner s = new Scanner(new File(s1+"/16.txt"));
    ArrayList<String> list = new ArrayList<String>();
    while (s.hasNextLine()){
        list.add(s.nextLine());
    }
    s.close();

    return list;

}
</code>```

<p>This way you should get the list with all of your numbers. Mine is with string, but should work with int.  </p>

Body:
My program is skipping the first line of my .txt file. Here is where my code is supposed to read from the .txt file.

static int getPints(int[] pints) throws IOException {
    Scanner inputFile = new Scanner(new File("BloodInFile.txt"));
    int count = 0;
    while (inputFile.hasNext()) {
        pints[count] = inputFile.nextInt();
        count++;
    }
    return pints[count];
}

It should be reading 7 integers, but I only get 6 of them to be read.
The rest of the code works, but I am not sure how to get it to read the first integer.

This is the rest of my code:

static int getPints(int[] pints) throws IOException {
    Scanner inputFile = new Scanner(new File("BloodInFile.txt"));
    int count = 0;
    while (inputFile.hasNext()) {
        pints[count] = inputFile.nextInt();
        count++;
    }
    inputFile.close();
    return pints[count];
}

static double getAverage(int pints[], int MAX_HOURS) {
    int counter;
    double totalPints = 1;
    double averagePints;
    for (counter = 1; counter < MAX_HOURS - 1; counter++) {
        System.out.println("pints:" + pints[counter]);
        totalPints = totalPints + pints[counter];
    }
    averagePints = totalPints / (MAX_HOURS - 2);
    System.out.println("Total pints: " + totalPints);
    return averagePints;
}

static double getHigh(int pints[], int MAX_HOURS) {
    int index = 1;
    double highest = pints[index];
    for (index = 1; index < MAX_HOURS - 1; index++) {
        if (pints[index] > highest) {
            highest = pints[index];
        }
    }
    return highest;
}

static double getLow(int pints[], int MAX_HOURS) {
    int index = 1;
    double lowest = pints[index];
    for (index = 1; index < MAX_HOURS - 1; index++) {
        if (pints[index] < lowest) {
            lowest = pints[index];
        }
    }
    return lowest;
}

Body:
I did it once just like this, maybe that works for you too

public static List<String> get16TeamsFromTxt() throws IOException {
    Path currentRelativePath = Paths.get("");
    String s1 = currentRelativePath.toAbsolutePath().normalize().toString();

    Scanner s = new Scanner(new File(s1+"/16.txt"));
    ArrayList<String> list = new ArrayList<String>();
    while (s.hasNextLine()){
        list.add(s.nextLine());
    }
    s.close();

    return list;

}

This way you should get the list with all of your numbers. Mine is with string, but should work with int.


问:
How can I pause thread?
Relevant code:

```<code>private static Thread m_thread = null;
private static Boolean m_stop = false;

public static Boolean Start(SearcherParams pars)
{
    Boolean success = false;

    if (m_thread == null)
    {
        // Perform a reset of all variables,
        // to ensure that the state of the searcher is the same on every new start:
        ResetVariables();

        // Remember the parameters:
        m_pars = pars;

        // Start searching for FileSystemInfos that match the parameters:
        m_thread = new Thread(new ThreadStart(SearchThread));
        m_thread.Start();

        success = true;
    }

    return success;
}

private static void SearchThread()
{
    Boolean success = true;
    String errorMsg = "";

    // Search for FileSystemInfos that match the parameters:
    if ((m_pars.SearchDir.Length >= 3) && (Directory.Exists(m_pars.SearchDir)))
    {
        if (m_pars.FileNames.Count > 0)
        {
            // Convert the string to search for into bytes if necessary:
            if (m_pars.ContainingChecked)
            {
                if (m_pars.ContainingText != "")
                {
                    try
                    {
                        m_containingBytes =
                            m_pars.Encoding.GetBytes(m_pars.ContainingText);
                    }
                    catch (Exception)
                    {
                        success = false;
                        errorMsg = "The string\r\n" + m_pars.ContainingText +
                                    "\r\ncannot be converted into bytes.";
                    }
                }
                else
                {
                    success = false;
                    errorMsg = "The string to search for must not be empty.";
                }
            }

            if (success)
            {
                // Get the directory info for the search directory:
                DirectoryInfo dirInfo = null;

                try
                {
                    dirInfo = new DirectoryInfo(m_pars.SearchDir);
                }
                catch (Exception ex)
                {
                    success = false;
                    errorMsg = ex.Message;
                }

                if (success)
                {
                    // Search the directory (maybe recursively),
                    // and raise events if something was found:
                    SearchDirectory(dirInfo);
                }
            }
        }
        else
        {
            success = false;
            errorMsg = "Please enter one or more filenames to search for.";
        }
    }
    else
    {
        success = false;
        errorMsg = "The directory\r\n" + m_pars.SearchDir + "\r\ndoes not exist.";
    }

    // Remember the thread has ended:
    m_thread = null;

    // Raise an event:
    if (ThreadEnded != null)
    {
        ThreadEnded(new ThreadEndedEventArgs(success, errorMsg));
    }
}

private static void SearchDirectory(DirectoryInfo dirInfo)
{
    if (!m_stop)
    {
        try
        {
            foreach (String fileName in m_pars.FileNames)
            {
                FileSystemInfo[] infos = dirInfo.GetFileSystemInfos(fileName);

                foreach (FileSystemInfo info in infos)
                {
                    if (m_stop)
                    {
                        break;
                    }

                    if (MatchesRestrictions(info))
                    {
                        // We have found a matching FileSystemInfo,
                        // so let's raise an event:
                        if (FoundInfo != null)
                        {
                            FoundInfo(new FoundInfoEventArgs(info));
                        }
                    }
                }
            }

            if (m_pars.IncludeSubDirsChecked)
            {
                DirectoryInfo[] subDirInfos = dirInfo.GetDirectories();

                foreach (DirectoryInfo subDirInfo in subDirInfos)
                {
                    if (m_stop)
                    {
                        break;
                    }

                    // Recursion:
                    SearchDirectory(subDirInfo);
                }
            }
        }
        catch (Exception)
        {
        }
    }
}
</code>```

The stop is working fine I wanted to add also a pause button to pause and resume the thread.
I added a button click event but how do I make the pause/resume actions and where?

This is a link for the complete code : https://pastebin.com/fYYnHBB6

答:
You can use the ManualResetEvent object.

Here is the simplified version.

In your class, create the object:

```<code>public static ManualResetEvent _mrsevent = new ManualResetEvent(false);
</code>```

In your thread function, as part of the loops that search for files/directories:

```<code>private static void SearchThread()
{
   foreach (String fileName in m_pars.FileNames)
   {
      _mrsevent.WaitOne();
   }
}
</code>```

From outside the thread you can call:

a) _mrsevent.Set(); // resume the thread.

b) _mrsevent.Reset(); // pause

Title: How can I pause thread?

Body:
Relevant code:

private static Thread m_thread = null;
private static Boolean m_stop = false;

public static Boolean Start(SearcherParams pars)
{
    Boolean success = false;

    if (m_thread == null)
    {
        // Perform a reset of all variables,
        // to ensure that the state of the searcher is the same on every new start:
        ResetVariables();

        // Remember the parameters:
        m_pars = pars;

        // Start searching for FileSystemInfos that match the parameters:
        m_thread = new Thread(new ThreadStart(SearchThread));
        m_thread.Start();

        success = true;
    }

    return success;
}

private static void SearchThread()
{
    Boolean success = true;
    String errorMsg = "";

    // Search for FileSystemInfos that match the parameters:
    if ((m_pars.SearchDir.Length >= 3) && (Directory.Exists(m_pars.SearchDir)))
    {
        if (m_pars.FileNames.Count > 0)
        {
            // Convert the string to search for into bytes if necessary:
            if (m_pars.ContainingChecked)
            {
                if (m_pars.ContainingText != "")
                {
                    try
                    {
                        m_containingBytes =
                            m_pars.Encoding.GetBytes(m_pars.ContainingText);
                    }
                    catch (Exception)
                    {
                        success = false;
                        errorMsg = "The string\r\n" + m_pars.ContainingText +
                                    "\r\ncannot be converted into bytes.";
                    }
                }
                else
                {
                    success = false;
                    errorMsg = "The string to search for must not be empty.";
                }
            }

            if (success)
            {
                // Get the directory info for the search directory:
                DirectoryInfo dirInfo = null;

                try
                {
                    dirInfo = new DirectoryInfo(m_pars.SearchDir);
                }
                catch (Exception ex)
                {
                    success = false;
                    errorMsg = ex.Message;
                }

                if (success)
                {
                    // Search the directory (maybe recursively),
                    // and raise events if something was found:
                    SearchDirectory(dirInfo);
                }
            }
        }
        else
        {
            success = false;
            errorMsg = "Please enter one or more filenames to search for.";
        }
    }
    else
    {
        success = false;
        errorMsg = "The directory\r\n" + m_pars.SearchDir + "\r\ndoes not exist.";
    }

    // Remember the thread has ended:
    m_thread = null;

    // Raise an event:
    if (ThreadEnded != null)
    {
        ThreadEnded(new ThreadEndedEventArgs(success, errorMsg));
    }
}

private static void SearchDirectory(DirectoryInfo dirInfo)
{
    if (!m_stop)
    {
        try
        {
            foreach (String fileName in m_pars.FileNames)
            {
                FileSystemInfo[] infos = dirInfo.GetFileSystemInfos(fileName);

                foreach (FileSystemInfo info in infos)
                {
                    if (m_stop)
                    {
                        break;
                    }

                    if (MatchesRestrictions(info))
                    {
                        // We have found a matching FileSystemInfo,
                        // so let's raise an event:
                        if (FoundInfo != null)
                        {
                            FoundInfo(new FoundInfoEventArgs(info));
                        }
                    }
                }
            }

            if (m_pars.IncludeSubDirsChecked)
            {
                DirectoryInfo[] subDirInfos = dirInfo.GetDirectories();

                foreach (DirectoryInfo subDirInfo in subDirInfos)
                {
                    if (m_stop)
                    {
                        break;
                    }

                    // Recursion:
                    SearchDirectory(subDirInfo);
                }
            }
        }
        catch (Exception)
        {
        }
    }
}

The stop is working fine I wanted to add also a pause button to pause and resume the thread.
I added a button click event but how do I make the pause/resume actions and where?

This is a link for the complete code : https://pastebin.com/fYYnHBB6

Body:
You can use the ManualResetEvent object.

Here is the simplified version.

In your class, create the object:

public static ManualResetEvent _mrsevent = new ManualResetEvent(false);

In your thread function, as part of the loops that search for files/directories:

private static void SearchThread()
{
   foreach (String fileName in m_pars.FileNames)
   {
      _mrsevent.WaitOne();
   }
}

From outside the thread you can call:

a) _mrsevent.Set(); // resume the thread.

b) _mrsevent.Reset(); // pause


问:
Certificate being rejected by Apple
While configuring certificate for Push Notification on my ios build of cordova project using OneSignal, the certificate is getting rejected every time I'm trying to configure it.

I've followed steps mentioned in https://documentation.onesignal.com/docs/generate-an-ios-push-certificate

I've tried using OneSignal Provisionator Tool, and generated certificate using KeyChain access as well without any result.

答:
Ok, I contacted the support and here is a troubleshoot for future reference:

1.With your newest certificate, try renaming it to something different than previous certificates and then uploading it again.

2.Also, some users have reported that their security software blocks this from uploading, please make sure that is not the case.

3.Please make sure you are uploading a .p12 Push Certificate and not a Distribution Certificate or anything else besides a .p12 Push Certificate.
Just click the "Choose File..." button if this is your first time uploading like this: https://imgur.com/a/JQQya
Or the "I'd like to replace my production .p12 certificate" check box if you are replacing the certificate like this: http://imgur.com/a/hRIqJ

4.You can generate one with OneSignal provisionator tool or if you have been and it is not working, you will need to try to generate one manually.
You can follow this Generate iOS certificate doc step by step to generate certificate, I followed it and uploaded it successfully.

If it is still not working, you can contact them providing the p12 cert to them with password and OneSignal AppID. they may upload it for you as soon as they can.

Title: Certificate being rejected by Apple


问:
How to use Poco to open a secure UDP socket
I am trying to migrate a system using ACE, which seems to be abandoned at this point.

I have been looking at Poco which seems to be an ideal solution. However for the project I want to be using both a TCP and a UDP socket (VoIP / Video Streaming). Ideally I would like them both to be using TLS by default.

SecureServerSocket and SecureStreamSocket seem to do this well for TCP, and seem to imply I could use SecureStreamSocketImpl for UDP (here) but I am not sure how? I can't seem to find an example of this being done anywhere.

On the github issues page for Poco there is an open ticket for using DTLS, which suggests it might not be possible.

EDIT: Any other suggestions of how best to secure UDP transmissions would be helpful as well.

答:
I found this while thinking the same thing. While I have not yet proven it though, I think that is just an erroneous/copy-pasted comment from elsewhere in poco. I have actually found a few things in Poco's handling of Datagrams where the comments (Which match the TCP class comments) do NOT match the implementation.

DTLS is the "Proper" way to secure a UDP socket, but POCO doesn't support it right now (And has a several year old ticket about adding the support... So does Asio)

I'm personally in the process of trying to get DTLS working either alongside or possibly inside of poco. It looks like a pain though.


问:
Align value labels in horizontal stacked bar plot (Matplotlib)
Using the following code, I've added value labels to the horizontal stacked bar plot in Matplotlib:

```<code>import pandas
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

def sumzip(*items):
    return [sum(values) for values in zip(*items)]

fig, ax = plt.subplots(figsize=(10,6))

N = 5
values1 = [130, 120, 170, 164, 155]
values2 = [120, 185, 162, 150, 153]
values3 = [100, 170, 160, 145, 150]

ind = np.arange(N) + .15
width = 0.3

rects1 = plt.barh(ind, values1, width, color='blue')
rects2 = plt.barh(ind, values2, width, left = sumzip(values1), color='green')
rects3 = plt.barh(ind, values3, width, left = sumzip(values1, values2), color='red')

extra_space = 0.15
ax.set_yticks(ind+width-extra_space)
ax.set_yticklabels( ('Label1', 'Label2', 'Label3', 'Label4', 'Label5') )
ax.yaxis.set_tick_params(length=0,labelbottom=True)

for i, v in enumerate(values1):
    plt.text(v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values2):
    plt.text(v * 1.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values3):
    plt.text(v * 2.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.show()
</code>```

And the code gives me the following result:

As you can see, the labels in green and red sections are not aligned properly. What to I need to do to correct this issue?

答:
I would replace all three for i,v loops with this:

```<code>for patch in ax.patches:
    x,y = patch.get_xy()
    w, h = patch.get_width(), patch.get_height()
    ax.text(x+w/2, y+h/2, str(w),
            ha='center', va='center',
            color='white', fontweight='bold', fontsize=10,
           )
</code>```

Output:

Body:
Using the following code, I've added value labels to the horizontal stacked bar plot in Matplotlib:

import pandas
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

def sumzip(*items):
    return [sum(values) for values in zip(*items)]

fig, ax = plt.subplots(figsize=(10,6))

N = 5
values1 = [130, 120, 170, 164, 155]
values2 = [120, 185, 162, 150, 153]
values3 = [100, 170, 160, 145, 150]

ind = np.arange(N) + .15
width = 0.3

rects1 = plt.barh(ind, values1, width, color='blue')
rects2 = plt.barh(ind, values2, width, left = sumzip(values1), color='green')
rects3 = plt.barh(ind, values3, width, left = sumzip(values1, values2), color='red')

extra_space = 0.15
ax.set_yticks(ind+width-extra_space)
ax.set_yticklabels( ('Label1', 'Label2', 'Label3', 'Label4', 'Label5') )
ax.yaxis.set_tick_params(length=0,labelbottom=True)

for i, v in enumerate(values1):
    plt.text(v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values2):
    plt.text(v * 1.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values3):
    plt.text(v * 2.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.show()

And the code gives me the following result:

As you can see, the labels in green and red sections are not aligned properly. What to I need to do to correct this issue?

Body:
I would replace all three for i,v loops with this:

for patch in ax.patches:
    x,y = patch.get_xy()
    w, h = patch.get_width(), patch.get_height()
    ax.text(x+w/2, y+h/2, str(w),
            ha='center', va='center',
            color='white', fontweight='bold', fontsize=10,
           )

Output:


问:
Typescript errors for function return types
I'm using Typescript with Node and am getting some errors I don't quite understand.

index.ts

```<code>import read_json_remote from './toolkit/read_json_remote';
const url: string = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson';
read_json_remote(url).then(data => {
    console.log(data.features);
})
.catch(err => {
    console.log(err);
});
</code>```

read_json_remote.ts

```<code>import got from 'got';
export default (url: string) => {
    return got(url).then((res: object) : object =>  {
        return JSON.parse(res.body);
    })
    .catch(err => {
        console.log(err);
    });
};
</code>```

VSCode shows an error on:

```<code>return JSON.parse(res.body);
</code>```

in read_json_remote.ts that says the property 'body' does not exist on the object 'res'.

When I console.log res, I see the 'body' property there, in accordance with what is in the Got documentation.

I'm obviously new to Typescript, what am I missing?

Thanks in advance.

答:
Api is returning response in JSON , so no need to use JSON.parse() .</p>

```<code>import got from 'got';
export default (url: string) => {
    return got(url).then((res: object) : object =>  {
        return res;
    })
    .catch(err => {
        console.log(err);
    });
};
</code>```

Body:
I'm using Typescript with Node and am getting some errors I don't quite understand.

index.ts

import read_json_remote from './toolkit/read_json_remote';
const url: string = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson';
read_json_remote(url).then(data => {
    console.log(data.features);
})
.catch(err => {
    console.log(err);
});

read_json_remote.ts

import got from 'got';
export default (url: string) => {
    return got(url).then((res: object) : object =>  {
        return JSON.parse(res.body);
    })
    .catch(err => {
        console.log(err);
    });
};

VSCode shows an error on:

return JSON.parse(res.body);

in read_json_remote.ts that says the property 'body' does not exist on the object 'res'.

When I console.log res, I see the 'body' property there, in accordance with what is in the Got documentation.

I'm obviously new to Typescript, what am I missing?

Thanks in advance.

Body:
Api is returning response in JSON , so no need to use JSON.parse() .

import got from 'got';
export default (url: string) => {
    return got(url).then((res: object) : object =>  {
        return res;
    })
    .catch(err => {
        console.log(err);
    });
};


问:
mocha and ts-node UnhandledPromiseRejectionWarning:TypeError: Cannot convert undefined or null to object
I am trying to setup ts-node with mocha however the test script always fails.

I have tried

```<code>mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ts,tsx}'
</code>```

and

```<code>mocha --require ts-node/register src/**/*.spec.ts
</code>```

Also I tried installing ts-node locally and globally but always this is the output

```<code>> project@1.0.0 test /home/moamen/foo/baz
> mocha --require ts-node/register src/**/*.spec.ts

(node:48106) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Object.help (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:240:22)
    at Object.self.showHelp (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:432:15)
    at Array.<anonymous> (/home/moamen/foo/baz/node_modules/mocha/lib/cli/cli.js:53:13)
    at Object.fail (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:41:17)
    at /home/moamen/foo/baz/node_modules/yargs/lib/command.js:246:36
(Use `node --trace-warnings ...` to show where the warning was created)
(node:48106) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:48106) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

and this is my tsconfig.json

```<code>{
    "compilerOptions": {
        "target": "es6" ,
        "module": "commonjs",
        "sourceMap": true ,
        "outDir": "dist" ,
        "strict": true ,
        "moduleResolution": "node" ,
        "esModuleInterop": true
        },
    "lib": ["es2015"]
}
</code>```

答: After seeing this example https://github.com/mochajs/mocha-examples/tree/master/packages/typescript. The problem was that I had typescript installed globally. This shouldn't have been a problem but it was.</p>

Body:
I am trying to setup ts-node with mocha however the test script always fails.

I have tried

mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ts,tsx}'

and

mocha --require ts-node/register src/**/*.spec.ts

Also I tried installing ts-node locally and globally but always this is the output

> project@1.0.0 test /home/moamen/foo/baz
> mocha --require ts-node/register src/**/*.spec.ts

(node:48106) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Object.help (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:240:22)
    at Object.self.showHelp (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:432:15)
    at Array.<anonymous> (/home/moamen/foo/baz/node_modules/mocha/lib/cli/cli.js:53:13)
    at Object.fail (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:41:17)
    at /home/moamen/foo/baz/node_modules/yargs/lib/command.js:246:36
(Use `node --trace-warnings ...` to show where the warning was created)
(node:48106) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:48106) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

and this is my tsconfig.json

{
    "compilerOptions": {
        "target": "es6" ,
        "module": "commonjs",
        "sourceMap": true ,
        "outDir": "dist" ,
        "strict": true ,
        "moduleResolution": "node" ,
        "esModuleInterop": true
        },
    "lib": ["es2015"]
}


问:
ANGULAR - How the EventEmitter Service below, works exactly?
On my work, we've been using this service below to subscribe and emit notifications right and fourth. As a junior developer I already understand Input and Outputs of Angular and sort of how Emitters work.

But this service simplys confuse me. The dev who made this service already left the company and since this code is almost a boilerplate for all projects, I cannot ask him how exactly it works.

specifically this line: private static emitters: { [notificationName: string]: EventEmitter } = {}

```<code>import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    private static emitters: { [notificationName: string]: EventEmitter<any> } = {}

    static get(notificationName: string): EventEmitter<any> {
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}

/**
to SUBSCRIBE:

private subscriptions = new Subscription();
constructor(){
    this.subscriptions.add( EventEmitterService.get("notification_name").subscribe(payload => this.notificationHandler(payload)) );
}

TO EMIT:

EventEmitterService.get("notificationName").emit(payload);

to UNSUBSCRIBE:

ngOnDestroy(){
    this.subscriptions.unsubscribe();
}
*/
</code>```

Following instructions from the user Michael D, I've change the code

```<code>import { Subject } from 'rxjs';

private emitters: { [notificationName: string]: Subject<any> } = { };
</code>```

and got this error:

The error was caused because the return of static get(notificationName: string): was not changed to Observable<any>

So the final form of service, updated according to MichaelD comment :

```<code>import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    // private static emitters: { [notificationName: string]: EventEmitter<any> } = {}
    private  emitters: { [notificationName: string]: Subject<any> } = {};

    get(notificationName: string): Observable<any>{
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}
</code>```

答:
private static emitters: { [notificationName: string]: EventEmitter } = {}
```

This line just means that emitters is an internal property of the EventEmitterService class of type object, for which keys are strings, and values instances of EventEmitter. It's being used to keep track of active subscriptions.
The consumers of the service are not concerned with other consumers, they just want to emit or subscribe to a given notification, that's why it's private.

If you look at the EventEmitter interface, you'll see that you can indeed either emit or subscribe. When you emit you send a payload that will be passed as a parameter to the function consumers subscribed with.

When you subscribe to an EventEmitter, it returns a subscription which you can then unsubscribe from.
When you add your EventEmitter subscription to subscriptions, you're allowing yourself to be able to unsubscribe to all of them at once by calling its unsubscribe.

Body:
On my work, we've been using this service below to subscribe and emit notifications right and fourth. As a junior developer I already understand Input and Outputs of Angular and sort of how Emitters work.

But this service simplys confuse me. The dev who made this service already left the company and since this code is almost a boilerplate for all projects, I cannot ask him how exactly it works.

specifically this line: private static emitters: { [notificationName: string]: EventEmitter } = {}

import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    private static emitters: { [notificationName: string]: EventEmitter<any> } = {}

    static get(notificationName: string): EventEmitter<any> {
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}

/**
to SUBSCRIBE:

private subscriptions = new Subscription();
constructor(){
    this.subscriptions.add( EventEmitterService.get("notification_name").subscribe(payload => this.notificationHandler(payload)) );
}

TO EMIT:

EventEmitterService.get("notificationName").emit(payload);

to UNSUBSCRIBE:

ngOnDestroy(){
    this.subscriptions.unsubscribe();
}
*/

Following instructions from the user Michael D, I've change the code

import { Subject } from 'rxjs';

private emitters: { [notificationName: string]: Subject<any> } = { };

and got this error:

The error was caused because the return of static get(notificationName: string): was not changed to Observable<any>

So the final form of service, updated according to MichaelD comment :

import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    // private static emitters: { [notificationName: string]: EventEmitter<any> } = {}
    private  emitters: { [notificationName: string]: Subject<any> } = {};

    get(notificationName: string): Observable<any>{
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}

Body:
private static emitters: { [notificationName: string]: EventEmitter } = {}

This line just means that emitters is an internal property of the EventEmitterService class of type object, for which keys are strings, and values instances of EventEmitter. It's being used to keep track of active subscriptions.
The consumers of the service are not concerned with other consumers, they just want to emit or subscribe to a given notification, that's why it's private.

If you look at the EventEmitter interface, you'll see that you can indeed either emit or subscribe. When you emit you send a payload that will be passed as a parameter to the function consumers subscribed with.

When you subscribe to an EventEmitter, it returns a subscription which you can then unsubscribe from.
When you add your EventEmitter subscription to subscriptions, you're allowing yourself to be able to unsubscribe to all of them at once by calling its unsubscribe.


问:
I am moving series of div's which is inside the container using jQuery using a button
Series of div's which is inside the container. If button click train should move.   </p>

```<code><script>
    $('document').ready(function(){
    $("button").click(function(){
    $("#train").animate({left: "300px"}, 2000);
       });
     });
 </script>
</code>```

答:
Your #train may need absolute positioning. Consider the following example.

$(function() {
  $("button").click(function() {
    $("#train").animate({
      left: "300px"
    }, 2000);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#train {
  width: 100px;
  height: 30px;
  border: 1px solid #222;
  border-radius: 6px;
  background: #ccc;
  position: absolute;
  padding-top: 8px;
  text-align: center;
}</code>```

<button>Go</button>

Train
```

Body:
Your #train may need absolute positioning. Consider the following example.

$(function() {
  $("button").click(function() {
    $("#train").animate({
      left: "300px"
    }, 2000);
  });
});

#train {
  width: 100px;
  height: 30px;
  border: 1px solid #222;
  border-radius: 6px;
  background: #ccc;
  position: absolute;
  padding-top: 8px;
  text-align: center;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Go</button>
<div id="train">Train</div>


问:
Can't get an element's value by class name with Javascript?
I have a patient number that is posted on my website coming from a Caspio database.  I want to pull this number and save it as a Javascript var patientNumber.  I have tried to do this by ClassName, ID, Name and nothing works.  I get 'undefined' returned to me.

Here is a screenshot from the Inspector screen.
https://recordit.co/MUAGMqpUgn

The HTML tag I'm targeting:

ClinicA11-PF-TR1-P1

```

<p>Here is the code I've tried.</p>

```<?php
add_action( 'wp_head', function () { ?>

<?php } );
```

答:
Try to add innerText at the end of this line - var patientNumber = document.getElementsByClassName("dd.cbResultSetData.cbResultSetNestedAlign")[0]; like this

```<code>var patientNumber = document.getElementsByClassName("dd.cbResultSetData.cbResultSetNestedAlign")[0].innerText;
</code>```

Body:
I have a patient number that is posted on my website coming from a Caspio database.  I want to pull this number and save it as a Javascript var patientNumber.  I have tried to do this by ClassName, ID, Name and nothing works.  I get 'undefined' returned to me.

Here is a screenshot from the Inspector screen.
https://recordit.co/MUAGMqpUgn

The HTML tag I'm targeting:

ClinicA11-PF-TR1-P1

Here is the code I've tried.

<?php
add_action( 'wp_head', function () { ?>

<?php } );

Body:
Try to add innerText at the end of this line - var patientNumber = document.getElementsByClassName("dd.cbResultSetData.cbResultSetNestedAlign")[0]; like this

var patientNumber = document.getElementsByClassName("dd.cbResultSetData.cbResultSetNestedAlign")[0].innerText;


答:
Simply add the value from each of the previous lists with the corresponding index, like this:

```<code>for i, v in enumerate(values1):
    plt.text(v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values2):
    plt.text(v * 0.45 + values1[i], i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values2):
    plt.text(v * 0.45 + values1[i] + values2[i], i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')
</code>```

Result:

Title: Align value labels in horizontal stacked bar plot (Matplotlib)

Body:
Simply add the value from each of the previous lists with the corresponding index, like this:

for i, v in enumerate(values1):
    plt.text(v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values2):
    plt.text(v * 0.45 + values1[i], i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values2):
    plt.text(v * 0.45 + values1[i] + values2[i], i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

Result:


问:
Using the g++ C++ compiler from cygwin
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

```<code>#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}
</code>```

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

And here is what I get when I try to compile the program in the cygwin shell:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

答:
Try to create a new file and type in the code yourself without copying and pasting it.
You may have an illegal character in your code which may not be visible in your editor of choice.</p>

ContentLicense: CC BY-SA 2.5

Title: Using the g++ C++ compiler from cygwin

Body:
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

And here is what I get when I try to compile the program in the cygwin shell:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

LastEditorDisplayName: Rich B

OwnerDisplayName: NAF


问:
local host not responding when ejs templates are added
local host is not loading when partials(ejs templates)  are added to the pages.The page loads at first if the partials are not added.But once the partials are added the page no longer loads.Also no error is also being reported.The page keeps on loading and finally shows unable to reach the adress.

```<code>var express = require("express");
var app = express();
var bodyparser = require("body-parser");

app.use(bodyparser.urlencoded({extended: true}));
app.set("view engine", "ejs");

app.get("/", function(req , res){
    res.render("landing");
});

app.get("/campgrounds", function(req,res){
   res.render("campgrounds",{campgrounds:campgrounds});
});

app.post("/campgrounds",function(req,res){
    var name = req.body.name;
    var image = req.body.image;
    var newCamp = {name: name, image:image}
    campgrounds.push(newCamp)
    res.redirect("/campgrounds");
});

app.get("/campgrounds/new", function(req, res){
    res.render("new.ejs");
});
app.listen(3000, function(){
    console.log("Yelp camp server has started");
});

</code>```

when the headers are added to the the following page the page no longer loads

```<code> <%- include('partials/header.ejs') %>

<h1>landing page</h1>

<a href="/campgrounds">view all campgrounds</a>
<p>asdasdasda</p>

<%- include('partials/footer.ejs') %>
</code>```

Please help!!!!
also here is the code for the header

```<code>    <!DOCTYPE html>
<html>
    <head>
        <title>YELPCAMP</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
    </head>

<body>
<p>header tabs</p>
</code>```

答:
You're missing a - from the closing tag:

```<code><%- include('partials/header.ejs') -%>

...

<%- include('partials/footer.ejs') -%>
</code>```

Body:
local host is not loading when partials(ejs templates)  are added to the pages.The page loads at first if the partials are not added.But once the partials are added the page no longer loads.Also no error is also being reported.The page keeps on loading and finally shows unable to reach the adress.

var express = require("express");
var app = express();
var bodyparser = require("body-parser");

app.use(bodyparser.urlencoded({extended: true}));
app.set("view engine", "ejs");

app.get("/", function(req , res){
    res.render("landing");
});

app.get("/campgrounds", function(req,res){
   res.render("campgrounds",{campgrounds:campgrounds});
});

app.post("/campgrounds",function(req,res){
    var name = req.body.name;
    var image = req.body.image;
    var newCamp = {name: name, image:image}
    campgrounds.push(newCamp)
    res.redirect("/campgrounds");
});

app.get("/campgrounds/new", function(req, res){
    res.render("new.ejs");
});
app.listen(3000, function(){
    console.log("Yelp camp server has started");
});

when the headers are added to the the following page the page no longer loads

 <%- include('partials/header.ejs') %>

landing page

view all campgrounds

asdasdasda

<%- include('partials/footer.ejs') %>

Please help!!!!
also here is the code for the header

    <!DOCTYPE html>

        <title>YELPCAMP</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

header tabs

Body:
You're missing a - from the closing tag:

<%- include('partials/header.ejs') -%>

...

<%- include('partials/footer.ejs') -%>


问:
Create a block of a sequence of numbers - R
I would like to create a block, meaning an immutable list of numbers, of a sequence of numbers in R.
Meaning that when I index the list, I will get the group of numbers.

```<code>ts <- cbind(1:11, 12:22, 23:33, 34:44, 45:55, 56:66, 67:77, 78:88, 89:99, 100:110, 111:121)
#divide numbers in 11 groups
sample(a, 11, replace=TRUE)
#should "shuffle" the blocks so that I have for example (12:22, 34:44, 45:55, 56:66, 56:66, 34:44, etc.)
ts[3]
[23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
</code>```

This will be used to bootstrap. Rest of the code is already set, which I will post for reference below.

```<code>for (j in 1:10){
    s <- NULL
    #ts is the above sequence
    s <- sample(ts, 11, replace = TRUE)
    a3 <- Three_grosslarger2[s,]
    x <- factors[s,]

    for (i in 1:length(Four_grosslarger2)){
            m_a3 <- summary(lm(a3[,i] - x[,4] ~ x[,1] + x[,2] + x[,3] + x[,5], na.action = na.exclude), data = a3)
            Four_grosslarger2_a[j, i] <- m_a3$coefficients[1,1]
            Four_grosslarger2_ta[j, i] <- m_a3$coefficients[1,3]
</code>```

Thank you!

Body:
I would like to create a block, meaning an immutable list of numbers, of a sequence of numbers in R.
Meaning that when I index the list, I will get the group of numbers.

ts <- cbind(1:11, 12:22, 23:33, 34:44, 45:55, 56:66, 67:77, 78:88, 89:99, 100:110, 111:121)
#divide numbers in 11 groups
sample(a, 11, replace=TRUE)
#should "shuffle" the blocks so that I have for example (12:22, 34:44, 45:55, 56:66, 56:66, 34:44, etc.)
ts[3]
[23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]

This will be used to bootstrap. Rest of the code is already set, which I will post for reference below.

for (j in 1:10){
    s <- NULL
    #ts is the above sequence
    s <- sample(ts, 11, replace = TRUE)
    a3 <- Three_grosslarger2[s,]
    x <- factors[s,]

    for (i in 1:length(Four_grosslarger2)){
            m_a3 <- summary(lm(a3[,i] - x[,4] ~ x[,1] + x[,2] + x[,3] + x[,5], na.action = na.exclude), data = a3)
            Four_grosslarger2_a[j, i] <- m_a3$coefficients[1,1]
            Four_grosslarger2_ta[j, i] <- m_a3$coefficients[1,3]

Thank you!

Body:
If you change the structure to a list

ts <- list(c(1:11), c(12:22), c(23:33), c(34:44), c(45:55), c(56:66), c(67:77), c(78:88), c(89:99), c(100:110), c(111:121))
#divide numbers in 11 groups
sample(ts, 11, replace=TRUE)
#should "shuffle" the blocks so that I have for example (12:22, 34:44, 45:55, 56:66, 56:66, 34:44, etc.)


问:
react-native-notification foreground messages
Hi everyone

I use library wix/react-native-notifications

It looks like I do something wrong with my android (ios works fine).
For me:

registerRemoteNotificationsRegistered

registerRemoteNotificationsRegistered

registerNotificationOpened

getInitialNotification

work good.

But:

registerNotificationReceivedForeground

registerNotificationReceivedBackground

have never triggered.

I think I put something wrong in AndroidManifest.xml (I have tried different variant but it still doesn't work).

Or problem occurs from using

react-native-notification

react-native-pusher-push-notifications

at the same time.

Please maybe someone have some ideas?

I use:

"react-native-notifications": "^3.2.2",

"react-native-pusher-push-notifications": "^2.4.0",

"react": "16.9.0",

"react-native": "0.61.5",

Part of AndroidManifest.xml that I think can be wrong:

```<code><service
  android:name=".java.MyFirebaseMessagingService"
  android:exported="false"
>
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
  </intent-filter>
</service>
</code>```

答:
Ok, maybe it will be helpful for someone or just start some discussions )

Well, from my understanding the react-native-pusher-push-notifications handle notification first, so library react-native-notifications can't catch that.

Not the better decision but it will works before I find better solution.

I modified file PusherWrapper.java in react-native-pusher-push-notifications library to handle more information. The main problem was that library doesn't return info that send in data part of notification.

Body:
Hi everyone

I use library wix/react-native-notifications

It looks like I do something wrong with my android (ios works fine).
For me:

registerRemoteNotificationsRegistered

registerRemoteNotificationsRegistered

registerNotificationOpened

getInitialNotification

work good.

But:

registerNotificationReceivedForeground

registerNotificationReceivedBackground

have never triggered.

I think I put something wrong in AndroidManifest.xml (I have tried different variant but it still doesn't work).

Or problem occurs from using

react-native-notification

react-native-pusher-push-notifications

at the same time.

Please maybe someone have some ideas?

I use:

"react-native-notifications": "^3.2.2",

"react-native-pusher-push-notifications": "^2.4.0",

"react": "16.9.0",

"react-native": "0.61.5",

Part of AndroidManifest.xml that I think can be wrong:

<service
  android:name=".java.MyFirebaseMessagingService"
  android:exported="false"
>
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
  </intent-filter>
</service>


问:
While using Spring Boot 2.3.0.RELEASE parent version, SpringBootApplication class is not compiling
I am trying to develop simple CRUD app using Spring Boot Parent 2.3.0 and Postgresql.

Getting below errors in SpringBootApplication class and could not able to compile or run the project.

- The type org.springframework.data.repository.query.QueryLookupStrategy$Key cannot be resolved. It is indirectly referenced from required .class files

- The type org.springframework.data.repository.config.BootstrapMode cannot be resolved. It is indirectly referenced from required .class files

On previous version of spring parent everything working fine. This issue is with 2.3.0.

Any help appreciated!!

答: Maybe its dependency conflict or something wrong in m2 directory, So You can try to delete org/springframework from m2 directory, Then mvn clean install, Maybe it will work fine.


问:
Get response in JSON format in Yii2
I'm trying to convert and array of response into JSON format. I have tried all the answers that were posted on SO and other websites like web1,web2 adding header('Content-Type: application/json') and then echo json_encode($data,JSON_PRETTY_PRINT);
But I'm always getting the output in text format.
Can some one help me in solving this.

Helpers Class:

```<code>public static function renderJSON($data) {
    header('Content-Type: application/json');
    echo json_encode($data,JSON_PRETTY_PRINT);
}
</code>```

My Controller:

```<code>if ($model->login()) {
    $user =  User::findByUsernameOrEmail($request->post('username'));
    $userArray = ArrayHelper::toArray($user);
    Helpers::renderJSON($userArray);
</code>```

I tried to printing the userArray and it looks like this:

```<code>Array
(
    [name] => abc
    [lastname] => xyz
    [username] => test_test
)
</code>```

Json output: (html/text)

```<code>{
    "name": "abc",
    "lastname": "xyz",
    "username": "test_test"
}
</code>```

答:
```<code>use yii\helpers\Json;
use yii\web\Response;
</code>```

Firstly include the 2 lines above at the top of your controller, then in any of your Controller actions, just before the return statements, include the below

```<code>Yii::$app->response->format = Response::FORMAT_JSON;
return Json::encode([
            'message' => 'success'
]);
</code>```

You can build the return array as you deem fit.

Title: Get response in JSON format in Yii2

Body:
I'm trying to convert and array of response into JSON format. I have tried all the answers that were posted on SO and other websites like web1,web2 adding header('Content-Type: application/json') and then echo json_encode($data,JSON_PRETTY_PRINT);
But I'm always getting the output in text format.
Can some one help me in solving this.

Helpers Class:

public static function renderJSON($data) {
    header('Content-Type: application/json');
    echo json_encode($data,JSON_PRETTY_PRINT);
}

My Controller:

if ($model->login()) {
    $user =  User::findByUsernameOrEmail($request->post('username'));
    $userArray = ArrayHelper::toArray($user);
    Helpers::renderJSON($userArray);

I tried to printing the userArray and it looks like this:

Array
(
    [name] => abc
    [lastname] => xyz
    [username] => test_test
)

Json output: (html/text)

{
    "name": "abc",
    "lastname": "xyz",
    "username": "test_test"
}

Body:
use yii\helpers\Json;
use yii\web\Response;

Firstly include the 2 lines above at the top of your controller, then in any of your Controller actions, just before the return statements, include the below

Yii::$app->response->format = Response::FORMAT_JSON;
return Json::encode([
            'message' => 'success'
]);

You can build the return array as you deem fit.


问:
How to I restart a canceled check on github?
On github, one of the checks for my PR was canceled:

This check was cancelled

How do I restart the check?

答: You can't, you must ask for a pr review again.</p>


问:
Premake, command line options don't do anything
I have the following section in my lua script:

```<code>newoption {
    trigger     = "build-tests",
    description = "Build tests."
}

configuration "build-tests"
    print("bbbbbbbbb")
    include("Src/tests/tests.lua")

configuration "not build-tests"
    print("aaaaaaaaaaa")
</code>```

running premake5 gmake --help gives:

```<code>Usage: premake5 [options] action [arguments]

OPTIONS - General

 --build-benchmarks  Build benchmarks.
 --build-tests       Build tests.
 --debugger          Start MobDebug remote debugger. Works with ZeroBrane Studio
 --fatal             Treat warnings from project scripts as errors
 --file=FILE         Read FILE as a Premake script; default is 'premake5.lua'
 --help              Display this information
</code>```

However running premake5 --build-tests gmake outputs:

```<code>bbbbbbbbb
aaaaaaaaaaa
Building configurations...
Running action 'gmake'...
Done (362ms).
</code>```

BOTH versions are running, I don't understand. I am trying to get a toggle to select whether I want to build tests or not.

答:
configuration() is a function, not an if-then. Your example above is equivalent to...

configuration("build-tests")
print("bbbbbbbbb")
include("Src/tests/tests.lua")

configuration("not build-tests")
print("aaaaaaaaaaa")
```

It has no effect on which code runs or does not run in your script; all the code in your script is always run, and then the configuration conditions are evaluated later.

Instead look at the actual generated project output to see if things are working or not.

Body:
I have the following section in my lua script:

newoption {
    trigger     = "build-tests",
    description = "Build tests."
}

configuration "build-tests"
    print("bbbbbbbbb")
    include("Src/tests/tests.lua")

configuration "not build-tests"
    print("aaaaaaaaaaa")

running premake5 gmake --help gives:

Usage: premake5 [options] action [arguments]

OPTIONS - General

 --build-benchmarks  Build benchmarks.
 --build-tests       Build tests.
 --debugger          Start MobDebug remote debugger. Works with ZeroBrane Studio
 --fatal             Treat warnings from project scripts as errors
 --file=FILE         Read FILE as a Premake script; default is 'premake5.lua'
 --help              Display this information

However running premake5 --build-tests gmake outputs:

bbbbbbbbb
aaaaaaaaaaa
Building configurations...
Running action 'gmake'...
Done (362ms).

BOTH versions are running, I don't understand. I am trying to get a toggle to select whether I want to build tests or not.

Body:
configuration() is a function, not an if-then. Your example above is equivalent to...

configuration("build-tests")
print("bbbbbbbbb")
include("Src/tests/tests.lua")

configuration("not build-tests")
print("aaaaaaaaaaa")

It has no effect on which code runs or does not run in your script; all the code in your script is always run, and then the configuration conditions are evaluated later.

Instead look at the actual generated project output to see if things are working or not.


问:
Put email addresses stored in an array into "To" field of an Outlook email
I want email addresses that are stored in the array "emails" put into the "To" part of an email.

I get a type mismatch error.

Sub Email_Click()
    Dim myOutlook As Outlook.Application
    Dim objMailMessage As Outlook.MailItem

    Dim emails As Variant
    emails = Array("a@a.com", "b@b.com")

    Set myOutlook = Outlook.Application
    Set objMailMessage = myOutlook.CreateItem(0)

    With objMailMessage
        .Display
        .To = emails
        .Subject = ""
        .HTMLBody = ""

        .Save
        .Close olPromptForSave
    End With

End Sub
```

答:
To close this question out, use Join:

```<code>.To = Join(emails, ";")
</code>```

Body:
To close this question out, use Join:

.To = Join(emails, ";")


问:
Deserialize UUID using marshmallow
I am using marshmallow and sqlalchemy in my RESTful flask application to serialize and deserialize my models (It's my first time doing all of this). I have created a route to retrieve all users from a MySQL database. When querying the database, I am able to retrieve all the users (id, first_name, last_name). When printing out users, I see:

```<code>[
  ('UUID1', 'firstname1', 'lastname1'),
  ('UUID2', 'firstname2', 'lastname2')
]
</code>```

NOTE: I store the ID as a binary and utilize the BIN_TO_UUID() and UUID_TO_BIN() database functions.

The response I get back when I hit this route is:

```<code>[
  {"first_name": "firstname1", "last_name": "lastname1"},
  {"first_name": "firstname2", "last_name": "lastname2"}
]
</code>```

```<code>class UsersSchema(Schema):
    id = fields.UUID(attribute="id")
    first_name = fields.String()
    last_name = fields.String()

    class Meta:
        fields = ("id", "first_name", "last_name")

class Users(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Binary(16), primary_key=True)
    first_name = db.Column(db.VARCHAR(255))
    last_name = db.Column(db.VARCHAR(255))

@app.route('/users')
def users():
    try:
        users = db.session.query(
            func.bin_to_uuid(Users.id),
            Users.first_name,
            Users.last_name,
        ).all()

    except Exception as e:
        print('we got an error in users route')
        print(e)
    finally:
        return jsonify(UsersSchema(many=True).dump(users))

</code>```

答:
The first column in your query is probably not called id because of the bin_to_uuid function application. Then the Schema does not yield an id value because there is no such column. The solution should be to alias the first columnn in the query to id:

```<code>db.session.query(
    func.bin_to_uuid(Users.id).label('id'),
    Users.first_name,
    Users.last_name,
)
</code>```

Title: Deserialize UUID using marshmallow

Body:
I am using marshmallow and sqlalchemy in my RESTful flask application to serialize and deserialize my models (It's my first time doing all of this). I have created a route to retrieve all users from a MySQL database. When querying the database, I am able to retrieve all the users (id, first_name, last_name). When printing out users, I see:

[
  ('UUID1', 'firstname1', 'lastname1'),
  ('UUID2', 'firstname2', 'lastname2')
]

NOTE: I store the ID as a binary and utilize the BIN_TO_UUID() and UUID_TO_BIN() database functions.

The response I get back when I hit this route is:

[
  {"first_name": "firstname1", "last_name": "lastname1"},
  {"first_name": "firstname2", "last_name": "lastname2"}
]

class UsersSchema(Schema):
    id = fields.UUID(attribute="id")
    first_name = fields.String()
    last_name = fields.String()

    class Meta:
        fields = ("id", "first_name", "last_name")

class Users(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Binary(16), primary_key=True)
    first_name = db.Column(db.VARCHAR(255))
    last_name = db.Column(db.VARCHAR(255))

@app.route('/users')
def users():
    try:
        users = db.session.query(
            func.bin_to_uuid(Users.id),
            Users.first_name,
            Users.last_name,
        ).all()

    except Exception as e:
        print('we got an error in users route')
        print(e)
    finally:
        return jsonify(UsersSchema(many=True).dump(users))

Body:
The first column in your query is probably not called id because of the bin_to_uuid function application. Then the Schema does not yield an id value because there is no such column. The solution should be to alias the first columnn in the query to id:

db.session.query(
    func.bin_to_uuid(Users.id).label('id'),
    Users.first_name,
    Users.last_name,
)


问:
Issue with image and link alignment
So i've got this issue with my CSS where I cannot display a text-link inline with my image.
The links are on a different height relative to my image? What can the issue be? I've tried using different alignment methods such as vertical-align etc.

Maybe I should rewrite the whole code?

```<code>html,
body {
    font-family: 'Open Sans', sans-serif;
    background-color: #efefef;
}

body{
    margin: 0;
}

.left_div {
    margin: 0;
    padding: 0;
    width: 25%;
    background-color: #fff;
    position: fixed;
    height: 100%;
    overflow: auto;
    text-align: center;
}

.left_div img {
    width: 50%;
    height: auto;
    margin: 2vh 0 2vh 0;
}

.left_div a {
    display: block;
    color: black;
    background-color: rgb(217, 50, 141);
    padding: 16px;
    text-decoration: none;
    width: 75%;
    margin: 2vh auto;
    border-radius: 5px;
    color: rgb(255, 255, 255);
    transition: all .2s ease-in-out;
}

.left_div a.active {
    background-color: rgb(65, 29, 100);
    color: white;
}

.left_div a:hover:not(.active) {
    background-color: rgb(153, 22, 94);
    color: white;
}

@media screen and (min-width: 765px) and (max-width: 968px) {
    .left_div {
        width: 100%;
        height: auto;
        position: relative;
        text-align: left;
    }

    .left_div img {
        width: 12.5%;
        height: auto;
        margin: 0 0 0 2vw;
    }

    .left_div a {
        display: inline;
        color: black;
        background-color: rgb(217, 50, 141);
        padding: 16px;
        text-decoration: none;
        margin: 0 auto;
        border-radius: 5px;
        color: rgb(255, 255, 255);
        transition: all .2s ease-in-out;

    }
}

@media screen and (max-width: 765px) {
    .left_div {
        width: 100%;
        height: auto;
        position: relative;
    }
    .left_div a {
        text-align: center;
        float: none;
    }
}

<!-- HTML -->

    <div class="left_div">

        <img src="img/mlp_logo.png" alt="My Little Pony Logo">

        <a class="active" href="#">Home</a>
        <a href="#">News</a>
        <a href="#">Contact</a>
        <a href="#">About</a>
      </div>

</code>```

Here is a jsfiddle to show the issue.

https://jsfiddle.net/bcyu0f52

Thanks!

edit (screenshot added)

https://imgur.com/hwbmAKR
As you see on the screenshot the image and text are misaligned height-wise.

答:
As already stated in the comments, setting the proper vertical alignment did the trick:

Solution was to add:

```<code>.left_div img {
  vertical-align: middle;
}
</code>```

Title: Issue with image and link alignment

Body:
So i've got this issue with my CSS where I cannot display a text-link inline with my image.
The links are on a different height relative to my image? What can the issue be? I've tried using different alignment methods such as vertical-align etc.

Maybe I should rewrite the whole code?

html,
body {
    font-family: 'Open Sans', sans-serif;
    background-color: #efefef;
}

body{
    margin: 0;
}

.left_div {
    margin: 0;
    padding: 0;
    width: 25%;
    background-color: #fff;
    position: fixed;
    height: 100%;
    overflow: auto;
    text-align: center;
}

.left_div img {
    width: 50%;
    height: auto;
    margin: 2vh 0 2vh 0;
}

.left_div a {
    display: block;
    color: black;
    background-color: rgb(217, 50, 141);
    padding: 16px;
    text-decoration: none;
    width: 75%;
    margin: 2vh auto;
    border-radius: 5px;
    color: rgb(255, 255, 255);
    transition: all .2s ease-in-out;
}

.left_div a.active {
    background-color: rgb(65, 29, 100);
    color: white;
}

.left_div a:hover:not(.active) {
    background-color: rgb(153, 22, 94);
    color: white;
}

@media screen and (min-width: 765px) and (max-width: 968px) {
    .left_div {
        width: 100%;
        height: auto;
        position: relative;
        text-align: left;
    }

    .left_div img {
        width: 12.5%;
        height: auto;
        margin: 0 0 0 2vw;
    }

    .left_div a {
        display: inline;
        color: black;
        background-color: rgb(217, 50, 141);
        padding: 16px;
        text-decoration: none;
        margin: 0 auto;
        border-radius: 5px;
        color: rgb(255, 255, 255);
        transition: all .2s ease-in-out;

    }
}

@media screen and (max-width: 765px) {
    .left_div {
        width: 100%;
        height: auto;
        position: relative;
    }
    .left_div a {
        text-align: center;
        float: none;
    }
}

        Home
        News
        Contact
        About

Here is a jsfiddle to show the issue.

https://jsfiddle.net/bcyu0f52

Thanks!

edit (screenshot added)

https://imgur.com/hwbmAKR
As you see on the screenshot the image and text are misaligned height-wise.

Body:
As already stated in the comments, setting the proper vertical alignment did the trick:

Solution was to add:

.left_div img {
  vertical-align: middle;
}


问:
Flutter Center align widget to specific coordinate
Ive create a popup menu widget which takes two arguments :a button widget, and a menu widget . When the button is pressed the menu widget is passed to an OverlayEntry as the child which is then added to the Overlay.of(context)

I'd like the resulting display to be as such:

```<code>     O   (Button)
 ____|____
 | MENU  |
 |_______|
</code>```

I can place the menu widget inside a Positioned Widget to move it freely around the Overlay, but I dont know how to get the correct coordinates. I can get the center of the Button by finding it's Renderbox, but I cant know the size, and therefore the correct position, of the Menu until after it's draw (as it can be any widget).

Is there some soft of layout option to tell a Widget of any size to vertically or horzontally align itself with a given coordinate?

答:
To get the size of a widget:

First give your Widget a key:

```<code>key: _key,
</code>```

Then you can get the size(and position) like this:

```<code>_getSize() {
    final RenderBox renderBox = _key.currentContext.findRenderObject();
    final size = renderBox.size;
    final position = renderBox.localToGlobal(Offset.zero);

    final height = size.height; //same for width
 }
</code>```

Body:
Ive create a popup menu widget which takes two arguments :a button widget, and a menu widget . When the button is pressed the menu widget is passed to an OverlayEntry as the child which is then added to the Overlay.of(context)

I'd like the resulting display to be as such:

     O   (Button)
 ____|____
 | MENU  |
 |_______|

I can place the menu widget inside a Positioned Widget to move it freely around the Overlay, but I dont know how to get the correct coordinates. I can get the center of the Button by finding it's Renderbox, but I cant know the size, and therefore the correct position, of the Menu until after it's draw (as it can be any widget).

Is there some soft of layout option to tell a Widget of any size to vertically or horzontally align itself with a given coordinate?

Body:
To get the size of a widget:

First give your Widget a key:

key: _key,

Then you can get the size(and position) like this:

_getSize() {
    final RenderBox renderBox = _key.currentContext.findRenderObject();
    final size = renderBox.size;
    final position = renderBox.localToGlobal(Offset.zero);

    final height = size.height; //same for width
 }