答:
```<code>#!/usr/bin/env python3

array = [
      27,  28,  29,  30,  31,  38,  39,  40,  43,  44,  45,  46,  57,
      58,  59,  74,  85,  87,  88,  89,  90,  95,  96,  97, 166, 182,
      183, 265, 269, 271, 272, 279, 280, 281, 282, 288, 326, 327, 328,
      356, 387, 399, 407, 408, 437, 438, 439, 453, 454, 455, 456, 457,
      480, 489, 537, 538, 673, 674, 676, 677, 682, 687, 704, 729, 730,
      732, 733, 745, 746, 747, 748
]

def groupByDistance(distance, array):
    index_key = 65 # Like 'A'
    index = 0
    ret = {}
    found = []
    array.append(min(array)-1) # To be sure that there isnt yet in

    while index < len(array)-1:
        if array[index]+distance == array[index+1]:
            found.append(array[index])
        else:
            found.append(array[index])
            ret[chr(index_key)] = found
            index_key+=1
            if index_key >= 91 and index_key <= 96:
                index_key = 97 # Go to 'a' but it can overlap...
            found = []

        index+=1

    return ret

res = groupByDistance(1, array)

for _ in res:
    print(_, " : ", res[_])
</code>```

<p>Is just an hint. Note that for a large array the ascii characters are not sufficent, use something else, like string punctuation module, instead. obviusly the returned dict are not in order but you can easly supply a  function for reorder. </p>

Title: Finding and grouping sequence of +1 numbers python

Body:
I'd like to recognize sequences in this array but all of my ideas are very inefficent:

np.array([ 27,  28,  29,  30,  31,  38,  39,  40,  43,  44,  45,  46,  57,
             58,  59,  74,  85,  87,  88,  89,  90,  95,  96,  97, 166, 182,
            183, 265, 269, 271, 272, 279, 280, 281, 282, 288, 326, 327, 328,
            356, 387, 399, 407, 408, 437, 438, 439, 453, 454, 455, 456, 457,
            480, 489, 537, 538, 673, 674, 676, 677, 682, 687, 704, 729, 730,
            732, 733, 745, 746, 747, 748],
           dtype='int64')

I expect to get array [27,28,29,30,31] as group 'A' or group '1'; 31 as group 'B' or 2; [38,39,40] as group 3 or 'C', etc.

Do you know any library that do this or any "kind of " efficent way to do it?

Body:
#!/usr/bin/env python3

array = [
      27,  28,  29,  30,  31,  38,  39,  40,  43,  44,  45,  46,  57,
      58,  59,  74,  85,  87,  88,  89,  90,  95,  96,  97, 166, 182,
      183, 265, 269, 271, 272, 279, 280, 281, 282, 288, 326, 327, 328,
      356, 387, 399, 407, 408, 437, 438, 439, 453, 454, 455, 456, 457,
      480, 489, 537, 538, 673, 674, 676, 677, 682, 687, 704, 729, 730,
      732, 733, 745, 746, 747, 748
]

def groupByDistance(distance, array):
    index_key = 65 # Like 'A'
    index = 0
    ret = {}
    found = []
    array.append(min(array)-1) # To be sure that there isnt yet in

    while index < len(array)-1:
        if array[index]+distance == array[index+1]:
            found.append(array[index])
        else:
            found.append(array[index])
            ret[chr(index_key)] = found
            index_key+=1
            if index_key >= 91 and index_key <= 96:
                index_key = 97 # Go to 'a' but it can overlap...
            found = []

        index+=1

    return ret

res = groupByDistance(1, array)

for _ in res:
    print(_, " : ", res[_])

Is just an hint. Note that for a large array the ascii characters are not sufficent, use something else, like string punctuation module, instead. obviusly the returned dict are not in order but you can easly supply a  function for reorder.


来源: stackexchange

问:
Displaying session array variable values displays on one page but not another - php
I have a form on page5_form.php:

```<code><form action="page6_form.php" method="post">
<input class="chk" id="check1" type="checkbox" name="infoCollectedAndSold[]" value="Identifiers">Identifiers<br>
            <input class="chk" type="checkbox" name="infoCollectedAndSold[]" value="Collect">
            <input class="chk" type="checkbox" name="infoCollectedAndSold[]" value="Sell">
           <input class="chk" id="disclosed" type="checkbox" name="infoCollectedAndSold[]" value="Disclose"><br><br>
<input type="submit" value="Next" />
</form>
</code>```

The form inputs are stored in session variable like so:

```<code><?php
session_start();
foreach ($_POST as $key => $value) {
    $_SESSION[$key] = $value;
}
?>
</code>```

Then on another page called page6_form.php I display the values chosen from that form:

```<code><?php
session_start();
$arr = $_POST['infoCollectedAndSold'];
foreach ($arr as $key => $val) {
   echo '<b>' . $val . '</b>';
}
?>
</code>```

I then do the same exact thing on page7_form.php:

```<code><?php
session_start();
$arr = $_POST['infoCollectedAndSold'];
foreach ($arr as $key => $val) {
   echo '<b>' . $val . '</b>';
}
?>
</code>```

but get the error message:

```<code>Notice: Undefined index: infoCollectedAndSold in C:\xampp\htdocs\legalForm\page7_form.php
</code>```

答:
Could you provide some extra details about your use case, as the question title is misleading.
You are definitely not having a sessions issue as you title suggestion since you're never trying to display session information on different pages.

