问:
Windows form UI freezing and unable to execute user action when too much data is coming in
Created a simple window form to receive and process data from serial port
also logging the data in textfile and displaying in the rich-text box.

For some reason, it is going into unresponsive state and not able to execute user action and freeze.

According to my understanding, earlier code was using two threads one UI and another one for data received event. Is this correct

But now as i am using background worker, it should create anther thread to process and append in the log and richtext box. Is this correct?

This is my first project in c# so pardon me if it is already answered somewhere else as i am unable to correlate this situation with the given answers and not able to implement them.

Is it a good idea to background worker if not then how can i solve this problem.

Thanks in advance.

Earlier the entire application was running on UI thread. Now i have tried to use background to create a new thread to store data receiving from serial port and processing inside that thread

```<code>//earlier code
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];
        Port.Read(buffer, 0, bytes);
        receivedBytes.AddRange(buffer);
        ProcessRecievedBytes(null);
    }
}

//latest code with background worker
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];

        Port.Read(buffer, 0, bytes);
        receivingBytes.AddRange(buffer);

        if (!essentialBgWorker.IsBusy)
        {
            receivedBytes.AddRange(receivingBytes);
            receivingBytes.Clear();
            essentialBgWorker.RunWorkerAsync();
        }
    }
 }

private void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    foreach (byte hexByte in receivedBytes)
    {
        //color = Color.Gray;
        if ((Config.Data.Serial_DisplayLevel == GLOBAL.HEX_LEVEL_NONE))
        {
            if ((hexByte == '\n') || ((hexByte >= 0x20) && (hexByte <= 0x7E)))
            {
                String tmpString = new String((char)hexByte, 1);
                //essentialBgWorker.ReportProgress(0, tmpString);
                //in here i am putting in the log file and appending in the richtext box
                PreprocessAppend(tmpString, Color.Black, false);
            }
        }
    }

    process.ProcessData(receivedBytes);//in here i am processing the data
    receivedBytes.Clear();
}

private void essentialBgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string str = e.UserState.ToString();
    logWriter.Write(str);
    logWriter.Flush();

    if (e.ProgressPercentage == 0)
    {
        AppendSerial(str, Color.Black, false);
    }
    else if (e.ProgressPercentage == 1)
    {
        AppendSerial(str, Color.Black, false);
    }
}

SerialTab.SerialPort.AppendSerial += delegate (string data, Color txtColor, bool newLineCheck)
{
    this.BeginInvoke((MethodInvoker)(delegate ()
    {
        if (newLineCheck && (serialTextBox.Text != "") && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\r') && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\n'))
        {
            data = "\n" + data;
        }

        AppendTextbox(serialTextBox, data, txtColor);
    }));
};

void AppendTextbox(RichTextBox tb, string data, Color txtColor)
{
    if (data == null)
    {
        return;
    }

    int start = tb.TextLength;
    tb.AppendText(data);
    int end = tb.TextLength;

    // Textbox may transform chars, so (end-start) != text.Length
    tb.Select(start, end - start);
    tb.SelectionColor = txtColor;

    //reset color to defaults
    tb.SelectionLength = 0;
    tb.SelectionColor = serialTextBox.ForeColor;

    //move caret to bottom of page
    ScrollToBottom(tb);

    //ensure text buffer stays below 15000 characters
    checkTextBoxLength(tb);
}

void checkTextBoxLength(RichTextBox box)
{
    //ensure text buffer in text box gets too large
    if (box.Text.Length > 15000)
    {
        box.ReadOnly = false;
        box.SelectionStart = 0;
        box.SelectionLength = box.TextLength - 10000;
        box.SelectedText = "";
        box.ReadOnly = true;
    }
}
</code>```

答:
I see what you are trying to do and you kind of have the right idea, I think you are just having a threading issue.  Do you have the code for your PreprocessAppend method?  You probably need to use BeginInvoke in that function and that should fix your issue.

Personally, I don't think you need a backgroundworker, as the Serial DataReceived event is threaded.  I would recommend what the other answer said and use ReadExisting as that will grab all the characters in the received buffer and you can determine what to do from there.  Just be careful because the DataReceived event can fire whenever it determines is a good time, so you could only get a partial line back.  If you go this route you'll have to build your string until you know you have the whole thing and then process it.

In my example below, I'm expecting a Line Feed as my terminator so I build a string until I have the whole line then I process it.

```<code>//private variables
private SerialPort sp;
private StringBuilder sb;
private char LF = (char)10;

//function to initialize all my objects
public void init_state_machine()
{
    sp = new SerialPort(currentSettings.ComPort, currentSettings.BaudRate);
    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

    sb = new StringBuilder();
    sb.Clear();
}

private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string currentLine = "";
    string Data = sp.ReadExisting();

    foreach (char c in Data)
    {
        if (c == LF)
        {
            sb.Append(c);

            //because it's threaded its possible to enter this code while processing so we will
            //clear our string building immediately
            currentLine = sb.ToString();
            sb.Clear();

            //process your line here or whatever
            processReceivedData(currentLine);
        }
        else
        {
            sb.Append(c);
        }
    }
}

//this is where you process the response.  For a simple example I just append the string
//to our textbox, but you could do any computations in here.
private void processReceivedData(string s)
{
    this.BeginInvoke((MethodInvoker)delegate
    {
        serialTextBox.Text += s;
    });
}
</code>```

Body:
Created a simple window form to receive and process data from serial port
also logging the data in textfile and displaying in the rich-text box.

For some reason, it is going into unresponsive state and not able to execute user action and freeze.

According to my understanding, earlier code was using two threads one UI and another one for data received event. Is this correct

But now as i am using background worker, it should create anther thread to process and append in the log and richtext box. Is this correct?

This is my first project in c# so pardon me if it is already answered somewhere else as i am unable to correlate this situation with the given answers and not able to implement them.

Is it a good idea to background worker if not then how can i solve this problem.

Thanks in advance.

Earlier the entire application was running on UI thread. Now i have tried to use background to create a new thread to store data receiving from serial port and processing inside that thread

//earlier code
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];
        Port.Read(buffer, 0, bytes);
        receivedBytes.AddRange(buffer);
        ProcessRecievedBytes(null);
    }
}

//latest code with background worker
void DataReceived_Event(object sender, SerialDataReceivedEventArgs e)
{
    if (Port.IsOpen)
    {
        int bytes = Port.BytesToRead;
        byte[] buffer = new byte[bytes];

        Port.Read(buffer, 0, bytes);
        receivingBytes.AddRange(buffer);

        if (!essentialBgWorker.IsBusy)
        {
            receivedBytes.AddRange(receivingBytes);
            receivingBytes.Clear();
            essentialBgWorker.RunWorkerAsync();
        }
    }
 }

private void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    foreach (byte hexByte in receivedBytes)
    {
        //color = Color.Gray;
        if ((Config.Data.Serial_DisplayLevel == GLOBAL.HEX_LEVEL_NONE))
        {
            if ((hexByte == '\n') || ((hexByte >= 0x20) && (hexByte <= 0x7E)))
            {
                String tmpString = new String((char)hexByte, 1);
                //essentialBgWorker.ReportProgress(0, tmpString);
                //in here i am putting in the log file and appending in the richtext box
                PreprocessAppend(tmpString, Color.Black, false);
            }
        }
    }

    process.ProcessData(receivedBytes);//in here i am processing the data
    receivedBytes.Clear();
}

private void essentialBgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string str = e.UserState.ToString();
    logWriter.Write(str);
    logWriter.Flush();

    if (e.ProgressPercentage == 0)
    {
        AppendSerial(str, Color.Black, false);
    }
    else if (e.ProgressPercentage == 1)
    {
        AppendSerial(str, Color.Black, false);
    }
}

SerialTab.SerialPort.AppendSerial += delegate (string data, Color txtColor, bool newLineCheck)
{
    this.BeginInvoke((MethodInvoker)(delegate ()
    {
        if (newLineCheck && (serialTextBox.Text != "") && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\r') && (serialTextBox.Text[serialTextBox.TextLength - 1] != '\n'))
        {
            data = "\n" + data;
        }

        AppendTextbox(serialTextBox, data, txtColor);
    }));
};

void AppendTextbox(RichTextBox tb, string data, Color txtColor)
{
    if (data == null)
    {
        return;
    }

    int start = tb.TextLength;
    tb.AppendText(data);
    int end = tb.TextLength;

    // Textbox may transform chars, so (end-start) != text.Length
    tb.Select(start, end - start);
    tb.SelectionColor = txtColor;

    //reset color to defaults
    tb.SelectionLength = 0;
    tb.SelectionColor = serialTextBox.ForeColor;

    //move caret to bottom of page
    ScrollToBottom(tb);

    //ensure text buffer stays below 15000 characters
    checkTextBoxLength(tb);
}

void checkTextBoxLength(RichTextBox box)
{
    //ensure text buffer in text box gets too large
    if (box.Text.Length > 15000)
    {
        box.ReadOnly = false;
        box.SelectionStart = 0;
        box.SelectionLength = box.TextLength - 10000;
        box.SelectedText = "";
        box.ReadOnly = true;
    }
}

Body:
I see what you are trying to do and you kind of have the right idea, I think you are just having a threading issue.  Do you have the code for your PreprocessAppend method?  You probably need to use BeginInvoke in that function and that should fix your issue.

Personally, I don't think you need a backgroundworker, as the Serial DataReceived event is threaded.  I would recommend what the other answer said and use ReadExisting as that will grab all the characters in the received buffer and you can determine what to do from there.  Just be careful because the DataReceived event can fire whenever it determines is a good time, so you could only get a partial line back.  If you go this route you'll have to build your string until you know you have the whole thing and then process it.

In my example below, I'm expecting a Line Feed as my terminator so I build a string until I have the whole line then I process it.

//private variables
private SerialPort sp;
private StringBuilder sb;
private char LF = (char)10;

//function to initialize all my objects
public void init_state_machine()
{
    sp = new SerialPort(currentSettings.ComPort, currentSettings.BaudRate);
    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

    sb = new StringBuilder();
    sb.Clear();
}

private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string currentLine = "";
    string Data = sp.ReadExisting();

    foreach (char c in Data)
    {
        if (c == LF)
        {
            sb.Append(c);

            //because it's threaded its possible to enter this code while processing so we will
            //clear our string building immediately
            currentLine = sb.ToString();
            sb.Clear();

            //process your line here or whatever
            processReceivedData(currentLine);
        }
        else
        {
            sb.Append(c);
        }
    }
}

//this is where you process the response.  For a simple example I just append the string
//to our textbox, but you could do any computations in here.
private void processReceivedData(string s)
{
    this.BeginInvoke((MethodInvoker)delegate
    {
        serialTextBox.Text += s;
    });
}


来源: stackexchange

