问:
Solving set of ODEs with Scipy

I am trying to develop an algorithm (use scipy.integrate.odeint()) that predicts the changing concentration of cells, substrate and product (i.e., , , ) over time until the system reaches steady- state (~100 or 200 hours). The initial concentration of cells in the bioreactor is 0.1 / and there is no glucose or product in the reactor initially. I want to test the algorithm for a range of different flow rates, , between 0.01 /ℎ and 0.25 /ℎ and analyze the impact of the flow rate on product production (i.e.,  ⋅  in /ℎ). Eventually, I would like to generate a plot that shows product production rate (y-axis) versus flow rate, , on the x-axis. My goal is to estimate the flow rate that results in the maximum (or critical) production rate. This is my code so far:

```<code>from scipy.integrate import odeint
import numpy as np

# Constants
u_max = 0.65
K_s = 0.14
K_1 = 0.48
V = 2
X_in = 0
S_in = 4
Y_s = 0.38
Y_p = 0.2

# Variables
# Q - Flow Rate (L/h), value between 0.01 and 0.25 that produces best Q * P
# X - Cell Concentration (g/L)
# S - The glucose concentration (g/L)
# P - Product Concentration (g/L)

# Equations
def func_dX_dt(X, t, S):
    u = (u_max) / (1 + (K_s / S))
    dX_dt = (((Q * S_in) - (Q * S)) / V) + (u * X)
    return dX_dt

def func_dS_dt(S, t, X):
    u = (u_max) / (1 + (K_s / S))
    dS_dt = (((Q * S_in) - (Q * S)) / V) - (u * (X / Y_s))
    return dS_dt

def func_dP_dt(P, t, X, S):
    u = (u_max) / (1 + (K_s / S))
    dP_dt = ((-Q * P) / V) - (u * (X / Y_p))
    return dP_dt

t = np.linspace(0, 200, 200)

# Q placeholder
Q = 0.01

# Attempt to solve the Ordinary differential equations
sol_dX_dt = odeint(func_dX_dt, 0.1, t, args=(S,))
sol_dS_dt = odeint(func_dS_dt, 0.1, t, args=(X,))
sol_dP_dt = odeint(func_dP_dt, 0.1, t, args=(X,S))
</code>```

In the programs current state there does not seem to be be a way to generate the steady state value for P. I attempted to make this modification to get the value of X.

```<code>sol_dX_dt = odeint(func_dX_dt, 0.1, t, args=(odeint(func_dS_dt, 0.1, t, args=(X,)),))
</code>```

It produces the error:

```<code>NameError: name 'X' is not defined
</code>```

At this point I am not sure how to move forward.

(Edit 1: Added Original Equations)

First Equation

Second Equation and Third Equation

答:
You do not have to apply the functions to each part but return a tuple of the derivatives as I show below:

```<code>import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

Q = 0.01
V = 2
Ys = 0.38
Sin = 4
Yp = 0.2
Xin = 0
umax = 0.65
Ks = 0.14
K1 = 0.48

def mu(S, umax, Ks, K1):
    return umax/((1+Ks/S)*(1+S/K1))

def dxdt(x, t, *args):
    X, S, P = x
    Q, V, Xin, Ys, Sin, Yp, umax, Ks, K1 = args
    m = mu(S, umax, Ks, K1)
    dXdt = (Q*Xin - Q*X)/V + m*X
    dSdt = (Q*Sin - Q*S)/V - m*X/Ys
    dPdt = -Q*P/V - m*X/Yp
    return dXdt, dSdt, dPdt

t = np.linspace(0, 200, 200)
X0 = 0.1
S0 = 0.1
P0 = 0.1
x0 = X0, S0, P0
sol = odeint(dxdt, x0, t, args=(Q, V, Xin, Ys, Sin, Yp, umax, Ks, K1))

plt.plot(t, sol[:, 0], 'r', label='X(t)')
plt.plot(t, sol[:, 1], 'g', label='S(t)')
plt.plot(t, sol[:, 2], 'b', label='P(t)')
plt.legend(loc='best')
plt.xlabel('t')
plt.grid()
plt.show()
</code>```

Output:

Title: Solving set of ODEs with Scipy

Body:
I am trying to develop an algorithm (use scipy.integrate.odeint()) that predicts the changing concentration of cells, substrate and product (i.e., , , ) over time until the system reaches steady- state (~100 or 200 hours). The initial concentration of cells in the bioreactor is 0.1 / and there is no glucose or product in the reactor initially. I want to test the algorithm for a range of different flow rates, , between 0.01 /ℎ and 0.25 /ℎ and analyze the impact of the flow rate on product production (i.e.,  ⋅  in /ℎ). Eventually, I would like to generate a plot that shows product production rate (y-axis) versus flow rate, , on the x-axis. My goal is to estimate the flow rate that results in the maximum (or critical) production rate. This is my code so far:

from scipy.integrate import odeint
import numpy as np

# Constants
u_max = 0.65
K_s = 0.14
K_1 = 0.48
V = 2
X_in = 0
S_in = 4
Y_s = 0.38
Y_p = 0.2

# Variables
# Q - Flow Rate (L/h), value between 0.01 and 0.25 that produces best Q * P
# X - Cell Concentration (g/L)
# S - The glucose concentration (g/L)
# P - Product Concentration (g/L)

# Equations
def func_dX_dt(X, t, S):
    u = (u_max) / (1 + (K_s / S))
    dX_dt = (((Q * S_in) - (Q * S)) / V) + (u * X)
    return dX_dt

def func_dS_dt(S, t, X):
    u = (u_max) / (1 + (K_s / S))
    dS_dt = (((Q * S_in) - (Q * S)) / V) - (u * (X / Y_s))
    return dS_dt

def func_dP_dt(P, t, X, S):
    u = (u_max) / (1 + (K_s / S))
    dP_dt = ((-Q * P) / V) - (u * (X / Y_p))
    return dP_dt

t = np.linspace(0, 200, 200)

# Q placeholder
Q = 0.01

# Attempt to solve the Ordinary differential equations
sol_dX_dt = odeint(func_dX_dt, 0.1, t, args=(S,))
sol_dS_dt = odeint(func_dS_dt, 0.1, t, args=(X,))
sol_dP_dt = odeint(func_dP_dt, 0.1, t, args=(X,S))

In the programs current state there does not seem to be be a way to generate the steady state value for P. I attempted to make this modification to get the value of X.

sol_dX_dt = odeint(func_dX_dt, 0.1, t, args=(odeint(func_dS_dt, 0.1, t, args=(X,)),))

It produces the error:

NameError: name 'X' is not defined

At this point I am not sure how to move forward.

(Edit 1: Added Original Equations)

First Equation

Second Equation and Third Equation

Body:
You do not have to apply the functions to each part but return a tuple of the derivatives as I show below:

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

Q = 0.01
V = 2
Ys = 0.38
Sin = 4
Yp = 0.2
Xin = 0
umax = 0.65
Ks = 0.14
K1 = 0.48

def mu(S, umax, Ks, K1):
    return umax/((1+Ks/S)*(1+S/K1))

def dxdt(x, t, *args):
    X, S, P = x
    Q, V, Xin, Ys, Sin, Yp, umax, Ks, K1 = args
    m = mu(S, umax, Ks, K1)
    dXdt = (Q*Xin - Q*X)/V + m*X
    dSdt = (Q*Sin - Q*S)/V - m*X/Ys
    dPdt = -Q*P/V - m*X/Yp
    return dXdt, dSdt, dPdt

t = np.linspace(0, 200, 200)
X0 = 0.1
S0 = 0.1
P0 = 0.1
x0 = X0, S0, P0
sol = odeint(dxdt, x0, t, args=(Q, V, Xin, Ys, Sin, Yp, umax, Ks, K1))

plt.plot(t, sol[:, 0], 'r', label='X(t)')
plt.plot(t, sol[:, 1], 'g', label='S(t)')
plt.plot(t, sol[:, 2], 'b', label='P(t)')
plt.legend(loc='best')
plt.xlabel('t')
plt.grid()
plt.show()

Output:


来源: stackexchange

问:
Get the ID of the label associated with the input type file field
I have a requirement where I have to get the ID of the label associated with the input type file field. I have a set of 4 input type file fields with id's photo1, photo2, photo3, photo4. The labels associated with these file fields are label-1, label-2, label-3 and label-4 respectively. My requirement is that I want to get the respective label fields and update the text of the label. This is what I have tried so far.

```<code><div class="koh-contact-photo">
                            <span><fmt:message key='photo1' /></span> <label id="upload-1" class="button-default" ><fmt:message
                                    key='photo.upload' /></label>
                            <div id="preview-1" class="preview"></div>
                            <button type="button" class="koh-photo-remove remove-button">
                                <span class="icon" data-icon="&#xe605"></span> <span
                                    class="label"><fmt:message key='photo.remove.text' /></span>
                            </button>

                        <!-- The Modal -->
                            <div id="myModal1" class="modal">
                                 <!-- Modal content -->

                                 <div class="modal-content">
                                 <span class="close">×</span>
                                 <h3 class="modal-title"> Upload Photo </h3>

                                <div class="modal-inner">
                                <span>Browse for a photo</span> <label id="label-1" style="margin-bottom:20px;" class="button-default browse" for="photo1">BROWSE</label><input id="photo1" type="file"
                                name="photo1" data-parsley-filesize="3"
                                data-parsley-filetype="image/jpeg, image/png, image/gif, image/bmp"
                                data-parsley-trigger="change" />

                                <hr class="modal-hr" />
                                <div class="guidelines-modal">
                                    <p> GENERAL GUIDELINES </p>
                                    <p> Supported files are: .jpg, .gif, .png, .bmp </p>
                                    <p> Maximum File Size: 3MB</p>
                                    <p style="margin-bottom:10px;"> For best results: upload at 400 x 300</p>
                                    <p> Note: images are automatically resized</p>
                                </div>
                                <div class="koh-contact-captcha modal-hr">
                                <!--div class="g-recaptcha" data-sitekey=<fmt:message key='kohlerSterling.google.captcha.key' />></div-->
                                    <!--div class="g-recaptcha" id="recaptcha1"></div-->
                                    <div id="recaptcha3" class="captcha"></div>
                                    <div class="error-message">
                                        <span><fmt:message key='required.field.text' /></span>
                                    </div>

                                </div>
                                <div class="terms-modal">
                                <div class="checkbox">
                                <input type="checkbox" id="terms-condns" required/>
                                <label style="font-family:Helvetica Neue LT Pro Roman !important;font-size:12px !important;color:#000 !important;font-weight:400 !important;" for="terms-condns">I agree to the <a class="modal-anchor" href="#">Terms and Conditions</a></label>
                                </div>
                                </div>
                                <hr class="modal-hr" />
                                <div class="modal-buttons">
                                    <label class="button-default-modal" style="margin-right:20px;">CANCEL</label>
                                    <label id="input-button-modal-1" class="input-button-modal">UPLOAD</label>
                                </div>

                                </div>
                              </div>
                              <input type="hidden" id="captchaKey" value="<fmt:message key='google.recaptcha.site.key'/>">
                              </div>
                              </div>
</code>```

