问:
TypeError: expected string or bytes-like object Tqdm
I have gone through several sources in stackoverflow regarding this issue, but couldn't resolve it.
Thus I have posted it here, kindly resolve.

```<code># Combining all the above statemennts
from tqdm import tqdm
Other_skill = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['Other skills'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    Other_skill.append(sent.lower().strip())
</code>```

Error:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-12-30687b6f17e1> in <module>()
      4 # tqdm is for printing the status bar
      5 for sentance in tqdm(project_data['Other skills'].values):
----> 6     sent = decontracted(sentance)
      7     sent = sent.replace('\\r', ' ')
      8     sent = sent.replace('\\"', ' ')

<ipython-input-7-a344e4b38b78> in decontracted(phrase)
      4 def decontracted(phrase):
      5     # specific
----> 6     phrase = re.sub(r"won't", "will not", phrase)
      7     phrase = re.sub(r"can\'t", "can not", phrase)
      8

C:\ProgramData\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
    189     a callable, it's passed the match object and must return
    190     a replacement string to be used."""
--> 191     return _compile(pattern, flags).sub(repl, string, count)
    192
    193 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or bytes-like object
</code>```

答:
Looking at the stacktrace we can see that sub is given a wrong input in decontracted.

Best would be to place a breakpoint where the arrow is to check the value of phrase:

```<code>      4 def decontracted(phrase):
      5     # specific
----> 6     phrase = re.sub(r"won't", "will not", phrase)
</code>```

If you do not know how to do so, you can add some debugging code like so:

```<code>  def decontracted(phrase):
      # specific
      print(f'phrase: {phrase}\ttype: {type(phrase)}')
      phrase = re.sub(r"won't", "will not", phrase)
      [...]
</code>```

This will print each phrase given to decontracted and its type. There should only be bytes or str. If not then you find your bug and can correct it accordingly.

I hope it helps, we do not have enough information to help you more.

Body:
I have gone through several sources in stackoverflow regarding this issue, but couldn't resolve it.
Thus I have posted it here, kindly resolve.

# Combining all the above statemennts
from tqdm import tqdm
Other_skill = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['Other skills'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    Other_skill.append(sent.lower().strip())

Error:

TypeError                                 Traceback (most recent call last)
<ipython-input-12-30687b6f17e1> in <module>()
      4 # tqdm is for printing the status bar
      5 for sentance in tqdm(project_data['Other skills'].values):
----> 6     sent = decontracted(sentance)
      7     sent = sent.replace('\\r', ' ')
      8     sent = sent.replace('\\"', ' ')

<ipython-input-7-a344e4b38b78> in decontracted(phrase)
      4 def decontracted(phrase):
      5     # specific
----> 6     phrase = re.sub(r"won't", "will not", phrase)
      7     phrase = re.sub(r"can\'t", "can not", phrase)
      8

C:\ProgramData\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
    189     a callable, it's passed the match object and must return
    190     a replacement string to be used."""
--> 191     return _compile(pattern, flags).sub(repl, string, count)
    192
    193 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or bytes-like object

Body:
Looking at the stacktrace we can see that sub is given a wrong input in decontracted.

Best would be to place a breakpoint where the arrow is to check the value of phrase:

      4 def decontracted(phrase):
      5     # specific
----> 6     phrase = re.sub(r"won't", "will not", phrase)

If you do not know how to do so, you can add some debugging code like so:

  def decontracted(phrase):
      # specific
      print(f'phrase: {phrase}\ttype: {type(phrase)}')
      phrase = re.sub(r"won't", "will not", phrase)
      [...]

This will print each phrase given to decontracted and its type. There should only be bytes or str. If not then you find your bug and can correct it accordingly.

I hope it helps, we do not have enough information to help you more.


来源: stackexchange

问:
Is there a way to compare every array value with eachother effectively?
So Ive been trying to compare given double values in an array with eachother to return the smallest one, but the way I do it does not seem to work consistently and very efficient. Im feeling lost.</p>

```<code>public static double FindSmallestNum(double[] arr)
    {
            double max = 0;
      for (int x=0;x<arr.Length-1;x++){
                if ( arr[x]>= arr[x+1]){
                    if (max >= arr[x+1]){
                       max = arr[x+1];
                    }
                }
                else if (max >=arr[x]){
                        max = arr[x];
                }
                else {
                            max = arr[x];
                }
            }
            return max;
        }
</code>```

答:
Just use Linq:

```<code>var min = arr.OrderBy(v => v).FirstOrDefault();
</code>```

min will be the smallest number in your array.

ContentLicense: CC BY-SA 4.0

Body:
So Ive been trying to compare given double values in an array with eachother to return the smallest one, but the way I do it does not seem to work consistently and very efficient. Im feeling lost.

public static double FindSmallestNum(double[] arr)
    {
            double max = 0;
      for (int x=0;x<arr.Length-1;x++){
                if ( arr[x]>= arr[x+1]){
                    if (max >= arr[x+1]){
                       max = arr[x+1];
                    }
                }
                else if (max >=arr[x]){
                        max = arr[x];
                }
                else {
                            max = arr[x];
                }
            }
            return max;
        }

Body:
Just use Linq:

var min = arr.OrderBy(v => v).FirstOrDefault();

min will be the smallest number in your array.


问:
How to Play RAW Audio Files?
I am currently working on a project that consists of a chart that shows audio levels picked up by another device. The charts are made through the flot API and I have zooming and selecting capabilities in order to select a time range on the chart and zoom into that selected region. My next step is to allow the user to listen to the audio that corresponds to that region of the chart. I have the audio files stored on a shared server and all of the files are in individual, minute by minute, RAW data files. I have no experience with using audio in a webpage and am currently struggling on how to complete this task. As far as I have found, the <audio> HTML tag is incapable of processing RAW data files for playback. I have been looking into the Web Audio API but am confused about how it works and how to implement it.

My first question is how do I go about decoding RAW audio files from a server and displaying them on an HTML page for a client to listen to?

My second task is to grab all of the audio files corresponding to the selected range and combine them into one audio output. For example, if the client selected a time range of 1:00pm - 1:50pm, I would need to access 50 RAW data audio files each a minute in length. I would then want to combine them together to produce one single playback sound. Therefore, my second question is if anyone knows a way to accomplish this smoothly.

Thank you for any help anyone has to offer!

答:
An alternative that might be a bit easier with Web Audio, you can basically do the same as above, but don't use an Audio element.  If necessary convert the raw audio data to a float array, say, f, and do something like this:

```<code>// Only need to do this once when setting up the page
let c = new AudioContext();

// Do this for each clip:
let b = new AudioBuffer({length: f.length, sampleRate: c.sampleRate});
b.copyToChannel(f, 0);
let s = new AudioBufferSourceNode(c, {buffer: b});
s.connect(c.destination);
s.start();
</code>```

This is rough sketch of how to use Web Audio to do the playback.  It can be refined to reuse AudioBuffers.  And you have to take care of calling s.start() with the right time values.  But I hope this is enough to get you started.  If not, please ask more questions.

Title: How to Play RAW Audio Files?

Body:
An alternative that might be a bit easier with Web Audio, you can basically do the same as above, but don't use an Audio element.  If necessary convert the raw audio data to a float array, say, f, and do something like this:

// Only need to do this once when setting up the page
let c = new AudioContext();

// Do this for each clip:
let b = new AudioBuffer({length: f.length, sampleRate: c.sampleRate});
b.copyToChannel(f, 0);
let s = new AudioBufferSourceNode(c, {buffer: b});
s.connect(c.destination);
s.start();

This is rough sketch of how to use Web Audio to do the playback.  It can be refined to reuse AudioBuffers.  And you have to take care of calling s.start() with the right time values.  But I hope this is enough to get you started.  If not, please ask more questions.


问:
sum values in 2 JSON objects from 2 files
I am using jq tools to merge 2 json files but there are some duplicate keys, and I would like for the duplicate keys to sum their values.

Here are the files:

file1:

```<code>{
  "total": {
    "seconds": 1490
  },
  "days": {
    "2020-05-20": {
      "seconds": 1400
    },
    "2020-05-19": {
      "seconds": 30
    },
    "2020-05-18": {
      "seconds": 60
    }
  }
}
</code>```

file2:

```<code>{
  "total": {
    "seconds": 295
  },
  "days": {
    "2020-05-22": {
      "seconds": 120
    },
    "2020-05-21": {
      "seconds": 80
    },
    "2020-05-20": {
      "seconds": 95
    }
  }
}
</code>```

Expected output:

```<code>{
  "total": {
    "seconds": 1785
  },
  "days": {
    "2020-05-22": {
      "seconds": 120
    },
    "2020-05-21": {
      "seconds": 80
    },
    "2020-05-20": {
      "seconds": 1495
    },
    "2020-05-19": {
      "seconds": 30
    },
    "2020-05-18": {
      "seconds": 60
    }
  }
}
</code>```

I have tried starting with this command, but do not know where to go next:

```<code>jq -s '.[0] * .[1]' file1 file2
</code>```

答:
Below program works fine for your samples, but it won't work if the objects in your actual inputs have other keys with non-number values.

```<code>jq '. as $in |
reduce paths(numbers) as $p (input;
  setpath($p; getpath($p) + ($in | getpath($p))
)' file1 file2
</code>```

Online demo

Body:
I am using jq tools to merge 2 json files but there are some duplicate keys, and I would like for the duplicate keys to sum their values.

Here are the files:

file1:

{
  "total": {
    "seconds": 1490
  },
  "days": {
    "2020-05-20": {
      "seconds": 1400
    },
    "2020-05-19": {
      "seconds": 30
    },
    "2020-05-18": {
      "seconds": 60
    }
  }
}

file2:

{
  "total": {
    "seconds": 295
  },
  "days": {
    "2020-05-22": {
      "seconds": 120
    },
    "2020-05-21": {
      "seconds": 80
    },
    "2020-05-20": {
      "seconds": 95
    }
  }
}

Expected output:

{
  "total": {
    "seconds": 1785
  },
  "days": {
    "2020-05-22": {
      "seconds": 120
    },
    "2020-05-21": {
      "seconds": 80
    },
    "2020-05-20": {
      "seconds": 1495
    },
    "2020-05-19": {
      "seconds": 30
    },
    "2020-05-18": {
      "seconds": 60
    }
  }
}