问:
Auth0 allowLogIn and allowRegister
I have a web app and mobile app using same Auth0 application for login.
I have followed this Auth0 angular guide (https://auth0.com/docs/quickstart/spa/angular2/01-login) and Auth0 Ionic3 guide (https://auth0.com/docs/quickstart/native/ionic3/01-login) and everything works fine.

Now My app has two different buttons for login and registration. When login is clicked, I want to only show Auth0 login dialog and when register is clicked, I want to show only Auth0 registration.

As I am not using Auth0 Lock, allowLogin option does not work. I was wondering if there is a way to achieve this? Also, I will need to modify the Auth0 UI to match my app theme.

Any help would be appreciated.

Many thanks,
Jay

答:
I believe there are two ways to develop the app with our stack. You can either go for Lock which gives you a general UI that you can more or less customize based on your needs along with using the SDK it’s hitting proper API endpoints in the background etc etc (where you can make use of allowLogin)

The other approach requires more development work from your side as you will only be using our Authentication API hitting the right endpoints to handle login / signup / logout and with that solution you will need to build the UI itself (which you can build base on your project needs)

I hope this helps you in your path forward. Thanks!

ContentLicense: CC BY-SA 4.0

Title: Auth0 allowLogIn and allowRegister


问:
How to decide how many convolutions e deconvolutions apply to a GAN?
I'm trying to understand how the adversarial generative network works: I found an example in the book by François Chollet (Deep learning with Python) in which there is an example of a GAN he uses CIFAR10 dataset, using the 'frog' class which contains 32x32 RGB images.

I can't understand why:

In (1) the input is transformed into 16 × 16 128-channel (why 128-channel?) feature map

In (2) when a convolution is performed, with which filter? It is not specified

Next, run another Conv2DTranspose and then another 3 Conv2d. Why?!

At the end, I have a 32 × 32 1-channel feature map.

```<code>from keras import layers
import numpy as np
latent_dim = 32
height = 32
width = 32
channels = 3

generator_input = keras.Input(shape=(latent_dim,))

(1)
x = layers.Dense(128 * 16 * 16)(generator_input)
x = layers.LeakyReLU()(x)
x = layers.Reshape((16, 16, 128))(x)

(2)
x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2DTranspose(256, 4, strides=2, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)
x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2D(channels, 7, activation='tanh', padding='same')(x)
generator = keras.models.Model(generator_input, x)
generator.summary()
</code>```

答:
for 1) i do not think there is a reason for the number of dense nodes used (128x16x16), however the 16x16 is set because you only have 1 layer to up sample 16x16 to 32x32.

for 2) the first argument 256 used to instantiate Conv2D defines the number of filters.

In regards to your last question Next, run another Conv2DTranspose and then another 3 Conv2d. Why?!  I would recommend try increasing/decreasing the number of layers to get a feel on how the model behaves with those changes (performing better or not), this is part of the "hyper-parameter tuning" process when building a neural net.

Hope the above helps.

Body:
I'm trying to understand how the adversarial generative network works: I found an example in the book by François Chollet (Deep learning with Python) in which there is an example of a GAN he uses CIFAR10 dataset, using the 'frog' class which contains 32x32 RGB images.

I can't understand why:

In (1) the input is transformed into 16 × 16 128-channel (why 128-channel?) feature map

In (2) when a convolution is performed, with which filter? It is not specified

Next, run another Conv2DTranspose and then another 3 Conv2d. Why?!

At the end, I have a 32 × 32 1-channel feature map.

from keras import layers
import numpy as np
latent_dim = 32
height = 32
width = 32
channels = 3

generator_input = keras.Input(shape=(latent_dim,))

(1)
x = layers.Dense(128 * 16 * 16)(generator_input)
x = layers.LeakyReLU()(x)
x = layers.Reshape((16, 16, 128))(x)

(2)
x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2DTranspose(256, 4, strides=2, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)
x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2D(channels, 7, activation='tanh', padding='same')(x)
generator = keras.models.Model(generator_input, x)
generator.summary()


问:
Is it possible to apply css rules using json content in a data attribute?
Is it possible to put green background on the spans that have an id represented in the div?

//Edit. If it makes it easier, just using the keys in the div attribute would work too. data-ids='["1", "2"]' or even data-ids="1,2". Not sure what's possible. If not, is there any clever JS/jQuery implementation that could help out?

```<code><div data-ids='{"1":"Name A", "2":"Name B"}'>
    <span data-id="1">This should have green background</span>
    <span data-id="2">This should have green background</span>
    <span data-id="3">This should have no background</span>
</div>
</code>```

Dummy code:

```<code>div[data-ids=*] span[data-id=*] {
    background: green;
}
</code>```

答:
This loops through divs, then loops through data ids of those divs and then adds a class to the appropriate children span