I have 4 such div classes. and this is the javascript.

```<code>$contactPhotos.each(function () {
            var $photoInput = $(this).find("input[type=file]");
            var img = $("<img />");
            var photoPreview = $photoInput.parent().parent().parent().parent().find(".preview").attr("id");
            var photoPreviewImg = $("#" + photoPreview);
            function readURL(input) {
                if (input.files && input.files[0]) {
                    photoPreviewImg.html("");
                    //alert(JSON.stringify(photoPreviewImg, null, 4));
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        img.attr("style", "height:41px;");
                        img.attr("style", "width:210px;");
                        img.attr("src", e.target.result);
                    }
                    reader.readAsDataURL(input.files[0]);

                }
            }
            $(this).on('click','.input-button-modal', function(e) {
                    var contactModal = $(this).parent().parent().parent().parent().parent().find(".modal").attr('id');
                    var currentModal = $('#' + contactModal);
                    currentModal.attr("style", "display:none");
                    photoPreviewImg.append(img);
            });

            $photoInput.parsley().on('field:success', function() {
                    var inputID = $photoInput.attr('id');
                    var inputTarget = '#' + inputID;
                    var inputValue = document.getElementById(inputID);
                    //inputLabel.attr("style", 'width:70%;');
                    readURL(inputValue);
                    $(inputTarget).parent().parent().parent().parent().find('.koh-photo-remove').show();
                    $contactForm.find('#terms').prop('required',true);
                });
            });
</code>```

Any help is appreciated. I want to get the ID of the label associated with each of the input type file field. Thanks in advance.

答:
Label and input fields are linked by the for of the label being the id of input. You can simply take advantage of that link

```<code>function getLabelID(input){
    return $("label['for=" + $(input).attr("id") + "']").attr("id");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a requirement where I have to get the ID of the label associated with the input type file field. I have a set of 4 input type file fields with id's photo1, photo2, photo3, photo4. The labels associated with these file fields are label-1, label-2, label-3 and label-4 respectively. My requirement is that I want to get the respective label fields and update the text of the label. This is what I have tried so far.

                            <fmt:message key='photo1' /> <fmt:message
                                    key='photo.upload' />

                            <button type="button" class="koh-photo-remove remove-button">
                                 <fmt:message key='photo.remove.text' />
                            </button>

                                 ×

 Upload Photo

                                Browse for a photo BROWSE<input id="photo1" type="file"
                                name="photo1" data-parsley-filesize="3"
                                data-parsley-filetype="image/jpeg, image/png, image/gif, image/bmp"
                                data-parsley-trigger="change" />

 GENERAL GUIDELINES

 Supported files are: .jpg, .gif, .png, .bmp

 Maximum File Size: 3MB

 For best results: upload at 400 x 300

 Note: images are automatically resized

                                        <fmt:message key='required.field.text' />

                                <input type="checkbox" id="terms-condns" required/>
                                I agree to the Terms and Conditions

                                    CANCEL
                                    UPLOAD

                              <input type="hidden" id="captchaKey" value="<fmt:message key='google.recaptcha.site.key'/>">

I have 4 such div classes. and this is the javascript.

$contactPhotos.each(function () {
            var $photoInput = $(this).find("input[type=file]");
            var img = $("");
            var photoPreview = $photoInput.parent().parent().parent().parent().find(".preview").attr("id");
            var photoPreviewImg = $("#" + photoPreview);
            function readURL(input) {
                if (input.files && input.files[0]) {
                    photoPreviewImg.html("");
                    //alert(JSON.stringify(photoPreviewImg, null, 4));
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        img.attr("style", "height:41px;");
                        img.attr("style", "width:210px;");
                        img.attr("src", e.target.result);
                    }
                    reader.readAsDataURL(input.files[0]);

                }
            }
            $(this).on('click','.input-button-modal', function(e) {
                    var contactModal = $(this).parent().parent().parent().parent().parent().find(".modal").attr('id');
                    var currentModal = $('#' + contactModal);
                    currentModal.attr("style", "display:none");
                    photoPreviewImg.append(img);
            });

            $photoInput.parsley().on('field:success', function() {
                    var inputID = $photoInput.attr('id');
                    var inputTarget = '#' + inputID;
                    var inputValue = document.getElementById(inputID);
                    //inputLabel.attr("style", 'width:70%;');
                    readURL(inputValue);
                    $(inputTarget).parent().parent().parent().parent().find('.koh-photo-remove').show();
                    $contactForm.find('#terms').prop('required',true);
                });
            });

Any help is appreciated. I want to get the ID of the label associated with each of the input type file field. Thanks in advance.

Body:
Label and input fields are linked by the for of the label being the id of input. You can simply take advantage of that link

function getLabelID(input){
    return $("label['for=" + $(input).attr("id") + "']").attr("id");
}


问:
Reading integers from an input file, storing only the unique integers in the array C++
I've been stuck on this homework question for a couple of days now. I did some research and I got to this:

```<code>#include<iostream>
#include<fstream>
#include<string>
#include<array>
using namespace std;

const int MAX_SIZE = 100;

bool RepeatCheck(int storage[], int size, int checker);

int main()
{
    ifstream input("input.txt");

    if (!input) // if input file can't be opened
    {
        cout << "Can't open the input file successfuly." << endl;
        return 1;
    }

    int storage[MAX_SIZE];
    int inputCount;
    int checker;

    while (!input.eof())
    {
        for (int i = 0; i <= MAX_SIZE; i++)
        {
            input >> checker;
            if (!RepeatCheck(storage, MAX_SIZE, checker))
            {
                input >> storage[i];
            }

        }
    }

    // print array
    for (int i = 0; i < 100; i++)
    {
        cout << storage[i] << " ";
    }

    return 0;
}

bool RepeatCheck(int storage[], int size, int checker)
{
    for (int i = 0; i <= MAX_SIZE; i++)
    {
        if (storage[i] == checker)
        {
            return false;
        }
    }
}
</code>```

My input file needs to be filled with integers separated by white space or on new lines:

1 2 2 3 5 6 5
4 3 20 34 5 7
5 2 4
6 3 3 4 5
7 6 7 8

I need to read the integers from the file and store them in the storage[] array only if they aren't already in the array.

It's not doing what I need it to do. Please take a look at my code and tell me where the logic error is. Much appreciated.

答:
If std::set is allowed, use it instead of doing your own duplication check.

For your code, the problem happens here:

```<code>while (!input.eof())
{
    //for loop not needed
    for (int i = 0; i <= MAX_SIZE; i++) //increment regardless whether input is successful or not?
    {
        input >> checker; //take in a number
        //if the number is not repeated
        if (!RepeatCheck(storage, MAX_SIZE, checker))
        {
            input >> storage[i]; //read in another number to put it?
        }

    }
}
</code>```

Also here

```<code>bool RepeatCheck(int storage[], int size, int checker)
{
    for (int i = 0; i <= MAX_SIZE; i++)
    //check all values in the array regardless whether it has been used or not?
    //should just check until the end of used space, which is what size is meant for
    {
        if (storage[i] == checker)
        {
            return false;
        }
    }
    //there should be a return true here right?
}
</code>```

Have a look at this link to see why while (!iostream.eof()) is considered wrong.

The first part should look like this:

```<code>int i = 0;
while (input >> checker)
{
    if (!RepeatCheck(storage, i, checker))
    {
        storage[i] = checker;
        ++i;
    }
}
</code>```

For second part, use size instead of max size

Body:
I've been stuck on this homework question for a couple of days now. I did some research and I got to this:

#include<iostream>
#include<fstream>
#include<string>
#include<array>
using namespace std;

const int MAX_SIZE = 100;

bool RepeatCheck(int storage[], int size, int checker);

int main()
{
    ifstream input("input.txt");

    if (!input) // if input file can't be opened
    {
        cout << "Can't open the input file successfuly." << endl;
        return 1;
    }

    int storage[MAX_SIZE];
    int inputCount;
    int checker;

    while (!input.eof())
    {
        for (int i = 0; i <= MAX_SIZE; i++)
        {
            input >> checker;
            if (!RepeatCheck(storage, MAX_SIZE, checker))
            {
                input >> storage[i];
            }

        }
    }

    // print array
    for (int i = 0; i < 100; i++)
    {
        cout << storage[i] << " ";
    }

    return 0;
}

bool RepeatCheck(int storage[], int size, int checker)
{
    for (int i = 0; i <= MAX_SIZE; i++)
    {
        if (storage[i] == checker)
        {
            return false;
        }
    }
}

My input file needs to be filled with integers separated by white space or on new lines:

1 2 2 3 5 6 5
4 3 20 34 5 7
5 2 4
6 3 3 4 5
7 6 7 8

I need to read the integers from the file and store them in the storage[] array only if they aren't already in the array.

It's not doing what I need it to do. Please take a look at my code and tell me where the logic error is. Much appreciated.

Body:
If std::set is allowed, use it instead of doing your own duplication check.

For your code, the problem happens here:

while (!input.eof())
{
    //for loop not needed
    for (int i = 0; i <= MAX_SIZE; i++) //increment regardless whether input is successful or not?
    {
        input >> checker; //take in a number
        //if the number is not repeated
        if (!RepeatCheck(storage, MAX_SIZE, checker))
        {
            input >> storage[i]; //read in another number to put it?
        }

    }
}

Also here

bool RepeatCheck(int storage[], int size, int checker)
{
    for (int i = 0; i <= MAX_SIZE; i++)
    //check all values in the array regardless whether it has been used or not?
    //should just check until the end of used space, which is what size is meant for
    {
        if (storage[i] == checker)
        {
            return false;
        }
    }
    //there should be a return true here right?
}

Have a look at this link to see why while (!iostream.eof()) is considered wrong.

The first part should look like this:

int i = 0;
while (input >> checker)
{
    if (!RepeatCheck(storage, i, checker))
    {
        storage[i] = checker;
        ++i;
    }
}

For second part, use size instead of max size


问:
c# TCP Listener send message to all connected client
Is it possible to send message to all client with tcp listener?

Example:

TCP Listener running, Listener sending the default message to clients, client1 connect get the default message, client2 connect get the default message, if client1 or client2 modify the default message and send it to the listener then listener send the modified message to client1 and client2.

答:
Is it possible to send message to all client with tcp listener?

The answer is NO.

You use a socket server just for wait the new connections (Listener) and accept them. Each time that a socket server accept a new connection it assigns an independent socket client to attend the remote endpoint.

```<code>        while (keepRunning)
        {
            try
            {
                TcpClient socket = server.AcceptTcpClient(); //Socket Server accept a new connection and assigned an independent socket client.

                if (keepRunning)
                    RequestManager.askForRequestAdnRunIt(socket, idLayout); //The Socket Client is attending at the remote endpoint

            }
            catch (Exception ex)
            {
                log.Error("Se detecto un error en el puerto para atencion de peticiones. ERR: " + ex.Message);
                log.Error(ex.StackTrace);
            }
        }