In one case (page5_form.php) you have a form, that points to page6_form.php
you are also setting some data in session (also in page5_form.php - can you confirm that, as that's suggested but not explicitely mentioned).

On page6_form.php, the target of the form displayed on page5_form.php, you simply echo data from $_POST.

On page7_form.php, you also output data from $_POST.

you're never outputting data from $_SESSION

both page6 and page7 scripts only output data that's sent via POST to them. It's clear which form sends data to page6_form.php but not sure who sends data to page7_form.php, however assuming you just switch targets on the form displayed in page5_form.php, both page6 and page7 should display the same output assuming you're selecting the same things in the form.

Cheers!

ContentLicense: CC BY-SA 4.0

Body:
I have a form on page5_form.php:

<form action="page6_form.php" method="post">
<input class="chk" id="check1" type="checkbox" name="infoCollectedAndSold[]" value="Identifiers">Identifiers

            <input class="chk" type="checkbox" name="infoCollectedAndSold[]" value="Collect">
            <input class="chk" type="checkbox" name="infoCollectedAndSold[]" value="Sell">
           <input class="chk" id="disclosed" type="checkbox" name="infoCollectedAndSold[]" value="Disclose">

<input type="submit" value="Next" />
</form>

The form inputs are stored in session variable like so:

<?php
session_start();
foreach ($_POST as $key => $value) {
    $_SESSION[$key] = $value;
}
?>

Then on another page called page6_form.php I display the values chosen from that form:

<?php
session_start();
$arr = $_POST['infoCollectedAndSold'];
foreach ($arr as $key => $val) {
   echo '' . $val . '';
}
?>

I then do the same exact thing on page7_form.php:

<?php
session_start();
$arr = $_POST['infoCollectedAndSold'];
foreach ($arr as $key => $val) {
   echo '' . $val . '';
}
?>

but get the error message:

Notice: Undefined index: infoCollectedAndSold in C:\xampp\htdocs\legalForm\page7_form.php


问:
Keeps counting all the text values instead of me providing a criteria in SQL
I have very simple query, to count the number of Cause Cancel from the Decision column. It keeps counting all the text values in the column and not just cause cancel. </p>

```<code>SELECT Marketics.Case, Count(Marketics.Decision) AS CountOfDecision
FROM Marketics
GROUP BY Marketics.Case
HAVING Count(Marketics.Decision="Cause Cancel");
</code>```

答:
The problem is that your having clause doesn't have an actual comparison. It just says having count(). They all have a count... so, it's returning correctly.

Now, if your goal is to produce a result with a case number, a count of decisions where it's all decisions EXCEPT  "Cause Cancel" then you need to use a where clause, not a having clause. The having clause will simply filter any cases that don't have at least one "cause cancel" decision.

Of course, that assumes that the count() with an implicit where clause is allowed, which I've never seen before... but I come from a Microsoft SQL background.

```<code>SELECT Marketics.Case, Count(Marketics.Decision) AS CountOfDecision
FROM Marketics
GROUP BY Marketics.Case
HAVING Count(Marketics.Decision="Cause Cancel") > 0;
</code>```

Body:
I have very simple query, to count the number of Cause Cancel from the Decision column. It keeps counting all the text values in the column and not just cause cancel.

SELECT Marketics.Case, Count(Marketics.Decision) AS CountOfDecision
FROM Marketics
GROUP BY Marketics.Case
HAVING Count(Marketics.Decision="Cause Cancel");

Body:
The problem is that your having clause doesn't have an actual comparison. It just says having count(). They all have a count... so, it's returning correctly.

Now, if your goal is to produce a result with a case number, a count of decisions where it's all decisions EXCEPT  "Cause Cancel" then you need to use a where clause, not a having clause. The having clause will simply filter any cases that don't have at least one "cause cancel" decision.

Of course, that assumes that the count() with an implicit where clause is allowed, which I've never seen before... but I come from a Microsoft SQL background.

SELECT Marketics.Case, Count(Marketics.Decision) AS CountOfDecision
FROM Marketics
GROUP BY Marketics.Case
HAVING Count(Marketics.Decision="Cause Cancel") > 0;


问:
WinForm Button stops working after 1-2 uses
I have a program that quizzes the user by naming a Country (from a list) and asks the user to input it's Capital. If they get it correct, a counter for correct answers is shown with +1 added to it. If it is wrong, the same thing goes but for the incorrect counter. I finished the code for it, but whenever I use the Check Answer button, it doesn't verify the input from the TextBox anymore, and none of the counters (correct or incorrect) change at all. If the first one is right and the second is wrong, it counts both 1 for correct and 1 for incorrect. After that the code under the Check Answer button doesn't execute anymore. If I got 2 right or 2 wrong it only counts the first 1 and stops working after.

```<code>{
//  Declare structure
struct Country
{
    //  Declare strings
    public string countryName;
    public string capital;
}
public partial class Form1 : Form
{
    //  Create List for CourseInfo
    private List<Country> countryList = new List<Country>();

    Country currentCountry;

    public Form1()
    {
        InitializeComponent();
    }

    private void ReadFile()
    {
        try
        {
            //  Call StreamReader to use imported file
            StreamReader inputFile;
            string line;

            Country entry = new Country();

            //  Delimiter to separate values in text file
            char[] delim = { ',' };

            //  Open text file
            inputFile = File.OpenText("countries.txt");

            while (!inputFile.EndOfStream)
            {
                line = inputFile.ReadLine();

                //  Tokenize the strings separated by the delimiter ','
                string[] tokens = line.Split(delim);

                entry.countryName = tokens[0];   //  Tokenized entry for COUNTRY
                entry.capital = tokens[1];       //  Tokenized entry for CAPITAL

                countryList.Add(entry);
            }
        }
        catch (Exception ex)
        {
            //  Shows error message
            MessageBox.Show(ex.Message);
        }
    }

    private void DisplayCountry()
    {
        //  Create random variable
        Random rand = new Random();

        //  Country us randomly chosen from the list
        int countryPosition = rand.Next(countryList.Count);

        //  Selected country
        currentCountry = countryList[countryPosition];

        //  Show selected country in Label
        countryAnswerLabel.Text = currentCountry.countryName;
    }

    private void ExitButton_Click(object sender, EventArgs e)
    {
        //  Closes the form
        this.Close();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //  Call method to load StreamReader with the file
        ReadFile();
    }

    private void QuizButton_Click(object sender, EventArgs e)
    {
        //  Call method to show random country
        DisplayCountry();
    }

    private void CheckAnswerButton_Click(object sender, EventArgs e)
    {
        //  Declare integer variables for the counters and set to 0
        int correctCounter = 0;
        int incorrectCounter = 0;

        //  If the input is correct, +1 for the correct counter
        if (currentCountry.capital == capitalAnswerTextBox.Text)
        {
            correctCounter++;
            correctLabel.Text = correctCounter.ToString();
        }
        //  If the input is incorrect, +1 for the incorrect counter
        else
        {
            incorrectCounter++;
            incorrectLabel.Text = incorrectCounter.ToString();
        }
    }

    private void NextQuestionButton_Click(object sender, EventArgs e)
    {
        //  Clears input TextBox
        capitalAnswerTextBox.Text = string.Empty;
        DisplayCountry();

    }
}
</code>```

答:
Notice that whenever CheckAnswerButton_Click is executed, the variables correctCounter and incorrectCounter are initialised to 0. So every time you press the button, you start counting the answers from 0 again. So you will always be setting one of label's Text to "1". In case that label already shows "1", it would seem like it's "not doing anything".

Therefore, you should move the declarations of correctCount and incorrectCounter to outside the CheckAnswerButton_Click method:

```<code>//  Declare integer variables for the counters and set to 0
int correctCounter = 0;
int incorrectCounter = 0;
private void CheckAnswerButton_Click(object sender, EventArgs e)
{

    //  If the input is correct, +1 for the correct counter
    if (currentCountry.capital == capitalAnswerTextBox.Text)
    {
        correctCounter++;
        correctLabel.Text = correctCounter.ToString();
    }
    //  If the input is incorrect, +1 for the incorrect counter
    else
    {
        incorrectCounter++;
        incorrectLabel.Text = incorrectCounter.ToString();
    }
}
</code>```

This way, they will retain their value after CheckAnswerButton_Click has returned.

Body:
I have a program that quizzes the user by naming a Country (from a list) and asks the user to input it's Capital. If they get it correct, a counter for correct answers is shown with +1 added to it. If it is wrong, the same thing goes but for the incorrect counter. I finished the code for it, but whenever I use the Check Answer button, it doesn't verify the input from the TextBox anymore, and none of the counters (correct or incorrect) change at all. If the first one is right and the second is wrong, it counts both 1 for correct and 1 for incorrect. After that the code under the Check Answer button doesn't execute anymore. If I got 2 right or 2 wrong it only counts the first 1 and stops working after.

{
//  Declare structure
struct Country
{
    //  Declare strings
    public string countryName;
    public string capital;
}
public partial class Form1 : Form
{
    //  Create List for CourseInfo
    private List<Country> countryList = new List<Country>();

    Country currentCountry;

    public Form1()
    {
        InitializeComponent();
    }

    private void ReadFile()
    {
        try
        {
            //  Call StreamReader to use imported file
            StreamReader inputFile;
            string line;

            Country entry = new Country();

            //  Delimiter to separate values in text file
            char[] delim = { ',' };

            //  Open text file
            inputFile = File.OpenText("countries.txt");

            while (!inputFile.EndOfStream)
            {
                line = inputFile.ReadLine();

                //  Tokenize the strings separated by the delimiter ','
                string[] tokens = line.Split(delim);

                entry.countryName = tokens[0];   //  Tokenized entry for COUNTRY
                entry.capital = tokens[1];       //  Tokenized entry for CAPITAL

                countryList.Add(entry);
            }
        }
        catch (Exception ex)
        {
            //  Shows error message
            MessageBox.Show(ex.Message);
        }
    }

    private void DisplayCountry()
    {
        //  Create random variable
        Random rand = new Random();

        //  Country us randomly chosen from the list
        int countryPosition = rand.Next(countryList.Count);

        //  Selected country
        currentCountry = countryList[countryPosition];

        //  Show selected country in Label
        countryAnswerLabel.Text = currentCountry.countryName;
    }

    private void ExitButton_Click(object sender, EventArgs e)
    {
        //  Closes the form
        this.Close();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //  Call method to load StreamReader with the file
        ReadFile();
    }

    private void QuizButton_Click(object sender, EventArgs e)
    {
        //  Call method to show random country
        DisplayCountry();
    }

    private void CheckAnswerButton_Click(object sender, EventArgs e)
    {
        //  Declare integer variables for the counters and set to 0
        int correctCounter = 0;
        int incorrectCounter = 0;

        //  If the input is correct, +1 for the correct counter
        if (currentCountry.capital == capitalAnswerTextBox.Text)
        {
            correctCounter++;
            correctLabel.Text = correctCounter.ToString();
        }
        //  If the input is incorrect, +1 for the incorrect counter
        else
        {
            incorrectCounter++;
            incorrectLabel.Text = incorrectCounter.ToString();
        }
    }

    private void NextQuestionButton_Click(object sender, EventArgs e)
    {
        //  Clears input TextBox
        capitalAnswerTextBox.Text = string.Empty;
        DisplayCountry();

    }
}

Body:
Notice that whenever CheckAnswerButton_Click is executed, the variables correctCounter and incorrectCounter are initialised to 0. So every time you press the button, you start counting the answers from 0 again. So you will always be setting one of label's Text to "1". In case that label already shows "1", it would seem like it's "not doing anything".

Therefore, you should move the declarations of correctCount and incorrectCounter to outside the CheckAnswerButton_Click method:

//  Declare integer variables for the counters and set to 0
int correctCounter = 0;
int incorrectCounter = 0;
private void CheckAnswerButton_Click(object sender, EventArgs e)
{

    //  If the input is correct, +1 for the correct counter
    if (currentCountry.capital == capitalAnswerTextBox.Text)
    {
        correctCounter++;
        correctLabel.Text = correctCounter.ToString();
    }
    //  If the input is incorrect, +1 for the incorrect counter
    else
    {
        incorrectCounter++;
        incorrectLabel.Text = incorrectCounter.ToString();
    }
}

This way, they will retain their value after CheckAnswerButton_Click has returned.


问:
Keeping line breaks when reading a file
I want to read a file and modify it but whenever the new file is created everything stays on one line. Therefore, my question is how can I keep line breaks without removing them?</p>

```<code>public class JavaProgram {

    public static void main(String[] args) {
        String text = "";
        StringBuilder convert = new StringBuilder();
        Scanner keyboard = new Scanner (System.in);

        File file = new File ("PATH");

            try {
                Scanner input = new Scanner (file);
                while (input.hasNextLine()) {
                        text = input.nextLine();

                        char [] arr = text.toCharArray();
                        char [] newArr = encrypt(3, arr);

                        for (int i = 0; i < newArr.length; i++) {
                            convert.append(newArr[i]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    PrintWriter printer = new PrintWriter (document);

                    printer.append(convert);
                    printer.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
</code>```

答:
You are reading input one line at a time, which means implicitly that you have a line break every time your read stops.

So each time you write a saved buffer, write out a newline.

```<code>try {
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
    text = input.nextLine();

    char [] arr = text.toCharArray();
    char [] newArr = encrypt(3, arr);

    for (int i = 0; i < newArr.length; i++) {
        convert.append(newArr[i]);
        convert.append(System.lineSeparator());
    } catch (IOException e) {
        e.printStackTrace();
</code>```

}

Title: Keeping line breaks when reading a file

Body:
I want to read a file and modify it but whenever the new file is created everything stays on one line. Therefore, my question is how can I keep line breaks without removing them?

public class JavaProgram {

    public static void main(String[] args) {
        String text = "";
        StringBuilder convert = new StringBuilder();
        Scanner keyboard = new Scanner (System.in);

        File file = new File ("PATH");

            try {
                Scanner input = new Scanner (file);
                while (input.hasNextLine()) {
                        text = input.nextLine();

                        char [] arr = text.toCharArray();
                        char [] newArr = encrypt(3, arr);

                        for (int i = 0; i < newArr.length; i++) {
                            convert.append(newArr[i]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    PrintWriter printer = new PrintWriter (document);

                    printer.append(convert);
                    printer.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }

Body:
You are reading input one line at a time, which means implicitly that you have a line break every time your read stops.

So each time you write a saved buffer, write out a newline.

try {
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
    text = input.nextLine();

    char [] arr = text.toCharArray();
    char [] newArr = encrypt(3, arr);

    for (int i = 0; i < newArr.length; i++) {
        convert.append(newArr[i]);
        convert.append(System.lineSeparator());
    } catch (IOException e) {
        e.printStackTrace();

}


问:
Combine arrays of identical length into array of objects
I have 10 arrays of data that look like this:

```<code>var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays
</code>```

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

```<code>overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]
</code>```

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

答:
This is where Array.map() will be your friend. You can iterate through any of the arrays (since they have the same number of elements) and then access each element by index to get the corresponding value for each array in your dataset, like so:

var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];

let mapped = arr.map((elem, index) => {
  return {
    arr1: arr[index],
    arr2: arr2[index],
    arr3: arr3[index]
  }
});

console.log(mapped);```
</div>
</div>
</p>

<p>Edit: If you wanted to access them generically, you can add all of your arrays to one dictionary and iterate over the key/value pairs, like so:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
// combine all arrays into single dataset
let data = {arr, arr2, arr3};

let mapped = arr.map((elem, index) => {
  // iterate over the key/value pairs of the dataset, use the key to generate the
  // result object key, use the value to grab the item at the current index of the
  // corresponding array
  return Object.entries(data).reduce((res, [key, value]) => {
    res[key] = value[index];
    return res;
  }, {});
});

console.log(mapped);</code>```

Body:
I have 10 arrays of data that look like this:

var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

Body:
This is where Array.map() will be your friend. You can iterate through any of the arrays (since they have the same number of elements) and then access each element by index to get the corresponding value for each array in your dataset, like so:

var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];

let mapped = arr.map((elem, index) => {
  return {
    arr1: arr[index],
    arr2: arr2[index],
    arr3: arr3[index]
  }
});

console.log(mapped);

Edit: If you wanted to access them generically, you can add all of your arrays to one dictionary and iterate over the key/value pairs, like so:

var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
// combine all arrays into single dataset
let data = {arr, arr2, arr3};

let mapped = arr.map((elem, index) => {
  // iterate over the key/value pairs of the dataset, use the key to generate the
  // result object key, use the value to grab the item at the current index of the
  // corresponding array
  return Object.entries(data).reduce((res, [key, value]) => {
    res[key] = value[index];
    return res;
  }, {});
});

console.log(mapped);


问:
Using HTTP HEAD method when the underlying ressource does not allow GET
We have a REST API with hyperlink support. With our automated tests we can then walk through all of the links in the response and check if they are correct, i.e. actually reachable. For this we currently use the HEAD HTTP method. Now, the spec states that HEAD should essentially behave like GET, but without a body. So far so good.

But, we also have some endpoints which ONLY support DELETE or PUT, but no GET.

The question: is it still valid HTTP - or makes even sense - if we check those endpoints with HEAD as well? Of course in this case there shouldn't be any side effects, the purpose of the test essentially would only be: "Endpoint, are you alive and reachable"?

Any ideas (or maybe alternatives)?

答:
The question: is it still valid HTTP - or makes even sense - if we check those endpoints with HEAD as well?

Yes, it makes perfect sense.

405 Method Not Allowed is your ally here, that gives you a way to distinguish resources that aren't readable from resources without representations (404).

The broad principal is that, in REST, all resources understand the same methods the same way.  So HEAD is always a reasonable choice to use.

That said, you might want to review OPTIONS, which like HEAD is also safe, and is designed to allow you to inquire about which methods are supported by a given resource.


问:
Using log4j2 with slf4j: java.lang.StackOverflowError
So I have tried following this (non-maven implementation) and requirements in their web site for adding slf4j to log4j. and tried using this code

```<code>public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(Main.class);
        logger.info("test");
    }
</code>```

and added the following to my library

log4j-api-2.3.jar

log4j-core-2.3.jar

log4j-sl4j-impl-2.3.jar

log4j-to-sl4j-2.3.jar

slf4j-api-1.7.12.jar

when I try running it I get the following error

```<code>Exception in thread "main" java.lang.StackOverflowError
    at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
    at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:964)
    at org.apache.logging.slf4j.SLF4JLoggerContext.getLogger(SLF4JLoggerContext.java:40)
    at org.apache.logging.slf4j.Log4jLoggerFactory.newLogger(Log4jLoggerFactory.java:37)
    at org.apache.logging.slf4j.Log4jLoggerFactory.newLogger(Log4jLoggerFactory.java:29)
    at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:47)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:29)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:284)
    at org.apache.logging.slf4j.SLF4JLoggerContext.getLogger(SLF4JLoggerContext.java:41)
    at org.apache.logging.slf4j.Log4jLoggerFactory.newLogger(Log4jLoggerFactory.java:37)
    at org.apache.logging.slf4j.Log4jLoggerFactory.newLogger(Log4jLoggerFactory.java:29)
    at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:47)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:29)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:284)...
</code>```

Any idea where I am going wrong?

答: Just in case, if you have logback in your classpath, it must be removed as well!

Body:
So I have tried following this (non-maven implementation) and requirements in their web site for adding slf4j to log4j. and tried using this code

public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(Main.class);
        logger.info("test");
    }

and added the following to my library

log4j-api-2.3.jar

log4j-core-2.3.jar

log4j-sl4j-impl-2.3.jar

log4j-to-sl4j-2.3.jar

slf4j-api-1.7.12.jar

when I try running it I get the following error

Exception in thread "main" java.lang.StackOverflowError
    at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
    at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:964)
    at org.apache.logging.slf4j.SLF4JLoggerContext.getLogger(SLF4JLoggerContext.java:40)
    at org.apache.logging.slf4j.Log4jLoggerFactory.newLogger(Log4jLoggerFactory.java:37)
    at org.apache.logging.slf4j.Log4jLoggerFactory.newLogger(Log4jLoggerFactory.java:29)
    at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:47)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:29)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:284)
    at org.apache.logging.slf4j.SLF4JLoggerContext.getLogger(SLF4JLoggerContext.java:41)
    at org.apache.logging.slf4j.Log4jLoggerFactory.newLogger(Log4jLoggerFactory.java:37)
    at org.apache.logging.slf4j.Log4jLoggerFactory.newLogger(Log4jLoggerFactory.java:29)
    at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:47)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:29)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:284)...