$("div[data-ids]").each(function(){
    let obj = $(this);
    $.each($(this).data("ids"),function(k,v){
      $(obj).find("span[data-id='" + k + "']").addClass("highlight");
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight{
    background: green;
}</code>```

    This should have green background
    This should have green background
    This should have no background

```

Body:
Is it possible to put green background on the spans that have an id represented in the div?

//Edit. If it makes it easier, just using the keys in the div attribute would work too. data-ids='["1", "2"]' or even data-ids="1,2". Not sure what's possible. If not, is there any clever JS/jQuery implementation that could help out?

    This should have green background
    This should have green background
    This should have no background

Dummy code:

div[data-ids=*] span[data-id=*] {
    background: green;
}

Body:
This loops through divs, then loops through data ids of those divs and then adds a class to the appropriate children span

$("div[data-ids]").each(function(){
    let obj = $(this);
    $.each($(this).data("ids"),function(k,v){
      $(obj).find("span[data-id='" + k + "']").addClass("highlight");
    });
});

.highlight{
    background: green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-ids='{"1":"Name A", "2":"Name B"}'>
    <span data-id="1">This should have green background</span>
    <span data-id="2">This should have green background</span>
    <span data-id="3">This should have no background</span>
</div>


问:
SQL IN function and select not match criteria
Using a SQL IN clause to get student scores for a given grade e.g. 1,2,3,4 in Reading. A student may not receive any scores that have 4. Is there a way to select a not matched condition IN SQL clause

Here is the query

```<code>select
score,
count(*) as [countTimes]
from ScoresTable
where  score IN (1,2,3,4)
</code>```

Score

If a student has never received a 4, I need to create a row like 4,0
example resultset

```<code>Score Count
1       2
2       3
3       1
4       0
</code>```

the current query is using an IN clause. If there are no records that match IN clause, the row is not diislayed

```<code>Score Count
1       2
2       3
3       1
4       0
</code>```

答:
If you do not have a table with the available score values just 'build' one, and redo yout query like this (updated after @Serg comment)</p>

```<code>select
    S.score,
    count(ST.Score) as [countTimes]
from
(   Select 1 as Score
    union all
    Select 2 as Score
    union all
    Select 3 as Score
    union all
    Select 4 as Score ) as S
left join
    ScoresTable ST on S.Score = ST.Score
GROUP BY
    S.score
ORDER BY
    S.score
</code>```

Body:
Using a SQL IN clause to get student scores for a given grade e.g. 1,2,3,4 in Reading. A student may not receive any scores that have 4. Is there a way to select a not matched condition IN SQL clause

Here is the query

select
score,
count(*) as [countTimes]
from ScoresTable
where  score IN (1,2,3,4)

Score

If a student has never received a 4, I need to create a row like 4,0
example resultset

Score Count
1       2
2       3
3       1
4       0

the current query is using an IN clause. If there are no records that match IN clause, the row is not diislayed

Score Count
1       2
2       3
3       1
4       0

Body:
If you do not have a table with the available score values just 'build' one, and redo yout query like this (updated after @Serg comment)

select
    S.score,
    count(ST.Score) as [countTimes]
from
(   Select 1 as Score
    union all
    Select 2 as Score
    union all
    Select 3 as Score
    union all
    Select 4 as Score ) as S
left join
    ScoresTable ST on S.Score = ST.Score
GROUP BY
    S.score
ORDER BY
    S.score


问:
R not recognizing if statement in creating new column
I'm trying to create a new column based on if there is a direct character match across 3 columns of the same row. I then want to put a 1 in the new column if there is a match, or a 0 if there is no match. Here's an example of the data:

```<code>   ID    var1   var2  var3
1     1     abc    def   abc
2     2     def    xyz   jkl
3     3     ghi    abc   abc
4     4     jkl    jkl   def
5     4     jkl    jkl   NA
...
</code>```

Here's the code I have:

```<code>   prodprov$var_match <- 0
    for(i in 1:nrow(prodprov)) {
     if(prodprov$var1[i] == prodprov$var2[i] |
     prodprov$var1[i] == prodprov$var3[i] ) {
     prodprov$var_match <- 1
     }
    }
</code>```

But I get this error:
Error in if (prodprov$var1[i] == prodprov$var2[i] |  :
  missing value where TRUE/FALSE needed

The final data frame should look something like this:

```<code>     ID      var1  var2 var3 var_match
1     1     abc    def   abc      1
2     2     def    xyz   jkl      0
3     3     ghi    abc   abc      0
4     4     jkl    jkl   def      1
5     4     jkl    jkl   NA       1
...
</code>```

Any ideas on how to fix this? All of these variables are the same data type (characters). Thanks in advance!

答:
An option would be Reduce with |

```<code>as.integer(Reduce(`|`, lapply(df1[-(1:2)], `==`, df1$var1)))
</code>```

Or an option with rowSums

```<code>df1$var_match <- as.integer( rowSums(df1[c('var2', 'var3')] ==
             rep(df1$var1,  2)) > 0)
df1$var_match
#[1] 1 0 0 1
</code>```

data

```<code>df1 <- structure(list(ID = 1:4, var1 = c("abc", "def", "ghi", "jkl"),
    var2 = c("def", "xyz", "abc", "jkl"), var3 = c("abc", "jkl",
    "abc", "def")), class = "data.frame", row.names = c("1",
"2", "3", "4"))
</code>```

Body:
I'm trying to create a new column based on if there is a direct character match across 3 columns of the same row. I then want to put a 1 in the new column if there is a match, or a 0 if there is no match. Here's an example of the data:

   ID    var1   var2  var3
1     1     abc    def   abc
2     2     def    xyz   jkl
3     3     ghi    abc   abc
4     4     jkl    jkl   def
5     4     jkl    jkl   NA
...

Here's the code I have:

   prodprov$var_match <- 0
    for(i in 1:nrow(prodprov)) {
     if(prodprov$var1[i] == prodprov$var2[i] |
     prodprov$var1[i] == prodprov$var3[i] ) {
     prodprov$var_match <- 1
     }
    }

But I get this error:
Error in if (prodprov$var1[i] == prodprov$var2[i] |  :
  missing value where TRUE/FALSE needed

The final data frame should look something like this:

     ID      var1  var2 var3 var_match
1     1     abc    def   abc      1
2     2     def    xyz   jkl      0
3     3     ghi    abc   abc      0
4     4     jkl    jkl   def      1
5     4     jkl    jkl   NA       1
...

Any ideas on how to fix this? All of these variables are the same data type (characters). Thanks in advance!

Body:
An option would be Reduce with |

as.integer(Reduce(`|`, lapply(df1[-(1:2)], `==`, df1$var1)))

Or an option with rowSums

df1$var_match <- as.integer( rowSums(df1[c('var2', 'var3')] ==
             rep(df1$var1,  2)) > 0)
df1$var_match
#[1] 1 0 0 1

data

df1 <- structure(list(ID = 1:4, var1 = c("abc", "def", "ghi", "jkl"),
    var2 = c("def", "xyz", "abc", "jkl"), var3 = c("abc", "jkl",
    "abc", "def")), class = "data.frame", row.names = c("1",
"2", "3", "4"))


问:
How do I split/parse a URL string into an object?
I'm trying to split a URL into an object.

```<code>$url = "https://api.somedomain.com/v2/direct-access/producing-entities-details?entity_id=104194825&format=json&page=1
</code>```

The desired result would be

```<code>PS C:\WINDOWS\system32> $url.api
https://api.somedomain.com/v2/direct-access

PS C:\WINDOWS\system32> $url.dataset
producing-entities-details

PS C:\WINDOWS\system32> $url.params
entity_id=104194825&format=json&page=1
</code>```

I'm sure this can be done in combination with regex, but I am also wondering if this can be done just using built in PowerShell functionality.

答:
<pre class="lang-bsh prettyprint-override"><code>$url = "https://api.somedomain.com/v2/direct-access/producing-entities-details?entity_id=104194825&format=json&page=1"

$uri = [System.Uri]$url

$ParsedQueryString = [System.Web.HttpUtility]::ParseQueryString($uri.Query)

$i = 0
$queryParams = @()
foreach($QueryStringObject in $ParsedQueryString){
    $queryObject = New-Object -TypeName psobject
    $queryObject | Add-Member -MemberType NoteProperty -Name Query -Value $QueryStringObject
    $queryObject | Add-Member -MemberType NoteProperty -Name Value -Value $ParsedQueryString[$i]
    $queryParams += $queryObject
    $i++
}
$queryParams
</code>```

<p>Output:</p>

<pre class="lang-bsh prettyprint-override"><code>Query     Value
-----     -----
entity_id 104194825
format    json
page      1
</code>```

Body:
I'm trying to split a URL into an object.

$url = "https://api.somedomain.com/v2/direct-access/producing-entities-details?entity_id=104194825&format=json&page=1

The desired result would be

PS C:\WINDOWS\system32> $url.api
https://api.somedomain.com/v2/direct-access

PS C:\WINDOWS\system32> $url.dataset
producing-entities-details

PS C:\WINDOWS\system32> $url.params
entity_id=104194825&format=json&page=1

I'm sure this can be done in combination with regex, but I am also wondering if this can be done just using built in PowerShell functionality.

Body:
$url = "https://api.somedomain.com/v2/direct-access/producing-entities-details?entity_id=104194825&format=json&page=1"

$uri = [System.Uri]$url

$ParsedQueryString = [System.Web.HttpUtility]::ParseQueryString($uri.Query)

$i = 0
$queryParams = @()
foreach($QueryStringObject in $ParsedQueryString){
    $queryObject = New-Object -TypeName psobject
    $queryObject | Add-Member -MemberType NoteProperty -Name Query -Value $QueryStringObject
    $queryObject | Add-Member -MemberType NoteProperty -Name Value -Value $ParsedQueryString[$i]
    $queryParams += $queryObject
    $i++
}
$queryParams

Output:

Query     Value
-----     -----
entity_id 104194825
format    json
page      1


问:
How to automatically post a tweet on twitter
I am working on a site where users can submit data. Is it possible to set up an automated system such that a tweet goes out every time a new data set is received?</p>

答: I believe it's possible through their own API: http://apiwiki.twitter.com/w/page/22554648/FrontPage</p>

ContentLicense: CC BY-SA 3.0


问:
How can I handle Geo Location popup in Safari using selenium webdriver?
I am facing an issue with an auto prompt for geolocation on safari using selenium. I am not sure if I can do a selenium-click to disappear the prompt. does anyone know how can I disappear the prompt?

I tried several java code, I read some pages but look this issue was never result.

答: I have to set up on the preference on safari never ask the location only on that way the pop up on safari never appear.</p>


问:
How to clear memory from cache using ehcache programmatically during bulk transaction?
It takes lot of time to insert more records like 50000 in the database. I have found that, since hibernate stores objects in its cache while any insert or update it takes more time to insert as the number of records increases. I need to know in what name the cache will be saved while inserting so that I can evict using @CacheEvict annotation. I am using ehcache.

I have found that @CacheEvict can be used. But I don't know in what name the cache for the insert will be saved. I have created a cache in CacheConfiguration class, but I don't know whether it is correct. I have found there is a way to set cache name using ehcache.xml, but we are not using it. I am using ehcache, hibernate and spring mvc.

```<code>//Setting cache name in CacheConfiguration class:
@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
    return cm -> {
cm.createCache(com.cspl.cashflow.CashflowService.NAME,jcacheConfiguration);
             };
    }

//For loop for inserting:
public static final String NAME = "names";
 @Cacheable("names")
 public void getNames() {
     logger.info("saving");
    for(int i=1; i<=50000;i++){
        List<Cashflow> cashflowList = new ArrayList<>();
        Cashflow order = new Cashflow(1, "Stark", "Tony", true)
        cashflowList.add(order);
        cashflowRepository.save(cashflowList);
    if(i%1000==0) {
            evictAllCacheValues();
                }
        }
     logger.info("saved");
            }

@CacheEvict(value = "names",  allEntries = true)
    public void evictAllCacheValues() {
                      }

//I have also tried using
@Scheduled(cron = "0 0/30 * * * ?")       // execute after every 30 min
public void clearCacheSchedule(){
   for(String name:cacheManager.getCacheNames()){
            cacheManager.getCache(name).clear();  // clear cache by name
                           }
                        }
</code>```

Even after evicting, the insert takes more time. i don't know whether setting the cache name and using it in @Cacheable and @CacheEvict are correct.

答:
You can try to clear all the cache using cache.removeAll().

To do programmatically, you have to use like this.

```<code>Cache cache = getCache(cacheName); // <---- You have to get the instance of //Ehcache with Configuration
  if (null != cache) {
    cache.removeAll();
  }
</code>```

For more details, refer below the link.
https://www.ehcache.org/apidocs/2.9/net/sf/ehcache/Ehcache.html#removeAll()

Body:
It takes lot of time to insert more records like 50000 in the database. I have found that, since hibernate stores objects in its cache while any insert or update it takes more time to insert as the number of records increases. I need to know in what name the cache will be saved while inserting so that I can evict using @CacheEvict annotation. I am using ehcache.

I have found that @CacheEvict can be used. But I don't know in what name the cache for the insert will be saved. I have created a cache in CacheConfiguration class, but I don't know whether it is correct. I have found there is a way to set cache name using ehcache.xml, but we are not using it. I am using ehcache, hibernate and spring mvc.

//Setting cache name in CacheConfiguration class:
@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
    return cm -> {
cm.createCache(com.cspl.cashflow.CashflowService.NAME,jcacheConfiguration);
             };
    }

//For loop for inserting:
public static final String NAME = "names";
 @Cacheable("names")
 public void getNames() {
     logger.info("saving");
    for(int i=1; i<=50000;i++){
        List<Cashflow> cashflowList = new ArrayList<>();
        Cashflow order = new Cashflow(1, "Stark", "Tony", true)
        cashflowList.add(order);
        cashflowRepository.save(cashflowList);
    if(i%1000==0) {
            evictAllCacheValues();
                }
        }
     logger.info("saved");
            }

@CacheEvict(value = "names",  allEntries = true)
    public void evictAllCacheValues() {
                      }

//I have also tried using
@Scheduled(cron = "0 0/30 * * * ?")       // execute after every 30 min
public void clearCacheSchedule(){
   for(String name:cacheManager.getCacheNames()){
            cacheManager.getCache(name).clear();  // clear cache by name
                           }
                        }

Even after evicting, the insert takes more time. i don't know whether setting the cache name and using it in @Cacheable and @CacheEvict are correct.

Body:
You can try to clear all the cache using cache.removeAll().

To do programmatically, you have to use like this.

Cache cache = getCache(cacheName); // <---- You have to get the instance of //Ehcache with Configuration
  if (null != cache) {
    cache.removeAll();
  }

For more details, refer below the link.
https://www.ehcache.org/apidocs/2.9/net/sf/ehcache/Ehcache.html#removeAll()


答:
Left join the list of scores  and ScoresTable

```<code>select
 sl.score,
 count(st.score) as [countTimes]
from (
   values (1),(2),(3),(4)
 ) sl (score)
left join ScoresTable st on st.score = sl.score
group by sl.score
</code>```

Title: SQL IN function and select not match criteria

Body:
Left join the list of scores  and ScoresTable

select
 sl.score,
 count(st.score) as [countTimes]
from (
   values (1),(2),(3),(4)
 ) sl (score)
left join ScoresTable st on st.score = sl.score
group by sl.score


问:
C++ how to check a condition before using initialiser list?
I am writing a piece of code that is structured this way:

```<code>//field.h
class Field {
    std::vector<std::vector<double>> data;

    public:
    Field(int, int);
};
Field::Field (int dim0, int dim1) :: data(dim0, std::vector<double>(dim1, 0)) { }
</code>```

Then I am using this Field in another class like:

```<code>//approx.h
class Field;
class Approx {
    Field SWAP;

    public:
    Approx(int, int);
};
Approx::Approx (int size, int dim) { }
/*I want to initialise SWAP like this:
     if (size > dim) SWAP(size, dim)
     else SWAP(dim, size)
*/
</code>```

I do not know how to do this. I presume it is impossible without initialiser lists? Can I even ask inside initialiser list these questions?

If there is another way to do so, I'd be grateful for any type of solution.

答:
You can also use std::unique_ptr to initialize member variables in constructor body, like:

```<code>class Approx {
    std::unique_ptr<Field> SWAP {nullptr};

public:
    Approx(int, int);
};

Approx::Approx (int size, int dim) {
    if (size > dim) {
        SWAP = std::make_unique<Field>(size, dim);
    } else {
        SWAP = std::make_unique<Field>(dim, size);
    }
}
</code>```

Body:
I am writing a piece of code that is structured this way:

//field.h
class Field {
    std::vector<std::vector<double>> data;

    public:
    Field(int, int);
};
Field::Field (int dim0, int dim1) :: data(dim0, std::vector<double>(dim1, 0)) { }

Then I am using this Field in another class like:

//approx.h
class Field;
class Approx {
    Field SWAP;

    public:
    Approx(int, int);
};
Approx::Approx (int size, int dim) { }
/*I want to initialise SWAP like this:
     if (size > dim) SWAP(size, dim)
     else SWAP(dim, size)
*/

I do not know how to do this. I presume it is impossible without initialiser lists? Can I even ask inside initialiser list these questions?

If there is another way to do so, I'd be grateful for any type of solution.

Body:
You can also use std::unique_ptr to initialize member variables in constructor body, like:

class Approx {
    std::unique_ptr<Field> SWAP {nullptr};

public:
    Approx(int, int);
};

Approx::Approx (int size, int dim) {
    if (size > dim) {
        SWAP = std::make_unique<Field>(size, dim);
    } else {
        SWAP = std::make_unique<Field>(dim, size);
    }
}


问:
Ansible IP address variable remote hosts
I have the following problem:

I'm writing a playbook for configuring NFS server and NFS client.

in the same playbook, I include 2 other tasks :

CentOS_7_NFS_Server.yml and CentOS_7_NFS_Client.yml

for I can execute one of the tasks I need to compare the IP address of

the remote hosts

Example :

```<code>- include: CentOS_7_NFS_Server.yml
  when: ansible_all_ipv4_addresses == NFS_Server

- include: CentOS_7_NFS_Client.yml
  when:  ansible_all_ipv4_addresses == NFS_Client
</code>```

in the var :

```<code>NFS_Server: x.x.x.x
NFS_Client : y.y.y.y
</code>```

I got this error

```<code>FAILED! => {"msg": "The conditional check 'ansible_all_ipv4.address
== NFS_Client' failed. The error was: error while evaluating
conditional (ansible_all_ipv4.address == NFS_Client):
'ansible_all_ipv4' is undefined\n\nThe error appears to have been
in
</code>```

答:
Very probably the collecting of the facts is disabled. when you see the error:

ansible_all_ipv4_addresses: VARIABLE IS NOT DEFINED!

Enable it

```<code>- hosts: nfs_server_and_client
  gather_facts: yes
</code>```

There is one more problem. ansible_all_ipv4_addresses is list of all addresses. For example.

```<code>  ansible_all_ipv4_addresses:
  - 192.168.122.1
  - 10.1.0.11
  - 192.168.1.10
</code>```

You'll have to pick one, or more and assign it to NFS_Server and NFS_Client. Then the condition shall test if NFS_Server and NFS_Client, respectively,  is in the list ansible_all_ipv4_addresses.

```<code>- include: CentOS_7_NFS_Server.yml
  when: NFS_Server in ansible_all_ipv4_addresses

- include: CentOS_7_NFS_Client.yml
  when: NFS_Client in ansible_all_ipv4_addresses
</code>```

Body:
I have the following problem:

I'm writing a playbook for configuring NFS server and NFS client.

in the same playbook, I include 2 other tasks :

CentOS_7_NFS_Server.yml and CentOS_7_NFS_Client.yml

for I can execute one of the tasks I need to compare the IP address of

the remote hosts

Example :

- include: CentOS_7_NFS_Server.yml
  when: ansible_all_ipv4_addresses == NFS_Server

- include: CentOS_7_NFS_Client.yml
  when:  ansible_all_ipv4_addresses == NFS_Client

in the var :

NFS_Server: x.x.x.x
NFS_Client : y.y.y.y

I got this error

FAILED! => {"msg": "The conditional check 'ansible_all_ipv4.address
== NFS_Client' failed. The error was: error while evaluating
conditional (ansible_all_ipv4.address == NFS_Client):
'ansible_all_ipv4' is undefined\n\nThe error appears to have been
in

Body:
Very probably the collecting of the facts is disabled. when you see the error:

ansible_all_ipv4_addresses: VARIABLE IS NOT DEFINED!

Enable it

- hosts: nfs_server_and_client
  gather_facts: yes

There is one more problem. ansible_all_ipv4_addresses is list of all addresses. For example.

  ansible_all_ipv4_addresses:
  - 192.168.122.1
  - 10.1.0.11
  - 192.168.1.10

You'll have to pick one, or more and assign it to NFS_Server and NFS_Client. Then the condition shall test if NFS_Server and NFS_Client, respectively,  is in the list ansible_all_ipv4_addresses.

- include: CentOS_7_NFS_Server.yml
  when: NFS_Server in ansible_all_ipv4_addresses

- include: CentOS_7_NFS_Client.yml
  when: NFS_Client in ansible_all_ipv4_addresses


问:
Get all values of dictionary of lists
```<code>l_d_l = {
'a' : [1,2,3]
'b' : [2,3,4,5]
'c' : [5,6]
'd' : [1]
}
</code>```

I want to check if 1 exists in a in l_d_l. What's the best approach?

答:
Not only is the module a different scope, the function within is a different scope.  You have two variables names myBool; the one in module isn't even visible in the rest of the module.  If you want to have a module-level variable, you need to address is properly, such as:

```<code># main

import module
module.myBool = False
booleanChange()
if module.myBool:
    print("Hello World")

# module
myBool = True      # Not needed, but illustrates the scope.
def booleanChange():
    global myBool
    myBool = True
</code>```

Title: Get all values of dictionary of lists

Body:
l_d_l = {
'a' : [1,2,3]
'b' : [2,3,4,5]
'c' : [5,6]
'd' : [1]
}

I want to check if 1 exists in a in l_d_l. What's the best approach?

Body:
Not only is the module a different scope, the function within is a different scope.  You have two variables names myBool; the one in module isn't even visible in the rest of the module.  If you want to have a module-level variable, you need to address is properly, such as:

# main

import module
module.myBool = False
booleanChange()
if module.myBool:
    print("Hello World")

# module
myBool = True      # Not needed, but illustrates the scope.
def booleanChange():
    global myBool
    myBool = True


答:
You need to make myBool a global variable, and then import it.

module:

```<code>def booleanChange():
    global myBool
    myBool = True
</code>```

main:

```<code>from module import booleanChange, myBool
myBool = False
booleanChange()
if myBool:
    print("Hello World")
</code>```

Title: Get all values of dictionary of lists

Body:
You need to make myBool a global variable, and then import it.

module:

def booleanChange():
    global myBool
    myBool = True

main:

from module import booleanChange, myBool
myBool = False
booleanChange()
if myBool:
    print("Hello World")


问:
Selenium Maven test runs in console but not on Jenkins
I have deplyed my selenium test on Maven and all neccessary PATHS, JAVA_HOME, MAVEN_HOME have been set correctly . I tested my test using the command (mvn clean test) on CMD and was successful .  However i deployed this on Jenkins and used the same command to invoke test in the same directory . I got the error below

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

I have checked all the neccessary system and environmental variables and all seems fine

-

I expect the same test to be executed when i run the  build on Jenkins , This is working on command prompt

答: If your maven installation is empty then you will not be able to use maven, here is what mine looks like as a reference.


问:
How to pass a function to express-handlebars in nodejs-express?
I am trying to pass a function in express-handlebar,
 but it is not working.
I am using app.js as server file and index.handlebars as handlebar file.

app.js

```<code>const express=require('express');
const app=express();
const csc=require('countrycitystatejson');
const exphbs=require('express-handlebars');
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// console.log(csc.getAll());

function hello(){
  console.log('hello');
}

app.get('/', function (req, res) {
    res.render('index',{
      hello:hello
    });
});

 app.listen(3000);
</code>```

index.handlebars

```<code><button onclick="hello()">click</button>
</code>```

答:
Best to create a helper for this. Below an example and referring to Github for more info on the topic.

```<code>const express=require('express');
const app=express();
const csc=require('countrycitystatejson');
const exphbs=require('express-handlebars');

var hbs = exphbs.create({
    helpers: {
        hello: function () { console.log('hello'); }
    }
});

app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

// console.log(csc.getAll());

app.get('/', function (req, res) {
    res.render('index');
});

app.listen(3000);
</code>```

index.handlebars

```<code><button onclick="{{hello}}">click</button>
</code>```

Body:
I am trying to pass a function in express-handlebar,
 but it is not working.
I am using app.js as server file and index.handlebars as handlebar file.

app.js

const express=require('express');
const app=express();
const csc=require('countrycitystatejson');
const exphbs=require('express-handlebars');
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// console.log(csc.getAll());

function hello(){
  console.log('hello');
}

app.get('/', function (req, res) {
    res.render('index',{
      hello:hello
    });
});

 app.listen(3000);

index.handlebars

<button onclick="hello()">click</button>

Body:
Best to create a helper for this. Below an example and referring to Github for more info on the topic.

const express=require('express');
const app=express();
const csc=require('countrycitystatejson');
const exphbs=require('express-handlebars');

var hbs = exphbs.create({
    helpers: {
        hello: function () { console.log('hello'); }
    }
});

app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

// console.log(csc.getAll());

app.get('/', function (req, res) {
    res.render('index');
});

app.listen(3000);

index.handlebars

<button onclick="{{hello}}">click</button>


问:
How to create and use an "out" parameter with a SQL Server database
I am working on a C# desktop application. I want to use a stored procedure (insert query) to add a new record to a data table. I need to return the primary key which is an identity insert (bigint) to avoid another round trip to the database. I have searched the MS Help(less) files for a couple of hours and found nothing on how to set the out parameter of the stored procedure or how to obtain the return value.

答:
with the help of you guys that answered, I finally figured it out. I modified the stored procedure as follows:

//Stored Procedure

```<code>```` -- Add the parameters for the stored procedure here
````@Vendorcode nvarchar(17) = ''
````, @Name nvarchar(60) = ''
````...
````, @ID bigint output  --<<<<<<<<Added this line
````AS
````BEGIN
````    -- SET NOCOUNT ON added to prevent extra result sets from
````    -- interfering with SELECT statements.
````    SET NOCOUNT ON;
````    -- Insert statements for procedure here
````INSERT INTO APVendorShipTo
````        (Vendorcode, [Name], ...)
````VALUES  (@Vendorcode, @Name,...)

````Select @ID = SCOPE_IDENTITY(); -- <<<<<<<< Added this line
````END
*//end Stored Procedure*
----------

----------

*//C# Code in Desktop App*

````try
````{
````string connString = AdoHelper.ConnectionString;
````var myConnection = new SqlConnection(connString);
````var myCommand = new SqlCommand();
````using (myConnection)
````{
```` myConnection.Open();
```` myCommand.Connection = myConnection;
```` myCommand.CommandType = CommandType.StoredProcedure;
```` myCommand.CommandTimeout = 540;
```` myCommand.CommandText = "APVendorShipToAddNew";
```` myCommand.Parameters.AddWithValue(parameterName: "@Vendorcode", value:
this.txtAcctNo.Text);
```` myCommand.Parameters.AddWithValue(parameterName: "@Name", value: this.txtShipName.Text);
-- left out the rest of the parameters
--//Added the line below to retrieve the Identity Insert value from the query
````myCommand.Parameters.Add("@ID", SqlDbType.BigInt).Direction = ParameterDirection.Output;

````myCommand.ExecuteNonQuery();

--//Added next line to convert the returned value to a usable value in my program.
````liID = Convert.ToInt64(myCommand.Parameters["@ID"].Value);

````MessageBox.Show(Convert.ToString(liID));
--//Showed correct value Now available to  my code

````return true;
````}

</code>```

Body:
with the help of you guys that answered, I finally figured it out. I modified the stored procedure as follows:

//Stored Procedure

```` -- Add the parameters for the stored procedure here
````@Vendorcode nvarchar(17) = ''
````, @Name nvarchar(60) = ''
````...
````, @ID bigint output  --<<<<<<<<Added this line
````AS
````BEGIN
````    -- SET NOCOUNT ON added to prevent extra result sets from
````    -- interfering with SELECT statements.
````    SET NOCOUNT ON;
````    -- Insert statements for procedure here
````INSERT INTO APVendorShipTo
````        (Vendorcode, [Name], ...)
````VALUES  (@Vendorcode, @Name,...)

````Select @ID = SCOPE_IDENTITY(); -- <<<<<<<< Added this line
````END
*//end Stored Procedure*
----------

----------

*//C# Code in Desktop App*

````try
````{
````string connString = AdoHelper.ConnectionString;
````var myConnection = new SqlConnection(connString);
````var myCommand = new SqlCommand();
````using (myConnection)
````{
```` myConnection.Open();
```` myCommand.Connection = myConnection;
```` myCommand.CommandType = CommandType.StoredProcedure;
```` myCommand.CommandTimeout = 540;
```` myCommand.CommandText = "APVendorShipToAddNew";
```` myCommand.Parameters.AddWithValue(parameterName: "@Vendorcode", value:
this.txtAcctNo.Text);
```` myCommand.Parameters.AddWithValue(parameterName: "@Name", value: this.txtShipName.Text);
-- left out the rest of the parameters
--//Added the line below to retrieve the Identity Insert value from the query
````myCommand.Parameters.Add("@ID", SqlDbType.BigInt).Direction = ParameterDirection.Output;

````myCommand.ExecuteNonQuery();

--//Added next line to convert the returned value to a usable value in my program.
````liID = Convert.ToInt64(myCommand.Parameters["@ID"].Value);

````MessageBox.Show(Convert.ToString(liID));
--//Showed correct value Now available to  my code

````return true;
````}


问:
Comment after #else preprocessor directive
This is simple piece of C code and to my surprise it compiles successfully (at least in Visual Studio 2012 which I am using)

```<code>#include <stdio.h>

#define MYCONSTANT

int main(int argc, char* argv[])
{
    #ifdef MYCONSTANT // We can write anything here as comment
        printf("MYCONSTANT is defined");
    #else We can write any random words here without marking it as comment
        printf("MYCONSTANT is not defined");
    #endif

    return 0;
}
</code>```

Question: Is writing anything after #else allowed this way?

答:
In standard C, you are not allowed to put anything except comments on the line after #else or #endif. With the compiler on my computer, I get a warning from your code by default:

```<code>test.c: In function ‘main’:
test.c:9:11: warning: extra tokens at end of #else directive [-Wendif-labels]
     #else We can write any random words here without marking it as comment
           ^~
</code>```

and this becomes a hard error if I request strict conformance with C99.

However, the original "K&R" C preprocessor did allow arbitrary text to appear on the line after #else and #endif, and old programs would use that.  Your compiler is being backward-compatible and allowing those old programs to compile without error.

Many C compilers allow lots of things that are nowadays considered bad style or outright wrong, by default, for the sake of allowing old code to keep working.  Look through the manual for Visual Studio and see if there is a recommended configuration to use for new programs.  I don't use VS myself so I can't give any more specific advice.

Body:
This is simple piece of C code and to my surprise it compiles successfully (at least in Visual Studio 2012 which I am using)

#include <stdio.h>

#define MYCONSTANT

int main(int argc, char* argv[])
{
    #ifdef MYCONSTANT // We can write anything here as comment
        printf("MYCONSTANT is defined");
    #else We can write any random words here without marking it as comment
        printf("MYCONSTANT is not defined");
    #endif

    return 0;
}

Question: Is writing anything after #else allowed this way?

Body:
In standard C, you are not allowed to put anything except comments on the line after #else or #endif. With the compiler on my computer, I get a warning from your code by default:

test.c: In function ‘main’:
test.c:9:11: warning: extra tokens at end of #else directive [-Wendif-labels]
     #else We can write any random words here without marking it as comment
           ^~

and this becomes a hard error if I request strict conformance with C99.

However, the original "K&R" C preprocessor did allow arbitrary text to appear on the line after #else and #endif, and old programs would use that.  Your compiler is being backward-compatible and allowing those old programs to compile without error.

Many C compilers allow lots of things that are nowadays considered bad style or outright wrong, by default, for the sake of allowing old code to keep working.  Look through the manual for Visual Studio and see if there is a recommended configuration to use for new programs.  I don't use VS myself so I can't give any more specific advice.


问:
How to get table name for a simple Sequel Dataset object?
Ie, given a dataset object ds = DB[:transactions].where{updated_at > 1.day.ago} - no funny joins and stuff going on - how could I fetch the table name (:transactions) ?

答:
If you want it as a string you can do:

```<code>ds.first_source_table.to_s
</code>```

If you want a symbol, just omit .to_s

Body:
If you want it as a string you can do:

ds.first_source_table.to_s

If you want a symbol, just omit .to_s


问:
get access to child objects in react-native
I'm pulling data from an API which returns the data like this

```<code>[
   {
      "id":466,
      "createdDate":"2019-04-18 13:22:34",
      "updatedDate":null,
      "isAdmin":false,
      "createGroupRequestsCount":0,
      "createdGroupsCount":0,
      "postsCount":0,
      "community":{
         "id":7,
         "createdDate":"2019-04-18 13:14:34",
         "avatar":"",
         "name":"FAX International School Community",
         "description":"",
         "referenceId":6,
         "referenceName":"Fax International School",
         "referenceAlias":"FIS",
         "createGroupRequestsCount":0,
         "groupsCount":0,
         "postsCount":0
      },
      "member":{
         "id":501,
         "firstname":"Jack",
         "lastname":"Manson",
         "othernames":null,
         "createdDate":"2019-04-18 13:21:49",
         "updatedDate":null,
         "isEmployee":false,
         "email":"ernest.agyekum@minex360.com",
         "avatar":null,
         "primaryContact":"+233244908666",
         "referenceId":1112,
         "postsCount":0
      }
   }
]
</code>```

I pull the data with the below script, which returns the data with child objects as well

```<code>componentDidMount = async () => {
const communities = await API.getUserCommunityInfo(userId,schoolId);
const groups = await API.getGroups(communityMemberId);
console.log(communities)

}
</code>```

When I try to access the child object member with console.log(communities.member[0].id) I get an error message cannot read property of 0 undefined

Any help on how to retrieve the child objects?

答:
You are getting the error because member is not a direct child of communities

communities is an Array of Objects, so to access to the first member you should do communities[0].member.id.

Body:
I'm pulling data from an API which returns the data like this

[
   {
      "id":466,
      "createdDate":"2019-04-18 13:22:34",
      "updatedDate":null,
      "isAdmin":false,
      "createGroupRequestsCount":0,
      "createdGroupsCount":0,
      "postsCount":0,
      "community":{
         "id":7,
         "createdDate":"2019-04-18 13:14:34",
         "avatar":"",
         "name":"FAX International School Community",
         "description":"",
         "referenceId":6,
         "referenceName":"Fax International School",
         "referenceAlias":"FIS",
         "createGroupRequestsCount":0,
         "groupsCount":0,
         "postsCount":0
      },
      "member":{
         "id":501,
         "firstname":"Jack",
         "lastname":"Manson",
         "othernames":null,
         "createdDate":"2019-04-18 13:21:49",
         "updatedDate":null,
         "isEmployee":false,
         "email":"ernest.agyekum@minex360.com",
         "avatar":null,
         "primaryContact":"+233244908666",
         "referenceId":1112,
         "postsCount":0
      }
   }
]

I pull the data with the below script, which returns the data with child objects as well

componentDidMount = async () => {
const communities = await API.getUserCommunityInfo(userId,schoolId);
const groups = await API.getGroups(communityMemberId);
console.log(communities)

}

When I try to access the child object member with console.log(communities.member[0].id) I get an error message cannot read property of 0 undefined

Any help on how to retrieve the child objects?


问:
ESCPOS GS C commands
Can you please explain to me what aL, aH, bL, bH stands for

答:
aL = a low byte

aH = a high byte

bL = b low byte

bH = b high byte

In this case a is the minimum serial number count value and b is the maximum serial number count value.

Title: ESCPOS GS C commands


问:
Python add custom property/metadata to file
In Python, is it possible to add custom property/metadata to a file?
For example, I need to add "FileInfo" as a new property of the file.
I need a method that works on various file formats</p>

答:
Heads up: this answer only works on Linux

You can make use of extended file attributes which is a filesystem feature that do just what you want: store custom metadata along files.

In Python, this is implemented by the os module through setxattr() and  getxattr() functions.

```<code>import os

os.setxattr('foo.txt', 'user.bar', b'baz')
os.getxattr('foo.txt', 'user.bar')  # => b'baz'
</code>```

Note that you must prepend the xattr value with "user." otherwise this may raise an OSError.

Body:
Heads up: this answer only works on Linux

You can make use of extended file attributes which is a filesystem feature that do just what you want: store custom metadata along files.

In Python, this is implemented by the os module through setxattr() and  getxattr() functions.

import os

os.setxattr('foo.txt', 'user.bar', b'baz')
os.getxattr('foo.txt', 'user.bar')  # => b'baz'

Note that you must prepend the xattr value with "user." otherwise this may raise an OSError.


问:
RegEx for matching digits not followed by specific pattern
I am trying to build a regex to match the following style of lines:

```<code>123 warehouse
124 token warehouse.
153token token abc123; etc. - warehouse
223abdc token abc green warehouse
</code>```

But not these lines:

```<code>53red warehouse.
323 green token token etc warehouse.
</code>```

The regex I build uses negative lookahead, but testing it on https://regex101.com/ matches all lines:

```<code>\d+(?!( ?red| ?green)).*(\bwarehouse\b)
</code>```

What is the mistake and how should it be modified? If it matters, the regex should compile under Java (after escaping the necessary characters).

答:
Your pattern works, if you use a possessive quantifier for preventing backtracking:

\d++ instead of \d+

Here is a demo at regex101 which is pcre but Java regex should support those as well.

Body:
I am trying to build a regex to match the following style of lines:

123 warehouse
124 token warehouse.
153token token abc123; etc. - warehouse
223abdc token abc green warehouse

But not these lines:

53red warehouse.
323 green token token etc warehouse.

The regex I build uses negative lookahead, but testing it on https://regex101.com/ matches all lines:

\d+(?!( ?red| ?green)).*(\bwarehouse\b)

What is the mistake and how should it be modified? If it matters, the regex should compile under Java (after escaping the necessary characters).


问:
JavaFX background color using three colors

How I can create this type of background(white, black, white) in javafx?

I tried -fx-background-color: white, black, white; but is not what I want.

答:
I managed to come up with a CSS styling resulting in this:
Inner Circles example</p>

```<code>.circle-background{
    -fx-background-color: black, white; /* 2nd inner color, 3rd inner color*/
    -fx-background-insets: 10,60; /*2nd inner ring, 3rd inner ring */
    -fx-background-radius: 50%;
    -fx-border-width: 10;   /* outer ring width */
    -fx-border-color: white;/* outer ring color */
    -fx-border-radius: 50%;
}
</code>```

Body:
I managed to come up with a CSS styling resulting in this:
Inner Circles example

.circle-background{
    -fx-background-color: black, white; /* 2nd inner color, 3rd inner color*/
    -fx-background-insets: 10,60; /*2nd inner ring, 3rd inner ring */
    -fx-background-radius: 50%;
    -fx-border-width: 10;   /* outer ring width */
    -fx-border-color: white;/* outer ring color */
    -fx-border-radius: 50%;
}


问:
Permanently add a directory to PYTHONPATH?
Whenever I use sys.path.append, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH?

答:
Shortest path between A <-> B is a straight line;</p>

```<code>import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']
</code>```

Body:
Shortest path between A <-> B is a straight line;

import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']


问:
Trying to make an accessor funtion in qt
you should be able to see what I am tring to do by looking at the funtion called motorcontroll I am trying to make a funtion that can set the values of several spinboxes with the call of one funtion called motorcontrol If I put the function inside the:

```<code>Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
}
</code>```

I get the error that I can not declare a function there, but if I put it outside the brackets, I get the error ui was not declared in this scope. I understand why I am getting this error but I don't know a way around it. Could I make ui a global variable/object and if so how would I do that or is there another way to solve/get around this issue. here is my code:

```<code>#include "widget.h"
#include "ui_widget.h"
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QVBoxLayout>
#include <QMenu>
#include <QAction>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    mCamera = new QCamera(this);
    mCameraViewfinder = new QCameraViewfinder(this);
    mCameraImageCapture = new QCameraImageCapture(mCamera,this);
    mLayout = new QVBoxLayout;
    mOptionsMenu = new QMenu("Options",this);
    mCameraAction = new QAction("Camera",this);
    mGantryAction = new QAction("Gantry", this);
    mCaptureAction = new QAction("Capture",this);
    mLazerAction = new QAction("Lazer",this);
    mOptionsMenu->addActions({mCameraAction,mGantryAction,
                               mLazerAction});
    ui->optionsPushButton->setMenu(mOptionsMenu);
    ui->lazerDistance->setLayout(mLayout);

    ui->xAxis->setLayout(mLayout);
    ui->yAxis->setLayout(mLayout);
    ui->zAxis->setLayout(mLayout);
    ui->xRotate->setLayout(mLayout);
    ui->yRotate->setLayout(mLayout);
    ui->zRotate->setLayout(mLayout);
    ui->x1Label->setLayout(mLayout);
    ui->y1Label->setLayout(mLayout);
    ui->z1Label->setLayout(mLayout);
    ui->x2Label->setLayout(mLayout);
    ui->y2Label->setLayout(mLayout);
    ui->z2Label->setLayout(mLayout);
    ui->xAxis->hide();
    ui->yAxis->hide();
    ui->zAxis->hide();
    ui->xRotate->hide();
    ui->yRotate->hide();
    ui->zRotate->hide();
    ui->x1Label->hide();
    ui->y1Label->hide();
    ui->z1Label->hide();
    ui->x2Label->hide();
    ui->y2Label->hide();
    ui->z2Label->hide();
    ui->lazerDistance->hide();
    ui->scanButton->hide();
    ui->moterL->hide();
    ui->moterLLable->hide();

    connect(mCameraAction, &QAction::triggered, [&](){
        ui->moterL->hide();
        ui->moterLLable->hide();
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();
        ui->lazerDistance->hide();
        ui->scanButton->hide();
        mCamera->setViewfinder(mCameraViewfinder);
        mLayout->addWidget(mCameraViewfinder);
        mLayout->setMargin(0);
        ui->ScrollArea->setLayout(mLayout);
        ui->ScrollArea->show();
        ui->scrollAreaWidgetContents->show();
        mCameraViewfinder->show();
        mCamera->start();

      });

        connect(mGantryAction,&QAction::triggered, [&](){
           mCamera->stop();
         ui->ScrollArea->hide();
          ui->scrollAreaWidgetContents->hide();
          mCameraViewfinder->hide();
          ui->lazerDistance->hide();
          ui->scanButton->hide();

            ui->x1Label->show();
            ui->y1Label->show();
            ui->z1Label->show();
            ui->x2Label->show();
            ui->y2Label->show();
            ui->z2Label->show();
            ui->moterLLable->show();
            ui->xAxis->show();
            ui->yAxis->show();
            ui->zAxis->show();
            ui->xRotate->show();
            ui->yRotate->show();
            ui->zRotate->show();
            ui->moterL->show();

            ui->scanButton->show();

        });

    connect(mLazerAction, &QAction::triggered, [&](){

        mCamera->stop();
        ui->ScrollArea->hide();
        ui->scrollAreaWidgetContents->hide();
        mCameraViewfinder->hide();
        ui->scanButton->hide();
        ui->moterL->hide();
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();
        ui->moterLLable->hide();
        ui->lazerDistance->show();

    });

    //to change the value of the lazer distance
    //have ros input a new string
    ui->lazerDistance->setText("0");
    //funtions to set the values of the moters

    }

void motorcontroll(double x1,double x2, double y1, double y2, double z1, double z2,double l1)
{
    ui->xAxis->setValue(x1);
    ui->yAxis->setValue(y1);
    ui->zAxis->setValue(z1);
    ui->xRotate->setValue(x2);
    ui->yRotate->setValue(y2);
    ui->zRotate->setValue(z2);
    ui->moterL->setValue(l1);
}
</code>```

header file:

```<code>#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}
class QCamera;
class QCameraViewfinder;
class QCameraImageCapture;
class QVBoxLayout;
class QMenu;
class QAction;

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();
    void motorcontroll(double x1,double x2, double y1, double y2, double z1, double z2,double l1);

private:
    Ui::Widget *ui;
    QCamera * mCamera;
    QCameraViewfinder *mCameraViewfinder;
    QCameraImageCapture *mCameraImageCapture;
    QVBoxLayout *mLayout;
    QMenu *mOptionsMenu;
    QAction *mCameraAction;
    QAction *mGantryAction;
    QAction *mCaptureAction;
    QAction *mLazerAction;
};

#endif // WIDGET_H
</code>```

答:
You need to make motorcontroll() a member function of the Widget class. Then in the cpp file implement it as a member of Widget:

```<code>void Widget::motorcontroll(double x1, double x2, double y1, double y2,
                           double z1, double z2, double l1)
{
    // ...
}
</code>```

Body:
you should be able to see what I am tring to do by looking at the funtion called motorcontroll I am trying to make a funtion that can set the values of several spinboxes with the call of one funtion called motorcontrol If I put the function inside the:

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
}

I get the error that I can not declare a function there, but if I put it outside the brackets, I get the error ui was not declared in this scope. I understand why I am getting this error but I don't know a way around it. Could I make ui a global variable/object and if so how would I do that or is there another way to solve/get around this issue. here is my code:

#include "widget.h"
#include "ui_widget.h"
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QVBoxLayout>
#include <QMenu>
#include <QAction>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    mCamera = new QCamera(this);
    mCameraViewfinder = new QCameraViewfinder(this);
    mCameraImageCapture = new QCameraImageCapture(mCamera,this);
    mLayout = new QVBoxLayout;
    mOptionsMenu = new QMenu("Options",this);
    mCameraAction = new QAction("Camera",this);
    mGantryAction = new QAction("Gantry", this);
    mCaptureAction = new QAction("Capture",this);
    mLazerAction = new QAction("Lazer",this);
    mOptionsMenu->addActions({mCameraAction,mGantryAction,
                               mLazerAction});
    ui->optionsPushButton->setMenu(mOptionsMenu);
    ui->lazerDistance->setLayout(mLayout);

    ui->xAxis->setLayout(mLayout);
    ui->yAxis->setLayout(mLayout);
    ui->zAxis->setLayout(mLayout);
    ui->xRotate->setLayout(mLayout);
    ui->yRotate->setLayout(mLayout);
    ui->zRotate->setLayout(mLayout);
    ui->x1Label->setLayout(mLayout);
    ui->y1Label->setLayout(mLayout);
    ui->z1Label->setLayout(mLayout);
    ui->x2Label->setLayout(mLayout);
    ui->y2Label->setLayout(mLayout);
    ui->z2Label->setLayout(mLayout);
    ui->xAxis->hide();
    ui->yAxis->hide();
    ui->zAxis->hide();
    ui->xRotate->hide();
    ui->yRotate->hide();
    ui->zRotate->hide();
    ui->x1Label->hide();
    ui->y1Label->hide();
    ui->z1Label->hide();
    ui->x2Label->hide();
    ui->y2Label->hide();
    ui->z2Label->hide();
    ui->lazerDistance->hide();
    ui->scanButton->hide();
    ui->moterL->hide();
    ui->moterLLable->hide();

    connect(mCameraAction, &QAction::triggered, [&](){
        ui->moterL->hide();
        ui->moterLLable->hide();
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();
        ui->lazerDistance->hide();
        ui->scanButton->hide();
        mCamera->setViewfinder(mCameraViewfinder);
        mLayout->addWidget(mCameraViewfinder);
        mLayout->setMargin(0);
        ui->ScrollArea->setLayout(mLayout);
        ui->ScrollArea->show();
        ui->scrollAreaWidgetContents->show();
        mCameraViewfinder->show();
        mCamera->start();

      });

        connect(mGantryAction,&QAction::triggered, [&](){
           mCamera->stop();
         ui->ScrollArea->hide();
          ui->scrollAreaWidgetContents->hide();
          mCameraViewfinder->hide();
          ui->lazerDistance->hide();
          ui->scanButton->hide();

            ui->x1Label->show();
            ui->y1Label->show();
            ui->z1Label->show();
            ui->x2Label->show();
            ui->y2Label->show();
            ui->z2Label->show();
            ui->moterLLable->show();
            ui->xAxis->show();
            ui->yAxis->show();
            ui->zAxis->show();
            ui->xRotate->show();
            ui->yRotate->show();
            ui->zRotate->show();
            ui->moterL->show();

            ui->scanButton->show();

        });

    connect(mLazerAction, &QAction::triggered, [&](){

        mCamera->stop();
        ui->ScrollArea->hide();
        ui->scrollAreaWidgetContents->hide();
        mCameraViewfinder->hide();
        ui->scanButton->hide();
        ui->moterL->hide();
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();
        ui->moterLLable->hide();
        ui->lazerDistance->show();

    });

    //to change the value of the lazer distance
    //have ros input a new string
    ui->lazerDistance->setText("0");
    //funtions to set the values of the moters

    }

void motorcontroll(double x1,double x2, double y1, double y2, double z1, double z2,double l1)
{
    ui->xAxis->setValue(x1);
    ui->yAxis->setValue(y1);
    ui->zAxis->setValue(z1);
    ui->xRotate->setValue(x2);
    ui->yRotate->setValue(y2);
    ui->zRotate->setValue(z2);
    ui->moterL->setValue(l1);
}

header file:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}
class QCamera;
class QCameraViewfinder;
class QCameraImageCapture;
class QVBoxLayout;
class QMenu;
class QAction;

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();
    void motorcontroll(double x1,double x2, double y1, double y2, double z1, double z2,double l1);

private:
    Ui::Widget *ui;
    QCamera * mCamera;
    QCameraViewfinder *mCameraViewfinder;
    QCameraImageCapture *mCameraImageCapture;
    QVBoxLayout *mLayout;
    QMenu *mOptionsMenu;
    QAction *mCameraAction;
    QAction *mGantryAction;
    QAction *mCaptureAction;
    QAction *mLazerAction;
};

#endif // WIDGET_H

Body:
You need to make motorcontroll() a member function of the Widget class. Then in the cpp file implement it as a member of Widget:

void Widget::motorcontroll(double x1, double x2, double y1, double y2,
                           double z1, double z2, double l1)
{
    // ...
}


问:
URL Rewriting based on form input
I'm creating a frontpage for my website with a single form and input text, Google-style. It's working fine, however, I want to generate a pretty URL based on the input. Let's say, my input is called "id", and using the GET method of form, and the action defined to "/go/", on submission, the URL will be:

```<code>site.com/go/?id=whateverIType
</code>```

and I want to change it to

```<code>site.com/go/whateverIType
</code>```

I was thinking on Mod Rewrite, but if the user put something in the URL, like:

```<code>site.com/go/?dontwant=this&id=whateverIType&somemore=trash
</code>```

I want to ignore the other variables but "id", and rewrite the rule.

What's the better way of get this done? Thanks in advance!

PS: I'm using CodeIgniter, maybe there's something I can use for it as well. I already have a controller for "go".

答:
In application/config/routes.php

```<code>$route['go/(:any)'] = "go/index/$1";
</code>```

Where go is your controller and index is the index action.

http://codeigniter.com/user_guide/general/routing.html

You can use something like this in your .htaccess if you aren't already:

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
</code>```

Title: URL Rewriting based on form input

Body:
I'm creating a frontpage for my website with a single form and input text, Google-style. It's working fine, however, I want to generate a pretty URL based on the input. Let's say, my input is called "id", and using the GET method of form, and the action defined to "/go/", on submission, the URL will be:

site.com/go/?id=whateverIType

and I want to change it to

site.com/go/whateverIType

I was thinking on Mod Rewrite, but if the user put something in the URL, like:

site.com/go/?dontwant=this&id=whateverIType&somemore=trash

I want to ignore the other variables but "id", and rewrite the rule.

What's the better way of get this done? Thanks in advance!

PS: I'm using CodeIgniter, maybe there's something I can use for it as well. I already have a controller for "go".

Body:
In application/config/routes.php

$route['go/(:any)'] = "go/index/$1";

Where go is your controller and index is the index action.

http://codeigniter.com/user_guide/general/routing.html

You can use something like this in your .htaccess if you aren't already:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]


问:
facility count not using list
I have a SQL statement:

```<code>SELECT
  p.id
  ,SUM(CASE WHEN pf.facility_code in ('S','H','E') then 1 ELSE 0 END) as facility_count
FROM people p
  inner JOIN people_facilities pf ON p.ID = pf.ID
group by p.id
</code>```

and from the above statement, you'd understand that the facility_count can't be greater than 3.  However, the first one in the list has 18 facilities in the count.

I'm referring to count with case and list

Why is this count not working?

答:
If you want to count the number of different facilities, use count(distinct):

```<code>SELECT p.id,
       COUNT(DISTINCT CASE WHEN pf.facility_code in ('S','H','E') THEN pf.facility_code END) as facility_count
FROM people p JOIN
     people_facilities pf
     ON p.ID = pf.ID
GROUP BY p.id;
</code>```

Your query is suspicious.  I would expect the JOIN to be more like pf.PeopleID = p.id.

If not, this query can be simplified by removing the JOIN, because the ID you are aggregating by is in the people_facilities table.  I also suspect the condition can be moved to a WHERE clause:

```<code>SELECT pf.id, COUNT(DISTINCT pf.facility_code) as facility_count
FROM people_facilities pf
WHERE pf.facility_code IN ('S', 'H', 'E')
GROUP BY pf.id;
</code>```

Title: facility count not using list

Body:
I have a SQL statement:

SELECT
  p.id
  ,SUM(CASE WHEN pf.facility_code in ('S','H','E') then 1 ELSE 0 END) as facility_count
FROM people p
  inner JOIN people_facilities pf ON p.ID = pf.ID
group by p.id

and from the above statement, you'd understand that the facility_count can't be greater than 3.  However, the first one in the list has 18 facilities in the count.

I'm referring to count with case and list

Why is this count not working?

Body:
If you want to count the number of different facilities, use count(distinct):

SELECT p.id,
       COUNT(DISTINCT CASE WHEN pf.facility_code in ('S','H','E') THEN pf.facility_code END) as facility_count
FROM people p JOIN
     people_facilities pf
     ON p.ID = pf.ID
GROUP BY p.id;

Your query is suspicious.  I would expect the JOIN to be more like pf.PeopleID = p.id.

If not, this query can be simplified by removing the JOIN, because the ID you are aggregating by is in the people_facilities table.  I also suspect the condition can be moved to a WHERE clause:

SELECT pf.id, COUNT(DISTINCT pf.facility_code) as facility_count
FROM people_facilities pf
WHERE pf.facility_code IN ('S', 'H', 'E')
GROUP BY pf.id;


问:
Assign value from successful promise resolve to external variable
I have a pretty silly problem. Consider the following:

```<code>vm.feed = getFeed().then(function(data) {return data;});
</code>```

getFeed() returns a $q deferred promise (I am on angular) that resolves successfully.

My goal is to set vm.feed equal to the data value returned by the successful callback. As it is right now, the code simply assigns vm.feed equal to the $promise object returned by getFeed().

I know I could simply do: vm.feed = data inside the resolved function but I want to understand why this code does not work as it is.

PD: the promise resolves correctly and even after it has been resolved vm.feed keeps being equal to the Promise, and not data. I copy the console.log of vm.feed after +10 seconds have elapsed:

```<code>Promise {$$state: Object} $$state: Objectstatus:1 value: Object
</code>```

That value property inside the Promise object contains the actual solution of the promise that I want to assign to vm.feed (e.i. data).

thank you!

答:
You could provide your function with the object and its attribute. Next, do what you need to do inside the function. Finally, assign the value returned in the promise to the right place in your object. Here's an example:

```<code>let myFunction = function (vm, feed) {
    getFeed().then( data => {
        vm[feed] = data
    })
}

myFunction(vm, "feed")
</code>```

You can also write a self-invoking function if you want.

Body:
I have a pretty silly problem. Consider the following:

vm.feed = getFeed().then(function(data) {return data;});

getFeed() returns a $q deferred promise (I am on angular) that resolves successfully.

My goal is to set vm.feed equal to the data value returned by the successful callback. As it is right now, the code simply assigns vm.feed equal to the $promise object returned by getFeed().

I know I could simply do: vm.feed = data inside the resolved function but I want to understand why this code does not work as it is.

PD: the promise resolves correctly and even after it has been resolved vm.feed keeps being equal to the Promise, and not data. I copy the console.log of vm.feed after +10 seconds have elapsed:

Promise {$$state: Object} $$state: Objectstatus:1 value: Object

That value property inside the Promise object contains the actual solution of the promise that I want to assign to vm.feed (e.i. data).

thank you!

Body:
You could provide your function with the object and its attribute. Next, do what you need to do inside the function. Finally, assign the value returned in the promise to the right place in your object. Here's an example:

let myFunction = function (vm, feed) {
    getFeed().then( data => {
        vm[feed] = data
    })
}

myFunction(vm, "feed")

You can also write a self-invoking function if you want.


问:
Return list of instances from generic method
I need to return a coordinate list of rectangle in generic method. Coordinate is a class 'cart' instance.

I try return it with make-instance

(defclass line ()
  ((start :initarg :start :accessor line-start)
   (end   :initarg :end   :accessor line-end)))

(defmethod print-object ((lin line) stream)
  (format stream "[LINE ~s ~s]"
          (line-start lin) (line-end lin)))

(defclass cart ()
  ((x :initarg :x :reader cart-x)
   (y :initarg :y :reader cart-y)))

(defmethod print-object ((c cart) stream)
  (format stream "[CART x ~d y ~d]"
          (cart-x c) (cart-y c)))

(setq lin (make-instance 'line
             :start (make-instance 'cart :x 4 :y 3)
             :end (make-instance 'cart :x 7 :y 5)))

(defgeneric containing-rect (shape))

(defmethod containing-rect ((l line))
  (let ((x1 (cart-x (line-start l)))
        (y1 (cart-y (line-start l)))
        (x2 (cart-x (line-end l)))
        (y2 (cart-y (line-end l))))
    (cond ((= x1 x2)
           '((make-instance 'cart :x (1- x1) :y y1)
             (make-instance 'cart :x (1+ x1) :y y1)
             (make-instance 'cart :x (1- x2) :y y2)
             (make-instance 'cart :x (1+ x2) :y y2)))
          ((= y1 y2)
           '((make-instance 'cart :x x1 :y (1- y1))
             (make-instance 'cart :x x1 :y (1+ y1))
             (make-instance 'cart :x x2 :y (1- y2))
             (make-instance 'cart :x x2 :y (1+ y2))))
          (t
           (rect '((make-instance 'cart :x x1 :y y1)
                   (make-instance 'cart :x x1 :y y2)
                   (make-instance 'cart :x x2 :y y2)
                   (make-instance 'cart :x x2 :y y1)))))))

(print (containing-rect lin))
```

<p>I suppose <code>make-instance</code> should assign an instance to something</p>

<p>So i get incorrect result</p>

<pre class="lang-lisp prettyprint-override"><code>((MAKE-INSTANCE 'CART :X X1 :Y Y1) (MAKE-INSTANCE 'CART :X X1 :Y Y2)
 (MAKE-INSTANCE 'CART :X X2 :Y Y2) (MAKE-INSTANCE 'CART :X X2 :Y Y1))
</code>```

but I need an output like that

([CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3])
```

答:
Some additional hints about your code.

Classes

Not a hard rule, but accessor functions (which are generic functions) are often only named after the slot, i.e. x and not get-X (definitely "bad" style) or object-X (not bad, still quite common).

```<code>(defclass line ()
 ((start :initarg :start :accessor start)
  (end   :initarg :end   :accessor end)))

(defclass cart ()
 ((x :initarg :x :reader x)
  (y :initarg :y :reader y)))

(defclass rect ()
  ((upper-left :initarg :upper-left :accessor upper-left)
   (bootom-right :initarg :bottom-right :accessor bottom-right)))
</code>```

I don't know what your requirements are, so I invented some; in particular, I represent rectangles as 2 points (upper-left and bottom-right).

Constructor functions

Having constructor functions helps a lot to have concise and readable code:

```<code>(defun cart (x y)
  (make-instance 'cart :x x :y y))

(defun line (start end)
  (make-instance 'line :start start :end end))
</code>```

In the case of  rectangles, points are sorted first in order to build the upper-left and bottom-right points.

```<code>(defun sorted-coordinate (points coordinate)
  (sort (mapcar coordinate points) #'<))

(defun rect (point-1 point-2)
  (let ((points (list point-1 point-2)))
    (destructuring-bind (low-x high-x) (sorted-coordinate points #'x)
      (destructuring-bind (low-y high-y) (sorted-coordinate points #'y)
        (make-instance 'rect
                       :upper-left (cart low-x high-y)
                       :bottom-right (cart high-x low-y))))))
</code>```

 Printer methods

Your code almost printed Lisp forms, and for no added complexity, you can in fact make the printer method emit code that can be read back to build the same data. The following methods print readably your objects with PRIN1, as calls to the previously defined constructor functions:

```<code>(defmethod print-object ((line line) stream)
  (prin1 `(line ,(start line) ,(end line)) stream))

(defmethod print-object ((c cart) stream)
  (prin1 `(cart ,(x c) ,(y c)) stream))

(defmethod print-object ((rect rect) stream)
  (prin1 `(rect ,(upper-left rect) ,(bottom-right rect)) stream))
</code>```

Example

```<code>(defparameter *test-line*
  (line (cart 4 3) (cart 7 5)))
</code>```

Then, evaluating the resulting line gives:

```<code>CL-USER> *TEST-LINE*
=> (LINE (CART 4 3) (CART 7 5))
</code>```

This above is a value, as printed by the REPL, which is exactly the expression that was used to build it.

Boundary of a shape as a rectangle

The generic function is much simpler (but maybe wrong, since rectangles are handled differently):

```<code>(defgeneric containing-rect (shape))

(defmethod containing-rect ((line line))
  (rect (start line) (end line)))
</code>```

For example:

```<code>CL-USER> (containing-rect *test-line*)
=> (RECT (CART 4 5) (CART 7 3))
</code>```

Body:
I need to return a coordinate list of rectangle in generic method. Coordinate is a class 'cart' instance.

I try return it with make-instance

(defclass line ()
  ((start :initarg :start :accessor line-start)
   (end   :initarg :end   :accessor line-end)))

(defmethod print-object ((lin line) stream)
  (format stream "[LINE ~s ~s]"
          (line-start lin) (line-end lin)))

(defclass cart ()
  ((x :initarg :x :reader cart-x)
   (y :initarg :y :reader cart-y)))

(defmethod print-object ((c cart) stream)
  (format stream "[CART x ~d y ~d]"
          (cart-x c) (cart-y c)))

(setq lin (make-instance 'line
             :start (make-instance 'cart :x 4 :y 3)
             :end (make-instance 'cart :x 7 :y 5)))

(defgeneric containing-rect (shape))

(defmethod containing-rect ((l line))
  (let ((x1 (cart-x (line-start l)))
        (y1 (cart-y (line-start l)))
        (x2 (cart-x (line-end l)))
        (y2 (cart-y (line-end l))))
    (cond ((= x1 x2)
           '((make-instance 'cart :x (1- x1) :y y1)
             (make-instance 'cart :x (1+ x1) :y y1)
             (make-instance 'cart :x (1- x2) :y y2)
             (make-instance 'cart :x (1+ x2) :y y2)))
          ((= y1 y2)
           '((make-instance 'cart :x x1 :y (1- y1))
             (make-instance 'cart :x x1 :y (1+ y1))
             (make-instance 'cart :x x2 :y (1- y2))
             (make-instance 'cart :x x2 :y (1+ y2))))
          (t
           (rect '((make-instance 'cart :x x1 :y y1)
                   (make-instance 'cart :x x1 :y y2)
                   (make-instance 'cart :x x2 :y y2)
                   (make-instance 'cart :x x2 :y y1)))))))

(print (containing-rect lin))

I suppose make-instance should assign an instance to something

So i get incorrect result

((MAKE-INSTANCE 'CART :X X1 :Y Y1) (MAKE-INSTANCE 'CART :X X1 :Y Y2)
 (MAKE-INSTANCE 'CART :X X2 :Y Y2) (MAKE-INSTANCE 'CART :X X2 :Y Y1))

but I need an output like that

([CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3])

Body:
Some additional hints about your code.

Classes

Not a hard rule, but accessor functions (which are generic functions) are often only named after the slot, i.e. x and not get-X (definitely "bad" style) or object-X (not bad, still quite common).

(defclass line ()
 ((start :initarg :start :accessor start)
  (end   :initarg :end   :accessor end)))

(defclass cart ()
 ((x :initarg :x :reader x)
  (y :initarg :y :reader y)))

(defclass rect ()
  ((upper-left :initarg :upper-left :accessor upper-left)
   (bootom-right :initarg :bottom-right :accessor bottom-right)))

I don't know what your requirements are, so I invented some; in particular, I represent rectangles as 2 points (upper-left and bottom-right).

Constructor functions

Having constructor functions helps a lot to have concise and readable code:

(defun cart (x y)
  (make-instance 'cart :x x :y y))

(defun line (start end)
  (make-instance 'line :start start :end end))

In the case of  rectangles, points are sorted first in order to build the upper-left and bottom-right points.

(defun sorted-coordinate (points coordinate)
  (sort (mapcar coordinate points) #'<))

(defun rect (point-1 point-2)
  (let ((points (list point-1 point-2)))
    (destructuring-bind (low-x high-x) (sorted-coordinate points #'x)
      (destructuring-bind (low-y high-y) (sorted-coordinate points #'y)
        (make-instance 'rect
                       :upper-left (cart low-x high-y)
                       :bottom-right (cart high-x low-y))))))

 Printer methods

Your code almost printed Lisp forms, and for no added complexity, you can in fact make the printer method emit code that can be read back to build the same data. The following methods print readably your objects with PRIN1, as calls to the previously defined constructor functions:

(defmethod print-object ((line line) stream)
  (prin1 `(line ,(start line) ,(end line)) stream))