</code>```

So, if you want to send a message to all the TCPClients sockets, you must send it one by one, i suggest send it by a Asynchronous method to improve the performance and avoid bottlenecks. Check this answer of mine to see how to send with asynchronous methods.

Body:
Is it possible to send message to all client with tcp listener?

The answer is NO.

You use a socket server just for wait the new connections (Listener) and accept them. Each time that a socket server accept a new connection it assigns an independent socket client to attend the remote endpoint.

        while (keepRunning)
        {
            try
            {
                TcpClient socket = server.AcceptTcpClient(); //Socket Server accept a new connection and assigned an independent socket client.

                if (keepRunning)
                    RequestManager.askForRequestAdnRunIt(socket, idLayout); //The Socket Client is attending at the remote endpoint

            }
            catch (Exception ex)
            {
                log.Error("Se detecto un error en el puerto para atencion de peticiones. ERR: " + ex.Message);
                log.Error(ex.StackTrace);
            }
        }

So, if you want to send a message to all the TCPClients sockets, you must send it one by one, i suggest send it by a Asynchronous method to improve the performance and avoid bottlenecks. Check this answer of mine to see how to send with asynchronous methods.


问:
is it ok to have persistent classes as fields in a DTO?
I have a class which models a data transfer object, I have an object attribute in it which is based of a persistent class. Is it good practice to do that? Here's the class in question:</p>

```<code>    public class WorkRequest {

    private Long id;

    private String type;

    private Worker worker;

    private JobItem jobItem; // persistent class object

    private Set<WorkQuantity> quantities;

    public WorkRequest() {}
}
</code>```

答:
It is not good practice, because in general it is good to separate the domain model data from the data transported to other systems. Meaning if in the future you add some fields to JobItem class, you may accidentally also send them with your DTO to other systems causing data leaks or bugs.

However in many cases that concern does not matter much.

Body:
I have a class which models a data transfer object, I have an object attribute in it which is based of a persistent class. Is it good practice to do that? Here's the class in question:

    public class WorkRequest {

    private Long id;

    private String type;

    private Worker worker;

    private JobItem jobItem; // persistent class object

    private Set<WorkQuantity> quantities;

    public WorkRequest() {}
}


问:
ReCAPTCHA couldn't find user-provided function: myCallBack
I'm trying to use ReCAPTCHA where I am getting following error.

ReCAPTCHA couldn't find user-provided function: myCallBack.

How can I solve this issue?

```<code>var verifyCallback3 = function(response) {
    if(response!=null){
        $("#rss").show();
    }
};