I have tried starting with this command, but do not know where to go next:

jq -s '.[0] * .[1]' file1 file2

Body:
Below program works fine for your samples, but it won't work if the objects in your actual inputs have other keys with non-number values.

jq '. as $in |
reduce paths(numbers) as $p (input;
  setpath($p; getpath($p) + ($in | getpath($p))
)' file1 file2

Online demo


问:
AttributeError: module 'rasa.nlu.utils' has no attribute 'pycloud_pickle'
I am trying to implement Sentiment_Analyzer in rasa based on the instructions given in the rasa official site. But it seems to be for the older version. Anyway the only change that doesn't work now is persisting the learnt model. The previous versions had the method
utils.pycloud_pickle(classifier_file, self)
to do this. Is there any replacement for this in the newer version of rasa (1.0.1), or has it been completely removed?

```<code>def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:
    classifier_file = os.path.join(model_dir, SENTIMENT_MODEL_FILE_NAME)
    utils.pycloud_pickle(classifier_file, self)
    return {"classifier_file": SENTIMENT_MODEL_FILE_NAME}
</code>```

I got the following error:

```<code>AttributeError: module 'rasa.nlu.utils' has no attribute 'pycloud_pickle'
</code>```

答:
install rasa==1.5.0.
Downgrading existing rasa resolved for me.</p>

Body:
I am trying to implement Sentiment_Analyzer in rasa based on the instructions given in the rasa official site. But it seems to be for the older version. Anyway the only change that doesn't work now is persisting the learnt model. The previous versions had the method
utils.pycloud_pickle(classifier_file, self)
to do this. Is there any replacement for this in the newer version of rasa (1.0.1), or has it been completely removed?

def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:
    classifier_file = os.path.join(model_dir, SENTIMENT_MODEL_FILE_NAME)
    utils.pycloud_pickle(classifier_file, self)
    return {"classifier_file": SENTIMENT_MODEL_FILE_NAME}

I got the following error:

AttributeError: module 'rasa.nlu.utils' has no attribute 'pycloud_pickle'


问:
Removing n columns from all the files from directory in Unix
I have around 2000+ files which has random number of columns in each file.
I wanted to remove last 4 columns from each of the file.

I tried to use below command, but it is not an inline command. Delimiter of the file is #

awk -F"#" '{NF-=4;OFS="#";print}' test > testing.csv

I wanted to save the file with the same name.(e.g. filename test with test only)

How to remove last 4 columns and save the file with same name?
Can someone please help?

答:
You really, really, really do not want to edit the files "in-place".  It is (almost) always the wrong thing to do.  For something like this, you want to do something like:

```<code>$ rm -rf new-dir/
$ mkdir new-dir
$ for file in old-dir/*; do
    f=${file#old-dir/};
    awk '{NF-=4; $1=$1; print}' FS=# OFS=# "$file" > new-dir/"$f"; done
</code>```

Then, after you know things have worked, you can replace your original directory with the new one.

Body:
You really, really, really do not want to edit the files "in-place".  It is (almost) always the wrong thing to do.  For something like this, you want to do something like:

$ rm -rf new-dir/
$ mkdir new-dir
$ for file in old-dir/*; do
    f=${file#old-dir/};
    awk '{NF-=4; $1=$1; print}' FS=# OFS=# "$file" > new-dir/"$f"; done

Then, after you know things have worked, you can replace your original directory with the new one.


问:
How can I access my downloads folder using Dockerfile?
I have to following Dockerfile to create a container image. This works fine for some scripts.

```<code>FROM python:3.8-slim-buster

COPY . /work

WORKDIR /work

RUN apt-get update

RUN apt-get upgrade -y

RUN pip install -r requirements.txt
</code>```

However, I have a script which requires access to my local downloads folder. My understanding is that the container creates an image with the copy of the directory that the Dockerfile sits within. However, I do not understand how to give the container access to my downloads folder outside of this. Any help would be great!

答:
There are two ways that you can take:

Give it as a volume (Recommended)

Change the build context (Just for understanding it better)

Add a Volume:

After you build your Dockerfile. You can run it with a volume. Think volume as a shared folder between your host and the container. You can look at documentation here.

```<code>docker run [OPTIONS] -v /path/to/downloads:/work
</code>```

It will build fast and run fast. But if your folder change your container change too. If you want to persist your container;

Change Build Context:

When you building your image you are giving it a context.

```<code>docker build -t my-tag .
</code>```

The dot at the end of the command represents current directory that you run the command. If you want to give your /Downloads folder to the context, you need to run build function like below. After that you can state COPY Downloads/ Downloads/ in your Dockerfile. Remember all of the paths that are use the local file system in Dockerfile is relative to build context. For below example if you want to perform COPY . /work line in your answer, you need to change it to COPY /path/to/your/docker/file/ /work

# Go to your users root directory.
cd ~/

# This will add all of the folders including Downloads to your build context.
docker run build -t my-tag -f /path/to/your/docker/file/Dockerfile .
```

Remember it is recommended to keep your build context small as possible. When you add your all folders to the build context it will be slow. As i said it is for experiment. But if you really want a fast and persistent solution, simply copy your /Download folder in same folder with your Dockerfile. Cheers!

Body:
I have to following Dockerfile to create a container image. This works fine for some scripts.

FROM python:3.8-slim-buster

COPY . /work

WORKDIR /work

RUN apt-get update

RUN apt-get upgrade -y

RUN pip install -r requirements.txt

However, I have a script which requires access to my local downloads folder. My understanding is that the container creates an image with the copy of the directory that the Dockerfile sits within. However, I do not understand how to give the container access to my downloads folder outside of this. Any help would be great!

Body:
There are two ways that you can take:

Give it as a volume (Recommended)

Change the build context (Just for understanding it better)

Add a Volume:

After you build your Dockerfile. You can run it with a volume. Think volume as a shared folder between your host and the container. You can look at documentation here.

docker run [OPTIONS] -v /path/to/downloads:/work

It will build fast and run fast. But if your folder change your container change too. If you want to persist your container;

Change Build Context:

When you building your image you are giving it a context.

docker build -t my-tag .

The dot at the end of the command represents current directory that you run the command. If you want to give your /Downloads folder to the context, you need to run build function like below. After that you can state COPY Downloads/ Downloads/ in your Dockerfile. Remember all of the paths that are use the local file system in Dockerfile is relative to build context. For below example if you want to perform COPY . /work line in your answer, you need to change it to COPY /path/to/your/docker/file/ /work

# Go to your users root directory.
cd ~/

# This will add all of the folders including Downloads to your build context.
docker run build -t my-tag -f /path/to/your/docker/file/Dockerfile .

Remember it is recommended to keep your build context small as possible. When you add your all folders to the build context it will be slow. As i said it is for experiment. But if you really want a fast and persistent solution, simply copy your /Download folder in same folder with your Dockerfile. Cheers!


问:
Services - Rest Server Setup
I have the Services 6.x-2.4 module installed on a Drupal 6 site.
I am attempting to use REST but I am having difficulties getting things working.

For instance, http://mysite.com/services/xmlrpc returns some kind of feedback that the server is working.
While http://mysite.com/services/rest returns nothing and I am not sure if the server is actually working.

Can anyone offer some direction, please?

答: Make sure you have an endpoint configured and enabled.  You'll have to additionally enable resources for the endpoint.</p>

ContentLicense: CC BY-SA 3.0

Title: Services - Rest Server Setup


问:
How to insert value substring-before last '(' after tokenize with ',' in XSLT
I am trying to insert value subring-before last '(' after tokenize start-with, '('. I have try both  substring-before (e.g. <xsl:value-of select="concat(substring-before(current-grouping-key(), '('), .)"/>) '(' or replace function
<xsl:value-of select="concat(replace(substring-before(current-grouping-key(), ','), '^([0-9]+)|(\(.*\))(\(([a-z0-9])\))', '$1$2'), .)"/>
.

Input XML

```<code><root>
<p>17200(b)(2), (4)–(6), (8), (12), (16), (20), and (21)</p>
<p>1(a), (b), (c)</p>
<p>2</p>
<p>2</p>
</root>
</code>```

XSLT:

```<code>    <xsl:template match="root">
    <root>
        <xsl:for-each-group select="p" group-by=".">
            <xsl:choose>
                <xsl:when test="contains(current-grouping-key(), ', ')">
                    <xsl:for-each select="tokenize(current-grouping-key(), ', and |, ')">
                        <xsl:choose>
                            <xsl:when test="starts-with(., '(')">
                                <p><xsl:value-of select="concat(replace(substring-before(current-grouping-key(), ','), '^([0-9]+)|(\(.*\))(\(([a-z0-9])\))', '$1$2'), .)"/></p>
                                <!--<p><xsl:value-of select="concat(substring-before(current-grouping-key(), '('), .)"/></p>-->
                            </xsl:when>
                            <xsl:otherwise>
                                <p><xsl:value-of select="."/></p>
                            </xsl:otherwise>
                        </xsl:choose>
                    </xsl:for-each>
                </xsl:when>
                <xsl:otherwise>
                    <p><xsl:value-of select="current-grouping-key()"/></p>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </root>
</xsl:template>
</code>```

Expected Output

```<code>   <root>
   <p>17200(b)(2)</p>
   <p>17200(b)(4)–(6)</p>
   <p>17200(b)(8)</p>
   <p>17200(b)(12)</p>
   <p>17200(b)(16)</p>
   <p>17200(b)(20)</p>
   <p>17200(b)(21)</p>
   <p>1(a)</p>
   <p>1(b)</p>
   <p>1(c)</p>
   <p>2</p>
</root>
</code>```

CODE: https://xsltfiddle.liberty-development.net/3NSTbfj/31

答:
I think the you seem to simply want to concatenate any characters in the first token before the last ( to the tokenized value:

```<code><xsl:template match="root">
    <root>
        <xsl:for-each-group select="p" group-by=".">
            <xsl:choose>
                <xsl:when test="contains(current-grouping-key(), ', ')">
                    <xsl:variable name="tokens" select="tokenize(current-grouping-key(), ', and |, ')"/>
                    <xsl:for-each select="$tokens">
                        <p>
                            <xsl:value-of
                              select="if (starts-with(., '('))
                                      then replace(head($tokens), '(.*)\(.*?\)$', '$1') || .
                                      else ."/>
                        </p>

                    </xsl:for-each>
                </xsl:when>
                <xsl:otherwise>
                    <p><xsl:value-of select="current-grouping-key()"/></p>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </root>
</xsl:template>
</code>```

https://xsltfiddle.liberty-development.net/3NSTbfj/33

Body:
I am trying to insert value subring-before last '(' after tokenize start-with, '('. I have try both  substring-before (e.g. <xsl:value-of select="concat(substring-before(current-grouping-key(), '('), .)"/>) '(' or replace function
<xsl:value-of select="concat(replace(substring-before(current-grouping-key(), ','), '^([0-9]+)|(\(.*\))(\(([a-z0-9])\))', '$1$2'), .)"/>
.

Input XML

<root>

17200(b)(2), (4)–(6), (8), (12), (16), (20), and (21)

1(a), (b), (c)

2

2

</root>

XSLT:

    <xsl:template match="root">
    <root>
        <xsl:for-each-group select="p" group-by=".">
            <xsl:choose>
                <xsl:when test="contains(current-grouping-key(), ', ')">
                    <xsl:for-each select="tokenize(current-grouping-key(), ', and |, ')">
                        <xsl:choose>
                            <xsl:when test="starts-with(., '(')">

<xsl:value-of select="concat(replace(substring-before(current-grouping-key(), ','), '^([0-9]+)|(\(.*\))(\(([a-z0-9])\))', '$1$2'), .)"/>

                            </xsl:when>
                            <xsl:otherwise>

<xsl:value-of select="."/>

                            </xsl:otherwise>
                        </xsl:choose>
                    </xsl:for-each>
                </xsl:when>
                <xsl:otherwise>

<xsl:value-of select="current-grouping-key()"/>

                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </root>
</xsl:template>

Expected Output

   <root>

17200(b)(2)

17200(b)(4)–(6)

17200(b)(8)

17200(b)(12)

17200(b)(16)

17200(b)(20)

17200(b)(21)

1(a)

1(b)

1(c)

2

</root>

CODE: https://xsltfiddle.liberty-development.net/3NSTbfj/31

Body:
I think the you seem to simply want to concatenate any characters in the first token before the last ( to the tokenized value:

<xsl:template match="root">
    <root>
        <xsl:for-each-group select="p" group-by=".">
            <xsl:choose>
                <xsl:when test="contains(current-grouping-key(), ', ')">
                    <xsl:variable name="tokens" select="tokenize(current-grouping-key(), ', and |, ')"/>
                    <xsl:for-each select="$tokens">
                        <p>
                            <xsl:value-of
                              select="if (starts-with(., '('))
                                      then replace(head($tokens), '(.*)\(.*?\)$', '$1') || .
                                      else ."/>
                        </p>

                    </xsl:for-each>
                </xsl:when>
                <xsl:otherwise>
                    <p><xsl:value-of select="current-grouping-key()"/></p>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </root>
</xsl:template>

https://xsltfiddle.liberty-development.net/3NSTbfj/33


问:
Calico IPs Confusion
I am bit confused about Calico IPs :

If I add calico to kubernetes cluster using

```<code>kubectl apply -f https://docs.projectcalico.org/v3.14/manifests/calico.yaml
</code>```

The CALICO_IPV4POOL_CIDR is 192.168.0.0/16
So IP Range is 192.168.0.0 to 192.168.255.255

Now I have initiated the cluster using :

```<code>kubeadm init --pod-network-cidr=20.96.0.0/12 --apiserver-advertise-address=192.168.56.30
</code>```

So, now pods will have IP address (using pod network CIDR) will be between: 20.96.0.0 to 20.111.255.255

What are these two different IPs. My Pods are getting IP addresses 20.96.205.192 and so on.

答:
The CALICO_IPV4POOL_CIDR is #commented by default, look at these lines in calico.yaml:

```<code># The default IPv4 pool to create on startup if none exists. Pod IPs will be
# chosen from this range. Changing this value after installation will have
# no effect. This should fall within `--cluster-cidr`.
# - name: CALICO_IPV4POOL_CIDR
#   value: "192.168.0.0/16"
</code>```

For all effects, unless manually modified before deployment, those lines are not considered during deployment.

Another important line in the yaml itself is:

# Pod CIDR auto-detection on kubeadm needs access to config maps.

This confirms that the CIDR is obtained from the cluster, not from calico.yaml.

What are these two different IPs? My Pods are getting IP addresses 20.96.205.192 and so on.

Kubeadm supports many Pod network add-ons, Calico is one of those. Calico on the other hand is supported by many kinds of deployment, kubeadm is just one of those.

Kubeadm --pod-network-cidr in your deployment is the correct way to define the pod network CIDR, this is why the range 20.96.0.0/12 is effectively used.

CALICO_IPV4POOL_CIDR is required for other kinds of deployment that does not specify the CIDR pool reservation for pod networks.

Note:

The range 20.96.0.0/12 is not a Private Network range, and it can cause problems if a client with a Public IP from that range tries to access your service.

The classless reserved IP ranges for Private Networks are:

10.0.0.0/8 (16.777.216 addresses)

172.16.0.0/12 (1.048.576 addresses)

192.168.0.0/16 (65.536 addresses)

You can use any subnet size inside these ranges for your POD CIDR Network, just make sure it doesn't overlaps with any subnet in your network.

Additional References:

Calico - Create Single Host Kubernetes Cluster with Kubeadm

Kubeadm Calico Installation

IETF RFC1918 - Private Address Space

Title: Calico IPs Confusion

Body:
I am bit confused about Calico IPs :

If I add calico to kubernetes cluster using

kubectl apply -f https://docs.projectcalico.org/v3.14/manifests/calico.yaml

The CALICO_IPV4POOL_CIDR is 192.168.0.0/16
So IP Range is 192.168.0.0 to 192.168.255.255

Now I have initiated the cluster using :

kubeadm init --pod-network-cidr=20.96.0.0/12 --apiserver-advertise-address=192.168.56.30

So, now pods will have IP address (using pod network CIDR) will be between: 20.96.0.0 to 20.111.255.255

What are these two different IPs. My Pods are getting IP addresses 20.96.205.192 and so on.

Body:
The CALICO_IPV4POOL_CIDR is #commented by default, look at these lines in calico.yaml:

# The default IPv4 pool to create on startup if none exists. Pod IPs will be
# chosen from this range. Changing this value after installation will have
# no effect. This should fall within `--cluster-cidr`.
# - name: CALICO_IPV4POOL_CIDR
#   value: "192.168.0.0/16"

For all effects, unless manually modified before deployment, those lines are not considered during deployment.

Another important line in the yaml itself is:

# Pod CIDR auto-detection on kubeadm needs access to config maps.

This confirms that the CIDR is obtained from the cluster, not from calico.yaml.

What are these two different IPs? My Pods are getting IP addresses 20.96.205.192 and so on.

Kubeadm supports many Pod network add-ons, Calico is one of those. Calico on the other hand is supported by many kinds of deployment, kubeadm is just one of those.

Kubeadm --pod-network-cidr in your deployment is the correct way to define the pod network CIDR, this is why the range 20.96.0.0/12 is effectively used.

CALICO_IPV4POOL_CIDR is required for other kinds of deployment that does not specify the CIDR pool reservation for pod networks.

Note:

The range 20.96.0.0/12 is not a Private Network range, and it can cause problems if a client with a Public IP from that range tries to access your service.

The classless reserved IP ranges for Private Networks are:

10.0.0.0/8 (16.777.216 addresses)

172.16.0.0/12 (1.048.576 addresses)

192.168.0.0/16 (65.536 addresses)

You can use any subnet size inside these ranges for your POD CIDR Network, just make sure it doesn't overlaps with any subnet in your network.

Additional References:

Calico - Create Single Host Kubernetes Cluster with Kubeadm

Kubeadm Calico Installation

IETF RFC1918 - Private Address Space


问:
Unwind without Storyboard
I am replacing my current views in storyboard with xib files. But I encountered an issue about unwind.

In Xib files, I can't create unwind segues. And could not find to regular way to this. When I search on web this issue, I just found about "How to perform unwind segue programmatically." This is not what I wanted. I need a way to perform an unwind operation programmatically.

I found How an Unwind Segue Determines its Destination View Controller in Apple Documentation and thought I can do this programmatically. But, the viewControllerForUnwindSegueAction:fromViewController:withSender: method (now it is forUnwindSegueAction(_:from:withSender:)) is deprecated and new method for this operation(childContaining(_:)) uses an UIStoryboardUnwindSegueSource instance that cannot be initialized programmatically.

So, I can see two option.

Determine unwind points in app and create operations to do this manually for each of them

Create an unwind performer object works like Apple's unwind executor but uses it's own methods.

As I see, the second option is better. But, As I said on beginning of my question. I could not find anything in web, It is like just me encountered this situation and I am sure it is not true. I think I search this with wrong keywords and I need some help to solve this. I want to learn somethings before select one of this options:

Is there a third way to solve this

How do you(Programmers that does not use storyboard or xib) solve this problem

Here is some of my Google searches

Unwind without storyboard

Unwind without interface builder

How to create unwind segue without storyboard

答:
You are not alone and you are not the first person to have this problem. I call this the problem of reverse routing.

To illustrate the problem, I'll show a storyboard version of a relatively complex unwind situation:

We have a tab bar controller with two children. The first child is a navigation controller which has pushed one view controller (the green v.c. at the end of the first row) on top of its root view controller (the yellow v.c.). The second child is a normal view controller that has presented one view controller (the white v.c. at the end of the second row).

The goal is to unwind from the white v.c. to the yellow v.c. in the top row.

If you're using a storyboard, this is trivial. The yellow v.c. contains an unwind method (the name isn't actually important), and you "hook" the exit segue from the button in the white v.c. to that method. At runtime, the user taps the button, and the runtime "magically" dismisses the white v.c., switches the tab bar controller to the first child, and pops the green v.c., leaving us in the yellow v.c. as desired.

Now do that in code! Uh, yeah, sure. How? That's the problem.

The irony is palpable. Clearly the runtime knows how to solve this problem, because it does solve the problem when you use an unwind segue in the storyboard. But there is no built-in programmatic analog when you are not using a storyboard. There is no unwind command that causes the complex unwind mechanism to become activated and do the same thing that would happen if this were a storyboard-based app.

This is a huge flaw in UIKit. Apple basically requires us to use storyboards. But everyone knows that any app developed by a team is likely to avoid storyboards, because reconciling versions of a storyboard through git is darned near impossible. So Apple doesn't seem to live in the real world; they have not provided the runtime support needed for real world development of apps.

A simple solution — simple to the point of crudeness — is just to unwind "by hand". The app has a "coordinator" object whose job is to take care of this sort of backward routing. If you are in the white v.c. and you want to "unwind" to the yellow v.c., your coordinator simply has to know that this is something we might want to do, and it knows what the necessary steps are in order to get there.

Basically, what I'm saying is that the coordinator must be supplied with a fixed list of all the backward routes the app will ever need to perform, along with instructions for how to perform them. Given where we are and where we want to go back to, the coordinator just performs the corresponding steps.

(You, the OP, will observe that I have not told you anything you don't already know. What I have outlined is, apparently, exactly your option 1. And that is correct. What I'm telling you is: option 2 would be nice, but it doesn't exist and isn't worth trying to write, so just fall back on option 1.)

Title: Unwind without Storyboard

Body:
I am replacing my current views in storyboard with xib files. But I encountered an issue about unwind.

In Xib files, I can't create unwind segues. And could not find to regular way to this. When I search on web this issue, I just found about "How to perform unwind segue programmatically." This is not what I wanted. I need a way to perform an unwind operation programmatically.

I found How an Unwind Segue Determines its Destination View Controller in Apple Documentation and thought I can do this programmatically. But, the viewControllerForUnwindSegueAction:fromViewController:withSender: method (now it is forUnwindSegueAction(_:from:withSender:)) is deprecated and new method for this operation(childContaining(_:)) uses an UIStoryboardUnwindSegueSource instance that cannot be initialized programmatically.

So, I can see two option.

Determine unwind points in app and create operations to do this manually for each of them

Create an unwind performer object works like Apple's unwind executor but uses it's own methods.

As I see, the second option is better. But, As I said on beginning of my question. I could not find anything in web, It is like just me encountered this situation and I am sure it is not true. I think I search this with wrong keywords and I need some help to solve this. I want to learn somethings before select one of this options:

Is there a third way to solve this

How do you(Programmers that does not use storyboard or xib) solve this problem

Here is some of my Google searches

Unwind without storyboard

Unwind without interface builder

<a href="https://www.google.com/search?client=firefox-b-d&sxsrf=ALeKk00HTRlouXvH69v5rSoL1yL4440m1g%3A1591100852992&ei=tEXWXp-NPITYmwXi1Lg4&q=How%20to%20create%20unwind%20segue%20without%20storyboard&oq=How%20to%20create%20unwind%20segue%20without%20storyboard&gs_lcp=CgZwc3ktYWIQAzIICCEQFhAdEB46BAgAEEc6BAgjECc6AggAOgYIABAWEB46BQgAEMsBOgcIIxDqAhAnOgUIABCRAjoECAAQQzoHCAAQFBCHAjoHCCEQChCgAToECCEQFToFCCEQoAFQgJoEWOzrBGD57ARoAXAGeACAAbIBiAG4NpIBBDAuNDeYAQCgAQGqAQdnd3Mtd2l6sAEK&sclient=psy-ab&ved=0ahUKEwift5PJkOPpAhUE7KYKHWIqDgcQ4dUDCAs&uact=5" rel="nofollow noreferrer">How to create unwind segue without storyboard


问:
Firestore - Add field on Document that also has a subcollection
I am trying to add/update a field on a document that also has a subcollection.

On console it seems possible but trying to do it in different ways I can't do it.

For example when I try:

fb.db.collection('wani').doc('python').update({field:'value});

I get a "No document to update" error.

I can't find how to do this on documentation

答:
This has nothing to do with subcollections.  Your code is trying to update() a document with the path "wani/python".  That document doesn't exist.  You can tell because the console is showing the document ID "python" in italics.  Updates against documents that don't exist will give you that error.  (A document doesn't have to exist in order to have subcollections nested underneath it.)

If you want to update a document, you will need to first create it using set().  If you want to update a document OR create it if it doesn't exist, you will have to use set() with the merge option as described in the linked API documentation.


问:
Comparing two date/time fields to see if they occurred within 60 days
I have a dataset like this

```<code>Member   Open_date     Mort_Close_date  Share_type
1        6/1/2020                          1
1                       5/5/2020           2
1        9/15/2020                         3
</code>```

I'm trying to write either a case statement or an iif statement that Counts the number of Accounts opened (Open_Date) within 60 days after they close on a mortgage (Mort_Close_date). So in the example above, it bring back a count of 1, because only the third one was opened more than 60 days later. The problem is I don't feel this code is anywhere close. Even if the below code worked, it doesn't, how would I only compare the open_date, mort_close_date when the member matches?

```<code>CASE WHEN DATEDIFF(d, S.Open_Date,  MC_LOAN_DATE) <= 60, THEN 'Open New Account within 60 days'
ELSE 'No Accounts Opened') END AS NewAccountsOpened
</code>```

答:
I think this does what you want:</p>

```<code>select count(*)
from t
where exists (select 1
              from t t2
              where t2.member = t.member and
                    t2.open_date >= t.mort_close_date and
                    t2.open_date < dateadd(day, 60, mort_close_date)
             );
</code>```

Body:
I have a dataset like this

Member   Open_date     Mort_Close_date  Share_type
1        6/1/2020                          1
1                       5/5/2020           2
1        9/15/2020                         3

I'm trying to write either a case statement or an iif statement that Counts the number of Accounts opened (Open_Date) within 60 days after they close on a mortgage (Mort_Close_date). So in the example above, it bring back a count of 1, because only the third one was opened more than 60 days later. The problem is I don't feel this code is anywhere close. Even if the below code worked, it doesn't, how would I only compare the open_date, mort_close_date when the member matches?

CASE WHEN DATEDIFF(d, S.Open_Date,  MC_LOAN_DATE) <= 60, THEN 'Open New Account within 60 days'
ELSE 'No Accounts Opened') END AS NewAccountsOpened

Body:
I think this does what you want:

select count(*)
from t
where exists (select 1
              from t t2
              where t2.member = t.member and
                    t2.open_date >= t.mort_close_date and
                    t2.open_date < dateadd(day, 60, mort_close_date)
             );


问:
Angular Material Select w/ Columns
I am trying to style the selection panel such that the items display in several columns, but the last item of each column seems to become off-center and split, with the overflow starting at the top of the next column. Ideally the scroll would be vertical, but instead it seems to scroll horizontal to cover the overflow. My list has 30+ items and multiple selections are allowed. The goal is to display as many options as possible to the user at once so they don't have to scroll too much.

Full StackBlitz:
https://stackblitz.com/edit/angular-bt3gs6

select-multiple-example.scss

```<code>.toppings-panel.mat-select-panel {
  column-count: 2;
  column-width: 200px;
  width: 400px;
  max-width: 400px;
}
</code>```

select-multiple-example.html

```<code>  <mat-select [formControl]="toppings" panelClass="toppings-panel" multiple>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
</code>```

select-multiple-example.ts

```<code>export class SelectMultipleExample {
  toppings = new FormControl();
  toppingList: string[] = ['Pepperoni', 'Sausage', 'Ham', 'Bacon', 'Chicken',
                           'Mushroom', 'Red onion', 'White onion', 'Tomato', 'Olives',
                           'Green bell peppers', 'Pineapple', 'Artichoke', 'Spinach',
                           'Basil', 'Hot pepper flakes',
                           'Parmesan', 'Shredded cheddar', 'Extra mozzarella'];
}
</code>```

答:
The problem with the columns that become off-center and split, is the height of the .mat-select-panel.

It has max-height:256px; (setted in Angular Material code). But, since it has a horizontal scrollbar (which has a height of 17px, in Windows - Chrome), the available remaining space will be: 256 - 17 = 239px.

The height of the mat-option is 48px, so 5 options in a column will take 240px.

A quick solution would be to increase the height of the .mat-select-panel to 257px:

Demo: https://stackblitz.com/edit/angular-bt3gs6-wxwkgg

But, the example above will not display correctly on MacOS; which displays scrollbars like an absolute positioned content, and it has more space available:

I've found a cross platform solution by removing columns (which are kind of difficult to implement cross-browser and cross-platform) and taking an
approach with display: flex for the .mat-select-panel element:

Horizontal scrolling:

```<code>.toppings-panel.mat-select-panel {
  width: 400px;
  max-width: 400px;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  min-height: 257px;   // min-height needed for windows browsers
}

 .toppings-panel.mat-select-panel .mat-option {
   min-width: 50%;  // 50% to have 2 columns visible
  }
</code>```

Demo: https://stackblitz.com/edit/angular-bt3gs6-lwvwav

Vertical scrolling:

If you prefer vertical scrolling, just remove flex-direction: column; from the code above and play with the max-height in order to set the default visible rows:

```<code>.toppings-panel.mat-select-panel {
  width: 400px;
  max-width: 400px;
  display: flex;
  flex-wrap: wrap;

  max-height: 240px; /* 240px - for 5 items / column */
}