Any idea where I am going wrong?


问:
Create a WCF Proxy for a Rest Web Service
I have a complex WCF Rest service which take multiple inputs and objects. I cannot simply call it by doing an HTTP POST in Fiddler because there is too much data to provide (I could, but it will take me forever). So I would like to do it in code using a proxy. Is there a way to generate a proxy for a .NET 4 WCF Rest Service? Otherwise, what do you propose to allow me to easily test the service?

Thanks.

答: svcutil.exe will create a proxy class that you can consume in your calling application that will allow you to call the appropriate methods and pass the parameters in code</p>

ContentLicense: CC BY-SA 3.0


问:
Sum last two records including last record of a group
In SQL Server 2017, how do I sum the last two records and show the last record in a single query?

```<code>CREATE TABLE Billing
(
    Customer CHAR(12),
    Month INT,
    Amount INT
)
GO

INSERT INTO Billing VALUES ('AAAA', 3, 5)
INSERT INTO Billing VALUES ('AAAA', 2, 0)
INSERT INTO Billing VALUES ('AAAA', 1, 2)
INSERT INTO Billing VALUES ('BBBB', 10, 0)
INSERT INTO Billing VALUES ('BBBB', 12, 1)
INSERT INTO Billing VALUES ('BBBB', 11, 0)
INSERT INTO Billing VALUES ('BBBB', 13, 6)
</code>```

Expected output:

```<code>Customer   Total Last 2 Bills   Last Bill
-----------------------------------------
AAAA                         5          5
BBBB                         7          6
</code>```

I tried using SUM with LAST_VALUE with ORDER BY

答:
You can filter out rows by using the ROW_NUMBER() window function, as in:

```<code>select
  customer,
  sum(amount) as total_last_2_bills,
  sum(case when rn = 1 then amount else 0 end) as last_bill
from (
  select
    *,
    row_number() over (partition by customer order by month desc) as rn
  from billing
) x
where rn <= 2
group by customer
</code>```

See SQL Fiddle.

Body:
In SQL Server 2017, how do I sum the last two records and show the last record in a single query?

CREATE TABLE Billing
(
    Customer CHAR(12),
    Month INT,
    Amount INT
)
GO