var myCallBack = function() {
    grecaptcha.render('html_element', {
        'sitekey' : '6sssfffffffffAAPfEI_RkbAlUuw5FA4p-kiGy5Nea',
        'callback' : verifyCallback3,
        'theme' : 'light',
        'type':'image'
    });
};
</code>```

答: The same thing happening with me.I have checked my code carefully, every thing is fine but captcha not shown and in console the message is "ReCAPTCHA couldn't find user-provided function: myCallBack" but finally I found that my JavaScript code was is in page load function. I am just put out it from page load function and its working.</p>

Body:
I'm trying to use ReCAPTCHA where I am getting following error.

ReCAPTCHA couldn't find user-provided function: myCallBack.

How can I solve this issue?

var verifyCallback3 = function(response) {
    if(response!=null){
        $("#rss").show();
    }
};

var myCallBack = function() {
    grecaptcha.render('html_element', {
        'sitekey' : '6sssfffffffffAAPfEI_RkbAlUuw5FA4p-kiGy5Nea',
        'callback' : verifyCallback3,
        'theme' : 'light',
        'type':'image'
    });
};


问:
Android samples' gradle files refer to a non-existent file
I've been trying to import and run the new Android samples, specifically ArchitectureComponentsBasic example. However, the gradle files refer to a file that has not been downloaded with the project.

In the app module's gradle file:

```<code>buildscript {
    apply from: '../versions.gradle' // <-- This file!
    addRepos(repositories)
    dependencies {
        classpath deps.android_gradle_plugin

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
</code>```

the build script is applied from ../version.gradle file.

And in the project's gralde file:

```<code>android {
    compileSdkVersion build_versions.target_sdk
    buildToolsVersion build_versions.build_tools

..

dependencies {
    // Support libraries
    implementation deps.support.app_compat
    implementation deps.support.v4
    implementation deps.support.design

...

    androidTestImplementation deps.room.testing
    androidTestImplementation deps.arch_core.testing

    // Espresso UI Testing
    androidTestImplementation deps.espresso.core
    androidTestImplementation deps.espresso.contrib
    androidTestImplementation deps.espresso.intents

    // Resolve conflicts between main and test APK:
    androidTestImplementation deps.support.annotations
    androidTestImplementation deps.support.v4
    androidTestImplementation deps.support.app_compat
    androidTestImplementation deps.support.design
}
</code>```

The versions are defined in a variable which is not in the file itself.

How do I get the file versions.gradle and run the sample project? Also will that resolve the undefined variables in the project's gradle file?

答:
You did not download the entire repository, or you may have set your project up incorrectly.  the ".." in ../version.gradle is telling the code to go up a folder in the file system.

Here is the missing file.  You may be able to just download it, and edit your gradle, or your might have to clone the whole project again.

Body:
I've been trying to import and run the new Android samples, specifically ArchitectureComponentsBasic example. However, the gradle files refer to a file that has not been downloaded with the project.

In the app module's gradle file:

buildscript {
    apply from: '../versions.gradle' // <-- This file!
    addRepos(repositories)
    dependencies {
        classpath deps.android_gradle_plugin

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

the build script is applied from ../version.gradle file.

And in the project's gralde file:

android {
    compileSdkVersion build_versions.target_sdk
    buildToolsVersion build_versions.build_tools

..

dependencies {
    // Support libraries
    implementation deps.support.app_compat
    implementation deps.support.v4
    implementation deps.support.design

...

    androidTestImplementation deps.room.testing
    androidTestImplementation deps.arch_core.testing

    // Espresso UI Testing
    androidTestImplementation deps.espresso.core
    androidTestImplementation deps.espresso.contrib
    androidTestImplementation deps.espresso.intents

    // Resolve conflicts between main and test APK:
    androidTestImplementation deps.support.annotations
    androidTestImplementation deps.support.v4
    androidTestImplementation deps.support.app_compat
    androidTestImplementation deps.support.design
}

The versions are defined in a variable which is not in the file itself.

How do I get the file versions.gradle and run the sample project? Also will that resolve the undefined variables in the project's gradle file?


问:
Dialog flow coversation in chatbot
How to response for confirmation input from the user in dialog flow api.ai

Example :

user says :I want a pizza

Chatresponse : Do you want cheese pizza?

User says: Yes..

In this case how to connect with previous questions and response.Can anyone suggest any idea.

答:
Go to Dialogflow and create a new intent that looks like this:

Next create an follow up intent by going back to the intent screen (click on intents in the left panel) and click on create followup intent after hovering over your pizza intent:

Then click yes:

You will now have two intent: one that identifies the user's intent as "wanting pizza" and the other as a followup intent that will be triggered after the wanted pizza intent is matched that will capture if the user says "yes" or something similar.

Title: Dialog flow coversation in chatbot


问:
ArgumentError when accessing pageobject widget
```<code>class MainTabsWidget  < PageObject::Elements::UnorderedList
  include  PageObject
  include  PageObject::PageFactory

  link(:first_link, :text => 'First')
  link(:second_link, :text => 'Second')
  link(:third_link, :text => 'Third')
  link(:category_link, :text => 'Category')
  link(:subcat1_link, :text => 'Subcat1')
  link(:subcat2_link, :text => 'Subcat2')

  def goto_tab_item(tab_item)
    items = tab_item.split /\//
    items.each do |item|
      case item
        when 'First'
          first_link
        when 'Second'
          second_link
        when 'Third'
          third_link
        when 'Category'
          category_link
        when 'Subcat1'
          subcat1_link
        when 'Subcat2'
          subcat2_link
      end
    end
  end
end

PageObject.register_widget :main_menu, MainTabsWidget , :ul
</code>```

I have a page called landing page that uses the widget in the following manner....

```<code>class LandingPage
  include  PageObject
  include  PageObject::PageFactory

  main_menu(:menu_tabs, :id => 'mainMenu')

  def select_menu_item(item)
    menu_tabs_element.go_to_tab_item item
  end
end
</code>```

This actually did work at one point.  If you pass 'First' for  select_menu_item, it will click to the page specified by first_link.  If you specify 'Category/Subcat1' it will click on the category link and then subcat1.

Howerver, something changed.  We are transition from watir-webdriver gem to watir (6.10) gem, and now the code gets the argument exeption

```<code>'ArgumentError: wrong number of arguments (0 for 1..2)'
</code>```

This occurs when menu_tabs_element gets referenced in any way.  I've run out of ideas to remedy this.

Stack Trace:

```<code>ArgumentError: wrong number of arguments (0 for 1..2)
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/element_locators.rb:10:in `element'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/elements/element.rb:191:in `respond_to_missing?'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object.rb:53:in `respond_to_missing?'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object.rb:70:in `respond_to?'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object.rb:70:in `initialize'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/platforms/watir/page_object.rb:1047:in `new'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/platforms/watir/page_object.rb:1047:in `find_watir_element'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/platforms/watir/page_object.rb:1118:in `block in define_widget_singular_accessor'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/widgets.rb:38:in `block (3 levels) in define_accessors'
./lib/pages/menu.rb:13:in `select_menu_item'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page_navigation-0.10/lib/page_navigation.rb:134:in `block in navigate_through_pages'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page_navigation-0.10/lib/page_navigation.rb:129:in `each'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page_navigation-0.10/lib/page_navigation.rb:129:in `navigate_through_pages'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page_navigation-0.10/lib/page_navigation.rb:67:in `navigate_to'
./spec/refactor/test_spec.rb:6:in `block (2 levels) in <top (required)>'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:350:in `instance_exec'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:350:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:509:in `block in run_owned_hooks_for'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:508:in `each'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:508:in `run_owned_hooks_for'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:460:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/example_group.rb:537:in `block in run_before_context_hooks'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/memoized_helpers.rb:186:in `block in isolate_for_context_hook'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/memoized_helpers.rb:182:in `instance_exec'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/memoized_helpers.rb:182:in `isolate_for_context_hook'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/example_group.rb:536:in `run_before_context_hooks'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/example_group.rb:589:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:118:in `block (3 levels) in run_specs'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:118:in `map'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:118:in `block (2 levels) in run_specs'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/configuration.rb:1896:in `with_suite_hooks'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:113:in `block in run_specs'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/reporter.rb:79:in `report'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:112:in `run_specs'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:87:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:71:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:45:in `invoke'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/exe/rspec:4:in `<top (required)>'
C:/Ruby22/bin/rspec:23:in `load'
C:/Ruby22/bin/rspec:23:in `<top (required)>'
-e:1:in `load'
-e:1:in `<main>'

1 example, 1 failure, 0 passed

Finished in 6.087 seconds

Process finished with exit code 1
</code>```

答:
It is not clear to me which change in Watir would cause this issue. It seems more likely a change in Page-Object. At any rate, here are 2 solutions. Note that this was tested with Page-Object v 2.2.4.

Using Widgets

As pointed out by Alexis in Page-Object Issue 263, including page object accessor methods in widgets is not as straight forward as one would expect. In the MainTabsWidget class, instead of include PageObject, you need to do:

```<code>extend PageObject::Accessors  # to get the accessor methods
attr_reader :platform         # the accessor methods don't work without a platform
</code>```

With this change, your page object should work.

Using Page Section

Page-Object has a page section feature that might better suit your needs. It simplifies some of the code (ie address the above issue).

You define a class to represent your main tabs section. Note that you do not need to register the section or have the multi-line setup as with Widgets.

```<code>class MainTabs
  include PageObject
  include PageObject::PageFactory

  link(:first_link, :text => 'First')
  link(:second_link, :text => 'Second')
  link(:third_link, :text => 'Third')
  link(:category_link, :text => 'Category')
  link(:subcat1_link, :text => 'Subcat1')
  link(:subcat2_link, :text => 'Subcat2')

  def select_menu_item(tab_item)
    items = tab_item.split /\//
    items.each do |item|
      case item
        when 'First'
          first_link
        when 'Second'
          second_link
        when 'Third'
          third_link
        when 'Category'
          category_link
        when 'Subcat1'
          subcat1_link
        when 'Subcat2'
          subcat2_link
      end
    end
  end
end
</code>```

The page object can simply become:

```<code>class LandingPage
  include PageObject
  include PageObject::PageFactory

  page_section(:menu_tabs, MainTabs, :id => 'mainMenu')
end
</code>```

The clicking of the menu would change to:

```<code>page.menu_tabs.select_menu_item('First')
</code>```

(or you could continue to define a #select_menu_item method in LandingPage to avoid downstream changes)

Body:
class MainTabsWidget  < PageObject::Elements::UnorderedList
  include  PageObject
  include  PageObject::PageFactory

  link(:first_link, :text => 'First')
  link(:second_link, :text => 'Second')
  link(:third_link, :text => 'Third')
  link(:category_link, :text => 'Category')
  link(:subcat1_link, :text => 'Subcat1')
  link(:subcat2_link, :text => 'Subcat2')

  def goto_tab_item(tab_item)
    items = tab_item.split /\//
    items.each do |item|
      case item
        when 'First'
          first_link
        when 'Second'
          second_link
        when 'Third'
          third_link
        when 'Category'
          category_link
        when 'Subcat1'
          subcat1_link
        when 'Subcat2'
          subcat2_link
      end
    end
  end
end

PageObject.register_widget :main_menu, MainTabsWidget , :ul

I have a page called landing page that uses the widget in the following manner....

class LandingPage
  include  PageObject
  include  PageObject::PageFactory

  main_menu(:menu_tabs, :id => 'mainMenu')

  def select_menu_item(item)
    menu_tabs_element.go_to_tab_item item
  end
end

This actually did work at one point.  If you pass 'First' for  select_menu_item, it will click to the page specified by first_link.  If you specify 'Category/Subcat1' it will click on the category link and then subcat1.

Howerver, something changed.  We are transition from watir-webdriver gem to watir (6.10) gem, and now the code gets the argument exeption

'ArgumentError: wrong number of arguments (0 for 1..2)'

This occurs when menu_tabs_element gets referenced in any way.  I've run out of ideas to remedy this.

Stack Trace:

ArgumentError: wrong number of arguments (0 for 1..2)
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/element_locators.rb:10:in `element'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/elements/element.rb:191:in `respond_to_missing?'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object.rb:53:in `respond_to_missing?'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object.rb:70:in `respond_to?'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object.rb:70:in `initialize'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/platforms/watir/page_object.rb:1047:in `new'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/platforms/watir/page_object.rb:1047:in `find_watir_element'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/platforms/watir/page_object.rb:1118:in `block in define_widget_singular_accessor'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page-object-2.2.4/lib/page-object/widgets.rb:38:in `block (3 levels) in define_accessors'
./lib/pages/menu.rb:13:in `select_menu_item'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page_navigation-0.10/lib/page_navigation.rb:134:in `block in navigate_through_pages'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page_navigation-0.10/lib/page_navigation.rb:129:in `each'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page_navigation-0.10/lib/page_navigation.rb:129:in `navigate_through_pages'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/page_navigation-0.10/lib/page_navigation.rb:67:in `navigate_to'
./spec/refactor/test_spec.rb:6:in `block (2 levels) in <top (required)>'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:350:in `instance_exec'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:350:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:509:in `block in run_owned_hooks_for'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:508:in `each'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:508:in `run_owned_hooks_for'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/hooks.rb:460:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/example_group.rb:537:in `block in run_before_context_hooks'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/memoized_helpers.rb:186:in `block in isolate_for_context_hook'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/memoized_helpers.rb:182:in `instance_exec'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/memoized_helpers.rb:182:in `isolate_for_context_hook'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/example_group.rb:536:in `run_before_context_hooks'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/example_group.rb:589:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:118:in `block (3 levels) in run_specs'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:118:in `map'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:118:in `block (2 levels) in run_specs'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/configuration.rb:1896:in `with_suite_hooks'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:113:in `block in run_specs'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/reporter.rb:79:in `report'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:112:in `run_specs'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:87:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:71:in `run'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/lib/rspec/core/runner.rb:45:in `invoke'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/rspec-core-3.7.0/exe/rspec:4:in `<top (required)>'
C:/Ruby22/bin/rspec:23:in `load'
C:/Ruby22/bin/rspec:23:in `<top (required)>'
-e:1:in `load'
-e:1:in `'

1 example, 1 failure, 0 passed

Finished in 6.087 seconds

Process finished with exit code 1

Body:
It is not clear to me which change in Watir would cause this issue. It seems more likely a change in Page-Object. At any rate, here are 2 solutions. Note that this was tested with Page-Object v 2.2.4.

Using Widgets

As pointed out by Alexis in Page-Object Issue 263, including page object accessor methods in widgets is not as straight forward as one would expect. In the MainTabsWidget class, instead of include PageObject, you need to do:

extend PageObject::Accessors  # to get the accessor methods
attr_reader :platform         # the accessor methods don't work without a platform

With this change, your page object should work.

Using Page Section

Page-Object has a page section feature that might better suit your needs. It simplifies some of the code (ie address the above issue).

You define a class to represent your main tabs section. Note that you do not need to register the section or have the multi-line setup as with Widgets.

class MainTabs
  include PageObject
  include PageObject::PageFactory

  link(:first_link, :text => 'First')
  link(:second_link, :text => 'Second')
  link(:third_link, :text => 'Third')
  link(:category_link, :text => 'Category')
  link(:subcat1_link, :text => 'Subcat1')
  link(:subcat2_link, :text => 'Subcat2')

  def select_menu_item(tab_item)
    items = tab_item.split /\//
    items.each do |item|
      case item
        when 'First'
          first_link
        when 'Second'
          second_link
        when 'Third'
          third_link
        when 'Category'
          category_link
        when 'Subcat1'
          subcat1_link
        when 'Subcat2'
          subcat2_link
      end
    end
  end
end

The page object can simply become:

class LandingPage
  include PageObject
  include PageObject::PageFactory

  page_section(:menu_tabs, MainTabs, :id => 'mainMenu')
end

The clicking of the menu would change to:

page.menu_tabs.select_menu_item('First')

(or you could continue to define a #select_menu_item method in LandingPage to avoid downstream changes)


问:
C#: Split comma-separated strings, but not if comma enclosed in single quotes
I am parsing a text file from some old hardware and I need to extract an array of strings from one long string.

Elements are comma-separated

Each individual string is enclosed in single quotes

'Hello', 'World'

```<code>{"'Hello', "'World'"}
</code>```

Single quotes for any other reason are illegal and there is no escaping character equivalent; you cannot write the word "Bob's" nor can do something like "Bob\'s".

Ordinarily it would be easy to get the individual elements by splitting on the comma:

```<code>string testString = "'Hello', 'World'";
ArrayList result = new ArrayList(testString.Split(',');
</code>```

But I can't do this; if a comma is in-between single quotes it is text, not a separator.

This is one element:

'Hello, World'

```<code>{"'Hello, World'"}
</code>```

How can I extract the elements checking to see if the comma is in-between single quotes?

'Hello', 'World', 'Hello, World'

```<code>{"'Hello'", "'World'", "'Hello, World'"}
</code>```

One more detail: I cannot guarantee the amount of whitespace between elements:

'Hello',     'World',  'Hello, World'

P.S. Here is the same question I asked for Swift: Swift: Split comma-separated strings, but not if comma enclosed in single quotes

答:
I tried this approach but I wonder if this works most of the time.

```<code>        const string str = "'Hello', 'World', 'Hello, World'";
        ArrayList arrStr = new ArrayList(str.Split('\''));
        List<string> myString = new List<string>();
        for (int i = 0 + 1; i < arrStr.Count; i+=2)
        {
            myString.Add(arrStr[i].ToString());
        }
</code>```

Also, i'm not sure if your string has contractions in it.

Body:
I am parsing a text file from some old hardware and I need to extract an array of strings from one long string.

Elements are comma-separated

Each individual string is enclosed in single quotes

'Hello', 'World'

{"'Hello', "'World'"}

Single quotes for any other reason are illegal and there is no escaping character equivalent; you cannot write the word "Bob's" nor can do something like "Bob\'s".

Ordinarily it would be easy to get the individual elements by splitting on the comma:

string testString = "'Hello', 'World'";
ArrayList result = new ArrayList(testString.Split(',');

But I can't do this; if a comma is in-between single quotes it is text, not a separator.

This is one element:

'Hello, World'

{"'Hello, World'"}

How can I extract the elements checking to see if the comma is in-between single quotes?

'Hello', 'World', 'Hello, World'

{"'Hello'", "'World'", "'Hello, World'"}

One more detail: I cannot guarantee the amount of whitespace between elements:

'Hello',     'World',  'Hello, World'

P.S. Here is the same question I asked for Swift: Swift: Split comma-separated strings, but not if comma enclosed in single quotes

Body:
I tried this approach but I wonder if this works most of the time.

        const string str = "'Hello', 'World', 'Hello, World'";
        ArrayList arrStr = new ArrayList(str.Split('\''));
        List<string> myString = new List<string>();
        for (int i = 0 + 1; i < arrStr.Count; i+=2)
        {
            myString.Add(arrStr[i].ToString());
        }

Also, i'm not sure if your string has contractions in it.


问:
vim and .vimrc won't open after .vimrc modification. Need to force open
How do I force open my .vimrc?

I recently made a modification, not certain exactly what I did, but I think I accidentally typed an "x" in my plugins when trying to close. Suddenly neither vim or .vimrc will open.

I get a pause, several blank lines, and then terminal just returns to default command line.

答: Use vim -u NONE .vimrc to skip reading all startup files and edit .vimrc.


问:
Can't access mysql from command line on a Mac
MySQL on OS x 10.6 is located in /usr/local/mysql/bin/mysql.

I get command not found when I type mysql --version in the terminal. Is this because the socket path is wrong? If so how do I fix it?

答:
I've tried all the solutions from the answers but couldn't get mysql command to work from the terminal, always getting the message

```<code>bash: command not found
</code>```

The solution is to change the .bash_profile, and add the mysql path to .bash_profile

To do so follow these steps:
1. Open a new Terminal window or make sure you are in the home directory
2. Open .bash_profile using

```<code>nano .bash_profile
</code>```

3. Add the following command to add the mysql path

```<code>PATH="/usr/local/mysql/bin:${PATH}"
export PATH
</code>```

4. Press Ctrl+X, then press y and press enter.

The following is how my .bash_profile looks like

ContentLicense: CC BY-SA 4.0

Body:
I've tried all the solutions from the answers but couldn't get mysql command to work from the terminal, always getting the message

bash: command not found

The solution is to change the .bash_profile, and add the mysql path to .bash_profile

To do so follow these steps:
1. Open a new Terminal window or make sure you are in the home directory
2. Open .bash_profile using

nano .bash_profile

3. Add the following command to add the mysql path

PATH="/usr/local/mysql/bin:${PATH}"
export PATH

4. Press Ctrl+X, then press y and press enter.

The following is how my .bash_profile looks like


问:
Two ways to put image into graphics context - which is better?
I've noticed examples of two ways to put images into core graphics.  One is much simpler than the other.  So what's the advantage of the second, more sophisticated, approach?  Is it faster?

example 1

```<code>UIImage *myImage = [UIImage imageNamed:@"picture.png"];
CGRect imageRect = CGRectMake(70, 330, 40, 40);
[myImage drawInRect:imageRect];
[myImage release];
</code>```

example 2

```<code>// Load image from application bundle
NSString* imageFileName = [[[NSBundle mainBundle] resourcePath]         stringByAppendingPathComponent:@"picture.png"];
CGDataProviderRef provider = CGDataProviderCreateWithFilename([imageFileName UTF8String]);
CGImageRef image = CGImageCreateWithPNGDataProvider(provider, NULL, true,      kCGRenderingIntentDefault);
CGDataProviderRelease(provider);

// Draw image
CGContextTranslateCTM(context, 70, 370 );
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, 40, 40), image);
CGImageRelease(image);
</code>```

答:
In example 1 you are just gonna show the image in the view as it is, and it is good too to show static images.

But in example 2 you are using core graphics to display the image so you can do more operations on it, more than just a static image. You can rotate it, scale it, translate it, reduce its alpha value and many more that i also not aware of.

so it depends on your choice of use. whether you want to just show the image or want it to do something more than that.if you are begineer and want to develop utility apps than i dont think you will ever use 2 option. but if you want to develop games or want to animate the image you will use should 2 option.

Cheers

ContentLicense: CC BY-SA 2.5

Body:
I've noticed examples of two ways to put images into core graphics.  One is much simpler than the other.  So what's the advantage of the second, more sophisticated, approach?  Is it faster?

example 1

UIImage *myImage = [UIImage imageNamed:@"picture.png"];
CGRect imageRect = CGRectMake(70, 330, 40, 40);
[myImage drawInRect:imageRect];
[myImage release];

example 2

// Load image from application bundle
NSString* imageFileName = [[[NSBundle mainBundle] resourcePath]         stringByAppendingPathComponent:@"picture.png"];
CGDataProviderRef provider = CGDataProviderCreateWithFilename([imageFileName UTF8String]);
CGImageRef image = CGImageCreateWithPNGDataProvider(provider, NULL, true,      kCGRenderingIntentDefault);
CGDataProviderRelease(provider);

// Draw image
CGContextTranslateCTM(context, 70, 370 );
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, 40, 40), image);
CGImageRelease(image);


问:
Kendo Tabstrip with dynamic content in a Partial View
I am new to ASP.NET MVC. I am facing one or other issues to design the layout for below scenario. Could you someone help me with a solution and I will definitely appreciate your help.

The requirement is:

This is an existing application. While loading view there is a Master View and inside few partial views already defined.

In one of the Partial view, I need to have a same layout multiple times on demand. It is depends on the user how many required. may be 1 or 2 or more. We are using Telerik Kendo controls extensively in our UI and in existing View we strongly typed Model object with View.

I would like to go with Kendo Tabstrips control and add Tab dynamically when required by the user. Also, the layout is exactly same, So, would like to design (Html table with many controls like textbox, dropdown etc.) each tab layout as Partial View so that I can reuse the design. Please let me know whether this approach is best or any better approach is available.

I need to get the entire data when the user Submit the master view . Each main partial View contains  and the parent of the Tabstrips Partial view also contains a  but not defined  for each tabstrip partial view as I need data as collection of objects in one of the property in Parent Partial View Model Object.

Can you please let me know how to design model object for each tabs(Partial View) as well as Parent Partial View. it could be good, if you could show a small example code.

The below are the issues faced during designing this

Unable to add  inside another as getting below error

Inline markup blocks (@
Content
) cannot be nested.  Only one level of inline markup is allowed.

```<code>@(Html.Kendo().PanelBar().Name("panelBar_" + panelName).Items(pb =>    pb.Add().Text("PCG").Expanded(Expanded).Selected(true)
.Content(@<text>
<form id="frm_@(panelName)" onsubmit="DisableEvent(event)">
<div style="width:100%; height:auto;">
    <button class="k-button">Add new PCG</button>
    @(Html.Kendo().TabStrip()
    .Name("TabPCG").HtmlAttributes(new { style = "width:100%;" })
   .Items(items =>
   {
       items.Add()
           .Text("PCG 1 <button data-type='remove' class='k-button k-button-icon' onclick='deleteMe(this)'><span class='k-icon k-i-close'></span></button>")
           .Encoded(false)
           .Selected(true)
           .HtmlAttributes(new { style = "width:12%", id = "tabPCG1" })
           //.LoadContentFrom("_PCGTab", "Home", new { tabId ="tab1"});
           .Content(@<text>@(Html.Partial("_PCGTab"))</text>);
   })
    )
</div>
</form>
</text>)))
</code>```

2.Then Changed the design as shown below. defined partial view in Parent View

```<code>@helper RenderPCGTab()
{

<div style="width:100%; height:auto;">
    <button class="k-button">Add new PCG</button>
    @(Html.Kendo().TabStrip()
    .Name("TabPCG").HtmlAttributes(new { style = "width:100%;" })
   .Items(items =>
   {
       items.Add()
           .Text("PCG 1 <button data-type='remove' class='k-button k-button-icon' onclick='deleteMe(this)'><span class='k-icon k-i-close'></span></button>")
           .Encoded(false)
           .Selected(true)
           .HtmlAttributes(new { style = "width:12%", id = "tabPCG1" })
           //.LoadContentFrom("_PCGTab", "Home", new { tabId ="tab1"});
           .Content(@<text>@(Html.Partial("_PCGTab"))</text>);
   })
    )
</div>
</code>```

}

and designed Kendo panel as shown below the Parent Partial View

```<code>@(Html.Kendo().PanelBar().Name("panelBar_" + panelName).Items(pb => pb.Add().Text("PCG").Expanded(Expanded).Selected(true)
.Content(@<text>
 <form id="frm_@(panelName)" onsubmit="DisableEvent(event)">
 @RenderPCGTab()
</form>
</text>)))
</code>```

答:
Since you use a strongly typed View, I would recommend using a Tuple as the model.
The Item1 would hold the required model details, while Item2 would hold the required number of tabs (it holds the names of the tabs).

```<code>@model Tuple<[Model],List<string>>
</code>```

Now create a Kendo Tabstrip control, with dynamic items (based on model's Item2)

```<code> @(Html.Kendo().TabStrip()
      .Name("KendoTabStrip")                //You need to dynamically change the name by appending a unique parameter in case you need multiple Tabstrips
      .Animation(animation =>
          animation.Open(effect =>
              effect.Fade(FadeDirection.In)))
      .Items(tabstrip =>
      {
          var TabItemIndex = 0;
          foreach (var TabItem in Model.Item2)
          {
              tabstrip.Add().Text(TabItem)
             .Selected(false)
             .HtmlAttributes(new { id = "TabStripButton" + TabItem + "_" + TabItemIndex, title = TabItem})    //Generate a dynamic ID for each Tab
             .Content(" ");
              TabItemIndex++;
          }
      })
        )
</code>```

Once you have created the structure of the Tabstrip, you need to populate each tab with its corresponding content

In the View (Parent Partial View) itself, create a Ready function for the tabstrip and serialize the object using JSON

```<code>$(("KendoTabStrip")).ready(function () {
    _TBSModelName = @Html.Raw(JsonConvert.SerializeObject(this.Model.Item1))
    TabStripUserControl();
});
</code>```

Note: This is in case you need the Model Data in your child partial view.

Create a javascript file and place the function TabStripUserControl() in it. This function will create your content and place it into the tab.

```<code>function TabStripUserControl()
{
var _LocalTBSModel = _TBSModelName
var items = "#KendoTabStrip" + " .k-tabstrip-items";
$(items).click(function (z) {

}
);
}
</code>```

Inside the function (click function), create a div and provide a dynamic ID for the same before placing it inside the tab using Javascript/JQuery.

```<code>var div = $("<div/>");
</code>```

Use Ajax call to call your controller, which in turn will call your Child Partial View (which contains HTML controls) and render the partial view inside the above created div on Ajax call's success.

```<code>            $.ajax({
                url: 'Controller/ActionMethod',
                data: JSON.stringify({ Value: "SomeValue" }),
                type: 'POST',
                contentType: 'application/json;',
                async: false,
                success: function (data) {
                    div = data;
                }
            });
</code>```

Hope this helps.

Body:
I am new to ASP.NET MVC. I am facing one or other issues to design the layout for below scenario. Could you someone help me with a solution and I will definitely appreciate your help.

The requirement is:

This is an existing application. While loading view there is a Master View and inside few partial views already defined.

In one of the Partial view, I need to have a same layout multiple times on demand. It is depends on the user how many required. may be 1 or 2 or more. We are using Telerik Kendo controls extensively in our UI and in existing View we strongly typed Model object with View.

I would like to go with Kendo Tabstrips control and add Tab dynamically when required by the user. Also, the layout is exactly same, So, would like to design (Html table with many controls like textbox, dropdown etc.) each tab layout as Partial View so that I can reuse the design. Please let me know whether this approach is best or any better approach is available.

I need to get the entire data when the user Submit the master view . Each main partial View contains  and the parent of the Tabstrips Partial view also contains a  but not defined  for each tabstrip partial view as I need data as collection of objects in one of the property in Parent Partial View Model Object.

Can you please let me know how to design model object for each tabs(Partial View) as well as Parent Partial View. it could be good, if you could show a small example code.

The below are the issues faced during designing this

Unable to add  inside another as getting below error

Inline markup blocks (@
Content
) cannot be nested.  Only one level of inline markup is allowed.

@(Html.Kendo().PanelBar().Name("panelBar_" + panelName).Items(pb =>    pb.Add().Text("PCG").Expanded(Expanded).Selected(true)
.Content(@<text>
<form id="frm_@(panelName)" onsubmit="DisableEvent(event)">

    <button class="k-button">Add new PCG</button>
    @(Html.Kendo().TabStrip()
    .Name("TabPCG").HtmlAttributes(new { style = "width:100%;" })
   .Items(items =>
   {
       items.Add()
           .Text("PCG 1 <button data-type='remove' class='k-button k-button-icon' onclick='deleteMe(this)'></button>")
           .Encoded(false)
           .Selected(true)
           .HtmlAttributes(new { style = "width:12%", id = "tabPCG1" })
           //.LoadContentFrom("_PCGTab", "Home", new { tabId ="tab1"});
           .Content(@<text>@(Html.Partial("_PCGTab"))</text>);
   })
    )

</form>
</text>)))

2.Then Changed the design as shown below. defined partial view in Parent View

@helper RenderPCGTab()
{

    <button class="k-button">Add new PCG</button>
    @(Html.Kendo().TabStrip()
    .Name("TabPCG").HtmlAttributes(new { style = "width:100%;" })
   .Items(items =>
   {
       items.Add()
           .Text("PCG 1 <button data-type='remove' class='k-button k-button-icon' onclick='deleteMe(this)'></button>")
           .Encoded(false)
           .Selected(true)
           .HtmlAttributes(new { style = "width:12%", id = "tabPCG1" })
           //.LoadContentFrom("_PCGTab", "Home", new { tabId ="tab1"});
           .Content(@<text>@(Html.Partial("_PCGTab"))</text>);
   })
    )

}

and designed Kendo panel as shown below the Parent Partial View

@(Html.Kendo().PanelBar().Name("panelBar_" + panelName).Items(pb => pb.Add().Text("PCG").Expanded(Expanded).Selected(true)
.Content(@<text>
 <form id="frm_@(panelName)" onsubmit="DisableEvent(event)">
 @RenderPCGTab()
</form>
</text>)))

Body:
Since you use a strongly typed View, I would recommend using a Tuple as the model.
The Item1 would hold the required model details, while Item2 would hold the required number of tabs (it holds the names of the tabs).

@model Tuple<[Model],List<string>>

Now create a Kendo Tabstrip control, with dynamic items (based on model's Item2)

 @(Html.Kendo().TabStrip()
      .Name("KendoTabStrip")                //You need to dynamically change the name by appending a unique parameter in case you need multiple Tabstrips
      .Animation(animation =>
          animation.Open(effect =>
              effect.Fade(FadeDirection.In)))
      .Items(tabstrip =>
      {
          var TabItemIndex = 0;
          foreach (var TabItem in Model.Item2)
          {
              tabstrip.Add().Text(TabItem)
             .Selected(false)
             .HtmlAttributes(new { id = "TabStripButton" + TabItem + "_" + TabItemIndex, title = TabItem})    //Generate a dynamic ID for each Tab
             .Content(" ");
              TabItemIndex++;
          }
      })
        )

Once you have created the structure of the Tabstrip, you need to populate each tab with its corresponding content

In the View (Parent Partial View) itself, create a Ready function for the tabstrip and serialize the object using JSON

$(("KendoTabStrip")).ready(function () {
    _TBSModelName = @Html.Raw(JsonConvert.SerializeObject(this.Model.Item1))
    TabStripUserControl();
});

Note: This is in case you need the Model Data in your child partial view.

Create a javascript file and place the function TabStripUserControl() in it. This function will create your content and place it into the tab.

function TabStripUserControl()
{
var _LocalTBSModel = _TBSModelName
var items = "#KendoTabStrip" + " .k-tabstrip-items";
$(items).click(function (z) {

}
);
}

Inside the function (click function), create a div and provide a dynamic ID for the same before placing it inside the tab using Javascript/JQuery.

var div = $("<div/>");

Use Ajax call to call your controller, which in turn will call your Child Partial View (which contains HTML controls) and render the partial view inside the above created div on Ajax call's success.

            $.ajax({
                url: 'Controller/ActionMethod',
                data: JSON.stringify({ Value: "SomeValue" }),
                type: 'POST',
                contentType: 'application/json;',
                async: false,
                success: function (data) {
                    div = data;
                }
            });

Hope this helps.


问:
Android Studio - ADB start server fails, adbkey check fails
Problem: adb start-server fails.

```<code>--- adb starting (pid 1414) ---
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Version 27.0.0-4455170
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Installed as /Users/[username]/Library/Android/sdk/platform-tools/adb
adb I 12-05 17:28:30  1414 48453 main.cpp:57]
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:416]
adb_auth_init...
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:174] read_key_file '/Users/[username]/.android/adbkey'...
adb F 12-05 17:28:30  1414 48466 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)
</code>```

Catalyst: Installing platform tools v27.0.0

Solutions Tried: Restarting Android Studio, Restarting computer, Manually starting ADB via terminal, deleting /Users/[username]/.android/adbkey and adbkey.pub, and reinstalling platform tools

Also I am not using genymotion, just the stock emulator.

答:
It is a bug with the latest version of the platform tools (27.0.0), the solution I found was to downgrade to the previous version.

Remove the current platform-tools directory located in the android-sdk directory, then download the older version from here:

Mac: platform-tools_r26.0.2-darwin.zip

[Update]: Some users (myself included) have noticed that the issue only happens when your phone is plugged in, so if you don't need to test on it, try to unplug it and use an emulator.
Also worths noticing that all reported devices were from the Google Pixel line, so other devices might not cause the issue.

[Update 2]: This seems to be solved in the latest update of the platform-tools (27.0.1).

Body:
Problem: adb start-server fails.

--- adb starting (pid 1414) ---
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Version 27.0.0-4455170
adb I 12-05 17:28:30  1414 48453 main.cpp:57] Installed as /Users/[username]/Library/Android/sdk/platform-tools/adb
adb I 12-05 17:28:30  1414 48453 main.cpp:57]
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:416]
adb_auth_init...
adb I 12-05 17:28:30  1414 48453 adb_auth_host.cpp:174] read_key_file '/Users/[username]/.android/adbkey'...
adb F 12-05 17:28:30  1414 48466 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)

Catalyst: Installing platform tools v27.0.0

Solutions Tried: Restarting Android Studio, Restarting computer, Manually starting ADB via terminal, deleting /Users/[username]/.android/adbkey and adbkey.pub, and reinstalling platform tools

Also I am not using genymotion, just the stock emulator.


问:
How to run Elastic Beanstalk commands on EC2 instance before connecting Resources
We have a situation where we would like to run a Django server in the usual Elastic Beanstalk manner while hooking up a custom Docker container to be used by the Django website. So far, I basically have the following .ebextensions configuration file:

```<code>packages:
  yum:
    ecs-init: []

files:
  /etc/ecs/ecs.config:
    mode: "000644"
    owner/group: root
    content: ECS_CLUSTER=${Ref: MyCluster}

commands:
  01_start_docker: sudo service docker start
  02_start_ecs: sudo start ecs

Resources:
  MyCluster:
    Type: AWS::ECS::Cluster
  MyService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: ${Ref: MyCluster}
      DesiredCount: 1
      TaskDefinition: ${Ref: MyTask}
  MyTask:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - ...
</code>```

The problem is that the ECS service is trying to start up before the Elastic Beanstalk-provided EC2 instance is registered with the cluster. As a result, deploying to Elastic Beanstalk hangs. If I manually SSH'ed into the EC2 instance and manually installed ecs-init, created ecs.config, and ran the commands, the service continues being created and the EB environment is created successfully.

Is there a way to tell the service to wait until the EC2 instance created by EB's autoscaling group is registered with the cluster?

More context:

We want the Django server to be able to access the Docker container with localhost, but I wouldn't be opposed to including an EC2 instance in Resources specifically to host the Docker container, if it's easy to refer to in the auto-scaled EC2 instances

We've tried the multi-docker container approach, but this way seems closer to EB's usage (having the web server files directly in the environment instead of making a docker image for the environment to run)

答:
Solved it myself after thinking about it more clearly.

It doesn't make sense to register every EC2 instance that Elastic Beanstalk spins up (via AutoScaling) to the ECS cluster. There should only be one instance of the ECS task. So it's actually necessary to create a separate EC2 instance that connects to the ECS cluster (whose service can now depend on the EC2 instance).

Body:
We have a situation where we would like to run a Django server in the usual Elastic Beanstalk manner while hooking up a custom Docker container to be used by the Django website. So far, I basically have the following .ebextensions configuration file:

packages:
  yum:
    ecs-init: []

files:
  /etc/ecs/ecs.config:
    mode: "000644"
    owner/group: root
    content: ECS_CLUSTER=${Ref: MyCluster}

commands:
  01_start_docker: sudo service docker start
  02_start_ecs: sudo start ecs

Resources:
  MyCluster:
    Type: AWS::ECS::Cluster
  MyService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: ${Ref: MyCluster}
      DesiredCount: 1
      TaskDefinition: ${Ref: MyTask}
  MyTask:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - ...

The problem is that the ECS service is trying to start up before the Elastic Beanstalk-provided EC2 instance is registered with the cluster. As a result, deploying to Elastic Beanstalk hangs. If I manually SSH'ed into the EC2 instance and manually installed ecs-init, created ecs.config, and ran the commands, the service continues being created and the EB environment is created successfully.

Is there a way to tell the service to wait until the EC2 instance created by EB's autoscaling group is registered with the cluster?

More context:

We want the Django server to be able to access the Docker container with localhost, but I wouldn't be opposed to including an EC2 instance in Resources specifically to host the Docker container, if it's easy to refer to in the auto-scaled EC2 instances

We've tried the multi-docker container approach, but this way seems closer to EB's usage (having the web server files directly in the environment instead of making a docker image for the environment to run)


问:
c# - Ignore exception on client side when server is down
I use RestSharp to pass data between the clien-side (Xamarin android app) and my server.

When there is an error (usually because the server is down) the method that execute the request throw an exception.

I want the exception to go back all the way to the method who called it, so I can throw an error to the user.

For example, I want to login, but lets say the server is down.

A - The method that execute the request

```<code>public Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient
    {
        BaseUrl = new Uri(BaseUrl),
        Authenticator = new HttpBasicAuthenticator(_accountName, _password)
    };

    var taskCompletionSource = new TaskCompletionSource<T>();
    client.ExecuteAsync<T>(request, restResponse =>
    {
        if (restResponse.ErrorException != null)
        {
            throw (new Exception("Server returned an error"));
        }
        taskCompletionSource.SetResult(restResponse.Data);
    });
    return taskCompletionSource.Task;
}
</code>```

B - Method that uses method A to execute a request

```<code>public static async Task<LoginObject> Login(string accessNumber, string password, string token)
{
    var request = new RestRequest
    {
        Method = Method.POST,
        Resource = "Login"
    };
    request.AddJsonBody(
        new
        {
            accessNumber = accessNumber,
            password = password,
            token = token
        });

    var isDone = await Api.ExecuteAsync<LoginObject>(request);
    return isDone;
}
</code>```

C - The method where I want to handle the exception

```<code>public async Task Login(string PhoneNumber, string Password)
{
    try
    {
        LoginObject login = await LoginServices.Login(PhoneNumber, Password, Token);
        if (login.IsOk)
        {
            // Move to next activity
        }
        else
        {
        Toast.MakeText(this, "Login Error", ToastLength.Short).Show();
        }
    }
    catch (Exception ex) // Here I want to throw the server error
    {
        Toast.MakeText(this, "Server Error", ToastLength.Short).Show();
        return null;
    }
}
</code>```

Now when I run the code, the error is being thrown in A, and the app crash,

I want it to go from A to B and from B to C, and then I'll show an error to the user.

Edit: I tried to put a try/catch block but it still throws the exception in A.

答: Change method A to have async in the signature and then change your last line to return await taskCompletionSource.Task;

Body:
I use RestSharp to pass data between the clien-side (Xamarin android app) and my server.

When there is an error (usually because the server is down) the method that execute the request throw an exception.

I want the exception to go back all the way to the method who called it, so I can throw an error to the user.

For example, I want to login, but lets say the server is down.

A - The method that execute the request

public Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient
    {
        BaseUrl = new Uri(BaseUrl),
        Authenticator = new HttpBasicAuthenticator(_accountName, _password)
    };

    var taskCompletionSource = new TaskCompletionSource<T>();
    client.ExecuteAsync<T>(request, restResponse =>
    {
        if (restResponse.ErrorException != null)
        {
            throw (new Exception("Server returned an error"));
        }
        taskCompletionSource.SetResult(restResponse.Data);
    });
    return taskCompletionSource.Task;
}