.toppings-panel.mat-select-panel .mat-option {
  min-width: 50%;
}
</code>```

Demo: https://stackblitz.com/edit/angular-bt3gs6-iykn4w

Title: Angular Material Select w/ Columns

Body:
I am trying to style the selection panel such that the items display in several columns, but the last item of each column seems to become off-center and split, with the overflow starting at the top of the next column. Ideally the scroll would be vertical, but instead it seems to scroll horizontal to cover the overflow. My list has 30+ items and multiple selections are allowed. The goal is to display as many options as possible to the user at once so they don't have to scroll too much.

Full StackBlitz:
https://stackblitz.com/edit/angular-bt3gs6

select-multiple-example.scss

.toppings-panel.mat-select-panel {
  column-count: 2;
  column-width: 200px;
  width: 400px;
  max-width: 400px;
}

select-multiple-example.html

  <mat-select [formControl]="toppings" panelClass="toppings-panel" multiple>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>

select-multiple-example.ts

export class SelectMultipleExample {
  toppings = new FormControl();
  toppingList: string[] = ['Pepperoni', 'Sausage', 'Ham', 'Bacon', 'Chicken',
                           'Mushroom', 'Red onion', 'White onion', 'Tomato', 'Olives',
                           'Green bell peppers', 'Pineapple', 'Artichoke', 'Spinach',
                           'Basil', 'Hot pepper flakes',
                           'Parmesan', 'Shredded cheddar', 'Extra mozzarella'];
}

Body:
The problem with the columns that become off-center and split, is the height of the .mat-select-panel.

It has max-height:256px; (setted in Angular Material code). But, since it has a horizontal scrollbar (which has a height of 17px, in Windows - Chrome), the available remaining space will be: 256 - 17 = 239px.

The height of the mat-option is 48px, so 5 options in a column will take 240px.

A quick solution would be to increase the height of the .mat-select-panel to 257px:

Demo: https://stackblitz.com/edit/angular-bt3gs6-wxwkgg

But, the example above will not display correctly on MacOS; which displays scrollbars like an absolute positioned content, and it has more space available:

I've found a cross platform solution by removing columns (which are kind of difficult to implement cross-browser and cross-platform) and taking an
approach with display: flex for the .mat-select-panel element:

Horizontal scrolling:

.toppings-panel.mat-select-panel {
  width: 400px;
  max-width: 400px;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  min-height: 257px;   // min-height needed for windows browsers
}

 .toppings-panel.mat-select-panel .mat-option {
   min-width: 50%;  // 50% to have 2 columns visible
  }

Demo: https://stackblitz.com/edit/angular-bt3gs6-lwvwav

Vertical scrolling:

If you prefer vertical scrolling, just remove flex-direction: column; from the code above and play with the max-height in order to set the default visible rows:

.toppings-panel.mat-select-panel {
  width: 400px;
  max-width: 400px;
  display: flex;
  flex-wrap: wrap;

  max-height: 240px; /* 240px - for 5 items / column */
}

.toppings-panel.mat-select-panel .mat-option {
  min-width: 50%;
}

Demo: https://stackblitz.com/edit/angular-bt3gs6-iykn4w


问:
CS50 pset4 filter reflection
```<code>#include "helpers.h"
#include <math.h>
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for ( int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width ; w++)
        {
           int i = image[h][w].rgbtBlue + image[h][w].rgbtGreen + image[h][w].rgbtRed ;
           float j = i/3 ;
           int n = round(j) ;

           image[h][w].rgbtBlue = n ;
           image[h][w].rgbtGreen = n ;
           image[h][w].rgbtRed = n ;
        }
    }
    return;
}

// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for ( int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width ; w++)
        {
            float sr = .393 * image[h][w].rgbtRed + .769 * image[h][w].rgbtGreen + .189 * image[h][w].rgbtBlue ;
            float sg = .349 * image[h][w].rgbtRed + .686 * image[h][w].rgbtGreen + .168 * image[h][w].rgbtBlue ;
            float sb = .272 * image[h][w].rgbtRed + .534 * image[h][w].rgbtGreen + .131 * image[h][w].rgbtBlue ;

            int SR = round(sr);
            int SG = round(sg);
            int SB = round(sb);

            if ( SR>255)
            {
                SR = 255 ;
            }
            if (SG>255)
            {
                SG = 255 ;
            }
            if (SB>255)
            {
                 SB = 255 ;
            }

            image[h][w].rgbtBlue = SB ;
            image[h][w].rgbtGreen = SG ;
            image[h][w].rgbtRed = SR ;
        }
    }
    return;
}

// Reflect image horizontally
void swap (int *a , int *b) ;

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    for (int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width/2 ; w++)
        {
            for (int p=width-1 ; p>=round(width/2) ; p--)
            {
                int blue = image[h][w].rgbtBlue ;
                int B = image[h][p].rgbtBlue ;
                swap(&blue , &B);

                int g = image[h][w].rgbtGreen ;
                int G = image[h][p].rgbtGreen ;
                swap(&g , &G);

                int r = image[h][w].rgbtRed ;
                int R = image[h][p].rgbtRed ;
                swap(&r , &R );

            }
        }
    }
    return;
}
void swap (int *a , int *b)
    {
        int tmp = *a ;
            *a = *b ;
            *b = tmp ;
    }

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    return;
}
</code>```

I have written this code for helper.c. It compiles ok and works for grayscale and sepia but fails to reflect the image.

I am stuck in it . Please tell me where have i made the mistake.

答:
You don't need the third for loop

```<code>for (int p=width-1 ; p>=round(width/2) ; p--)
</code>```

instead, you can assign the opposite pixel inside the second loop as follows:

```<code>for (int w=0 ; w<width/2 ; w++)
{
    p = width - w - 1;
    ...
}
</code>```

Title: CS50 pset4 filter reflection

Body:
#include "helpers.h"
#include <math.h>
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for ( int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width ; w++)
        {
           int i = image[h][w].rgbtBlue + image[h][w].rgbtGreen + image[h][w].rgbtRed ;
           float j = i/3 ;
           int n = round(j) ;

           image[h][w].rgbtBlue = n ;
           image[h][w].rgbtGreen = n ;
           image[h][w].rgbtRed = n ;
        }
    }
    return;
}

// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for ( int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width ; w++)
        {
            float sr = .393 * image[h][w].rgbtRed + .769 * image[h][w].rgbtGreen + .189 * image[h][w].rgbtBlue ;
            float sg = .349 * image[h][w].rgbtRed + .686 * image[h][w].rgbtGreen + .168 * image[h][w].rgbtBlue ;
            float sb = .272 * image[h][w].rgbtRed + .534 * image[h][w].rgbtGreen + .131 * image[h][w].rgbtBlue ;

            int SR = round(sr);
            int SG = round(sg);
            int SB = round(sb);

            if ( SR>255)
            {
                SR = 255 ;
            }
            if (SG>255)
            {
                SG = 255 ;
            }
            if (SB>255)
            {
                 SB = 255 ;
            }

            image[h][w].rgbtBlue = SB ;
            image[h][w].rgbtGreen = SG ;
            image[h][w].rgbtRed = SR ;
        }
    }
    return;
}

// Reflect image horizontally
void swap (int *a , int *b) ;

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    for (int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width/2 ; w++)
        {
            for (int p=width-1 ; p>=round(width/2) ; p--)
            {
                int blue = image[h][w].rgbtBlue ;
                int B = image[h][p].rgbtBlue ;
                swap(&blue , &B);

                int g = image[h][w].rgbtGreen ;
                int G = image[h][p].rgbtGreen ;
                swap(&g , &G);

                int r = image[h][w].rgbtRed ;
                int R = image[h][p].rgbtRed ;
                swap(&r , &R );

            }
        }
    }
    return;
}
void swap (int *a , int *b)
    {
        int tmp = *a ;
            *a = *b ;
            *b = tmp ;
    }

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    return;
}

I have written this code for helper.c. It compiles ok and works for grayscale and sepia but fails to reflect the image.

I am stuck in it . Please tell me where have i made the mistake.

Body:
You don't need the third for loop

for (int p=width-1 ; p>=round(width/2) ; p--)

instead, you can assign the opposite pixel inside the second loop as follows:

for (int w=0 ; w<width/2 ; w++)
{
    p = width - w - 1;
    ...
}


问:
In GitAhead, it is not possible to create a new branch with upstream
With the command Branch | Neuer Branch ... a GitAhead Window appears an I can enter the Name of the new Branch. The pull down menu does not allow me to enter my desired starting point (select master?). The upstream pull down menu does also not allow to enter the branch name like "origin/new_Branch. Where can I find the instructions, how to create a new branch?
There is no chance to enter "origin/newbranch" - the pulldown menu do not offer "newbranch" and it is not possible to type in the name.
Thank you
Bahne</p>

答: When clicking on starting point you'll have branches|remotes|tags, choose your starting point and do not select an upstream. When using "pushing to", you can choose your newly created branch after doiing commits then use "set upstream". It will create you new origin/newbranch.</p>


问:
Extracting a value from an XML column in SQL Server
I am trying to extract the data values present in the FirstName and LastName from the below XML which is present as a string in a column in a SQL Server table.

```<code><ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel" xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel" xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel" xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel" xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel" xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel" xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel" xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel" xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel" xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel" xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel" xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel" xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel" xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel" xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>
</code>```

This is the query I tried:

```<code>select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact)[1]', 'varchar(max)') as FirstName
from
    [test1].[dbo].[test2]