INSERT INTO Billing VALUES ('AAAA', 3, 5)
INSERT INTO Billing VALUES ('AAAA', 2, 0)
INSERT INTO Billing VALUES ('AAAA', 1, 2)
INSERT INTO Billing VALUES ('BBBB', 10, 0)
INSERT INTO Billing VALUES ('BBBB', 12, 1)
INSERT INTO Billing VALUES ('BBBB', 11, 0)
INSERT INTO Billing VALUES ('BBBB', 13, 6)

Expected output:

Customer   Total Last 2 Bills   Last Bill
-----------------------------------------
AAAA                         5          5
BBBB                         7          6

I tried using SUM with LAST_VALUE with ORDER BY

Body:
You can filter out rows by using the ROW_NUMBER() window function, as in:

select
  customer,
  sum(amount) as total_last_2_bills,
  sum(case when rn = 1 then amount else 0 end) as last_bill
from (
  select
    *,
    row_number() over (partition by customer order by month desc) as rn
  from billing
) x
where rn <= 2
group by customer

See SQL Fiddle.


问:
With PostgreSQL how to determine the average completion time given two time stamps while accounting for nulls
In my PostgreSQL database I have an invitations table with the following fields:

```<code>Invitations: id, created_at, completed_at (timestamp)
</code>```

I am working to write a PostgreSQL query that tells me the average completion time for invitations per weekly cohort:

Here is what I have so far:

```<code>SELECT
    TRUNC(DATE_PART('day', CURRENT_DATE - i.created_at )/7)  AS weeks_ago,
    date(min(i.created_at)) AS "Date Start",
    date(max(i.created_at)) AS "Date End",
    avg(i.completed_at - i.created_at) as average_days_to_complete
FROM invitations i
GROUP BY weeks_ago
ORDER BY weeks_ago ASC;
</code>```

The problem with my query is this line:

```<code>`avg(i.completed_at - i.created_at) as average_days_to_complete`
</code>```

The problem is this select statement is not ignoring invitations that were not completed, meaning i.completed_at is NULL

How can I update the above to only include invitations that were completed?

答:
How do you want to treat them?  You can give them the current timestamp:

```<code>SELECT TRUNC(DATE_PART('day', CURRENT_DATE - i.created_at )/7)  AS weeks_ago,
       date(min(i.created_at)) AS "Date Start",
       date(max(i.created_at)) AS "Date End",
      avg(coalesce(i.completed_at, now()) - i.created_at) as average_days_to_complete
FROM invitations i
GROUP BY weeks_ago
ORDER BY weeks_ago ASC;
</code>```

If you want to ignore them, then your version does that:

```<code>avg(i.completed_at - i.created_at)
</code>```

When i.completed_at is NULL, then the result is NULL and avg() ignores NULL values.

Body:
In my PostgreSQL database I have an invitations table with the following fields:

Invitations: id, created_at, completed_at (timestamp)

I am working to write a PostgreSQL query that tells me the average completion time for invitations per weekly cohort:

Here is what I have so far:

SELECT
    TRUNC(DATE_PART('day', CURRENT_DATE - i.created_at )/7)  AS weeks_ago,
    date(min(i.created_at)) AS "Date Start",
    date(max(i.created_at)) AS "Date End",
    avg(i.completed_at - i.created_at) as average_days_to_complete
FROM invitations i
GROUP BY weeks_ago
ORDER BY weeks_ago ASC;

The problem with my query is this line:

`avg(i.completed_at - i.created_at) as average_days_to_complete`

The problem is this select statement is not ignoring invitations that were not completed, meaning i.completed_at is NULL

How can I update the above to only include invitations that were completed?

Body:
How do you want to treat them?  You can give them the current timestamp:

SELECT TRUNC(DATE_PART('day', CURRENT_DATE - i.created_at )/7)  AS weeks_ago,
       date(min(i.created_at)) AS "Date Start",
       date(max(i.created_at)) AS "Date End",
      avg(coalesce(i.completed_at, now()) - i.created_at) as average_days_to_complete
FROM invitations i
GROUP BY weeks_ago
ORDER BY weeks_ago ASC;

If you want to ignore them, then your version does that:

avg(i.completed_at - i.created_at)

When i.completed_at is NULL, then the result is NULL and avg() ignores NULL values.


问:
suitable image found ; xcode 13.3
After installing AdMob with CocoaPods in iOS, the same error is repeated continuously during app installation.

This only occurs when building on the iPhone and does not occur in the simulator.

```<code>dyld: Library not loaded: @rpath/GoogleUtilities.framework/GoogleUtilities
  Referenced from: /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/DDday
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: code signature invalid for '/private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities'

    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: stat() failed with errno=25
    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: code signature invalid for '/private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities'

    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: stat() failed with errno=1
    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: code signature invalid for '/private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities'

    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: stat() failed with errno=1
</code>```

答:
This is a known issue introduced with iOS 13.3.1. Hopefully Apple is working on a permanent fix.

To work-around try the following steps, they worked for me when experiencing the same issue:

Open your Podfile and replace the "use_frameworks!" line with "use_modular_headers!"

In Terminal execute pod update && pod install

In Xcode clean the build folder and re-run the project.

Title: suitable image found ; xcode 13.3

Body:
After installing AdMob with CocoaPods in iOS, the same error is repeated continuously during app installation.

This only occurs when building on the iPhone and does not occur in the simulator.

dyld: Library not loaded: @rpath/GoogleUtilities.framework/GoogleUtilities
  Referenced from: /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/DDday
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: code signature invalid for '/private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities'

    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: stat() failed with errno=25
    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: code signature invalid for '/private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities'

    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: stat() failed with errno=1
    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: code signature invalid for '/private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities'

    /private/var/containers/Bundle/Application/2C855177-A56F-404D-87E0-21273F9473EE/DDday.app/Frameworks/GoogleUtilities.framework/GoogleUtilities: stat() failed with errno=1


问:
Simulate API 29 Vibrations in 26 and below
I want to simulate API 29 vibration effects:

```<code>EFFECT_CLICK
EFFECT_DOUBLE_CLICK
EFFECT_HEAVY_CLICK
EFFECT_TICK
</code>```

in version 26 and lower as well. Does anybody know how these translate?

答:
Here is what I did. I am only covering two types of vibrations which will have to do. A longer single one and two short ones, which may translate to CLICK and DOUBLE_CLICK:</p>

```<code>private void vibrate(int vibrationMessageId) {

    long[] doubleClickPattern = {0, 75, 75, 75};

    if (Build.VERSION.SDK_INT >= 26) {
        Log.d(TAG, "vibrate: SDK 26+ " + Build.VERSION.SDK_INT);

        switch (vibrationMessageId) {
            case Constants.VIBRATION_HEAVY_CLICK:
                ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE));
                break;
            case Constants.VIBRATION_DOUBLE_CLICK:
                ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createWaveform(doubleClickPattern,-1));
                break;
        }

    } else {
        Log.d(TAG, "vibrate: SDK <26 " + Build.VERSION.SDK_INT);

        switch (vibrationMessageId) {
            case Constants.VIBRATION_HEAVY_CLICK:
                ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(200);
                break;
            case Constants.VIBRATION_DOUBLE_CLICK:

                ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(doubleClickPattern,-1);
                break;
        }
    }
}
</code>```

Body:
I want to simulate API 29 vibration effects:

EFFECT_CLICK
EFFECT_DOUBLE_CLICK
EFFECT_HEAVY_CLICK
EFFECT_TICK

in version 26 and lower as well. Does anybody know how these translate?

Body:
Here is what I did. I am only covering two types of vibrations which will have to do. A longer single one and two short ones, which may translate to CLICK and DOUBLE_CLICK:

private void vibrate(int vibrationMessageId) {

    long[] doubleClickPattern = {0, 75, 75, 75};

    if (Build.VERSION.SDK_INT >= 26) {
        Log.d(TAG, "vibrate: SDK 26+ " + Build.VERSION.SDK_INT);

        switch (vibrationMessageId) {
            case Constants.VIBRATION_HEAVY_CLICK:
                ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE));
                break;
            case Constants.VIBRATION_DOUBLE_CLICK:
                ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createWaveform(doubleClickPattern,-1));
                break;
        }

    } else {
        Log.d(TAG, "vibrate: SDK <26 " + Build.VERSION.SDK_INT);

        switch (vibrationMessageId) {
            case Constants.VIBRATION_HEAVY_CLICK:
                ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(200);
                break;
            case Constants.VIBRATION_DOUBLE_CLICK:

                ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(doubleClickPattern,-1);
                break;
        }
    }
}


问:
Python heapq sorting for string list not correct?
I am wondering why not the heapq in python sort the strings in lexical order when using heappush?
Below is the code I tried. Anyone know why they print different order?</p>

```<code>import heapq
string_list = ["TIA","AXA","JFK"]
result = []
for each in string_list:
    heapq.heappush(result, each)

print(result)
>>> ['AXA', 'TIA', 'JFK']

print(sorted(string_list))
>>> ['AXA', 'JFK', 'TIA']
</code>```

答:
Heap queue is minheap, it makes sure that min element in at the top of the queue, it doesn't sort list.
If you want to sort your list using heapq, then you need to do the following:

import heapq

string_list = ["TIA","AXA","JFK"]
heapq.heapify(string_list) # this will create max queue from your list
result = []
while string_list:
    result.append(heapq.heappop(string_list))