B - Method that uses method A to execute a request

public static async Task<LoginObject> Login(string accessNumber, string password, string token)
{
    var request = new RestRequest
    {
        Method = Method.POST,
        Resource = "Login"
    };
    request.AddJsonBody(
        new
        {
            accessNumber = accessNumber,
            password = password,
            token = token
        });

    var isDone = await Api.ExecuteAsync<LoginObject>(request);
    return isDone;
}

C - The method where I want to handle the exception

public async Task Login(string PhoneNumber, string Password)
{
    try
    {
        LoginObject login = await LoginServices.Login(PhoneNumber, Password, Token);
        if (login.IsOk)
        {
            // Move to next activity
        }
        else
        {
        Toast.MakeText(this, "Login Error", ToastLength.Short).Show();
        }
    }
    catch (Exception ex) // Here I want to throw the server error
    {
        Toast.MakeText(this, "Server Error", ToastLength.Short).Show();
        return null;
    }
}

Now when I run the code, the error is being thrown in A, and the app crash,

I want it to go from A to B and from B to C, and then I'll show an error to the user.

Edit: I tried to put a try/catch block but it still throws the exception in A.


问:
Can I get the current action that will fire in a before filter?
In a before filter action, can I get the action that will be executed after the before filter?</p>

答:
If you are using