</code>```

This query returns the data in all the sub-nodes from the XML node <AccountHolderContact>.

```<code>999-01-02T12:00:00-05:00ABCFABC9999-9999-9999AASIndividual999999999999 ABC SthomeAAAAAABC MMMAAAddress1Person
</code>```

When I change my query to the below, I get no data in my output column FirstName:

```<code>select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact/entity-Person/FirstName)[1]','varchar(max)') as FirstName
from
    [test1].[dbo].[test2]
</code>```

Is there a reason why I cannot extract from the sub-nodes of AccountHolderContact? If not, what is the easiest way to do this?

答:
Assuming that the XML can only contain 1 AccountHolderContact entity (or similar), then you can use WITHXMLSPACES and the XML operator value to get the information:

```<code>DECLARE @XML xml = '<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel" xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel" xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel" xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel" xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel" xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel" xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel" xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel" xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel" xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel" xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel" xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel" xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel" xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel" xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>';

WITH XMLNAMESPACES(DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel', 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns6)
SELECT V.X.value('(ns6:Account/ns6:AccountHolderContact/entity-Person/FirstName/text())[1]','nvarchar(20)') AS FirstName,
       V.X.value('(ns6:Account/ns6:AccountHolderContact/entity-Person/LastName/text())[1]','nvarchar(20)') AS FirstName
FROM(VALUES(@XML))V(X);
</code>```

If, however, you might have more than one person in the data, then you can use nodes to get 1 row per person (this will still bring back one with with the same sample data). If AccountHolderContact is the repeating item it'll look like this:

```<code>WITH XMLNAMESPACES(DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel', 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns6)
SELECT A.AHC.value('(entity-Person/FirstName/text())[1]','nvarchar(20)') AS FirstName,
       A.AHC.value('(entity-Person/LastName/text())[1]','nvarchar(20)') AS FirstName
FROM(VALUES(@XML))V(X)
    CROSS APPLY V.X.nodes('ns6:Account/ns6:AccountHolderContact')A(AHC);
</code>```

Body:
I am trying to extract the data values present in the FirstName and LastName from the below XML which is present as a string in a column in a SQL Server table.

<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel" xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel" xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel" xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel" xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel" xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel" xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel" xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel" xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel" xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel" xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel" xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel" xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel" xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel" xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>

This is the query I tried:

select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact)[1]', 'varchar(max)') as FirstName
from
    [test1].[dbo].[test2]

This query returns the data in all the sub-nodes from the XML node <AccountHolderContact>.

999-01-02T12:00:00-05:00ABCFABC9999-9999-9999AASIndividual999999999999 ABC SthomeAAAAAABC MMMAAAddress1Person

When I change my query to the below, I get no data in my output column FirstName:

select
    application_id, accountID,
    cast(payload as xml).value('(//*:Account//*:AccountHolderContact/entity-Person/FirstName)[1]','varchar(max)') as FirstName
from
    [test1].[dbo].[test2]

Is there a reason why I cannot extract from the sub-nodes of AccountHolderContact? If not, what is the easiest way to do this?

Body:
Assuming that the XML can only contain 1 AccountHolderContact entity (or similar), then you can use WITHXMLSPACES and the XML operator value to get the information:

DECLARE @XML xml = '<ns6:Account xmlns="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel" xmlns:ns2="http://example.com/pc/gx/abc.pc.dm.gx.shared.location.addressmodel" xmlns:ns4="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.officialidmodel" xmlns:ns3="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactaddressmodel" xmlns:ns6="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns5="http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.accountcontactmodel" xmlns:ns8="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.usermodel" xmlns:ns7="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.historymodel" xmlns:ns13="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc" xmlns:ns9="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.activitymodel" xmlns:ns12="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.industrycodemodel" xmlns:ns11="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.documentmodel" xmlns:ns10="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.groupmodel" xmlns:ns17="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.producercodemodel" xmlns:ns16="http://example.com/pc/gx/abc.pc.dm.gx.shared.producer.accountproducercodemodel" xmlns:ns15="http://example.com/pc/gx/abc.pc.dm.gx.shared.general.notemodel" xmlns:ns14="http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc">
    <ns6:AccountHolderContact>
        <entity-Person>
            <DateOfBirth>999-01-02T12:00:00-05:00</DateOfBirth>
            <FirstName>ABC</FirstName>
            <Gender>F</Gender>
            <LastName>ABC</LastName>
            <LicenseNumber>9999-9999-9999</LicenseNumber>
            <LicenseState>AA</LicenseState>
            <MaritalStatus>S</MaritalStatus>
            <OrganizationType_IC>individual</OrganizationType_IC>
        </entity-Person>
        <HomePhone>9999999999</HomePhone>
        <PrimaryAddress>
            <ns2:AddressLine1>99 ABC St</ns2:AddressLine1>
            <ns2:AddressType>home</ns2:AddressType>
            <ns2:City>AAA</ns2:City>
            <ns2:Country>AA</ns2:Country>
            <ns2:PostalCode>ABC MMM</ns2:PostalCode>
            <ns2:State>AA</ns2:State>
            <ns2:Subtype>Address</ns2:Subtype>
        </PrimaryAddress>
        <PublicID>1</PublicID>
        <Subtype>person</Subtype>
    </ns6:AccountHolderContact>
</ns6:Account>';

WITH XMLNAMESPACES(DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel', 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns6)
SELECT V.X.value('(ns6:Account/ns6:AccountHolderContact/entity-Person/FirstName/text())[1]','nvarchar(20)') AS FirstName,
       V.X.value('(ns6:Account/ns6:AccountHolderContact/entity-Person/LastName/text())[1]','nvarchar(20)') AS FirstName
FROM(VALUES(@XML))V(X);

If, however, you might have more than one person in the data, then you can use nodes to get 1 row per person (this will still bring back one with with the same sample data). If AccountHolderContact is the repeating item it'll look like this:

WITH XMLNAMESPACES(DEFAULT 'http://example.com/pc/gx/abc.pc.dm.gx.shared.contact.contactmodel', 'http://example.com/pc/gx/abc.pc.dm.gx.base.account.abc' AS ns6)
SELECT A.AHC.value('(entity-Person/FirstName/text())[1]','nvarchar(20)') AS FirstName,
       A.AHC.value('(entity-Person/LastName/text())[1]','nvarchar(20)') AS FirstName
FROM(VALUES(@XML))V(X)
    CROSS APPLY V.X.nodes('ns6:Account/ns6:AccountHolderContact')A(AHC);


问:
Use ACF to add content to post type archive
I'm trying to create a page with some custom fields (ACF) to display on a custom post type archive page. I tried to create a new page with the same slug as the custom post type archive (test.com/testimonials) and display the custom fields on that page.

I was hoping I could show the content of the custom fields on the testimonials archive page, but it doesn't seem to work. Can I accomplish the wanted result this way without creating a separate options page? This way it's easier for my client to find everything she needs.

答: I tried another approach. I added an options sub page to the custom post type and added the custom fields to this options page.</p>


问:
Alias a single Vue getter in mapGetters
I have a vuex module with getters. I am using this module's getters in a vue component:

```<code>...
computed: {
    ...mapGetters('myCoolModule', ['isActive', 'someOtherGetter', 'yetAnotherGetter']),
}
...
</code>```

I have other vuex modules that have an isActive getter, so I would like to alias it here. I am familiar with the object syntax, i.e.,

```<code>...
computed: {
    ...mapGetters('myCoolModule', { myCoolModuleIsActive: 'isActive', someOtherGetter: 'someOtherGetter', yetAnotherGetter: 'yetAnotherGetter' }),
}
...
</code>```

However, I do not need to alias 'someOtherGetter' or 'yetAnotherGetter', and the object syntax seems to require that I do just that.

Is there a syntax to use with mapGetters such that I can alias only one of the getters?

答:
What about using it twice ?

computed:
{
  ...mapGetters('myModule', {
    myCoolModuleIsActive: 'isActive',
  }),
  ...mapGetters('myModule', ['someOtherGetter', 'yetAnotherGetter']),
}
```

And why not namespacing your Vuex modules ? Thus name collisions like this will be avoided.

Title: Alias a single Vue getter in mapGetters

Body:
I have a vuex module with getters. I am using this module's getters in a vue component:

...
computed: {
    ...mapGetters('myCoolModule', ['isActive', 'someOtherGetter', 'yetAnotherGetter']),
}
...

I have other vuex modules that have an isActive getter, so I would like to alias it here. I am familiar with the object syntax, i.e.,

...
computed: {
    ...mapGetters('myCoolModule', { myCoolModuleIsActive: 'isActive', someOtherGetter: 'someOtherGetter', yetAnotherGetter: 'yetAnotherGetter' }),
}
...

However, I do not need to alias 'someOtherGetter' or 'yetAnotherGetter', and the object syntax seems to require that I do just that.

Is there a syntax to use with mapGetters such that I can alias only one of the getters?

Body:
What about using it twice ?

computed:
{
  ...mapGetters('myModule', {
    myCoolModuleIsActive: 'isActive',
  }),
  ...mapGetters('myModule', ['someOtherGetter', 'yetAnotherGetter']),
}

And why not namespacing your Vuex modules ? Thus name collisions like this will be avoided.


问:
Makefile multiple dependency lines for a single target?
To generate dependency files I can use something like this to generate dependency files:

```<code>-include $(patsubst %.cpp,build/%.d,$(SRC))
build/%.o: %.cpp
    $(CC) $(CXXFLAGS) -c -o $@ $<
    $(CC) $(CXXFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,%@) $<
</code>```

This generates everything and puts both the object and dependency files into the build dir where I want them. But this makes two dependency lines for the <file>.o targets, one from the -include rule and with all the header dependencies, and one which is from the pattern rule. Will this get interpreted correctly, i.e. when a header is modified, the object will be recompiled via the command specified for the pattern rule?

Edit: So this approach does in fact work quite well. I guess I'd like somebody to provide an answer which gives me some insight into what it is exactly that make does in these situations. For instance, what if a different command was given for both rules for the same target? My guess would be that it gives an error since it wouldn't be obvious which command to execute.

答:
You should add one more pattern rule to express the dependency between the .cpp and .d files and use that rule to create the .d files (second line in the pattern rule of your question) instead of creating the .d files unconditionally. It might make sense to introduce another dependency between all .h and .cpp files and all .d files to force re-creating the .d files if a header or source file changes.

Here's the separate rule for .d files (hope I got it right):

```<code>-include $(patsubst %.cpp,build/%.d,$(SRC))
build/%.o: %.cpp
    $(CC) $(CXXFLAGS) -c -o $@ $<

build/%.d: %.cpp
    $(CC) $(CXXFLAGS) -MM -MT $@ -MF $<
</code>```

Edit: So this approach does in fact
  work quite well. I guess I'd like
  somebody to provide an answer which
  gives me some insight into what it is
  exactly that make does in these
  situations.

I'm afraid currently it would only work by chance (or you have not given all relevant pieces from the make file). See, you have not expressed any dependency between .d files and .cpp files. This, however, is needed so that your .d files get updated before inclusion as make file fragment.

For instance, what if a
  different command was given for both
  rules for the same target? My guess
  would be that it gives an error since
  it wouldn't be obvious which command
  to execute.

With that syntax it wouldn't make a difference. But there are some special cases where splitting the rules into two (though otherwise identical rules) has merit. I strongly recommend you get the book "Managing Projects with GNU Make" to get a grip on the various ways of working with GNU Make. The only other recommendation in connection with GNU Make is to read to read the paper here.

Body:
To generate dependency files I can use something like this to generate dependency files:

-include $(patsubst %.cpp,build/%.d,$(SRC))
build/%.o: %.cpp
    $(CC) $(CXXFLAGS) -c -o $@ $<
    $(CC) $(CXXFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,%@) $<

This generates everything and puts both the object and dependency files into the build dir where I want them. But this makes two dependency lines for the <file>.o targets, one from the -include rule and with all the header dependencies, and one which is from the pattern rule. Will this get interpreted correctly, i.e. when a header is modified, the object will be recompiled via the command specified for the pattern rule?

Edit: So this approach does in fact work quite well. I guess I'd like somebody to provide an answer which gives me some insight into what it is exactly that make does in these situations. For instance, what if a different command was given for both rules for the same target? My guess would be that it gives an error since it wouldn't be obvious which command to execute.

Body:
You should add one more pattern rule to express the dependency between the .cpp and .d files and use that rule to create the .d files (second line in the pattern rule of your question) instead of creating the .d files unconditionally. It might make sense to introduce another dependency between all .h and .cpp files and all .d files to force re-creating the .d files if a header or source file changes.

Here's the separate rule for .d files (hope I got it right):

-include $(patsubst %.cpp,build/%.d,$(SRC))
build/%.o: %.cpp
    $(CC) $(CXXFLAGS) -c -o $@ $<

build/%.d: %.cpp
    $(CC) $(CXXFLAGS) -MM -MT $@ -MF $<

Edit: So this approach does in fact
  work quite well. I guess I'd like
  somebody to provide an answer which
  gives me some insight into what it is
  exactly that make does in these
  situations.

I'm afraid currently it would only work by chance (or you have not given all relevant pieces from the make file). See, you have not expressed any dependency between .d files and .cpp files. This, however, is needed so that your .d files get updated before inclusion as make file fragment.

For instance, what if a
  different command was given for both
  rules for the same target? My guess
  would be that it gives an error since
  it wouldn't be obvious which command
  to execute.

With that syntax it wouldn't make a difference. But there are some special cases where splitting the rules into two (though otherwise identical rules) has merit. I strongly recommend you get the book "Managing Projects with GNU Make" to get a grip on the various ways of working with GNU Make. The only other recommendation in connection with GNU Make is to read to read the paper here.


问:
Forming an sql query
I really hope that you can help me forming an sql query that can do the following:

I have 2 tables

```<code>Pages
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Key] [nvarchar](450) NULL,
    [CreatedAt] [datetimeoffset](7) NOT NULL,
    [Title] [nvarchar](max) NULL
)

Contents
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [PageId] [int] NULL,
    [Key] [nvarchar](450) NULL,
    [Version] [int] NOT NULL,
    [Text] [nvarchar](max) NULL
)

Id |   Key   | CreatedAt | Title
---+---------+-----------+-------
 1 | "page1" | 20200101  | ....

Id | PageId |   Key  | Version | Text
---+--------+--------+---------+------
 1 |    1   | "key1" |    1    | .....
 2 |    1   | "key1" |    2    | .....
 3 |    1   | "key2" |    1    | .....
 4 |    1   | "key2" |    2    | .....
 5 |    1   | "key3" |    1    | .....
</code>```

I'm interested in getting the page and the newest version of each content where PageId matches the page.

** Update **

Key is the key that is passed to get the result

```<code>Select * from Pages where [Key] = 'the key of the page'
</code>```

The desired result would be something like

```<code>Page.Id | Page.Key | Page.CreatedAt | Page.Title | Content.Id | Content.PageId | Content.Key | Content.Version | Content.Text
---------------------------------------------------------------------------------------------------------------------------------
   1    |  "Page1" |    20200101    |   ......   |     2      |        1       |    "Key1"     |    2     | ......
   1    |  "Page1" |    20200101    |   ......   |     4      |        1       |    "Key2"     |    2     | ......
   1    |  "Page1" |    20200101    |   ......   |     5      |        1       |    "Key3"     |    1     | ......
</code>```

答:
We need more info.
To get the newest results, you can order your output and limit the number of results like below: </p>

```<code>SELECT PageID FROM Contents WHERE PageID=$pageid ORDER BY id DESC LIMIT 3
</code>```

Title: Forming an sql query

Body:
I really hope that you can help me forming an sql query that can do the following:

I have 2 tables

Pages
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Key] [nvarchar](450) NULL,
    [CreatedAt] [datetimeoffset](7) NOT NULL,
    [Title] [nvarchar](max) NULL
)