(defmethod print-object ((c cart) stream)
  (prin1 `(cart ,(x c) ,(y c)) stream))

(defmethod print-object ((rect rect) stream)
  (prin1 `(rect ,(upper-left rect) ,(bottom-right rect)) stream))

Example

(defparameter *test-line*
  (line (cart 4 3) (cart 7 5)))

Then, evaluating the resulting line gives:

CL-USER> *TEST-LINE*
=> (LINE (CART 4 3) (CART 7 5))

This above is a value, as printed by the REPL, which is exactly the expression that was used to build it.

Boundary of a shape as a rectangle

The generic function is much simpler (but maybe wrong, since rectangles are handled differently):

(defgeneric containing-rect (shape))

(defmethod containing-rect ((line line))
  (rect (start line) (end line)))

For example:

CL-USER> (containing-rect *test-line*)
=> (RECT (CART 4 5) (CART 7 3))


问:
mod-rewrite recursive loop
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
</code>```

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

```<code>RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

None of the two url work.

答:
You need to inspect the URI in the HTTP request line (i.e. %{THE_REQUEST}) as the other could already have been rewritten (like in your case):

```<code>RewriteCond %{THE_REQUEST} ^GET\ /news\.php\?
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

Title: mod-rewrite recursive loop

Body:
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

None of the two url work.

Body:
You need to inspect the URI in the HTTP request line (i.e. %{THE_REQUEST}) as the other could already have been rewritten (like in your case):

RewriteCond %{THE_REQUEST} ^GET\ /news\.php\?
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]


问:
How do I show the Auth0 login page when using FeathersJS
I'm using FeathersJS as a REST service but I need the user to be able to login with Auth0. How do I show the Auth0 login page to the user?</p>

答:
After checking FeathersJS website, I saw you can run it paired with express. So it should be alright to use Auth0's express quickstart to build that connection. I have referenced said doc below should help you on your path. Thanks!

https://auth0.com/docs/quickstart/backend/nodejs/01-authorization


问:
How to use Visual Studio (vsdiffmerge) as external diff tool in SourceTree for Mercurial?
I am using Mercurial for my source control and SourceTree to manage it. I want to use Visual Studio's built in diff and merge tool (vsdiffmerge) for comparing files however this is not working.

I am currently using the following:

Diff Commands:

\"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\vsdiffmerge.exe\"

Diff Arguments:

\"$LOCAL\" \"$REMOTE\" //t

Merge Commands:

\"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\vsdiffmerge.exe\"

Merge Arguments:

\"$REMOTE\" \"$LOCAL\" \"$BASE\" \"$MERGED\" //m

The Visual Studio diff tool is not getting launched. Could you please take a look?

Update:-

```<code>   We should use like below:-
   Diff Command:
   full path of vsDiffMerge.exe
   For VS 2015 and below you can find it in the Visual Studio installation folder, under Common7\IDE subfolder. Visual Studio 2017 has it slightly more hidden. Look under Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer.

   Diff Argument: "$LOCAL" "$REMOTE" "Source" "Target" //t
   Merge Argument: $LOCAL" "$REMOTE" "$BASE" "$MERGED" //m
</code>```

答:
For Visual Studio 2019 Enterprise vsDiffMerge.exe location is:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\vsDiffMerge.exe

Body:
I am using Mercurial for my source control and SourceTree to manage it. I want to use Visual Studio's built in diff and merge tool (vsdiffmerge) for comparing files however this is not working.

I am currently using the following:

Diff Commands:

\"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\vsdiffmerge.exe\"

Diff Arguments:

\"$LOCAL\" \"$REMOTE\" //t

Merge Commands:

\"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\vsdiffmerge.exe\"

Merge Arguments:

\"$REMOTE\" \"$LOCAL\" \"$BASE\" \"$MERGED\" //m

The Visual Studio diff tool is not getting launched. Could you please take a look?

Update:-

   We should use like below:-
   Diff Command:
   full path of vsDiffMerge.exe
   For VS 2015 and below you can find it in the Visual Studio installation folder, under Common7\IDE subfolder. Visual Studio 2017 has it slightly more hidden. Look under Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer.

   Diff Argument: "$LOCAL" "$REMOTE" "Source" "Target" //t
   Merge Argument: $LOCAL" "$REMOTE" "$BASE" "$MERGED" //m