```<code>    IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
         string actionName = filterContext.ActionDescriptor.ActionName;
    }
</code>```

then filterContext.ActionDescriptor.ActionName will give you the action name

Body:
If you are using

    IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
         string actionName = filterContext.ActionDescriptor.ActionName;
    }

then filterContext.ActionDescriptor.ActionName will give you the action name


问:
background image not taking up full width
I am currently positioning a background image that is small in height but large in width to stretch all the way across the browser. I am only able to achieve this when I do background size cover, but not when I set a certain size to the image other than cover. I tried background repeat-x but that does not seem to work either.

```<code><html>
  <body>
    <div class="background">
      <div class=“header”></div>
      //some content
    </div>
    <footer><footer/>
  </body>
 </html>
</code>```

CSS

```<code>.background {
    background-image: url(some image);
    background-size: //tried cover and it works but not when I set it to width 100% or something like 2800px
    background-repeat: repeat-x;
    background-position-y: bottom;
}
html, body, .background {
    height: 100%;
}
</code>```

答:
I'm curious if the CSS unit vw (view width) will accomplish what you are trying to do with width: 100%

Instead of width: 100%, try width: 100vw

https://www.w3schools.com/cssref/css_units.asp

Body:
I am currently positioning a background image that is small in height but large in width to stretch all the way across the browser. I am only able to achieve this when I do background size cover, but not when I set a certain size to the image other than cover. I tried background repeat-x but that does not seem to work either.

      //some content