Contents
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [PageId] [int] NULL,
    [Key] [nvarchar](450) NULL,
    [Version] [int] NOT NULL,
    [Text] [nvarchar](max) NULL
)

Id |   Key   | CreatedAt | Title
---+---------+-----------+-------
 1 | "page1" | 20200101  | ....

Id | PageId |   Key  | Version | Text
---+--------+--------+---------+------
 1 |    1   | "key1" |    1    | .....
 2 |    1   | "key1" |    2    | .....
 3 |    1   | "key2" |    1    | .....
 4 |    1   | "key2" |    2    | .....
 5 |    1   | "key3" |    1    | .....

I'm interested in getting the page and the newest version of each content where PageId matches the page.

** Update **

Key is the key that is passed to get the result

Select * from Pages where [Key] = 'the key of the page'

The desired result would be something like

Page.Id | Page.Key | Page.CreatedAt | Page.Title | Content.Id | Content.PageId | Content.Key | Content.Version | Content.Text
---------------------------------------------------------------------------------------------------------------------------------
   1    |  "Page1" |    20200101    |   ......   |     2      |        1       |    "Key1"     |    2     | ......
   1    |  "Page1" |    20200101    |   ......   |     4      |        1       |    "Key2"     |    2     | ......
   1    |  "Page1" |    20200101    |   ......   |     5      |        1       |    "Key3"     |    1     | ......