print(result)
```

<p>But simpler and faster would be to just use in-place sort:</p>

```string_list.sort()
print(string_list)
```

Body:
I am wondering why not the heapq in python sort the strings in lexical order when using heappush?
Below is the code I tried. Anyone know why they print different order?

import heapq
string_list = ["TIA","AXA","JFK"]
result = []
for each in string_list:
    heapq.heappush(result, each)

print(result)
>>> ['AXA', 'TIA', 'JFK']

print(sorted(string_list))
>>> ['AXA', 'JFK', 'TIA']

Body:
Heap queue is minheap, it makes sure that min element in at the top of the queue, it doesn't sort list.
If you want to sort your list using heapq, then you need to do the following:

import heapq

string_list = ["TIA","AXA","JFK"]
heapq.heapify(string_list) # this will create max queue from your list
result = []
while string_list:
    result.append(heapq.heappop(string_list))
print(result)

But simpler and faster would be to just use in-place sort:

string_list.sort()
print(string_list)


问:
v-bind in b-list-group-item not working in vue CLI-app with boootstrap-vue
i have an app made with vue-CLI including bootstrap-vue. In my App.vue i'am using axios to fetch some sample JSON-data. I generate a list with the b-list-group-item (bootstrap-tag) and want to bind a key in each element (v-bind:key="result.ItemId"). This is not working. In html no "key" is rendered.

This is the code snippet:

```<code> <b-list-group >
      <b-list-group-item
        href="#"
        class="flex-column align-items-start"
        v-for="result in post"
        v-bind:key="result.ItemId"
      >
        <div class="d-flex w-100 justify-content-between">
          <h6 class="mb-1">{{ result.ItemHeading }}</h6>
          <small>{{ result.ItemSubHeading }}</small>
        </div>

        <p class="mb-1">{{ result.ItemDetails }}</p>

      </b-list-group-item>
    </b-list-group>
</code>```

This is the rendered html with no key-binding:

This is the JSON-result:

```<code>0: {ItemId: "10075328", ItemHeading: "news im November", ItemSubHeading: "unter news",…}
Date4Itemnew: "24.11.2019"
ItemDetails: "lorem ipsum"
ItemHeading: "news im November"
ItemId: "10075328"
ItemSubHeading: "unter news"
u_date: "1574550000"
</code>```

I tried all possibilities to bind it. Please help.

答:
First you have to loop inside the json file by value of key [ result.ItemHeading ] , After you have to bind this value inside props by same name of value  props: ["ItemHeading", "ItemSubHeading", "ItemDetails"]

<template>

{{ result.ItemHeading }}

            {{ result.ItemSubHeading }}

{{ result.ItemDetails }}

</template>

```

Body:
i have an app made with vue-CLI including bootstrap-vue. In my App.vue i'am using axios to fetch some sample JSON-data. I generate a list with the b-list-group-item (bootstrap-tag) and want to bind a key in each element (v-bind:key="result.ItemId"). This is not working. In html no "key" is rendered.

This is the code snippet:

{{ result.ItemHeading }}

          {{ result.ItemSubHeading }}

{{ result.ItemDetails }}

This is the rendered html with no key-binding:

This is the JSON-result:

0: {ItemId: "10075328", ItemHeading: "news im November", ItemSubHeading: "unter news",…}
Date4Itemnew: "24.11.2019"
ItemDetails: "lorem ipsum"
ItemHeading: "news im November"
ItemId: "10075328"
ItemSubHeading: "unter news"
u_date: "1574550000"

I tried all possibilities to bind it. Please help.

Body:
First you have to loop inside the json file by value of key [ result.ItemHeading ] , After you have to bind this value inside props by same name of value  props: ["ItemHeading", "ItemSubHeading", "ItemDetails"]

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
   <b-list-group>
      <b-list-group-item
         href="#"
         class="flex-column align-items-start"
         v-for="result in post"
         v-bind:key="result.ItemId"
         v-bind:ItemHeading="result.ItemHeading"
         v-bind:ItemSubHeading="result.ItemSubHeading"
         v-bind:ItemDetails="result.ItemDetails"
      >
         <div class="d-flex w-100 justify-content-between">
            <h6 class="mb-1">{{ result.ItemHeading }}</h6>
            <small>{{ result.ItemSubHeading }}</small>
         </div>

         <p class="mb-1">{{ result.ItemDetails }}</p>
      </b-list-group-item>
   </b-list-group>
</template>

<script>
export default {
   props: ["ItemHeading", "ItemSubHeading", "ItemDetails"]
};
</script>


问:
If AD Description has certain number add to a specified group
I have a script I'm trying to expand on to create student accounts from a csv. Works great.

What I'm looking for:

If the description has the following number: 01, 02, 03, 04, 05, 06 add to. K-6 Students member group.

If the description has the following numbers: 07, 08, 09, 10, 11, or 12 add to 6-12 Students member group.

In addition to the All-Students group listed below.

Account example: https://imgur.com/a/h9UDFfJ

Here is part of the script I'm using

```<code> New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Path "$OU" -ChangePasswordAtLogon $false –PasswordNeverExpires $true -Enabled $true -server AD1.schoolname.k12.or.us -HomeDirectory $HomeDirectory -HomeDrive $HomeDrive

    Add-ADGroupMember -identity All-Students -members $SAM -server AD1.schoolname.k12.or.us

    Write-Host "AD Account $Displayname created!"

    add-content $SuccessLog  "User $Displayname created Sucessfully."

    Write-Host -ForegroundColor Green $Displayname
</code>```

答:
You can use the following to sort your students:

```<code>$students = Get-ADUser -Filter "Description -like '*0*' -or Description -like '*1*'" -Properties Description
$studentsK6 = $students | Where Description -match '0[1-6]'
$students712 = $students | Where Description -match '0[7-9]|1[0-2]'

Add-ADGroupMember -Identity 'K-6 Students' -Members $studentsK6.SamAccountName
Add-ADGroupMember -Identity '6-12 Students' -Members $students712.SamAccountName
</code>```

Explanation:

-Filter is used to help narrow down the user search, and it is typically faster than piping to Where-Object.

-Properties Description is used to ensure that $students contains the Description property so we can compare against it later. By default, the ADUser object does not show the Description property with the default output view.

0[1-6] matches any two-digit number that begins with 0 and ends with 1,2,3,4,5, or 6.

0[7-9]|1[0-2] first attempts to match 0 followed by a 7,8, or 9. If that fails, it will try matching 1 followed by 0,1, or 2.

You can make the matching more reliable if you know exactly where the number exists in the Description. For example, if it is always at the end of the Description, you can use 0[1-6]$ where $ matches the end of a string.

Body:
I have a script I'm trying to expand on to create student accounts from a csv. Works great.

What I'm looking for:

If the description has the following number: 01, 02, 03, 04, 05, 06 add to. K-6 Students member group.

If the description has the following numbers: 07, 08, 09, 10, 11, or 12 add to 6-12 Students member group.

In addition to the All-Students group listed below.

Account example: https://imgur.com/a/h9UDFfJ

Here is part of the script I'm using

 New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Path "$OU" -ChangePasswordAtLogon $false –PasswordNeverExpires $true -Enabled $true -server AD1.schoolname.k12.or.us -HomeDirectory $HomeDirectory -HomeDrive $HomeDrive

    Add-ADGroupMember -identity All-Students -members $SAM -server AD1.schoolname.k12.or.us

    Write-Host "AD Account $Displayname created!"

    add-content $SuccessLog  "User $Displayname created Sucessfully."

    Write-Host -ForegroundColor Green $Displayname

Body:
You can use the following to sort your students:

$students = Get-ADUser -Filter "Description -like '*0*' -or Description -like '*1*'" -Properties Description
$studentsK6 = $students | Where Description -match '0[1-6]'
$students712 = $students | Where Description -match '0[7-9]|1[0-2]'

Add-ADGroupMember -Identity 'K-6 Students' -Members $studentsK6.SamAccountName
Add-ADGroupMember -Identity '6-12 Students' -Members $students712.SamAccountName

Explanation:

-Filter is used to help narrow down the user search, and it is typically faster than piping to Where-Object.

-Properties Description is used to ensure that $students contains the Description property so we can compare against it later. By default, the ADUser object does not show the Description property with the default output view.

0[1-6] matches any two-digit number that begins with 0 and ends with 1,2,3,4,5, or 6.

0[7-9]|1[0-2] first attempts to match 0 followed by a 7,8, or 9. If that fails, it will try matching 1 followed by 0,1, or 2.

You can make the matching more reliable if you know exactly where the number exists in the Description. For example, if it is always at the end of the Description, you can use 0[1-6]$ where $ matches the end of a string.


答:
I think you want a WHERE clause not a HAVING clause:

```<code>SELECT Marketics.Case, Count(Marketics.Decision) AS CountOfDecision
FROM Marketics
WHERE Marketics.Decision = "Cause Cancel";
GROUP BY Marketics.Case
</code>```

Title: Keeps counting all the text values instead of me providing a criteria in SQL

Body:
I have very simple query, to count the number of Cause Cancel from the Decision column. It keeps counting all the text values in the column and not just cause cancel.

SELECT Marketics.Case, Count(Marketics.Decision) AS CountOfDecision
FROM Marketics
GROUP BY Marketics.Case
HAVING Count(Marketics.Decision="Cause Cancel");

Body:
I think you want a WHERE clause not a HAVING clause:

SELECT Marketics.Case, Count(Marketics.Decision) AS CountOfDecision
FROM Marketics
WHERE Marketics.Decision = "Cause Cancel";
GROUP BY Marketics.Case


答:
You can add a End Of Line \r\n:

```<code>convert.append("\r\n");
</code>```

Or a Line Separator:

```<code>convert.append(System.lineSeparator());
</code>```

So, this is an edit of your code:

```<code>public static void main(String[] args) {

    String text = "";
    StringBuilder convert = new StringBuilder();
    Scanner keyboard = new Scanner (System.in);

    File file = new File ("C:\\document.txt");

    try {
        Scanner input = new Scanner (file);
        while (input.hasNextLine()) {
            text = input.nextLine();

            char [] arr = text.toCharArray();
            char [] newArr = arr;

            for (int i = 0; i < newArr.length; i++) {
                convert.append(newArr[i]);
            }

           // use this:
            convert.append(System.lineSeparator());
           // Or this:
            convert.append("\r\n");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // write file
        PrintWriter printer = new PrintWriter("C:\\My New File.txt");

        printer.append(convert);
        printer.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Title: Keeping line breaks when reading a file

Body:
I want to read a file and modify it but whenever the new file is created everything stays on one line. Therefore, my question is how can I keep line breaks without removing them?

public class JavaProgram {

    public static void main(String[] args) {
        String text = "";
        StringBuilder convert = new StringBuilder();
        Scanner keyboard = new Scanner (System.in);

        File file = new File ("PATH");

            try {
                Scanner input = new Scanner (file);
                while (input.hasNextLine()) {
                        text = input.nextLine();

                        char [] arr = text.toCharArray();
                        char [] newArr = encrypt(3, arr);

                        for (int i = 0; i < newArr.length; i++) {
                            convert.append(newArr[i]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    PrintWriter printer = new PrintWriter (document);

                    printer.append(convert);
                    printer.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }

Body:
You can add a End Of Line \r\n:

convert.append("\r\n");

Or a Line Separator:

convert.append(System.lineSeparator());

So, this is an edit of your code:

public static void main(String[] args) {

    String text = "";
    StringBuilder convert = new StringBuilder();
    Scanner keyboard = new Scanner (System.in);

    File file = new File ("C:\\document.txt");

    try {
        Scanner input = new Scanner (file);
        while (input.hasNextLine()) {
            text = input.nextLine();

            char [] arr = text.toCharArray();
            char [] newArr = arr;

            for (int i = 0; i < newArr.length; i++) {
                convert.append(newArr[i]);
            }

           // use this:
            convert.append(System.lineSeparator());
           // Or this:
            convert.append("\r\n");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // write file
        PrintWriter printer = new PrintWriter("C:\\My New File.txt");

        printer.append(convert);
        printer.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}


问:
Cannot find "Paste Special" option in Visual Studio 2017
I cannot see the Paste Special option in my Visual Studio 2017 Professional Edition:

Microsoft Visual Studio Professional 2017

Version 15.4.5

VisualStudio.15.Release/15.4.5+27004.2010

Microsoft .NET Framework

Version 4.7.02046

In this blog post it is shown for Visual Studio 2013. On my machine, the edit menu appears as below:

Is there a way to get back the option? Do I need to enable this option somehow?

答:
The Paste Special option will not show if you are debugging.

I stopped my application and the Paste Special option appeared right away.

This was in Visual Studio 2017, but I assume it would be the same for all versions.


问:
How to change the tabs in react native application using native base components
i have a main screen that contains 2 Tabs in which every one renders different result.
At the end of the the first tabs, i have two buttons that :             First Button --> redirect to  First Tab year 1 (the default tab)
Second Button --> redirect to First Tab Version Two  year 2
So, basically the buttons redirect to different Tab every time selected . I need to only change the tab not the whole screen.
here is the code that i used and it's working fine for the default Tab but i don't know how to implement the buttons so that it redirects to different tabs with changing the main screen ... Any help ?

Main screen :

```<code><Tabs>
    <Tab heading="First Tab">
        <FirstTab text={key} />
    </Tab>
    <Tab heading="Second Tab">
        <SecondTab/>
    </Tab>
</Tabs>
</code>```

the First Tab (the default one)

```<code><ScrollView>
                ...
                    <View style={{flexDirection: 'row'}}>
                        <Button active>
                            <Text>
                                year 1
                            </Text>
                        </Button>
                        <Button>
                            <Text> year 2  </Text>
                        </Button>
                    </View>
                </View>
</ScrollView>
</code>```

Here is an image that explains what i need to do :

I also tried this method: Implementing Footer Tabs in Native React using Native Base and the code i used is :

```<code><Tabs>
    <Tab>
        <Content>{this.renderSelectedTab()} </Content>
    </Tab>
    <Tab>
        <SecondTab/>
    </Tab>
</Tabs>
<View style={{flexDirection: 'row'}}>
    <Button active={this.selectedTab==='2016'}
            onPress={() => this.state.setState({selectedTab: '2016'})}>
                  <Text> 2016 </Text>
    </Button>

    <Button active={this.state.selectedTab==='2015'}
            onPress={() => this.setState({selectedTab: '2015'})} >
                <Text> 2015 </Text>
    </Button>
</View>
</code>```

..

```<code>renderSelectedTab () {
   console.log("this.state.selectedTab", this.selectedTab )
        switch (this.state.selectedTab) {
            case '2016':
                return (<Tab2016 />);
                break;
            case '2015':
                return (<Tab2015 />);
                break;
            default:
                return (<Tab2016 />);
        }
    }
</code>```

And i get

If i use this.selectedTab instead of this.state.selectedTab it runs fine but i get in the console :  and it runs directly the default value and the buttons don't work

答:
Actually, that is not how it works.
You need to use the page and initialPage props of Tabs Component and then to change tabs you only need to update the page props to the tab index

So that is an example:

```<code>import React from 'react';
import { Button, Text } from 'react-native';
import { Container, Header, Content, Tab, Tabs } from 'native-base';

export default class AuthScreenContent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {activeTab: 0, initialTab: 0}
  }

  render() {
    return (
        <Container>
          <Tabs initialPage={this.state.initialTab} page={this.state.activeTab}>
            <Tab heading="Sign up">
              <Text>This is the register's content </Text>
              <Button
                  title="Go to login tab"
                  onPress={() => this.setState({activeTab: 1})}
              />
            </Tab>
            <Tab heading="Login">
              <Text>This is the login's content </Text>
              <Button
                  title="Go to register tab"
                  onPress={() => this.setState({activeTab: 0})}
              />
            </Tab>
          </Tabs>
        </Container>
    );
  }
};