CSS

.background {
    background-image: url(some image);
    background-size: //tried cover and it works but not when I set it to width 100% or something like 2800px
    background-repeat: repeat-x;
    background-position-y: bottom;
}
html, body, .background {
    height: 100%;
}


问:
How to change color of CNContactPickerViewController searchBar
I start a CNContactPickerViewController from a viewcontroller, but how can I change the textcolor of the searchbar inside it. The navigationbar is dark blue, in iOS11 the default searchbartext is black. </p>

答:
I updated the way to fix in swift
Before you present CNContactPickerViewController, you should set background color of UISearchBar</p>

```<code>            UISearchBar.appearance().backgroundColor = UIColor.white
        let cancelButtonAttributes = [NSForegroundColorAttributeName: ColorConstant.baseColorGray]
        UIBarButtonItem.appearance(whenContainedInInstancesOf:
         [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)
</code>```

Body:
I updated the way to fix in swift
Before you present CNContactPickerViewController, you should set background color of UISearchBar

            UISearchBar.appearance().backgroundColor = UIColor.white
        let cancelButtonAttributes = [NSForegroundColorAttributeName: ColorConstant.baseColorGray]
        UIBarButtonItem.appearance(whenContainedInInstancesOf:
         [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)


问:
No error for @MainThread annotation
I have a method:

```<code>/**
 * Call event without a value
 */
@MainThread
public void call() {
    setValue(null);
}
</code>```

And I call it here:

```<code>new Thread(new Runnable() {
    @Override
    public void run() {
        stopNavigation.call();
    }
}).start();
</code>```

Why is no error thrown because I am making this call from outside of the main thread? I have read everything I can about the @MainThread annotation (from android.support.annotation) but nothing has informed me on what the annotation actually does.

答:
As far as I know, AndroidStudio only show the warning about thread when we specific all thread  like

Here is an example in Activity to make annotations work

```<code>public class AActivity extends Activity {

    @MainThread
    protected void onCreate(Bundle savedInstanceState) {
        ...
        getData();
    }

    @AnyThread
    private void getData() {
        new Thread(new Runnable() {
            @WorkerThread // MUST DEFINE THREAD HERE
            @Override
            public void run() {
                updateUI(); // annotation error here
            }
        }).start();
    }

    @MainThread
    void updateUI() {

    }

    class A extends AsyncTask<Void, Void, Void> {
        @WorkerThread // MUST DEFINE THREAD HERE
        @Override
        protected Void doInBackground(Void... voids) {
            updateUI(); // annotation error here
            return null;
        }
    }
}
</code>```

Title: No error for @MainThread annotation

Body:
I have a method:

/**
 * Call event without a value
 */
@MainThread
public void call() {
    setValue(null);
}

And I call it here:

new Thread(new Runnable() {
    @Override
    public void run() {
        stopNavigation.call();
    }
}).start();

Why is no error thrown because I am making this call from outside of the main thread? I have read everything I can about the @MainThread annotation (from android.support.annotation) but nothing has informed me on what the annotation actually does.

Body:
As far as I know, AndroidStudio only show the warning about thread when we specific all thread  like

Here is an example in Activity to make annotations work

public class AActivity extends Activity {

    @MainThread
    protected void onCreate(Bundle savedInstanceState) {
        ...
        getData();
    }

    @AnyThread
    private void getData() {
        new Thread(new Runnable() {
            @WorkerThread // MUST DEFINE THREAD HERE
            @Override
            public void run() {
                updateUI(); // annotation error here
            }
        }).start();
    }

    @MainThread
    void updateUI() {

    }

    class A extends AsyncTask<Void, Void, Void> {
        @WorkerThread // MUST DEFINE THREAD HERE
        @Override
        protected Void doInBackground(Void... voids) {
            updateUI(); // annotation error here
            return null;
        }
    }
}


问:
How should I free an array in C?
I created a function to free an array in C, but I don't know
whether it is correct or not:

```<code>void dealloc_array(void *array[], int size) {

         int i = 0;

         for (i = 0; i < size; i++) {

                if (array[i]) free(array[i]);
         }

         if (array) free(array);

}
</code>```

I'm not sure whether I should execute free(array) at the end. Technically, we've already freed all the array elements, so we don't need to do free(array).

Thanks for the help.

答: You must write free(array) at the end, otherwise there will be memory leak.

Title: How should I free an array in C?

Body:
I created a function to free an array in C, but I don't know
whether it is correct or not:

void dealloc_array(void *array[], int size) {

         int i = 0;

         for (i = 0; i < size; i++) {

                if (array[i]) free(array[i]);
         }

         if (array) free(array);

}

I'm not sure whether I should execute free(array) at the end. Technically, we've already freed all the array elements, so we don't need to do free(array).

Thanks for the help.


问:
Hibernate OneToOne: Forced to chose between optional = false or cascade?
In order to keep transfered data small I created two entities for my files in the database. The fileheader to keep some general information about the files and the fileblob, including fileId and the blob. Often, I only need to ask for general fileinformations.

So I need to load the fileblobs lazily.

As I learned in this discussion and that discussion. this could be achieved with optional = false. It works perfect to load the fileblobs lazily. Unfortunately it affects save by cascade.

So here is my attribute in the Fileh.class for the blob:

```<code>@OneToOne(mappedBy = "fileh", targetEntity = Fileblob.class, fetch = FetchType.LAZY, optional = false)
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK })
private Fileblob fileblob;
</code>```

If I now save a fileh with attached fileblob, this error is thrown:

org.hibernate.id.IdentifierGenerationException: null id generated
  for:class Fileblob

if i switch from id-generation strategy "identity" to "increment" this error is thrown:

```<code>ERROR SqlExceptionHelper:147 - Cannot add or update a child row: a foreign key constraint fails (`CORE`.`FILEBLOB`, CONSTRAINT
</code>```

FKFILEBLOB412557 FOREIGN KEY (ID) REFERENCES FILEH (ID))
      Query is: insert into CORE.FILEBLOB (FILEBLOB, ID) values (?, ?)