Body:
We need more info.
To get the newest results, you can order your output and limit the number of results like below:

SELECT PageID FROM Contents WHERE PageID=$pageid ORDER BY id DESC LIMIT 3


问:
Using .horizontal ScrollArea at top of screen?
I'm trying to render a layout with a title area, horizontal scroll view, then more views below that. I've wrapped everything in a ZStack to allow me to expand one of the child views in the horizontal area to expand and fill the top 1/3 of the screen (like the App Store) when they're clicked.

```<code>    ZStack(alignment: .leading) {
        VStack {
            Text("Hello World").foregroundColor(.pink)

            ScrollView(.horizontal) {
                HStack(spacing: 20) {
                    ForEach(0..<2) {
                        Text("H/Item \($0)")
                            .foregroundColor(.white)
                            .frame(width: 200, height: 180)
                            .background(Color.red)
                    }
                }
            }.background(Color.orange)

            Spacer()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.green)
        .foregroundColor(.white)
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .foregroundColor(.white)
    .background(Color.pink)
    //.edgesIgnoringSafeArea(.all)
</code>```

If I comment out the edgesIgnoringSafeArea XCode complains that updating the preview took more than 5 seconds (running in the simulator only gives me a white screen). I guess it's a bug in SwiftUI, but is there a way to render the children of a ScrollView outside of its visible bounds?
I can re-position the views using GeometryReader, but they're clipped if the coordinates are outside of the ScrollView.