</code>```

Body:
i have a main screen that contains 2 Tabs in which every one renders different result.
At the end of the the first tabs, i have two buttons that :             First Button --> redirect to  First Tab year 1 (the default tab)
Second Button --> redirect to First Tab Version Two  year 2
So, basically the buttons redirect to different Tab every time selected . I need to only change the tab not the whole screen.
here is the code that i used and it's working fine for the default Tab but i don't know how to implement the buttons so that it redirects to different tabs with changing the main screen ... Any help ?

Main screen :

<Tabs>
    <Tab heading="First Tab">
        <FirstTab text={key} />
    </Tab>
    <Tab heading="Second Tab">
        <SecondTab/>
    </Tab>
</Tabs>

the First Tab (the default one)

<ScrollView>
                ...
                    <View style={{flexDirection: 'row'}}>
                        <Button active>
                            <Text>
                                year 1
                            </Text>
                        </Button>
                        <Button>
                            <Text> year 2  </Text>
                        </Button>
                    </View>
                </View>
</ScrollView>

Here is an image that explains what i need to do :

I also tried this method: Implementing Footer Tabs in Native React using Native Base and the code i used is :

<Tabs>
    <Tab>
        <Content>{this.renderSelectedTab()} </Content>
    </Tab>
    <Tab>
        <SecondTab/>
    </Tab>
</Tabs>
<View style={{flexDirection: 'row'}}>
    <Button active={this.selectedTab==='2016'}
            onPress={() => this.state.setState({selectedTab: '2016'})}>
                  <Text> 2016 </Text>
    </Button>

    <Button active={this.state.selectedTab==='2015'}
            onPress={() => this.setState({selectedTab: '2015'})} >
                <Text> 2015 </Text>
    </Button>
</View>

..

renderSelectedTab () {
   console.log("this.state.selectedTab", this.selectedTab )
        switch (this.state.selectedTab) {
            case '2016':
                return (<Tab2016 />);
                break;
            case '2015':
                return (<Tab2015 />);
                break;
            default:
                return (<Tab2016 />);
        }
    }

And i get

If i use this.selectedTab instead of this.state.selectedTab it runs fine but i get in the console :  and it runs directly the default value and the buttons don't work

Body:
Actually, that is not how it works.
You need to use the page and initialPage props of Tabs Component and then to change tabs you only need to update the page props to the tab index

So that is an example:

import React from 'react';
import { Button, Text } from 'react-native';
import { Container, Header, Content, Tab, Tabs } from 'native-base';

export default class AuthScreenContent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {activeTab: 0, initialTab: 0}
  }

  render() {
    return (
        <Container>
          <Tabs initialPage={this.state.initialTab} page={this.state.activeTab}>
            <Tab heading="Sign up">
              <Text>This is the register's content </Text>
              <Button
                  title="Go to login tab"
                  onPress={() => this.setState({activeTab: 1})}
              />
            </Tab>
            <Tab heading="Login">
              <Text>This is the login's content </Text>
              <Button
                  title="Go to register tab"
                  onPress={() => this.setState({activeTab: 0})}
              />
            </Tab>
          </Tabs>
        </Container>
    );
  }
};


问:
react-native-maps: AirGoogleMaps dir must be added to your xCode project to support GoogleMaps on iOS
I'm trying to use google maps on iOS and I get this error:

react-native-maps: AirGoogleMaps dir must be added to your xCode project to support GoogleMaps on iOS.

Error Image

I'm using react-native.maps
 https://github.com/react-community/react-native-maps

I followed the install instructions, in Android it worked perfectly but it doesn't in IOS

macOS: 10.14.1 (18B75)

```<code>dependencies {

"react": "16.5.0",

"react-native": "0.57.1",

"react-native-maps": "^0.22.1",

}
</code>```

答:
Or, if the provider isn't important for you, just remove following prop in MapView:

provider={MapView.PROVIDER_GOOGLE}

It solved the issue for me

Body:
I'm trying to use google maps on iOS and I get this error:

react-native-maps: AirGoogleMaps dir must be added to your xCode project to support GoogleMaps on iOS.

Error Image

I'm using react-native.maps
 https://github.com/react-community/react-native-maps

I followed the install instructions, in Android it worked perfectly but it doesn't in IOS

macOS: 10.14.1 (18B75)

dependencies {

"react": "16.5.0",

"react-native": "0.57.1",

"react-native-maps": "^0.22.1",

}


问:
Summing across SAS arrays based on intervals i.e. start date and end date
I am trying to sum variables in an array based on start and end date. For each ID there is one row (if the start and end date are within the same year), two rows (if the start and end date are within consecutive years) or multiple rows for different periods of start and end dates. There are 12 variables with counts for each month i.e. v1-v12 where v1 is january and v12 is december. The two rows for some ID contain monthly values for the 2 consecutive years i.e. within the stat year and the end year. I am trying to get the sum count for the array variables but only from the start date to the end date for each ID. For example, for ID 1  the start date is 07/23/2007 and end date is 06/07/2008, i would like to sum from V7 (july start month) to v12 in 2007 and V1 to V6 (june end month) in 2008 i.e. second row.  Here's what I have:

```<code>ID  STARTDATE   ENDDATE      YR    V1  V2  V3  V4  V5  V6  V7  V8  V9  V10 V11 V12
1   07/23/2007  06/07/2008  2007    3   5   2   6   3   2   1   3   4   1   2   3
1   07/23/2007  06/07/2008  2008    0   4   2   2   3   0   1   3   1   0   2   3
2   02/01/2002  07/27/2002  2002    1   0   2   3   1   0   1   2   3   0   0   2
3   05/26/2008  03/07/2009  2008    2   0   2   3   1   2   1   1   3   0   0   1
3   05/26/2008  03/07/2009  2009    4   1   4   3   1   0   2   3   3   1   0   3
3   10/17/2011  08/17/2012  2011    3   3   0   1   0   1   1   5   3   1   0   1
3   10/17/2011  08/17/2012  2012    1   3   2   3   1   0   1   2   3   2   0   2
4   02/27/2004  01/22/2005  2004    2   0   2   3   1   2   1   1   3   0   0   1
4   02/27/2004  01/22/2005  2005    0   4   2   2   3   0   1   3   1   0   2   3
</code>```

and this is what I want :

```<code>ID  STARTDATE   ENDDATE      YR    V1  V2  V3  V4  V5  V6  V7  V8  V9  V10  V11  V12  sum
1   07/23/2007  06/07/2008  2007    3   5   2   6   3   2  [1   3   4    1    2    3]  25
1   07/23/2007  06/07/2008  2008   [0   4   2   2   3   0]  1   3   1    0    2    3   25
2   02/01/2002  07/27/2002  2002    1  [0   2   3   1   0   1]  2   3    0    0    2    8
3   05/26/2008  03/07/2009  2008    2   0   2   3  [1   2   1   1   3    0    0    1]  18
3   05/26/2008  03/07/2009  2009   [4   1   4]  3   1   0   2   3   3    1    0    3   18
3   10/17/2011  08/17/2012  2011    3   3   0   1   0   1   1   5   3   [1    0    1]  15
3   10/17/2011  08/17/2012  2011   [1   3   2   3   1   0   1   2]  3    2    0    2   15
4   02/27/2004  01/22/2005  2004    2  [0   2   3   1   2   1   1   3    0    0    1]  14
4   02/27/2004  01/22/2005  2005   [0]  4   2   2   3   0   1   3   1    0    2    3   14
</code>```

Here's the code I tried

```<code>data want;
  set have;
  array vars(*) V1-V12;
  DT_CHECK=intnx('month',ENDDATE,-12);
  start=intck('month','STARTDATE,DT_CHECK)+1;
  if start<1 then do;
    error 'Start date out of range';
    delete;
    end;
  else if start>dim(vars)-12 then do;
    error 'End date out of range';
    delete;
    end;
  do _N_=start to start+12;
    sum_n+vars(_N_);
    end;
  format DT_CHECK mmddyy10.;
run;
</code>```

But am having problems. Any help is appreciated. Thank you.

答:
A DOW / serial loop technique can compute a value for criteria over a group, and then apply that value to each row in group.

Example:

Requires the start to end date intervals within an id be mutually exclusive (i.e. do not overlap and data are sorted by id startdate enddate)

```<code>data want;
  * [sum] variable is implicitly reset to missing at the top of the step.;

  do _n_ = 1 by 1 until (last.enddate);
    set have;
    by id startdate enddate;

    array v(12);

    _month1 = intnx('month', startdate, 0);
    _month2 = intnx('month', enddate,   0);

    do _index = 1 to 12;
      if _month1 <= mdy(_index,1,yr) <= _month2 then sum = sum(sum,v(_index));
    end;
  end;

  do _n_ = 1 to _n_;
    set have;
    output;
  end;

  format sum 4.;
  drop _:;
run;
</code>```

The answer does not address the scenario of startdate to enddate intervals that overlap within an id.

Body:
I am trying to sum variables in an array based on start and end date. For each ID there is one row (if the start and end date are within the same year), two rows (if the start and end date are within consecutive years) or multiple rows for different periods of start and end dates. There are 12 variables with counts for each month i.e. v1-v12 where v1 is january and v12 is december. The two rows for some ID contain monthly values for the 2 consecutive years i.e. within the stat year and the end year. I am trying to get the sum count for the array variables but only from the start date to the end date for each ID. For example, for ID 1  the start date is 07/23/2007 and end date is 06/07/2008, i would like to sum from V7 (july start month) to v12 in 2007 and V1 to V6 (june end month) in 2008 i.e. second row.  Here's what I have:

ID  STARTDATE   ENDDATE      YR    V1  V2  V3  V4  V5  V6  V7  V8  V9  V10 V11 V12
1   07/23/2007  06/07/2008  2007    3   5   2   6   3   2   1   3   4   1   2   3
1   07/23/2007  06/07/2008  2008    0   4   2   2   3   0   1   3   1   0   2   3
2   02/01/2002  07/27/2002  2002    1   0   2   3   1   0   1   2   3   0   0   2
3   05/26/2008  03/07/2009  2008    2   0   2   3   1   2   1   1   3   0   0   1
3   05/26/2008  03/07/2009  2009    4   1   4   3   1   0   2   3   3   1   0   3
3   10/17/2011  08/17/2012  2011    3   3   0   1   0   1   1   5   3   1   0   1
3   10/17/2011  08/17/2012  2012    1   3   2   3   1   0   1   2   3   2   0   2
4   02/27/2004  01/22/2005  2004    2   0   2   3   1   2   1   1   3   0   0   1
4   02/27/2004  01/22/2005  2005    0   4   2   2   3   0   1   3   1   0   2   3

and this is what I want :

ID  STARTDATE   ENDDATE      YR    V1  V2  V3  V4  V5  V6  V7  V8  V9  V10  V11  V12  sum
1   07/23/2007  06/07/2008  2007    3   5   2   6   3   2  [1   3   4    1    2    3]  25
1   07/23/2007  06/07/2008  2008   [0   4   2   2   3   0]  1   3   1    0    2    3   25
2   02/01/2002  07/27/2002  2002    1  [0   2   3   1   0   1]  2   3    0    0    2    8
3   05/26/2008  03/07/2009  2008    2   0   2   3  [1   2   1   1   3    0    0    1]  18
3   05/26/2008  03/07/2009  2009   [4   1   4]  3   1   0   2   3   3    1    0    3   18
3   10/17/2011  08/17/2012  2011    3   3   0   1   0   1   1   5   3   [1    0    1]  15
3   10/17/2011  08/17/2012  2011   [1   3   2   3   1   0   1   2]  3    2    0    2   15
4   02/27/2004  01/22/2005  2004    2  [0   2   3   1   2   1   1   3    0    0    1]  14
4   02/27/2004  01/22/2005  2005   [0]  4   2   2   3   0   1   3   1    0    2    3   14

Here's the code I tried

data want;
  set have;
  array vars(*) V1-V12;
  DT_CHECK=intnx('month',ENDDATE,-12);
  start=intck('month','STARTDATE,DT_CHECK)+1;
  if start<1 then do;
    error 'Start date out of range';
    delete;
    end;
  else if start>dim(vars)-12 then do;
    error 'End date out of range';
    delete;
    end;
  do _N_=start to start+12;
    sum_n+vars(_N_);
    end;
  format DT_CHECK mmddyy10.;
run;

But am having problems. Any help is appreciated. Thank you.

Body:
A DOW / serial loop technique can compute a value for criteria over a group, and then apply that value to each row in group.

Example:

Requires the start to end date intervals within an id be mutually exclusive (i.e. do not overlap and data are sorted by id startdate enddate)

data want;
  * [sum] variable is implicitly reset to missing at the top of the step.;

  do _n_ = 1 by 1 until (last.enddate);
    set have;
    by id startdate enddate;

    array v(12);

    _month1 = intnx('month', startdate, 0);
    _month2 = intnx('month', enddate,   0);

    do _index = 1 to 12;
      if _month1 <= mdy(_index,1,yr) <= _month2 then sum = sum(sum,v(_index));
    end;
  end;

  do _n_ = 1 to _n_;
    set have;
    output;
  end;

  format sum 4.;
  drop _:;
run;

The answer does not address the scenario of startdate to enddate intervals that overlap within an id.


问:
Remove default HTTP Headers from HTTPie's request
There are a couple of default headers that HTTPie sets. I'm wondering if there is a way to remove some header, like Accept-Encoding?

The reason I like to unset Accept-Encoding is to check our server's behavior about HTTP Compression.

答:
Add the Headers follow by a colon.

No headers:

```<code>http -v https://jsonplaceholder.typicode.com/todos/1 \
     Accept: \
     Accept-Encoding: \
     Connection: \
     Host: \
     User-Agent:
</code>```

Request:

```<code>GET /todos/1 HTTP/1.1
Host: jsonplaceholder.typicode.com
</code>```

Response:

```<code>HTTP/1.1 200 OK
...
</code>```

Standard:

```<code>http -v https://jsonplaceholder.typicode.com/todos/1
</code>```

Request:

```<code>GET /todos/1 HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: jsonplaceholder.typicode.com
User-Agent: HTTPie/0.9.8
</code>```

Response:

```<code>HTTP/1.1 200 OK
...
</code>```

The -v option display the request. Also, remember no spaces after \ in multiline bash commands.

Body:
Add the Headers follow by a colon.

No headers:

http -v https://jsonplaceholder.typicode.com/todos/1 \
     Accept: \
     Accept-Encoding: \
     Connection: \
     Host: \
     User-Agent:

Request:

GET /todos/1 HTTP/1.1
Host: jsonplaceholder.typicode.com

Response:

HTTP/1.1 200 OK
...

Standard:

http -v https://jsonplaceholder.typicode.com/todos/1

Request:

GET /todos/1 HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: jsonplaceholder.typicode.com
User-Agent: HTTPie/0.9.8

Response:

HTTP/1.1 200 OK
...

The -v option display the request. Also, remember no spaces after \ in multiline bash commands.


问:
Constrain layout is not working on all android devices screen size
I have the following layout, it works fine for big screens like note 9 Samsung, but it will not shrink to fit the screen size in small phones, please refer to the attached picture and codes.
I like to use the constraint layouts , I did choised all items to be in form of WRAPCONTENT or MATCHCONSTRAIN , but still have the start button jump out of screen in small phones .

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/scroll"
    tools:context=".teamselect">

    <EditText
        android:id="@+id/team1EdtTxt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:layout_marginBottom="22dp"
        android:ems="10"
        android:hint="اللاعب 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/team1EdtTxt2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/team1EdtTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:layout_marginBottom="54dp"
        android:clickable="false"
        android:editable="false"
        android:ems="10"
        android:hint="اللاعب 2"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team1EdtTxt1" />

    <EditText
        android:id="@+id/team2EdtTxt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:layout_marginBottom="22dp"
        android:clickable="false"
        android:ems="10"
        android:hint="اللاعب 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/team2EdtTxt2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <EditText
        android:id="@+id/team2EdtTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginLeft="148dp"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:clickable="false"
        android:ems="10"
        android:hint="اللاعب 2"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team2EdtTxt1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="209dp"
        android:layout_marginLeft="209dp"
        android:layout_marginTop="129dp"
        android:layout_marginEnd="41dp"
        android:layout_marginRight="41dp"
        android:layout_marginBottom="24dp"
        android:text="الفريق الاول"
        android:textSize="36sp"
        app:fontFamily="@font/advent_pro_thin"
        app:layout_constraintBottom_toTopOf="@+id/team1EdtTxt1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="209dp"
        android:layout_marginLeft="209dp"
        android:layout_marginTop="44dp"
        android:layout_marginEnd="41dp"
        android:layout_marginRight="41dp"
        android:layout_marginBottom="24dp"
        android:text="الفريق الثاني"
        android:textSize="36sp"
        app:layout_constraintBottom_toTopOf="@+id/team2EdtTxt1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team1EdtTxt2" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="110dp"
        android:layout_marginLeft="110dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="110dp"
        android:layout_marginRight="110dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/buttondomeno"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team2EdtTxt2" />
</androidx.constraintlayout.widget.ConstraintLayout>```

答:
Adding to @Hamza Khan answer, try to avoid using any fixed sizes on your views, you can use this layout:

```<code> <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="0dp">

    <EditText
        android:id="@+id/team1EdtTxt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="اللاعب 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/team1EdtTxt2"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/team1EdtTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:clickable="false"
        android:editable="false"
        android:ems="10"
        android:hint="اللاعب 2"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/team1EdtTxt1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="الفريق الاول"
        android:textSize="36sp"
        app:layout_constraintBottom_toTopOf="@+id/team1EdtTxt1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="الفريق الثاني"
        android:textSize="36sp"
        app:layout_constraintBottom_toTopOf="@+id/team2EdtTxt1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline3" />

    <EditText
        android:id="@+id/team2EdtTxt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:clickable="false"
        android:ems="10"
        android:hint="اللاعب 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/team2EdtTxt2"
        app:layout_constraintEnd_toEndOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <EditText
        android:id="@+id/team2EdtTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="false"
        android:ems="10"
        android:hint="اللاعب 2"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/startBtn"
        app:layout_constraintEnd_toEndOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/team2EdtTxt1" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="start"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintWidth_percent="0.3" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.50" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.10" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

It will look like this:

Notice that I have used 2 very useful attributes:

```<code>  app:layout_constraintHeight_percent="0.1"
  app:layout_constraintWidth_percent="0.3"
</code>```

In addition, I have used Guidelines so now if you want to change the look of your layout you can simply change this attrubute:

```<code>  app:layout_constraintGuide_percent="0.x"
</code>```

Body:
Adding to @Hamza Khan answer, try to avoid using any fixed sizes on your views, you can use this layout:

 <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="0dp">

    <EditText
        android:id="@+id/team1EdtTxt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="اللاعب 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/team1EdtTxt2"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/team1EdtTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:clickable="false"
        android:editable="false"
        android:ems="10"
        android:hint="اللاعب 2"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/team1EdtTxt1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="الفريق الاول"
        android:textSize="36sp"
        app:layout_constraintBottom_toTopOf="@+id/team1EdtTxt1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="الفريق الثاني"
        android:textSize="36sp"
        app:layout_constraintBottom_toTopOf="@+id/team2EdtTxt1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline3" />

    <EditText
        android:id="@+id/team2EdtTxt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:clickable="false"
        android:ems="10"
        android:hint="اللاعب 1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/team2EdtTxt2"
        app:layout_constraintEnd_toEndOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <EditText
        android:id="@+id/team2EdtTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="false"
        android:ems="10"
        android:hint="اللاعب 2"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/startBtn"
        app:layout_constraintEnd_toEndOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/team2EdtTxt1" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="start"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintWidth_percent="0.3" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.50" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.10" />

</androidx.constraintlayout.widget.ConstraintLayout>

It will look like this:

Notice that I have used 2 very useful attributes:

  app:layout_constraintHeight_percent="0.1"
  app:layout_constraintWidth_percent="0.3"

In addition, I have used Guidelines so now if you want to change the look of your layout you can simply change this attrubute:

  app:layout_constraintGuide_percent="0.x"


问:
Typescript: Module X has no exported member Y
EDIT/NOTE, found problem: This was happening when an import above it was silently failing because I had not installed a certain @types/package.

I'm getting this baffling error from Typescript:

```<code>ERROR in C:\...\src\components\App.tsx(26,10)
      TS2614: Module '"../.../src/components/PriceCharting"' has no exported member 'PriceChart'.
Did you mean to use 'import PriceChart from "../.../src/components/PriceCharting"' instead?
</code>```

I'm exporting like

```<code>export const PriceChart = () => ...
</code>```

and I'm importing like

```<code>import { PriceChart } from "./PriceCharting";
</code>```

Has anyone experienced this problem?

Workaround: if I export instead like

```<code>export default PriceChart;
</code>```

and import like

```<code>import PriceChart from "./PriceCharting";
</code>```

Then it works!

答:
I got it to work and I believe I found the problem.  Above the import I had another import that must caused the problem:

import {
  LineChart,
  ...
} from "recharts";

I believe this was failing because I did not add @types/recharts, but I was getting that other error instead for some reason.

Body:
EDIT/NOTE, found problem: This was happening when an import above it was silently failing because I had not installed a certain @types/package.

I'm getting this baffling error from Typescript:

ERROR in C:\...\src\components\App.tsx(26,10)
      TS2614: Module '"../.../src/components/PriceCharting"' has no exported member 'PriceChart'.
Did you mean to use 'import PriceChart from "../.../src/components/PriceCharting"' instead?

I'm exporting like

export const PriceChart = () => ...

and I'm importing like

import { PriceChart } from "./PriceCharting";

Has anyone experienced this problem?

Workaround: if I export instead like

export default PriceChart;

and import like

import PriceChart from "./PriceCharting";

Then it works!