So there is a problem with generating the id...
If i now turn off save by cascade my attribute looks like this.

```<code>@OneToOne(mappedBy = "fileh", targetEntity = Fileblob.class, fetch = FetchType.LAZY, optional = false)
private Fileblob fileblob;
</code>```

In order to save now, I have to call

```<code>persistentSession.saveOrUpdate(fileh);
persistentSession.saveOrUpdate(fileblob);
</code>```

Is this not just what CascadeType.SAVE_UPDATE is supposed to do?
Why is this working for "manual cascading" but not automatically?

P.s.: To complete my example here the counterpart in fileblob.class

```<code>@PrimaryKeyJoinColumn
@OneToOne(targetEntity=Fileh.class, fetch=FetchType.LAZY)
@org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK})
@JoinColumns({ @JoinColumn(name="`ID`", referencedColumnName="`ID`", unique=true, nullable=false) })
private Fileh fileh;

@Column(name="`ID`", nullable=false, insertable=false, updatable=false, unique=true)
@Id
@GeneratedValue(generator="FILEBLOB_FILEHID_GENERATOR")
@org.hibernate.annotations.GenericGenerator(name="FILEBLOB_FILEHID_GENERATOR", strategy="foreign", parameters=@org.hibernate.annotations.Parameter(name="property", value="fileh"))
private int filehId;
</code>```

答:
I encountered exactly the same issue and tried to solve it for several days! It turns out it's an issue which has lied in Hibernate's bug system for more than 2 years!

Though the answer here does help resolve the issue, we are forced to give up using Persist Cascade from the parent Entity (the inverse side, also the side with mappedBy defined)

Please see this link: https://hibernate.atlassian.net/browse/HHH-9670

If you want to apply lazy loading to a OneToOne relationship, and be able to do Persist cascade as usual, please leave a comment to show your concern for the issue!

Body:
In order to keep transfered data small I created two entities for my files in the database. The fileheader to keep some general information about the files and the fileblob, including fileId and the blob. Often, I only need to ask for general fileinformations.

So I need to load the fileblobs lazily.

As I learned in this discussion and that discussion. this could be achieved with optional = false. It works perfect to load the fileblobs lazily. Unfortunately it affects save by cascade.

So here is my attribute in the Fileh.class for the blob:

@OneToOne(mappedBy = "fileh", targetEntity = Fileblob.class, fetch = FetchType.LAZY, optional = false)
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK })
private Fileblob fileblob;

If I now save a fileh with attached fileblob, this error is thrown:

org.hibernate.id.IdentifierGenerationException: null id generated
  for:class Fileblob

if i switch from id-generation strategy "identity" to "increment" this error is thrown:

ERROR SqlExceptionHelper:147 - Cannot add or update a child row: a foreign key constraint fails (`CORE`.`FILEBLOB`, CONSTRAINT

FKFILEBLOB412557 FOREIGN KEY (ID) REFERENCES FILEH (ID))
      Query is: insert into CORE.FILEBLOB (FILEBLOB, ID) values (?, ?)

So there is a problem with generating the id...
If i now turn off save by cascade my attribute looks like this.

@OneToOne(mappedBy = "fileh", targetEntity = Fileblob.class, fetch = FetchType.LAZY, optional = false)
private Fileblob fileblob;

In order to save now, I have to call

persistentSession.saveOrUpdate(fileh);
persistentSession.saveOrUpdate(fileblob);

Is this not just what CascadeType.SAVE_UPDATE is supposed to do?
Why is this working for "manual cascading" but not automatically?

P.s.: To complete my example here the counterpart in fileblob.class

@PrimaryKeyJoinColumn
@OneToOne(targetEntity=Fileh.class, fetch=FetchType.LAZY)
@org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK})
@JoinColumns({ @JoinColumn(name="`ID`", referencedColumnName="`ID`", unique=true, nullable=false) })
private Fileh fileh;

@Column(name="`ID`", nullable=false, insertable=false, updatable=false, unique=true)
@Id
@GeneratedValue(generator="FILEBLOB_FILEHID_GENERATOR")
@org.hibernate.annotations.GenericGenerator(name="FILEBLOB_FILEHID_GENERATOR", strategy="foreign", parameters=@org.hibernate.annotations.Parameter(name="property", value="fileh"))
private int filehId;


问:
Find all occurrences and return value of the top cell in a range

Hi,

I am trying the find all occurrences of a value (e.g. cat in my sample screenshot) in each month (e.g. Dec, Jan etc.) and collect all the days (e.g. 1, 4) that it occurs. I then need to do that for other values (e.g. horse, dog etc.)

The value may or may not appear in cell range, and if it does appear it only appears once in a day.

Screenshot of worksheet

I have tried array formulae of index() and match() but couldn't get my head around to get something to work.

The result on another worksheet I am trying to achieve is:

cat

Dec 1 4

Jan 2

dog

Dec

Jan 1

horse

Dec 3 4

Jan

I just need to know how to collect the days.

Thanks.

答:
Modification of UDF code from Concatenate top row cells if column below has 1.

```<code>Option Explicit

Public Function conditional_concat(rSTRs As Range, rCRITs As Range, sCRIT As String, _
                                   sLBL As String, Optional sDELIM As String = ", ")
    Dim c As Long, sTMP As String
    For c = 1 To rCRITs.Cells.Count
        If LCase(rCRITs(c).Value2) = LCase(sCRIT) Then _
            sTMP = sTMP & sDELIM & rSTRs.Cells(1, rCRITs(c).Column).Value
    Next c
    conditional_concat = sLBL & Chr(32) & Mid(sTMP, Len(sDELIM) + 1)
End Function
</code>```

Body:
Modification of UDF code from Concatenate top row cells if column below has 1.

Option Explicit

Public Function conditional_concat(rSTRs As Range, rCRITs As Range, sCRIT As String, _
                                   sLBL As String, Optional sDELIM As String = ", ")
    Dim c As Long, sTMP As String
    For c = 1 To rCRITs.Cells.Count
        If LCase(rCRITs(c).Value2) = LCase(sCRIT) Then _
            sTMP = sTMP & sDELIM & rSTRs.Cells(1, rCRITs(c).Column).Value
    Next c
    conditional_concat = sLBL & Chr(32) & Mid(sTMP, Len(sDELIM) + 1)
End Function


答:
If you malloc the pointer as well as each element of the array you will need to free that pointer after your for loop.

For example:

```<code>int **array;
array = malloc(SIZE*sizeof(int*));
for(int ii = 0; ii < SIZE; ii++)
{
     array[ii] = (int*)malloc(sizeof(int));
}
</code>```

you will have to free each element and free array.
Essentially for every malloc/calloc you have, you must have a free

Title: How should I free an array in C?

Body:
If you malloc the pointer as well as each element of the array you will need to free that pointer after your for loop.

For example:

int **array;
array = malloc(SIZE*sizeof(int*));
for(int ii = 0; ii < SIZE; ii++)
{
     array[ii] = (int*)malloc(sizeof(int));
}

you will have to free each element and free array.
Essentially for every malloc/calloc you have, you must have a free


问:
No module named 'websocket'
I'm a fairly new to Python and I am trying to enter the following code:

```<code>from websocket import create_connection as cc
import json, time
</code>```

I want to look at BTC and LTC stocks in a live feed type-fashion but I keep getting this error:

ModuleNotFoundError: No module named 'websocket'

I've been looking around and it seems that a common solution is:

```<code>pip install websocket
</code>```

that just didn't connect with me. Most sites say install this and just have the above code but I have no idea where to install it or what to do with it.

答:
First, you need to install pip if you don't have it. Type pip in your terminal or cmd to see if it is installed. Or else, install it first by downloading get-pip.py and executing it.

Then you do pip install websocket, which will install the module for you.

Title: No module named 'websocket'

Body:
I'm a fairly new to Python and I am trying to enter the following code:

from websocket import create_connection as cc
import json, time

I want to look at BTC and LTC stocks in a live feed type-fashion but I keep getting this error:

ModuleNotFoundError: No module named 'websocket'

I've been looking around and it seems that a common solution is:

pip install websocket

that just didn't connect with me. Most sites say install this and just have the above code but I have no idea where to install it or what to do with it.