答:
Here is a possible solution (irrelative to goal, because anyway I could not understood why needed Text at the top, `cause finally it is anyway invisible). Tested with Xcode 11.4 / iOS 13.4.

```<code>var body: some View {
    ZStack(alignment: .leading) {
        VStack {
            Text("Hello World").foregroundColor(.pink)

            ScrollView(.horizontal) {
                HStack(spacing: 20) {
                    ForEach(0..<2) {
                        Text("H/Item \($0)")
                            .foregroundColor(.white)
                            .frame(maxHeight: .infinity)
                            .frame(width: 200)
                            .background(Color.red)
                    }
                }.edgesIgnoringSafeArea(.top)
            }
            .frame(height: 180)
            .background(Color.orange)
        }
        .background(Color.green)
        .foregroundColor(.white)
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
    .foregroundColor(.white)
    .background(Color.pink)
    .edgesIgnoringSafeArea(.all)
}
</code>```

Body:
I'm trying to render a layout with a title area, horizontal scroll view, then more views below that. I've wrapped everything in a ZStack to allow me to expand one of the child views in the horizontal area to expand and fill the top 1/3 of the screen (like the App Store) when they're clicked.

    ZStack(alignment: .leading) {
        VStack {
            Text("Hello World").foregroundColor(.pink)

            ScrollView(.horizontal) {
                HStack(spacing: 20) {
                    ForEach(0..<2) {
                        Text("H/Item \($0)")
                            .foregroundColor(.white)
                            .frame(width: 200, height: 180)
                            .background(Color.red)
                    }
                }
            }.background(Color.orange)

            Spacer()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.green)
        .foregroundColor(.white)
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .foregroundColor(.white)
    .background(Color.pink)
    //.edgesIgnoringSafeArea(.all)

If I comment out the edgesIgnoringSafeArea XCode complains that updating the preview took more than 5 seconds (running in the simulator only gives me a white screen). I guess it's a bug in SwiftUI, but is there a way to render the children of a ScrollView outside of its visible bounds?
I can re-position the views using GeometryReader, but they're clipped if the coordinates are outside of the ScrollView.

Body:
Here is a possible solution (irrelative to goal, because anyway I could not understood why needed Text at the top, `cause finally it is anyway invisible). Tested with Xcode 11.4 / iOS 13.4.

var body: some View {
    ZStack(alignment: .leading) {
        VStack {
            Text("Hello World").foregroundColor(.pink)

            ScrollView(.horizontal) {
                HStack(spacing: 20) {
                    ForEach(0..<2) {
                        Text("H/Item \($0)")
                            .foregroundColor(.white)
                            .frame(maxHeight: .infinity)
                            .frame(width: 200)
                            .background(Color.red)
                    }
                }.edgesIgnoringSafeArea(.top)
            }
            .frame(height: 180)
            .background(Color.orange)
        }
        .background(Color.green)
        .foregroundColor(.white)
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
    .foregroundColor(.white)
    .background(Color.pink)
    .edgesIgnoringSafeArea(.all)
}


问:
Can't signin into microsoft account
I didn't have any problems before with signin into ms account, but now I can't get access to any account (to my account and even to new accounts) from any browser on my pc (but can signin from other pc, so, I know for sure - my account is active and havn't been blocked).

How it works (or, actually, doesn't):

1. Open https://azure.microsoft.com/en-us/services/devops/

2. click on "Sign in to Azure DevOps"

3. enter email and press enter

4. after few seconds and few requests (and few redirects), browser shows signin page again

OR:

1. Open https://portal.azure.com

2. enter email and press enter

3. after few seconds and few requests (and few redirects), I retrieve page "Sign-in failed. Sorry, we had some trouble signing you in, Click 'Try again' to try again."

Other details:

OS: Windows (maybe it happend after latest windows update, I'm not sure)

No installed antivirus or security software (just windows defender)

Browsers: Chrome, Edge on chromium, Firefox, Opera

It happened one week ago, and I still can't signin

There is no failed responses (4xx or 5xx), and no errors in console, so I really dont know how to fix it, maybe someone can help me with this problem

Importang thing: If I change network from my home wifi to another, I can signin there, so problem somewhere in wifi/router

答:
Check to see what's under Credential Manager and, if the account is there, clear it out.

To go there, simply open Start and type credential manager.

You should be good to go.

Title: Can't signin into microsoft account


问:
Facebook Graph API, how to get users email?
I'm using the Graph API, but I can't figure out how to get a logged-in users email address.

The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday"

All well and good, but how do I access that info?

This is what I have so far:

```<code>$json = $facebook->api('/me');

$first = $json['first_name']; // gets first name
$last = $json['last_name'];
</code>```

答:
For me the problem with collecting user's email addres on PHP side (getGraphUser() method) was, that the default behavior of facebook-rendered button (on WEBSIDE side, created with xfbml=1) is to implicity calling FB.login() with the scope NOT including "email".

That means you MUST:

1) call

```

FB.login(....,{scope: email})

```

manifestly, creating your own button to start login process

OR

2) add scope="email" attribute to the xfbml button

```

<div class="fb-login-button" data-size="large" data-button-type="continue_with" data-
layout="rounded" data-auto-logout-link="false" data-use-continue-as="true" data-
width="1000px" scope="email"></div>

```

to be able to collect email address on PHP side.

Hope it helps.

Body:
I'm using the Graph API, but I can't figure out how to get a logged-in users email address.

The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday"

All well and good, but how do I access that info?

This is what I have so far:

$json = $facebook->api('/me');

$first = $json['first_name']; // gets first name
$last = $json['last_name'];

Body:
For me the problem with collecting user's email addres on PHP side (getGraphUser() method) was, that the default behavior of facebook-rendered button (on WEBSIDE side, created with xfbml=1) is to implicity calling FB.login() with the scope NOT including "email".

That means you MUST:

1) call

FB.login(....,{scope: email})

manifestly, creating your own button to start login process

OR

2) add scope="email" attribute to the xfbml button

<div class="fb-login-button" data-size="large" data-button-type="continue_with" data-
layout="rounded" data-auto-logout-link="false" data-use-continue-as="true" data-
width="1000px" scope="email"></div>

to be able to collect email address on PHP side.

Hope it helps.


问:
Oauth2_proxy with Keycloak : getting "invalid_token" with /userinfo API
I am trying Keycloak for the first time and using Keycoak as provider with oauth2_proxy (https://github.com/oauth2-proxy/oauth2-proxy/blob/v5.1.1/providers/keycloak.go) to achieve user authentication via LDAP.
I have followed all steps inside Keycloak to create a realm, create client, client id, client secret etc. Also the Keycloak API "/token" is passing. However once I pass username/password in the keycloak login screen, I get following error in oauth2_proxy:

```<code>[2020/05/30 10:15:37] [requests.go:25] 401 GET http://172.20.0.10:8080/auth/realms/master/protocol/openid-connect/userinfo {"error":"invalid_token","error_description":"Token verification failed"}
</code>```

Also I am passing following parameters when bringing up oauth2_proxy docker container:

```<code>command: -upstream=static://200 -http-address=0.0.0.0:8080 -https-address=0.0.0.0:8443
      -redirect-url="https://portal.acme.com/oauth2/callback"
      -scope='test-scope' -email-domain=* -cookie-domain=* -cookie-secure=false -cookie-secret=skjgfsgfsf23524
      -cookie-samesite="none" -provider=keycloak
      -client-id='abcd-client' -client-secret='c0281257-b600-40b2-beae-68d1f2d72f02'
      --tls-cert-file=/etc/acme.com.pem
      --tls-key-file=/etc/acme.com.key
      -login-url="http://localhost:7575/auth/realms/master/protocol/openid-connect/auth"
      -redeem-url="http://172.20.0.10:8080/auth/realms/master/protocol/openid-connect/token"
      -validate-url="http://172.20.0.10:8080/auth/realms/master/protocol/openid-connect/userinfo"
</code>```

Can someone please help what could be missing or going wrong?
Any lead or hint will be really helpful.

答:
I found the solution to this problem. This was because the issuer in the JWT token was not matching with the URL I gave when bringing up this oauth2_proxy container.
To fix this, what was needed is that the docker container needed to talk to the host network and port exposed by Keycloak. This needs 2 things:

Use "host.docker.internal" as host in all Keycloak APIs when bringing up oauth2_proxy so that oauth2_proxy container communicates Keycloak via host network.

Map "host.docker.internal" to 127.0.0.1 in local machine/host so that the browser redirect is accessible.
After this little hack, the setup works.
Thanks!

Body:
I am trying Keycloak for the first time and using Keycoak as provider with oauth2_proxy (https://github.com/oauth2-proxy/oauth2-proxy/blob/v5.1.1/providers/keycloak.go) to achieve user authentication via LDAP.
I have followed all steps inside Keycloak to create a realm, create client, client id, client secret etc. Also the Keycloak API "/token" is passing. However once I pass username/password in the keycloak login screen, I get following error in oauth2_proxy:

[2020/05/30 10:15:37] [requests.go:25] 401 GET http://172.20.0.10:8080/auth/realms/master/protocol/openid-connect/userinfo {"error":"invalid_token","error_description":"Token verification failed"}

Also I am passing following parameters when bringing up oauth2_proxy docker container:

command: -upstream=static://200 -http-address=0.0.0.0:8080 -https-address=0.0.0.0:8443
      -redirect-url="https://portal.acme.com/oauth2/callback"
      -scope='test-scope' -email-domain=* -cookie-domain=* -cookie-secure=false -cookie-secret=skjgfsgfsf23524
      -cookie-samesite="none" -provider=keycloak
      -client-id='abcd-client' -client-secret='c0281257-b600-40b2-beae-68d1f2d72f02'
      --tls-cert-file=/etc/acme.com.pem
      --tls-key-file=/etc/acme.com.key
      -login-url="http://localhost:7575/auth/realms/master/protocol/openid-connect/auth"
      -redeem-url="http://172.20.0.10:8080/auth/realms/master/protocol/openid-connect/token"
      -validate-url="http://172.20.0.10:8080/auth/realms/master/protocol/openid-connect/userinfo"

Can someone please help what could be missing or going wrong?
Any lead or hint will be really helpful.


问:
How to build mysql docker image with custom value for max_allowed_packet?
How to build mysql docker image with custom value for max_allowed_packet?

```<code>#my-custom.cnf
[mysqld]
max_allowed_packet=64M
</code>```

```<code>#Dockerfile
FROM mysql/mysql-server:5.7
RUN echo "Custom mysql build"
COPY ./my-custom.cnf /etc/mysql/conf.d/
RUN echo "Listing customized configurations" && cat /etc/mysql/conf.d/lj-mysql.conf
</code>```

The customized mysql container still shows 4MB only.

```<code>mysql> show variables like '%max_allowed_packet%';
+--------------------------+------------+
| Variable_name            | Value      |
+--------------------------+------------+
| max_allowed_packet       | 4194304    |
| slave_max_allowed_packet | 1073741824 |
+--------------------------+------------+
</code>```

Any suggestions?

答:
One way you can resolve this with an imperative command

docker run -it -e MYSQL_ROOT_PASSWORD=<sql-pw> mysql:5.7 --max-allowed-packet=67108864

And other way is to using docker-compose

```<code>version: "3"
services:
  data:
    image: "mysql:5.7.20"
    #(it is 64 mb mean 67108864 bytes)
    command: --max_allowed_packet=67108864
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=db
      - MYSQL_USER=user
      - MYSQL_PASSWORD=user_password
</code>```

Use of docker-compose is a good way to start a docker containers and easy to work with docker-compose.

Body:
How to build mysql docker image with custom value for max_allowed_packet?

#my-custom.cnf
[mysqld]
max_allowed_packet=64M

#Dockerfile
FROM mysql/mysql-server:5.7
RUN echo "Custom mysql build"
COPY ./my-custom.cnf /etc/mysql/conf.d/
RUN echo "Listing customized configurations" && cat /etc/mysql/conf.d/lj-mysql.conf

The customized mysql container still shows 4MB only.

mysql> show variables like '%max_allowed_packet%';
+--------------------------+------------+
| Variable_name            | Value      |
+--------------------------+------------+
| max_allowed_packet       | 4194304    |
| slave_max_allowed_packet | 1073741824 |
+--------------------------+------------+

Any suggestions?

Body:
One way you can resolve this with an imperative command

docker run -it -e MYSQL_ROOT_PASSWORD=<sql-pw> mysql:5.7 --max-allowed-packet=67108864

And other way is to using docker-compose

version: "3"
services:
  data:
    image: "mysql:5.7.20"
    #(it is 64 mb mean 67108864 bytes)
    command: --max_allowed_packet=67108864
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=db
      - MYSQL_USER=user
      - MYSQL_PASSWORD=user_password

Use of docker-compose is a good way to start a docker containers and easy to work with docker-compose.