问:
How to fit an implicit equation to a data set, with one fitting parameter: MATLAB
I am trying to fit an implicit equation to a set of data extracted from a paper as shown below.

The data set contains particle concentration, phi, across a gap of radius, R. The data for phi and R are given below.

```<code>phi(Ri) = phi(1);
Ri = R(1);
n = 2;
phiM = 0.68
Kc / Ku = fitting parameters.
R = [4.47 4.59 4.69 4.81 4.92 5.02 5.13 5.24 5.35 5.46 5.57 5.68];
phi = [0.569 0.570 0.573 0.576 0.578 0.581 0.585 0.589 0.593 0.595 0.598 0.602];
</code>```

I am trying to fit the equation 16 to the data set provided. I am at a complete loss as to how to fit an equation to a set of data where phi is on both sides of the equation. I have fitted data to equation before. However it was always explicit (y = f(x)) .

Every time I try to type the fitting equation into the curve fitting toolbox, I am warned that I can not have y on both sides of the equation. What do I do for these types of equation where the curve fitting tool cannot be used?

Any help or guidance towards how I can learn move about these sort of fitting will be very much appreciated.

答:
Let's start by defining your known variables, as given in your question:

```<code>% Known parameters
R = [4.47 4.59 4.69 4.81 4.92 5.02 5.13 5.24 5.35 5.46 5.57 5.68];
phi = [0.569 0.570 0.573 0.576 0.578 0.581 0.585 0.589 0.593 0.595 0.598 0.602];
phi_Ri = phi(1);  Ri = R(1);
n = 2;            phiM = 0.68;
</code>```

Now define your function, but subtract the left hand side so that we can put the equation equal to zero. This function will be in terms of the x parameter (R), the y parameter (phi) and the only unknown, kk which is defined as Ku/Kc in (16).

```<code>F = @(x,y,kk) ((x/Ri).^2).*((1-phi_Ri/phiM)./(1-y/phiM)).^(n*(1-kk)) - (y/phi_Ri);
</code>```

Now we can use fminsearch, with some initial guess for kk, to find the "best" value. You can define "best" however you like, in this case I've taken the norm of F, meaning the distance between the calculated x and y coordinates and the given values for R and phi. Because the function F should be equal to 0, minimising it makes sense!

```<code>% Min search based on norm, with initial guess KuKcMin = 1
KuKcMin = fminsearch(@(KuKc) norm(F(R,phi,KuKc)), 1);
</code>```

In this example, KuKcMin = 1.6735 so Kc/Ku = 1/1.6735 = 0.5975 which is similar to right-hand figure in paper.

Now we have to use ezplot to plot the implicit function, we'll also plot the original points.

```<code>ezplot(@(x,y)F(x,y,KuKcMin), [4.2,6,0.56,0.61]); % 4-element array is axes limits
hold on;
plot(R,phi,'o');
xlabel('R'); ylabel('\phi'); title('');
</code>```

Output:

You can verify that the plotting and function F are working correctly by changing the parameters n, phiM and KuKcMin to reproduce the plots in the paper above:

Edit:

The axes range passed as an input to ezplot is the entire plotting range, not just what is visible. Your new data doesn't lie within the old limits, so we must adapt!

```<code>phi = [0.285 0.285 0.293 0.298 0.299 0.303 0.309 0.310 0.310 0.312 0.315 0.317 0.318 0.318 0.321 0.321 0.321 0.324 0.327 0.325 0.326 0.332 0.335 0.333 0.336];
R = [4.190 4.365 4.540 4.714 4.889 5.063 5.238 5.413 5.587 5.762 5.937 6.111 6.286 6.460 6.635 6.810 6.984 7.159 7.333 7.508 7.683 7.857 8.032 8.206 8.381];
phi_Ri = phi(1);  Ri = R(1);  n = 2;  phiM = 0.68;
F = @(x,y,kk) ((x/Ri).^2).*((1-phi_Ri/phiM)./(1-y/phiM)).^(n*(1-kk)) - (y/phi_Ri);
KuKcMin = fminsearch(@(KuKc) norm(F(R,phi,KuKc)), 1);
% NOTE: change the ezplot    <-- axes limits -->
ezplot(@(x,y)F(x,y,KuKcMin), [4.18,8.4,0.28,0.34]); % 4-element array is axes limits
hold on; plot(R,phi,'o'); xlabel('R'); ylabel('\phi'); title('');
</code>```

To make your code more generic, you could always use ezplot over the same range as your data. You may want to add some padding or rounding.

```<code>ezplot(@(x,y)F(x,y,KuKcMin), [min(R),max(R),min(phi),max(phi)]);
</code>```

Output:

Body:
I am trying to fit an implicit equation to a set of data extracted from a paper as shown below.

The data set contains particle concentration, phi, across a gap of radius, R. The data for phi and R are given below.

phi(Ri) = phi(1);
Ri = R(1);
n = 2;
phiM = 0.68
Kc / Ku = fitting parameters.
R = [4.47 4.59 4.69 4.81 4.92 5.02 5.13 5.24 5.35 5.46 5.57 5.68];
phi = [0.569 0.570 0.573 0.576 0.578 0.581 0.585 0.589 0.593 0.595 0.598 0.602];

I am trying to fit the equation 16 to the data set provided. I am at a complete loss as to how to fit an equation to a set of data where phi is on both sides of the equation. I have fitted data to equation before. However it was always explicit (y = f(x)) .

Every time I try to type the fitting equation into the curve fitting toolbox, I am warned that I can not have y on both sides of the equation. What do I do for these types of equation where the curve fitting tool cannot be used?

Any help or guidance towards how I can learn move about these sort of fitting will be very much appreciated.

Body:
Let's start by defining your known variables, as given in your question:

% Known parameters
R = [4.47 4.59 4.69 4.81 4.92 5.02 5.13 5.24 5.35 5.46 5.57 5.68];
phi = [0.569 0.570 0.573 0.576 0.578 0.581 0.585 0.589 0.593 0.595 0.598 0.602];
phi_Ri = phi(1);  Ri = R(1);
n = 2;            phiM = 0.68;

Now define your function, but subtract the left hand side so that we can put the equation equal to zero. This function will be in terms of the x parameter (R), the y parameter (phi) and the only unknown, kk which is defined as Ku/Kc in (16).

F = @(x,y,kk) ((x/Ri).^2).*((1-phi_Ri/phiM)./(1-y/phiM)).^(n*(1-kk)) - (y/phi_Ri);

Now we can use fminsearch, with some initial guess for kk, to find the "best" value. You can define "best" however you like, in this case I've taken the norm of F, meaning the distance between the calculated x and y coordinates and the given values for R and phi. Because the function F should be equal to 0, minimising it makes sense!

% Min search based on norm, with initial guess KuKcMin = 1
KuKcMin = fminsearch(@(KuKc) norm(F(R,phi,KuKc)), 1);

In this example, KuKcMin = 1.6735 so Kc/Ku = 1/1.6735 = 0.5975 which is similar to right-hand figure in paper.

Now we have to use ezplot to plot the implicit function, we'll also plot the original points.

ezplot(@(x,y)F(x,y,KuKcMin), [4.2,6,0.56,0.61]); % 4-element array is axes limits
hold on;
plot(R,phi,'o');
xlabel('R'); ylabel('\phi'); title('');

Output:

You can verify that the plotting and function F are working correctly by changing the parameters n, phiM and KuKcMin to reproduce the plots in the paper above:

Edit:

The axes range passed as an input to ezplot is the entire plotting range, not just what is visible. Your new data doesn't lie within the old limits, so we must adapt!

phi = [0.285 0.285 0.293 0.298 0.299 0.303 0.309 0.310 0.310 0.312 0.315 0.317 0.318 0.318 0.321 0.321 0.321 0.324 0.327 0.325 0.326 0.332 0.335 0.333 0.336];
R = [4.190 4.365 4.540 4.714 4.889 5.063 5.238 5.413 5.587 5.762 5.937 6.111 6.286 6.460 6.635 6.810 6.984 7.159 7.333 7.508 7.683 7.857 8.032 8.206 8.381];
phi_Ri = phi(1);  Ri = R(1);  n = 2;  phiM = 0.68;
F = @(x,y,kk) ((x/Ri).^2).*((1-phi_Ri/phiM)./(1-y/phiM)).^(n*(1-kk)) - (y/phi_Ri);
KuKcMin = fminsearch(@(KuKc) norm(F(R,phi,KuKc)), 1);
% NOTE: change the ezplot    <-- axes limits -->
ezplot(@(x,y)F(x,y,KuKcMin), [4.18,8.4,0.28,0.34]); % 4-element array is axes limits
hold on; plot(R,phi,'o'); xlabel('R'); ylabel('\phi'); title('');

To make your code more generic, you could always use ezplot over the same range as your data. You may want to add some padding or rounding.

ezplot(@(x,y)F(x,y,KuKcMin), [min(R),max(R),min(phi),max(phi)]);

Output:


来源: stackexchange

问:
KendoUI. Virtualization for dropdown doesn't work correctly
I'm trying to make dropdown with server filtering and paging. Paging works fine, but when I begin typing filter, my control sends an infinit count of queries to the server. Please help me to configure this control.
Datasource:

```<code>getDataSource = function () {
        return new kendo.data.DataSource({
            type: "json",
            transport: {
                read:{
                    url:"...",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                },
                parameterMap: function (options, operation) {
                    switch (operation) {
                        case "read":
                            return JSON.stringify(options);
                            break;
                    }
                }
            },
            schema: {
                data: "Data",
                total: "Total",
                model: {
                    id: "Id"
                }
            },
            pageSize: 20,
            serverPaging: true,
            serverFiltering: true
        });
    }
</code>```

options for dropdown:

```<code>$scope.DropDownOptions = {
        dataTextField: "Value",
        dataValueField: "Id",
        dataSource: getDataSource(),
        filter: "contains",
        virtual: {
            itemHeight: 26,
            valueMapper: function (options) {
                $.ajax({
                    url: "...",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({
                        skip: 0, pageSize: 20, take: 1, filter: { logic: "and", filters: [{ value: options.value, field: "Value", operator: "contains", ignoreCase: true }] }
                    }),
                    success: function (data) {
                        options.success([]);
                    }
                })
            }
        },
        height: 290,
    }
</code>```

and server side:

```<code>[OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public DictionaryQueryResponse GetDictionary(KendoUIDropDownRequest request)
        {
            var response = new DictionaryQueryResponse();
            string filterQuery = request.filter.filters[0].value;
            var data = _client.GetDictionary(filter: filterQuery, skip: request.skip, take: request.take);
            response.Data = data;
            response.Total = 1000;
            return response;
        }
</code>```

One more important thing:
when i change
options.success([]) to options.success(data.Data), it still sends infinit queries, but in addition there is stratification in first item (2 same values draws in one container) and paging is slowing down. When I scroll list a little, paging normalizes

答:
problem solved. this strange behavior was caused by
response.Total = 1000;
i needed to write in this field real count from database</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make dropdown with server filtering and paging. Paging works fine, but when I begin typing filter, my control sends an infinit count of queries to the server. Please help me to configure this control.
Datasource:

getDataSource = function () {
        return new kendo.data.DataSource({
            type: "json",
            transport: {
                read:{
                    url:"...",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                },
                parameterMap: function (options, operation) {
                    switch (operation) {
                        case "read":
                            return JSON.stringify(options);
                            break;
                    }
                }
            },
            schema: {
                data: "Data",
                total: "Total",
                model: {
                    id: "Id"
                }
            },
            pageSize: 20,
            serverPaging: true,
            serverFiltering: true
        });
    }

options for dropdown:

$scope.DropDownOptions = {
        dataTextField: "Value",
        dataValueField: "Id",
        dataSource: getDataSource(),
        filter: "contains",
        virtual: {
            itemHeight: 26,
            valueMapper: function (options) {
                $.ajax({
                    url: "...",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({
                        skip: 0, pageSize: 20, take: 1, filter: { logic: "and", filters: [{ value: options.value, field: "Value", operator: "contains", ignoreCase: true }] }
                    }),
                    success: function (data) {
                        options.success([]);
                    }
                })
            }
        },
        height: 290,
    }

and server side:

[OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public DictionaryQueryResponse GetDictionary(KendoUIDropDownRequest request)
        {
            var response = new DictionaryQueryResponse();
            string filterQuery = request.filter.filters[0].value;
            var data = _client.GetDictionary(filter: filterQuery, skip: request.skip, take: request.take);
            response.Data = data;
            response.Total = 1000;
            return response;
        }

One more important thing:
when i change
options.success([]) to options.success(data.Data), it still sends infinit queries, but in addition there is stratification in first item (2 same values draws in one container) and paging is slowing down. When I scroll list a little, paging normalizes


问:
Difference between apply node and op node in theano
Theano beginner here. I was just going through the graph structures section on deeplearning.net and I have a doubt.

It is stated that in the tutorial that, "Apply node represents the application of an op to some variables. It is important to draw the difference between the definition of a computation represented by an op and its application to some actual data which is represented by the apply node."

In theano, the application of a computation to data is performed by first creating a function and plugging the appropriate value in f(). Where does the op node come into the picture ?

答:
OP in theano means the computation, like add, dot, convolution. And we define all our works by OPs and then build it to a specific graph by theano.function(). Look at here.

Theano represents symbolic mathematical computations as graphs. These
  graphs are composed of interconnected Apply, Variable and Op nodes.
  Apply node represents the application of an op to some variables.

I am not sure this answers your questions. Let's me know if it's still unclear.


问:
Change events execution order using jQuery.live()
I have the following piece of code:

```<code><html>
<head>
 <script src="myplugin.js" />
 <script>
  $(document).ready(function() {
   $('#mytable tbody tr').live('click', function() {
    alert('Hi');
   });
  });
 </script>
</head>
<body>
 <script>
  $('#mytable').myplugin();
 </script>

 <table id="mytable">
  <tbody>
   <tr>
    <td>Something</td>
   </tr>
  </tbody>
 </table>
</body>
</html>

myplugin.js code

.....
return this.each(function(index, id) {
 $(id + ' tbody tr').live('click', function() {
  alert('Hello');
 });
});
.....
</code>```

Under that circustances, the order of executiong would be:

```<code>alert('Hi');
alert('Hello');
</code>```

but I want to be the inverse.
It's possible to change the execution order for this?
thank you

答: You should swap the order of the scripts.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have the following piece of code:

    Something

myplugin.js code

.....
return this.each(function(index, id) {
 $(id + ' tbody tr').live('click', function() {
  alert('Hello');
 });
});
.....

Under that circustances, the order of executiong would be:

alert('Hi');
alert('Hello');

but I want to be the inverse.
It's possible to change the execution order for this?
thank you


问:
Error while sourcing shell script
In order to complete an installation, I need to source the following .sh file:

```<code>function addvar () {
local tmp="${!1}" ;
tmp="${tmp//:${2}:/:}" ; tmp="${tmp/#${2}:/}" ; tmp="${tmp/%:${2}/}" ;
export $1="${2}:${tmp}" ;
}

if [ -z "${PATH}" ]; then
PATH=/share/MontePython/plc-2.0/bin
export PATH
else
addvar PATH /share/MontePython/plc-2.0/bin
fi
if [ -z "${PYTHONPATH}" ]; then
PYTHONPATH=/share/MontePython/plc-2.0/lib/python2.7/site-packages
export PYTHONPATH
else
addvar PYTHONPATH /share/MontePython/plc-2.0/lib/python2.7/site-packages
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64/
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64/
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/lib64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /lib64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/lib
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /lib
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64/
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64/
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/MontePython/plc-2.0/lib
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/MontePython/plc-2.0/lib
fi
CLIK_PATH=/share/MontePython/plc-2.0
export CLIK_PATH

CLIK_DATA=/share/MontePython/plc-2.0/share/clik
export CLIK_DATA

CLIK_PLUGIN=rel2015
export CLIK_PLUGIN
</code>```

but when I source it, I get the following error:

```<code>() not correctly positioned
</code>```

Any idea why?
The curious thing is that this error is happening when I operate on a cluster, while I don't have it on my PC.

EDIT:

The output of lsb_release -a   is:

```<code>LSB Version:    :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: CentOS
Description:    CentOS release 6.9 (Final)
Release:    6.9
Codename:   Final
</code>```

The output of echo $0 is -tcsh.

答:
I think you're using a different shell (tcsh) rather than sh or bash. Most probably you have to adapt your source code to make it load using tcsh. Under sh/bash works just fine</p>

```<code>root@pve1:~# echo $0
-bash
</code>```

Title: Error while sourcing shell script

Body:
In order to complete an installation, I need to source the following .sh file:

function addvar () {
local tmp="${!1}" ;
tmp="${tmp//:${2}:/:}" ; tmp="${tmp/#${2}:/}" ; tmp="${tmp/%:${2}/}" ;
export $1="${2}:${tmp}" ;
}

if [ -z "${PATH}" ]; then
PATH=/share/MontePython/plc-2.0/bin
export PATH
else
addvar PATH /share/MontePython/plc-2.0/bin
fi
if [ -z "${PYTHONPATH}" ]; then
PYTHONPATH=/share/MontePython/plc-2.0/lib/python2.7/site-packages
export PYTHONPATH
else
addvar PYTHONPATH /share/MontePython/plc-2.0/lib/python2.7/site-packages
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64/
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64/
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/compiler/lib/intel64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/lib64
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /lib64
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/lib
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /lib
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64/
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/apps/intel/l_ics_2015.1.133/composer_xe_2015.1.133/ipp/../compiler/lib/intel64/
fi
if [ -z "${LD_LIBRARY_PATH}" ]; then
LD_LIBRARY_PATH=/share/MontePython/plc-2.0/lib
export LD_LIBRARY_PATH
else
addvar LD_LIBRARY_PATH /share/MontePython/plc-2.0/lib
fi
CLIK_PATH=/share/MontePython/plc-2.0
export CLIK_PATH

CLIK_DATA=/share/MontePython/plc-2.0/share/clik
export CLIK_DATA

CLIK_PLUGIN=rel2015
export CLIK_PLUGIN

but when I source it, I get the following error:

() not correctly positioned

Any idea why?
The curious thing is that this error is happening when I operate on a cluster, while I don't have it on my PC.

EDIT:

The output of lsb_release -a   is:

LSB Version:    :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: CentOS
Description:    CentOS release 6.9 (Final)
Release:    6.9
Codename:   Final

The output of echo $0 is -tcsh.

Body:
I think you're using a different shell (tcsh) rather than sh or bash. Most probably you have to adapt your source code to make it load using tcsh. Under sh/bash works just fine

root@pve1:~# echo $0
-bash


答:
In bash, your script is syntactically correct. But if you use sh, then there are a few errors. Check the shellcheck output:

```<code>$ shellcheck script.sh

In script.sh line 3:
function addvar () {
^-- SC2112: 'function' keyword is non-standard. Delete it.

In script.sh line 4:
local tmp="${!1}" ;
^-- SC2039: In POSIX sh, 'local' is undefined.
           ^-- SC2039: In POSIX sh, indirect expansion is undefined.

In script.sh line 5:
tmp="${tmp//:${2}:/:}" ; tmp="${tmp/#${2}:/}" ; tmp="${tmp/%:${2}/}" ;
     ^-- SC2039: In POSIX sh, string replacement is undefined.
                              ^-- SC2039: In POSIX sh, string replacement is undefined.
                                                     ^-- SC2039: In POSIX sh, string replacement is undefined.
</code>```

In summary:

function keyword is not needed (or even recommended)

local isn't supported in POSIX sh

string replacement ${//} is not supported in sh.

Title: Error while sourcing shell script

Body:
In bash, your script is syntactically correct. But if you use sh, then there are a few errors. Check the shellcheck output:

$ shellcheck script.sh

In script.sh line 3:
function addvar () {
^-- SC2112: 'function' keyword is non-standard. Delete it.

In script.sh line 4:
local tmp="${!1}" ;
^-- SC2039: In POSIX sh, 'local' is undefined.
           ^-- SC2039: In POSIX sh, indirect expansion is undefined.

In script.sh line 5:
tmp="${tmp//:${2}:/:}" ; tmp="${tmp/#${2}:/}" ; tmp="${tmp/%:${2}/}" ;
     ^-- SC2039: In POSIX sh, string replacement is undefined.
                              ^-- SC2039: In POSIX sh, string replacement is undefined.
                                                     ^-- SC2039: In POSIX sh, string replacement is undefined.

In summary:

function keyword is not needed (or even recommended)

local isn't supported in POSIX sh

string replacement ${//} is not supported in sh.


问:
Cannot add EntityFrameworkCore Tools 1.0.1 to class library in Visual Studio 2017
I am using the latest  VS2017 update with  donet core 1 I try to create an ef migration to my project
with the command dotnet ef
but I get

```<code>dotnet : No executable found matching command "dotnet-ef"
</code>```

I then remove any reference to EntityFrameworkCore it from my Class Library csproj (.Net Core) and wanted to add the package Microsoft.EntityFrameworkCore.Tools.DotNet 1.0.1 . However I refuses and I get the following error

Severity Code Description Project File Line Suppression State Error Package
  'Microsoft.EntityFrameworkCore.Tools.DotNet 1.0.1' has a package type 'DotnetCliTool' that is not supported by project
  'MyVS2017Project'. 0 I also tried it in a Class Library (.Net
  Framework)

Same error message when using the Package Manager Console command

Install-Package Microsoft.EntityFrameworkCore.Tools.DotNet

I tried editing the csproj file directly and adding

```<code><ItemGroup>
    <DotNetCliToolReference
     Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
     Version="1.0.0" />
 </ItemGroup>
</code>```

but dotnet ef still gives the same error message and nuget package manager doesn't see it

I tried to create a new dot net core class library but even a blank one refuses to install the tools

I have run dotnet restore multiple times and restarted visual studio.

I have downloaded the latest dot net SDK 1.0.4 and run repair to reinstall it. This allows nuget package to install  but despite but whatever I do I cannot get the class library to understand dotnet ef

答: My project targets the full .NET framework, so I can only use the PowerShell commands e.g. add-migration, update-database and not the dotnet ef commands</p>

Body:
I am using the latest  VS2017 update with  donet core 1 I try to create an ef migration to my project
with the command dotnet ef
but I get

dotnet : No executable found matching command "dotnet-ef"

I then remove any reference to EntityFrameworkCore it from my Class Library csproj (.Net Core) and wanted to add the package Microsoft.EntityFrameworkCore.Tools.DotNet 1.0.1 . However I refuses and I get the following error

Severity Code Description Project File Line Suppression State Error Package
  'Microsoft.EntityFrameworkCore.Tools.DotNet 1.0.1' has a package type 'DotnetCliTool' that is not supported by project
  'MyVS2017Project'. 0 I also tried it in a Class Library (.Net
  Framework)

Same error message when using the Package Manager Console command

Install-Package Microsoft.EntityFrameworkCore.Tools.DotNet

I tried editing the csproj file directly and adding

<ItemGroup>
    <DotNetCliToolReference
     Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
     Version="1.0.0" />
 </ItemGroup>

but dotnet ef still gives the same error message and nuget package manager doesn't see it

I tried to create a new dot net core class library but even a blank one refuses to install the tools

I have run dotnet restore multiple times and restarted visual studio.

I have downloaded the latest dot net SDK 1.0.4 and run repair to reinstall it. This allows nuget package to install  but despite but whatever I do I cannot get the class library to understand dotnet ef


问:
Angular Form Undefined In Controller
Have an angular form that I'm passing into my controller.

When I open browser to inspect form, it is undefined. I've tried changing the name of the form, and moving the form tag to enclose the entire body. Here is my form:

```<code>         <form layout-padding id="form-container" ng-controller="RegisterController as RgCtrl" layout="column" ng-cloak name="projectForm">
          <div id="content-row-header">What is your email?</div>
          <md-input-container class="md-block md-input-focused">
            <label>Email</label>
            <input required type="email" name="email" ng-model="email"
                   minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/" />
            <div ng-messages="projectForm.email.$error" role="alert">
              <div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
                Your email must be between 10 and 100 characters long and look like an e-mail address.
              </div>
            </div>
          </md-input-container>
          <div id="content-row-header">Set a password</div>
          <md-input-container class="md-block md-input-focused">
            <label>Password</label>
            <input required name="password" ng-model="password">
            <div ng-messages="projectForm.password.$error">
              <div ng-message="required">This is required.</div>
            </div>
          </md-input-container>
        </form>
</code>```

Here is my function call:

<md-button id="orange-button" ui-sref="app.unauthenticated.purchase.agent" ng-click="doRegistration(projectForm)" flex>Create Account</md-button>

and here is my controller:

```<code> (function () {
  'use strict';

  angular
    .module('app.auth.register')
    .controller('RegisterController', RegisterController);

  /** @ngInject */
  function RegisterController($scope, $auth, $log, $location,$rootScope,$state,app_auth,$stateParams) {
    // Data
    var vm = this;

    // Methods
    $scope.doRegistration = function (form) {
      console.log(form);
      app_auth.register(form.email.$viewValue,form.password.$viewValue,form.passwordConfirm.$viewValue);
    };

    // $scope.goHome = function () {
    /
/   $state.go('app.public');
    // };
  }
})();
</code>```

right now when that console.log(form) runs, form is undefined

答:
name attribute will bind form controller to $scope, so you have name="projectForm" in your controller you should be able
to use $scope.projectForm

check jsfiddle here

https://jsfiddle.net/hurricanew/6tqywue6/

Title: Angular Form Undefined In Controller

Body:
Have an angular form that I'm passing into my controller.

When I open browser to inspect form, it is undefined. I've tried changing the name of the form, and moving the form tag to enclose the entire body. Here is my form:

         <form layout-padding id="form-container" ng-controller="RegisterController as RgCtrl" layout="column" ng-cloak name="projectForm">

What is your email?

          <md-input-container class="md-block md-input-focused">
            Email
            <input required type="email" name="email" ng-model="email"
                   minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/" />

                Your email must be between 10 and 100 characters long and look like an e-mail address.

          </md-input-container>

Set a password

          <md-input-container class="md-block md-input-focused">
            Password
            <input required name="password" ng-model="password">

This is required.

          </md-input-container>
        </form>

Here is my function call:

<md-button id="orange-button" ui-sref="app.unauthenticated.purchase.agent" ng-click="doRegistration(projectForm)" flex>Create Account</md-button>

and here is my controller:

 (function () {
  'use strict';

  angular
    .module('app.auth.register')
    .controller('RegisterController', RegisterController);

  /** @ngInject */
  function RegisterController($scope, $auth, $log, $location,$rootScope,$state,app_auth,$stateParams) {
    // Data
    var vm = this;

    // Methods
    $scope.doRegistration = function (form) {
      console.log(form);
      app_auth.register(form.email.$viewValue,form.password.$viewValue,form.passwordConfirm.$viewValue);
    };

    // $scope.goHome = function () {
    /
/   $state.go('app.public');
    // };
  }
})();

right now when that console.log(form) runs, form is undefined


问:
Angular / Jasmine / Karma - can't start app due to $http call in main module
I manually bootstrap my Angular app following the response to an API call (and corresponding setting of a constant), thus:

```<code>(function() {

    var myApp = angular.module('myApp');

    // Bootstrap the app once we've got a config
    var initInjector = angular.injector(['ng']);
    var $http = initInjector.get('$http');

    $http.get('/api/configs').then(
        function(response) {
            myApp.constant('myConfig', response.data);
            bootstrapApp();
        },
        function(error) {
            console.log('Unable to get config', error);
        }
    );

    function bootstrapApp() {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ['myApp']);
        });
    }

})();
</code>```

This is preventing my tests from running as the $http call isn't being mocked.

```<code>04 07 2017 14:05:53.965:WARN [karma]: No captured browser, open http://localhost:9876/
04 07 2017 14:05:53.987:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
04 07 2017 14:05:55.169:INFO [Chrome 59.0.3071 (Linux 0.0.0)]: Connected on socket /#y-gZChEZ25VdBB7YAAAA with id manual-6637
04 07 2017 14:05:56.270:WARN [web-server]: 404: /api/configs
</code>```

As you can see, the /api/configs call is unsurprisingly 404'ing.

I can't get my head around how to mock this. Creating a test for this module and mocking the $http call doesn't fix it as the call is being made when Karma starts the app.

It feels like I need a "global" $http mock that is available to the test runner when it starts. But I could barking up completely the wrong tree.

Does anyone have any thoughts? Thanks! :)

答:
What you can do is to have a setup file that is added in the files:[ 'mysetup.js', ... ] in karma.conf.js. There you can mock the $http something like this:

```<code>//----mysetup.js----
var response = null;
var replaceHttpGet = function( get ){
    get.success( response ); // or whatever you need
};
//another variable for failure
</code>```

and then you can do in your test:

```<code>//---in test---
var oldHttpGet = $http.get;
$http.get = replaceHttpGet;
response = { //mock response };
...test...
$http.get=oldHttpGet;
</code>```

Body:
I manually bootstrap my Angular app following the response to an API call (and corresponding setting of a constant), thus:

(function() {

    var myApp = angular.module('myApp');

    // Bootstrap the app once we've got a config
    var initInjector = angular.injector(['ng']);
    var $http = initInjector.get('$http');

    $http.get('/api/configs').then(
        function(response) {
            myApp.constant('myConfig', response.data);
            bootstrapApp();
        },
        function(error) {
            console.log('Unable to get config', error);
        }
    );

    function bootstrapApp() {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ['myApp']);
        });
    }

})();

This is preventing my tests from running as the $http call isn't being mocked.

04 07 2017 14:05:53.965:WARN [karma]: No captured browser, open http://localhost:9876/
04 07 2017 14:05:53.987:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
04 07 2017 14:05:55.169:INFO [Chrome 59.0.3071 (Linux 0.0.0)]: Connected on socket /#y-gZChEZ25VdBB7YAAAA with id manual-6637
04 07 2017 14:05:56.270:WARN [web-server]: 404: /api/configs

As you can see, the /api/configs call is unsurprisingly 404'ing.

I can't get my head around how to mock this. Creating a test for this module and mocking the $http call doesn't fix it as the call is being made when Karma starts the app.

It feels like I need a "global" $http mock that is available to the test runner when it starts. But I could barking up completely the wrong tree.

Does anyone have any thoughts? Thanks! :)

Body:
What you can do is to have a setup file that is added in the files:[ 'mysetup.js', ... ] in karma.conf.js. There you can mock the $http something like this:

//----mysetup.js----
var response = null;
var replaceHttpGet = function( get ){
    get.success( response ); // or whatever you need
};
//another variable for failure

and then you can do in your test:

//---in test---
var oldHttpGet = $http.get;
$http.get = replaceHttpGet;
response = { //mock response };
...test...
$http.get=oldHttpGet;


问:
Error: $injector:modulerr Module Error p0=task
i have a simple angular code with wont run due to this error;
ive add the angular-router file the server found it but it keeps giving me this error

```<code>Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=task&p1=Error%3A%20…0Uc%20(http%3A%2F%2Flocalhost%3A3000%2Fangular%2Fangular.min.js%3A22%3A332)
    at angular.min.js:7
    at angular.min.js:43
    at p (angular.min.js:8)
    at g (angular.min.js:42)
    at gb (angular.min.js:46)
    at c (angular.min.js:22)
    at Uc (angular.min.js:22)
    at xe (angular.min.js:21)
    at angular.min.js:333
    at HTMLDocument.b (angular.min.js:38)
</code>```

my view code is

```<code><html >
    <head>
        <title>
        </title>
    </head>
    <body ng-app="task" ng-init="first = 1;">
        <h1>Task List</h1>

        <div ng-controller="ctrl">
            <span>Values: {{first}}</span>
            <input type="text" ng-model="first" />
        </div>

        <script src="angular/angular.min.js"></script>
        <script src="bower_components/angular-route/angular-route.js"></script>
         <script src="angular/app.js"></script>
    </body>

</html>
</code>```

my app.js code

```<code>var task = angular.module('myApp', ['ngRoute']);
task.controller('ctrl', function($scope){
    $scope.first = 1;
});
</code>```

please help.

答:
Think you might need to rewrite that app.js code slightly:

```<code>task.controller('ctrl', ['$scope', function($scope) {
  $scope.first = 1;
}]);
</code>```

Why initialise first here in the controller when you're also doing it in the template, btw? Was there a reason?

Body:
i have a simple angular code with wont run due to this error;
ive add the angular-router file the server found it but it keeps giving me this error

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=task&p1=Error%3A%20…0Uc%20(http%3A%2F%2Flocalhost%3A3000%2Fangular%2Fangular.min.js%3A22%3A332)
    at angular.min.js:7
    at angular.min.js:43
    at p (angular.min.js:8)
    at g (angular.min.js:42)
    at gb (angular.min.js:46)
    at c (angular.min.js:22)
    at Uc (angular.min.js:22)
    at xe (angular.min.js:21)
    at angular.min.js:333
    at HTMLDocument.b (angular.min.js:38)

my view code is

        <title>
        </title>

Task List

            Values: {{first}}
            <input type="text" ng-model="first" />

my app.js code

var task = angular.module('myApp', ['ngRoute']);
task.controller('ctrl', function($scope){
    $scope.first = 1;
});

please help.

Body:
Think you might need to rewrite that app.js code slightly:

task.controller('ctrl', ['$scope', function($scope) {
  $scope.first = 1;
}]);

Why initialise first here in the controller when you're also doing it in the template, btw? Was there a reason?


问:
Lock-free atomic operations on ARM architectures prior to ARMv6
Are there any implementations thereof in C? All those I've seen so far are based on the LDREX/STREX instructions, which were introduced only in the ARMv6 architecture. The only possible solution for previous architectures seems to be to disable/enable IRQs, which makes the operations blocking.</p>

答:
Are there any implementations thereof in C?

No.  It is impossible to implement this is 'C' without support from the compiler or assembly (assembly support in compiler).  'C' has no instruction to guarantee that something executes atomically.

The only possible solution for previous architectures seems to be to disable/enable IRQs, which makes the operations blocking.

Many lock-free algorithms need 'CAS' (compare-and-set).  swp and swpb can be used to do some primitive four value operations, but they are not CAS.  In order to do four sources and one consumer, you can give each of four bytes to the sources, using swpb and have the consumer use swp to transfer the four 'work' bytes.  Most ARM cpus prior to ARMv6 are single core and locking interrupts is the common way to do things.  ARMv6 cores have support for LDREX/STREX.  The swp instruction is not multi-cpu friendly as it locks the entire bus for the transaction (read/write).  However, swp can be used for spin locks if it is the only thing available.

Linux has support for a 'compare and exchange' with OS help.  The gist is that a small fixed assembler sequence does the compare and exchange.  Interrupt and data abort code is hooked to make sure if this code is interrupted that it is restarted.


问:
How to get the percentage of my brute forcer?
I need help on understanding how to calculate the percentage, of my scripts progress as it takes a while depending on the [CPU, clock speed, RAM, and length of the target password_list].

Would you point me in the right direction, or show me a snippet of how to calculate this?

```<code>import itertools, math
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") # Add or remove whatevs you think will be in the password you're cracking (example, [symbols])
counter = 1
CharLength = 1
start_range = int(raw_input("Enter start range: ") # <<< To begin brute force
end_range = int(raw_input("Enter end range: ")) # <<< To end brute force
filename = "bruteforce_%r-%r.txt" % (start_range, end_range)
</code>```

This below is where the calculation would be done; unfortunately percentages just nope my brain will not let me understand em :/

```<code># Math below don't let it bore you :)
y = len(Alphabet)
x = len(start_range)
total = math.pow(x, y)
f = open(filename, 'a')
# Math above don't let it bore you :(
</code>```

The First for loop

```<code>for CharLength in range(start_range, end_range):
    passwords = (itertools.product(Alphabet, repeat = CharLength))
</code>```

The Second for loop

```<code>    for i in passwords:
        counter += 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        f.write(i)
        f.write('\n')
        print "%r:  %r" % (i, percentage) # <--- *Display percentages on second format argument
        pass
</code>```

答:
Use python-progressbar. From their git repo:

The ProgressBar class manages the current progress, and the format of
  the line is given by a number of widgets. A widget is an object that
  may display differently depending on the state of the progress bar.
  There are three types of widgets:

a string, which always shows itself

a ProgressBarWidget, which may return a different value every time its    update method is called

a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it    expands to fill the remaining width of the line.

Example:

```<code>import progressbar as pb

progress = pb.ProgressBar(widgets=_widgets, maxval = 400000).start()
progvar = 0

for i in range(400000):
    # Your code here
    progress.update(progvar + 1)
    progvar += 1
</code>```

Output:

```<code>Progress: |####################################################            |80%
</code>```

Body:
I need help on understanding how to calculate the percentage, of my scripts progress as it takes a while depending on the [CPU, clock speed, RAM, and length of the target password_list].

Would you point me in the right direction, or show me a snippet of how to calculate this?

import itertools, math
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") # Add or remove whatevs you think will be in the password you're cracking (example, [symbols])
counter = 1
CharLength = 1
start_range = int(raw_input("Enter start range: ") # <<< To begin brute force
end_range = int(raw_input("Enter end range: ")) # <<< To end brute force
filename = "bruteforce_%r-%r.txt" % (start_range, end_range)

This below is where the calculation would be done; unfortunately percentages just nope my brain will not let me understand em :/

# Math below don't let it bore you :)
y = len(Alphabet)
x = len(start_range)
total = math.pow(x, y)
f = open(filename, 'a')
# Math above don't let it bore you :(

The First for loop

for CharLength in range(start_range, end_range):
    passwords = (itertools.product(Alphabet, repeat = CharLength))

The Second for loop

    for i in passwords:
        counter += 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        f.write(i)
        f.write('\n')
        print "%r:  %r" % (i, percentage) # <--- *Display percentages on second format argument
        pass

Body:
Use python-progressbar. From their git repo:

The ProgressBar class manages the current progress, and the format of
  the line is given by a number of widgets. A widget is an object that
  may display differently depending on the state of the progress bar.
  There are three types of widgets:

a string, which always shows itself

a ProgressBarWidget, which may return a different value every time its    update method is called

a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it    expands to fill the remaining width of the line.

Example:

import progressbar as pb

progress = pb.ProgressBar(widgets=_widgets, maxval = 400000).start()
progvar = 0

for i in range(400000):
    # Your code here
    progress.update(progvar + 1)
    progvar += 1

Output:

Progress: |####################################################            |80%


问:
how to dynamically insert datediff into webpage to keep updated in real time (now)
I can do a request in phpmyadmin to show the number of days between todays date and a date selected by a user:
SELECT DATEDIFF(CURDATE(), date_instructed) AS DAYS FROM date_tester

.. but i think this wont update all the table and will only update when a new record is created in the table.

So can anyone suggest the best way  to dynamically update/count  the days in a column by using a date entered by a user .

Should it even be put in a column? or should i use php to echo the result for each row on the webpage.

If I should be manipulating the ‘date_instructed’ with a script and then entering it in the html table seperatly is their a link to show me how to do this?

Many thanks

```<code><?php
include 'dbh.php';
?>
<table class="table table-sm table table-bordered
  table table-hover table table-striped  "> <!--, table table-inverse-->
  <thead class="thead-inverse">
    <tr class="warning">
      <th>First Name</th>
      <th>Last</th>
      <th>Date Instructed</th>
      <th>Days On Market</th>
    </tr>
  </thead>

    <?php

    $query  = "SELECT  first_name, last_name, date_instructed , days_onmarket
                FROM date_tester";
    $result = mysqli_query($conn, $query);
    while ($date_tester = mysqli_fetch_assoc($result)) {
        echo "<tr>";
        echo "<td>" . $date_tester['first_name'] . "</td>";
        echo "<td>" . $date_tester['last_name'] . "</td>";
        echo "<td>" . $date_tester['date_instructed'] . "</td>";
    }
    ?>
    </tbody>
</table>
</div>
</code>```

答:
From what i understand this is what you need:</p>

```<code> $query  = "SELECT  first_name, last_name, date_instructed ,    days_onmarket, DATEDIFF(CURDATE(), 'date_instructed') AS DAYS FROM date_tester";
   $result = mysqli_query($conn, $query);
while ($date_tester = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>" . $date_tester['first_name'] . "</td>";
    echo "<td>" . $date_tester['last_name'] . "</td>";
    echo "<td>" . $date_tester['date_instructed'] . "</td>";
    echo "<td>" . $date_tester['DAYS'] . "</td>";
}
</code>```

Body:
I can do a request in phpmyadmin to show the number of days between todays date and a date selected by a user:
SELECT DATEDIFF(CURDATE(), date_instructed) AS DAYS FROM date_tester

.. but i think this wont update all the table and will only update when a new record is created in the table.

So can anyone suggest the best way  to dynamically update/count  the days in a column by using a date entered by a user .

Should it even be put in a column? or should i use php to echo the result for each row on the webpage.

If I should be manipulating the ‘date_instructed’ with a script and then entering it in the html table seperatly is their a link to show me how to do this?

Many thanks

<?php
include 'dbh.php';
?>

      First Name
      Last
      Date Instructed
      Days On Market

    <?php

    $query  = "SELECT  first_name, last_name, date_instructed , days_onmarket
                FROM date_tester";
    $result = mysqli_query($conn, $query);
    while ($date_tester = mysqli_fetch_assoc($result)) {
        echo "
";
        echo "" . $date_tester['first_name'] . "	";
        echo "" . $date_tester['last_name'] . "	";
        echo "" . $date_tester['date_instructed'] . "	";
    }
    ?>

Body:
From what i understand this is what you need:

 $query  = "SELECT  first_name, last_name, date_instructed ,    days_onmarket, DATEDIFF(CURDATE(), 'date_instructed') AS DAYS FROM date_tester";
   $result = mysqli_query($conn, $query);
while ($date_tester = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>" . $date_tester['first_name'] . "</td>";
    echo "<td>" . $date_tester['last_name'] . "</td>";
    echo "<td>" . $date_tester['date_instructed'] . "</td>";
    echo "<td>" . $date_tester['DAYS'] . "</td>";
}


问:
*.min.* in gitignore is not ignoring .min.js files
```<code>## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.orig
*.min.*
</code>```

these are the first few lines of my git ignore files and I can't seem to figure out why git is not igoring any of my .min.js files. I've already checked other questions on here but can't seem to figure out why still. Also, the min.js files are being re-generated every time I compile. Am I doing something wrong here? Also using Git-Extensions if that helps at all.

答:
```<code>*.min.*
</code>```

is the correct syntax but that is not working if the files are added once to your repo. Then you have to remove them first from your repo to ignore that files.

```<code>git rm --cached filename
</code>```

Git ignoring all minified suffixed files

Body:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.orig
*.min.*

these are the first few lines of my git ignore files and I can't seem to figure out why git is not igoring any of my .min.js files. I've already checked other questions on here but can't seem to figure out why still. Also, the min.js files are being re-generated every time I compile. Am I doing something wrong here? Also using Git-Extensions if that helps at all.

Body:
*.min.*

is the correct syntax but that is not working if the files are added once to your repo. Then you have to remove them first from your repo to ignore that files.

git rm --cached filename

Git ignoring all minified suffixed files


问:
How to change Order Email Subject in Order.php Magento
I want to change order email subject in Magento for the order.php file.

Here is my code:

```<code>$mailSubject = "This is test subject";
Mage::getModel('core/email_template')->setTemplateSubject($mailSubject);
$translate = Mage::getSingleton('core/translate');
</code>```

It's not working. Is there any other way to set subject in order.php

I don't want to set from Transaction Emails option from back-end as there is a value generated by PHP I want to send in the subject line.

Any help would be appreciated.

Thanks

答: goto>/app/locale/en_US/template/email/sales select template and change subject directly</p>

Body:
I want to change order email subject in Magento for the order.php file.

Here is my code:

$mailSubject = "This is test subject";
Mage::getModel('core/email_template')->setTemplateSubject($mailSubject);
$translate = Mage::getSingleton('core/translate');

It's not working. Is there any other way to set subject in order.php

I don't want to set from Transaction Emails option from back-end as there is a value generated by PHP I want to send in the subject line.

Any help would be appreciated.

Thanks


问:
What are some good examples of JQuery using JSONP talking to .net?
As the question says, what are some good examples (or just examples really), of Jquery using JSONP to talk to a .net page or webservice?

I'm attempting to write a page which uses JQuery to call another website (Thus I need to use JSONP) which hosts the webservice/webpage (either is fine), and I can't find a good example of this.

答:
JSONP is just json wrapped inside a js method. jQuery provides the method name as a callback parameter on the querystring which the jsonp endpoint must then take and wrap the json in then send the response back. The server side language really is irrelevant.

JSONP with WCF

Good screencast

& a few articles below

Rick Strahl has a blog post on it

Another

OwnerDisplayName: Bravax

OwnerDisplayName: redsquare


问:
How to reference global variables in modular LESS files?
How can I reference a variable defined in a central variables.less file in an individual module.less file, when the module does not directly reference variables.less?

Here's the structure of my Styles folder:

```<code>Styles
  _variables.less
  Site.less

  Modules
    _forms.less
    _navbar-top.less
    _panels.less
    _titlebar.less
    Modules.less

  Pages
    _page1.less
    _page2.less
    Pages.less
</code>```

The file Site.less basically looks like this:

```<code>@import "_variables.less";
@import "Modules/Modules.less";
@import "Pages/Pages.less";
</code>```

(it only includes capitalized LESS files)

And Modules.less looks like:

```<code>@import "_forms.less";
@import "_navbar-top.less";
@import "_panels.less";
@import "_titlebar.less";
</code>```

(it only includes underscore-prefixed files in the same folder)

Pages.less is structured the same way.

What I want to do is have the following in the Modules/_panels.less file:

```<code>.panel-form {
    .panel-variant(1px; @text-color; @component-default-bg; 1px);
    border-top: solid darken(@component-default-bg, 1px);
    border-bottom: solid darken(@component-default-bg, 1px);
    border-left: none;
    border-right: none;
}
</code>```

But of course my LESS compiler (Visual Studio Web Essentials 2013.5) is throwing an error and refusing to compile the file _panels.less because it is referencing a variable that does not exist in its scope.

Currently my workaround is to declare .panel-form in Site.css but that is a hack -- I don't want to start declaring an arbitrary number of modules there.

Is it possible to reference a variable like this and still compile to CSS, and if so how? If not, is there a better structure I should use?

Incidentally I noticed that the LESS compiler doesn't like Bootstrap either, because it raises errors if I type a single space into a Bootstrap LESS file e.g. navbar.less and try to save it, reporting that (for navbar.less) the mixin .clearfix() is undefined. Which of course it is, because navbar.less does not reference mixins.less, yet if it can compile from bootstrap.less downward then everything will work just fine...

答:
I don't know what is your environment but with triple slash directives it usually works:

root

less

_vars.less

modules

someModule.less

Inside "someModule.less" you should try this:

```<code>/// <reference path="../_variables.less" />
</code>```

Body:
How can I reference a variable defined in a central variables.less file in an individual module.less file, when the module does not directly reference variables.less?

Here's the structure of my Styles folder:

Styles
  _variables.less
  Site.less

  Modules
    _forms.less
    _navbar-top.less
    _panels.less
    _titlebar.less
    Modules.less

  Pages
    _page1.less
    _page2.less
    Pages.less

The file Site.less basically looks like this:

@import "_variables.less";
@import "Modules/Modules.less";
@import "Pages/Pages.less";

(it only includes capitalized LESS files)

And Modules.less looks like:

@import "_forms.less";
@import "_navbar-top.less";
@import "_panels.less";
@import "_titlebar.less";

(it only includes underscore-prefixed files in the same folder)

Pages.less is structured the same way.

What I want to do is have the following in the Modules/_panels.less file:

.panel-form {
    .panel-variant(1px; @text-color; @component-default-bg; 1px);
    border-top: solid darken(@component-default-bg, 1px);
    border-bottom: solid darken(@component-default-bg, 1px);
    border-left: none;
    border-right: none;
}

But of course my LESS compiler (Visual Studio Web Essentials 2013.5) is throwing an error and refusing to compile the file _panels.less because it is referencing a variable that does not exist in its scope.

Currently my workaround is to declare .panel-form in Site.css but that is a hack -- I don't want to start declaring an arbitrary number of modules there.

Is it possible to reference a variable like this and still compile to CSS, and if so how? If not, is there a better structure I should use?

Incidentally I noticed that the LESS compiler doesn't like Bootstrap either, because it raises errors if I type a single space into a Bootstrap LESS file e.g. navbar.less and try to save it, reporting that (for navbar.less) the mixin .clearfix() is undefined. Which of course it is, because navbar.less does not reference mixins.less, yet if it can compile from bootstrap.less downward then everything will work just fine...

Body:
I don't know what is your environment but with triple slash directives it usually works:

root

less

_vars.less

modules

someModule.less

Inside "someModule.less" you should try this:

/// <reference path="../_variables.less" />


问:
Odoo 10 use configuration value (stored in ir.values) inside XML
I want to create a menu in the sidebar which shows products of a specific category. I was thinking to use a filter for this task, which is set by default.

However, I don't know how to use the value of my configuration inside my XML domain.

Here is how my XML code looks like:

```<code><record id="my_product_search_form_view" model="ir.ui.view">
    <field name="name">Products Of My Category Search</field>
    <field name="model">product.template</field>
    <field name="inherit_id" ref="product.product_template_search_view" />
    <field name="arch" type="xml">
        <xpath expr="//search" position="inside">
            <filter string="My Category" name="filter_my_categ" domain="[('categ_id','child_of',my_category)]"/>
        </xpath>
    </field>
</record>

<record id="my_product_action" model="ir.actions.act_window">
    <field name="name">Products Of My Category</field>
    <field name="type">ir.actions.act_window</field>
    <field name="res_model">product.template</field>
    <field name="view_mode">kanban,tree,form</field>
    <field name="context">{"search_default_filter_my_categ":1}</field>
    <field name="search_view_id" ref="my_product_search_form_view" />
</record>

<menuitem id="menu_my_products" name="Products Of my Category"
      parent="menu_product" action="my_product_action"
       />
</code>```

I hoped, that when adding 'my_category' to the ir.values table with the model 'product.template' the value will somehow be added to the context - which is not the case & I get an Odoo Client Error NameError: name 'my_category' is not defined

Does anyone know how I can use values of the ir.values table inside my XML view - or at least call a python method inside the context or domain tags? Or is there another solution for my task? Thanks for your help!

答:
In Addition to the solution in Odoo8 (posted by Viki Chavada), here is how the python code looks like for Odoo 10 & extending the product.template:</p>

```<code>class ProductTemplate(models.Model):
    _inherit = "product.template"

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        if self.env.context.get('custom_filter', False):
            category = self.env['ir.values'].get_default('my.config', 'my_category')
            args.append(['categ_id', 'child_of', category])

        result = super(ProductTemplate, self).search(args=args, offset=offset, limit=limit, order=order, count=count)

        return result
</code>```

Body:
I want to create a menu in the sidebar which shows products of a specific category. I was thinking to use a filter for this task, which is set by default.

However, I don't know how to use the value of my configuration inside my XML domain.

Here is how my XML code looks like:

<record id="my_product_search_form_view" model="ir.ui.view">
    <field name="name">Products Of My Category Search</field>
    <field name="model">product.template</field>
    <field name="inherit_id" ref="product.product_template_search_view" />
    <field name="arch" type="xml">
        <xpath expr="//search" position="inside">
            <filter string="My Category" name="filter_my_categ" domain="[('categ_id','child_of',my_category)]"/>
        </xpath>
    </field>
</record>

<record id="my_product_action" model="ir.actions.act_window">
    <field name="name">Products Of My Category</field>
    <field name="type">ir.actions.act_window</field>
    <field name="res_model">product.template</field>
    <field name="view_mode">kanban,tree,form</field>
    <field name="context">{"search_default_filter_my_categ":1}</field>
    <field name="search_view_id" ref="my_product_search_form_view" />
</record>

<menuitem id="menu_my_products" name="Products Of my Category"
      parent="menu_product" action="my_product_action"
       />

I hoped, that when adding 'my_category' to the ir.values table with the model 'product.template' the value will somehow be added to the context - which is not the case & I get an Odoo Client Error NameError: name 'my_category' is not defined

Does anyone know how I can use values of the ir.values table inside my XML view - or at least call a python method inside the context or domain tags? Or is there another solution for my task? Thanks for your help!

Body:
In Addition to the solution in Odoo8 (posted by Viki Chavada), here is how the python code looks like for Odoo 10 & extending the product.template:

class ProductTemplate(models.Model):
    _inherit = "product.template"

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        if self.env.context.get('custom_filter', False):
            category = self.env['ir.values'].get_default('my.config', 'my_category')
            args.append(['categ_id', 'child_of', category])

        result = super(ProductTemplate, self).search(args=args, offset=offset, limit=limit, order=order, count=count)

        return result


问:
How to define the translations manually using TranslationService.setTranslation method
I am using ng2-translate node package to implement translations in an Angular SPA application.

Following the instruction found at https://www.npmjs.com/package/ng2-translate (see Section #3 Define Translations), I defined the translations in one of the components as follows:

```<code>import { Component, } from '@angular/core';
import { TranslateService } from 'ng2-translate';

@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})
export class HomeComponent  {

    constructor(private translate: TranslateService) {

        this.translate.setTranslation('en', {
            "HELLO": "Hello World from TranslateServiceLand"
        }, true);

        this.translate.setTranslation('fr', {
            "HELLO": "Bonjour tout le moonde d'TranslateServiceLand"
        }, true);
    }
}
</code>```

This is however not working. Can someone please provide me with an example?

答:
Use Latest version ngx-translate/core

Actually setTranslation() is used for manually sets a object of translation for given language.

```<code>* @param lang
 * @param translations
 * @param shouldMerge
 */
setTranslation(lang: string, translations: Object, shouldMerge?: boolean): void;
</code>```

Create i18n folder in your component folder

```<code>-componentfolder
 -i18nfolder
 -component.html
 -component.ts
</code>```

component.ts

```<code>import { TranslateService } from '@ngx-translate/core';

        @Component({
            selector: 'home',
            templateUrl: './home.component.html'
        })

        export class HomeComponent  {

        constructor(translate: TranslateService) { }

         changeLanguage(lang) {
            this.translate.use(lang);
            let i18n = require(`./i18n/${lang}.json`);

            this.translate.setTranslation(lang, i18n, true);
          }
        }
</code>```

component.html looks like

```<code><ul class="dropdown-menu" role="menu">
                  <li>
                      <a class="dropdown-item" (click)="changeLanguage('en')">{{"Language.english" | translate}}</a>
                  </li>
                  <li>
                      <a class="dropdown-item"(click)="changeLanguage('es')">{{"Language.spanish" | translate}}</a>
                  </li>
</ul>
</code>```

Hoping, you know how to create json files in i18n folder.

Body:
I am using ng2-translate node package to implement translations in an Angular SPA application.

Following the instruction found at https://www.npmjs.com/package/ng2-translate (see Section #3 Define Translations), I defined the translations in one of the components as follows:

import { Component, } from '@angular/core';
import { TranslateService } from 'ng2-translate';

@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})
export class HomeComponent  {

    constructor(private translate: TranslateService) {

        this.translate.setTranslation('en', {
            "HELLO": "Hello World from TranslateServiceLand"
        }, true);

        this.translate.setTranslation('fr', {
            "HELLO": "Bonjour tout le moonde d'TranslateServiceLand"
        }, true);
    }
}

This is however not working. Can someone please provide me with an example?

Body:
Use Latest version ngx-translate/core

Actually setTranslation() is used for manually sets a object of translation for given language.

* @param lang
 * @param translations
 * @param shouldMerge
 */
setTranslation(lang: string, translations: Object, shouldMerge?: boolean): void;

Create i18n folder in your component folder

-componentfolder
 -i18nfolder
 -component.html
 -component.ts

component.ts

import { TranslateService } from '@ngx-translate/core';

        @Component({
            selector: 'home',
            templateUrl: './home.component.html'
        })

        export class HomeComponent  {

        constructor(translate: TranslateService) { }

         changeLanguage(lang) {
            this.translate.use(lang);
            let i18n = require(`./i18n/${lang}.json`);

            this.translate.setTranslation(lang, i18n, true);
          }
        }

component.html looks like

<ul class="dropdown-menu" role="menu">
                  <li>
                      <a class="dropdown-item" (click)="changeLanguage('en')">{{"Language.english" | translate}}</a>
                  </li>
                  <li>
                      <a class="dropdown-item"(click)="changeLanguage('es')">{{"Language.spanish" | translate}}</a>
                  </li>
</ul>

Hoping, you know how to create json files in i18n folder.


问:
Rename laravel collection "data" key
Is there way i can rename the data key in laravel collection results? At the moment this

```<code>DB::table('contracts AS C')->paginate(1)
</code>```

returns

  {
  "current_page": 1,
    "data": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}```
</div>
</div>
</p>

<p>What i would like is this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  {
  "current_page": 1,
    "parties": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}</code>```

The challenge here changing the data key to parties

答:
You could use the keyBy() method of collection.

```<code>$unfiltered = DB::table('contracts AS C')->paginate(1);

$filtered = $unfiltered->keyBy(function ($value, $key) {
     if ($key == 'data') {
         return 'parties';
     } else {
         return $key;
     }
});

return $filtered;
</code>```

Title: Rename laravel collection "data" key

Body:
Is there way i can rename the data key in laravel collection results? At the moment this

DB::table('contracts AS C')->paginate(1)

returns

  {
  "current_page": 1,
    "data": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}

What i would like is this

  {
  "current_page": 1,
    "parties": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}

The challenge here changing the data key to parties

Body:
You could use the keyBy() method of collection.

$unfiltered = DB::table('contracts AS C')->paginate(1);

$filtered = $unfiltered->keyBy(function ($value, $key) {
     if ($key == 'data') {
         return 'parties';
     } else {
         return $key;
     }
});

return $filtered;


问:
Combination of rules with Regex
In an android project, im trying to validate a password that the user inputs, and it must follow some rules

The rules are:
it must have 7 characters and 3 of the following conditions

**

-One lowercase character

-One uppercase character

-One number

-One special character

**

for example:

asd123!!!

PPPppp000

TTT999###

i was trying with this regex

```<code>^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{7,}+$
</code>```

but this enforces all rules at same time.

答:
Without going into the details of your lookaheads (which seem correct), here's how you would need to implement "three out of four criteria" in pure regex :

```<code>(?=.*A)(?=.*B)(?=.*C)|(?=.*A)(?=.*B)(?=.*D)|(?=.*A)(?=.*C)(?=.*D)|(?=.*B)(?=.*C)(?=.*D)
</code>```

You can test it here.

Factorizing doesn't really make it better :

```<code>(?=.*A)(?:(?=.*B)(?=.*(?:C|D))|(?=.*C)(?=.*D))|(?=.*B)(?=.*C)(?=.*D)
</code>```

I obviously recommend using a higher level language to implement these sorts of constraints.

Title: Combination of rules with Regex

Body:
In an android project, im trying to validate a password that the user inputs, and it must follow some rules

The rules are:
it must have 7 characters and 3 of the following conditions

**

-One lowercase character

-One uppercase character

-One number

-One special character

**

for example:

asd123!!!

PPPppp000

TTT999###

i was trying with this regex

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{7,}+$

but this enforces all rules at same time.

Body:
Without going into the details of your lookaheads (which seem correct), here's how you would need to implement "three out of four criteria" in pure regex :

(?=.*A)(?=.*B)(?=.*C)|(?=.*A)(?=.*B)(?=.*D)|(?=.*A)(?=.*C)(?=.*D)|(?=.*B)(?=.*C)(?=.*D)

You can test it here.

Factorizing doesn't really make it better :

(?=.*A)(?:(?=.*B)(?=.*(?:C|D))|(?=.*C)(?=.*D))|(?=.*B)(?=.*C)(?=.*D)

I obviously recommend using a higher level language to implement these sorts of constraints.


问:
Stored procedure query for selecting values
I have a Test table

```<code>CREATE TABLE [dbo].[Test](
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](50) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL,
</code>```

and Questions table as

```<code>CREATE TABLE [dbo].[Questions](
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL,
</code>```

Questions table stores all the questions for each test with Tid as foreign key.

I want to write a stored procedure to fetch TestName, TestId and number of questions in each test in a single stored procedure. But I am unable to get this.

答:
You can write the stored procedure as:

```<code>CREATE PROCEDURE [dbo].[procGetNumberofQuestionsForTest]
AS
BEGIN
    SELECT T.[TestId], T.[TestName], COUNT(Q.[Qid]) AS NumberOfQuestions
    FROM [dbo].[Test] T
    JOIN [dbo].[Questions] Q ON Q.Tid = T.TestId
    GROUP BY T.[TestId], T.[TestName]
END
</code>```

If you want to get the result for specific Test, then pass the parameter as @TestId INT and add the WHERE clause as WHERE T.[TestId] = @TestId before the GROUP BY.

Body:
I have a Test table

CREATE TABLE [dbo].[Test](
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](50) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL,

and Questions table as

CREATE TABLE [dbo].[Questions](
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL,

Questions table stores all the questions for each test with Tid as foreign key.

I want to write a stored procedure to fetch TestName, TestId and number of questions in each test in a single stored procedure. But I am unable to get this.

Body:
You can write the stored procedure as:

CREATE PROCEDURE [dbo].[procGetNumberofQuestionsForTest]
AS
BEGIN
    SELECT T.[TestId], T.[TestName], COUNT(Q.[Qid]) AS NumberOfQuestions
    FROM [dbo].[Test] T
    JOIN [dbo].[Questions] Q ON Q.Tid = T.TestId
    GROUP BY T.[TestId], T.[TestName]
END

If you want to get the result for specific Test, then pass the parameter as @TestId INT and add the WHERE clause as WHERE T.[TestId] = @TestId before the GROUP BY.


问:
Merging Tables - EXCEL
I have 12 sheets ( one for each month of the year ) with employes name and salary. Is there a way to merge these sheet, sort them by name then month and calculate their total salary earnings that years ? I tried using pivot tables and Consolidate and that did not work. Any Tips?</p>

答:
I have done this before with easily over 100 sheets (1 per contractor company), I've acheieved the merged sheet by using Extend Office. It adds a tonne of useful functionality to your Excel with their software I only needed it a handful of times so the 30 day trial was sufficient

Check it Out!

Title: Merging Tables - EXCEL


问:
How to access Scope value outside the method in angularjs
In below AngularJS controller:

Initially I declared 2 global variables, x and y

Then I perform an AJAX call using $http.get() and I got the correct response from the backend, and kept the required response values in variables x and y.

In an alert message I am trying to print the values of x and y.

I have gone through other question and answers in Stack Overflow and it is a duplicate question, but it's not successful here.

```<code>app.controller('MyController', function($scope, $http, $rootScope) {
    $scope.x = '';
    $scope.y = '';
    $http.get('javaAngularJS').then(function (response) {
        var data = response.data;
        $scope.smsresult = data;
        //need to print following x and y values in below alert message
        $scope.x = $scope.smsresult.failure;
        $scope.y = $scope.smsresult.success;
    });

    alert(x+"   "+y);
});
</code>```

But in the alert message, the values of x* and y are not printing.  What's my mistake  in above code?

答:
Should you not use $scope.x/y? Now they are undefined variables x and y.

x = $scope.smsresult.failure;
 y = $scope.smsresult.success;

to

$scope.x = $scope.smsresult.failure;
 $scope.y = $scope.smsresult.success;

(I would comment but don't have the karma)

Body:
In below AngularJS controller:

Initially I declared 2 global variables, x and y

Then I perform an AJAX call using $http.get() and I got the correct response from the backend, and kept the required response values in variables x and y.

In an alert message I am trying to print the values of x and y.

I have gone through other question and answers in Stack Overflow and it is a duplicate question, but it's not successful here.

app.controller('MyController', function($scope, $http, $rootScope) {
    $scope.x = '';
    $scope.y = '';
    $http.get('javaAngularJS').then(function (response) {
        var data = response.data;
        $scope.smsresult = data;
        //need to print following x and y values in below alert message
        $scope.x = $scope.smsresult.failure;
        $scope.y = $scope.smsresult.success;
    });

    alert(x+"   "+y);
});

But in the alert message, the values of x* and y are not printing.  What's my mistake  in above code?


问:
How to dynamically generate a TextBox control.
How does one dynamically generate a TextBox control at run-time as a result of a button click?  For each button click, I would like to create a TextBox control along with corresponding dynamic labels.  I would like to do this within ASP.NET using the C# language.</p>

答:
To add multiple controls as you asked, use a for loop:

```<code>for (int i = 0; i < 2; ) {
    TextBox textBox = new TextBox();
    textBox.Text = "Hi";
    textBox.Name = "textBox" + i.ToString();
    form2.Controls.Add(textBox);
}
</code>```

But the controls (textboxes) overlaps. You need to organize their locations.

EDIT: E.g

```<code>TextBox txt = new TextBox();
txt.Location = new Point(500, 100);
</code>```

Body:
To add multiple controls as you asked, use a for loop:

for (int i = 0; i < 2; ) {
    TextBox textBox = new TextBox();
    textBox.Text = "Hi";
    textBox.Name = "textBox" + i.ToString();
    form2.Controls.Add(textBox);
}

But the controls (textboxes) overlaps. You need to organize their locations.

EDIT: E.g

TextBox txt = new TextBox();
txt.Location = new Point(500, 100);


问:
testlink integration with mantis(interface:SOAP)
i have installed testlink 1.9.16 and mantis bugtracker 2.3.1 on wamp server 3.0.6.

i tried to integrate mantis and teslink on soap interface . but i'm getting these errors:

-in testlink events : "SOAP Fault: (code: Client, string: looks like we got no XML document)"

-in C:\wamp64\logs\php_error.log :

```<code>[22-Apr-2017 13:06:53 UTC] PHP Fatal error:  Uncaught SoapFault exception: [Server] Error Type: SYSTEM WARNING,
Error Description: Cannot modify header information - headers already sent in C:\wamp64\www\mantis\api\soap\mc_api.php:668
Stack trace:

    #0 [internal function]: mc_error_handler(2, 'Cannot modify h...', 'C:\\wamp64\\www\\m...', 84, Array)
    #1 C:\wamp64\www\mantis\api\soap\mantisconnect.php(84): SoapServer->handle()
    #2 {main}
      thrown in C:\wamp64\www\mantis\api\soap\mc_api.php on line 668
</code>```

this is my configuration for mantisbt in testlink:

```<code><!-- Template mantissoapInterface -->
<issuetracker>
<username>administrator</username>
<password>toor</password>
<uribase>http://localhost/mantis/</uribase>

<uriwsdl>http://localhost/mantis/api/soap/mantisconnect.php?wsdl</uriwsdl>
<uriview>http://localhost/mantis/view.php?id=</uriview>
<uricreate>http://localhost/mantis/</uricreate>
<!-- Configure This if you want be able TO CREATE ISSUES -->
<project>demo_bt</project>
<category>selenium</category>

</issuetracker>
</code>```

Anybody have any idea about this?

thanks.

答:
Please remove the comments in your configuration and check. Check my config please</p>

```<code><issuetracker>
<username>administrator</username>
<password>admin123</password>
<uribase>http://localhost/mantis/</uribase>
<uriwsdl>http://localhost/mantis/api/soap/mantisconnect.php?wsdl</uriwsdl>
<uriview>http://localhost/mantis/view.php?id=</uriview>
<uricreate>http://localhost/mantis/</uricreate>
<project>Testing</project>
<category>development</category>
<resolvedstatus>
<status><code>80</code><verbose>resolved</verbose></status>
<status><code>90</code><verbose>closed</verbose></status>
</resolvedstatus>
</issuetracker>
</code>```

Body:
i have installed testlink 1.9.16 and mantis bugtracker 2.3.1 on wamp server 3.0.6.

i tried to integrate mantis and teslink on soap interface . but i'm getting these errors:

-in testlink events : "SOAP Fault: (code: Client, string: looks like we got no XML document)"

-in C:\wamp64\logs\php_error.log :

[22-Apr-2017 13:06:53 UTC] PHP Fatal error:  Uncaught SoapFault exception: [Server] Error Type: SYSTEM WARNING,
Error Description: Cannot modify header information - headers already sent in C:\wamp64\www\mantis\api\soap\mc_api.php:668
Stack trace:

    #0 [internal function]: mc_error_handler(2, 'Cannot modify h...', 'C:\\wamp64\\www\\m...', 84, Array)
    #1 C:\wamp64\www\mantis\api\soap\mantisconnect.php(84): SoapServer->handle()
    #2 {main}
      thrown in C:\wamp64\www\mantis\api\soap\mc_api.php on line 668

this is my configuration for mantisbt in testlink:

<issuetracker>
<username>administrator</username>
<password>toor</password>
<uribase>http://localhost/mantis/</uribase>

<uriwsdl>http://localhost/mantis/api/soap/mantisconnect.php?wsdl</uriwsdl>
<uriview>http://localhost/mantis/view.php?id=</uriview>
<uricreate>http://localhost/mantis/</uricreate>

<project>demo_bt</project>
<category>selenium</category>

</issuetracker>

Anybody have any idea about this?

thanks.

Body:
Please remove the comments in your configuration and check. Check my config please

<issuetracker>
<username>administrator</username>
<password>admin123</password>
<uribase>http://localhost/mantis/</uribase>
<uriwsdl>http://localhost/mantis/api/soap/mantisconnect.php?wsdl</uriwsdl>
<uriview>http://localhost/mantis/view.php?id=</uriview>
<uricreate>http://localhost/mantis/</uricreate>
<project>Testing</project>
<category>development</category>
<resolvedstatus>
<status><code>80</code><verbose>resolved</verbose></status>
<status><code>90</code><verbose>closed</verbose></status>
</resolvedstatus>
</issuetracker>


问:
Why is JVM not instancing new TimerTask when using timer.schedule()?
I have a Timer in my Code, but the debugger jumps not into it. When it arrives at "timer.schedule()", jumps directly behind it and is not instancing the anonymous TimerTask. Can anyone help me why?

CODE:

```<code>timer = new Timer();

lastTimestamp = calendar.getTimeInMillis() / 1000;
</code>```

// WHEN DEBUGGING IT JUMPS FROM THIS LINE

```<code>timer.schedule(new TimerTask() {
        @Override
        public void run() {
            long now = calendar.getTimeInMillis() / 1000;
            secondsElapsed += now - lastTimestamp;
            lastTimestamp = now;
            // Abbruch-Bedingung
            if(secondsElapsed == totalSeconds)
            {
                // TODO:
                Log.d("MainActivity", "Zeit abgelaufen");
            }
            else
            {
                int minutes = (int)secondsElapsed / 60;
                int seconds = secondsElapsed - (minutes * 60);
                final String newValue = String.format("%02d:%02d", minutes, seconds);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        timerText.setText(newValue);
                    }
                });
            }
        }
    }, 0, 1000);
</code>```

// TO THIS LINE

答:
Those lines are executing in another thread. When that thread is scheduled to run they will run. If you place a breakpoint there you will see them execute

EDIT

```<code>try {
        Timer timer = new Timer();

         long lastTimestamp = System.currentTimeMillis() / 1000;
        // WHEN DEBUGGING IT JUMPS FROM THIS LINE

        timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("WWWWWWW");
                }
            }, 0, 1000);
    }
    catch(Exception x){

    }
}
</code>```

This code executes with no problem. The thread is executed inside the timer

Body:
I have a Timer in my Code, but the debugger jumps not into it. When it arrives at "timer.schedule()", jumps directly behind it and is not instancing the anonymous TimerTask. Can anyone help me why?

CODE:

timer = new Timer();

lastTimestamp = calendar.getTimeInMillis() / 1000;

// WHEN DEBUGGING IT JUMPS FROM THIS LINE

timer.schedule(new TimerTask() {
        @Override
        public void run() {
            long now = calendar.getTimeInMillis() / 1000;
            secondsElapsed += now - lastTimestamp;
            lastTimestamp = now;
            // Abbruch-Bedingung
            if(secondsElapsed == totalSeconds)
            {
                // TODO:
                Log.d("MainActivity", "Zeit abgelaufen");
            }
            else
            {
                int minutes = (int)secondsElapsed / 60;
                int seconds = secondsElapsed - (minutes * 60);
                final String newValue = String.format("%02d:%02d", minutes, seconds);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        timerText.setText(newValue);
                    }
                });
            }
        }
    }, 0, 1000);

// TO THIS LINE

Body:
Those lines are executing in another thread. When that thread is scheduled to run they will run. If you place a breakpoint there you will see them execute

EDIT

try {
        Timer timer = new Timer();

         long lastTimestamp = System.currentTimeMillis() / 1000;
        // WHEN DEBUGGING IT JUMPS FROM THIS LINE

        timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("WWWWWWW");
                }
            }, 0, 1000);
    }
    catch(Exception x){

    }
}

This code executes with no problem. The thread is executed inside the timer


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答:
I think what your teacher means that the exit condition can easily maintained. This because of code cleanup after the while loop. If you will do a hard return then everything after the while loop will not be executed. This can prevented by using a break instead of return.

```<code>int main()
{
 //create a file

 while (true)
 {
  OutputMenu();

  string UserChoice;
  cin >> UserChoice;

  //write UserChoice to file

  // ...

  if (UserChoice == "exit") return 0;
 }

 //close file
}
</code>```

//close file will then not be executed!

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

Body:
I think what your teacher means that the exit condition can easily maintained. This because of code cleanup after the while loop. If you will do a hard return then everything after the while loop will not be executed. This can prevented by using a break instead of return.

int main()
{
 //create a file

 while (true)
 {
  OutputMenu();

  string UserChoice;
  cin >> UserChoice;

  //write UserChoice to file

  // ...

  if (UserChoice == "exit") return 0;
 }

 //close file
}

//close file will then not be executed!


问:
Why does summary(object) work but plot(object) not?
I created a dataset "before_database" via read.table(). Afterwards this data frame was grouped by do.call() and stored into a object "fits":

```<code>fits<-do.call('rbind', by(before_database, before_database$Serial_number, function(before_database) broom::tidy(lm(Amplification ~ Voltage-1, data = before_database))))
</code>```

Now I want to see some results out of this. Summary(fits) works:

```<code>> summary(fits)
     term              estimate        std.error         statistic        p.value
 Length:54          Min.   :0.3601   Min.   :0.06611   Min.   :2.884   Min.   :3.000e-09
 Class :character   1st Qu.:0.4943   1st Qu.:0.11113   1st Qu.:3.384   1st Qu.:4.344e-05
 Mode  :character   Median :0.5866   Median :0.14816   Median :3.934   Median :2.015e-04
                    Mean   :0.6030   Mean   :0.16049   Mean   :4.026   Mean   :8.918e-04
                    3rd Qu.:0.7058   3rd Qu.:0.21271   3rd Qu.:4.318   3rd Qu.:1.199e-03
                    Max.   :0.9193   Max.   :0.27495   Max.   :6.410   Max.   :5.291e-03
>
</code>```

but plot(fits) not. I receive:

```<code>> plot(fits)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In data.matrix(x) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf
</code>```

Also coef(fits) seems not to work, I just get "NULL". What is the matter? What do I should go after?

edit: Added the summary info and I've a further question, maybe connected to the issue. I want to fit all the grouped data separately (am I doing this right now?) so by trying to plot it is not specified what shall be plotted exactly (which of the subsets)?

I guess my problem can be reduced to cirumstance that I do not know how I can apply regular r commands to the grouped data/subsets generated via do.call()? In the end I need a specific value out of the fit. I know fitted() can do this but how to do now for each group? E.g. I need the corresponding voltage of an amplification of 150 and the slope at this point.

Data (only a part shown):

Grouped & fitted by do.call() (only a part shown):

答:
The second issue (from the edit) is not connected, so I'll focus on the initial one. You are getting the error, because you are trying to plot a character() class, which doesn't work. In general, it's not the best idea to try to call plot the whole dataframe anyway - you probably want to plot some specific columns against one another, right? plot is kind of smart though, so it tries to plot something usually. Here's a reporducible example:

```<code>plot(data.frame(letters[1:10], 1:10, stringsAsFactors = F))   # error
plot(data.frame(1:10, sample(1:10,10), stringsAsFactors = F)) # sees two columns, makes a scatterplot
plot(data.frame(1:10, sample(1:10,10), sample(1:10,10), stringsAsFactors = F)) # sees 2+ columns, makes a scatterplot matrix
plot(data.frame(letters[1:5], 1:10, stringsAsFactors = T)) # if using factors (not character), plot wrangles data into a boxplot (recycling values!)
boxplot(data.frame(runif(10), runif(10)*2, runif(10)^2 )) # what I suspect you were after
</code>```

In short, it's better to figure out what you want to plot and then plot that.

Edit to reply to comment/edit. To subset, you could either just limit the plot boundaries

```<code>plot(sample(1:100, 100), ylim=c(0,50), xlim=c(2,10))
</code>```

or do a subset using logic operators, e.g.,

```<code>x = 1:10
x2 = x[which(x>5 & x < 10)]
plot(x2)
</code>```

Body:
I created a dataset "before_database" via read.table(). Afterwards this data frame was grouped by do.call() and stored into a object "fits":

fits<-do.call('rbind', by(before_database, before_database$Serial_number, function(before_database) broom::tidy(lm(Amplification ~ Voltage-1, data = before_database))))

Now I want to see some results out of this. Summary(fits) works:

> summary(fits)
     term              estimate        std.error         statistic        p.value
 Length:54          Min.   :0.3601   Min.   :0.06611   Min.   :2.884   Min.   :3.000e-09
 Class :character   1st Qu.:0.4943   1st Qu.:0.11113   1st Qu.:3.384   1st Qu.:4.344e-05
 Mode  :character   Median :0.5866   Median :0.14816   Median :3.934   Median :2.015e-04
                    Mean   :0.6030   Mean   :0.16049   Mean   :4.026   Mean   :8.918e-04
                    3rd Qu.:0.7058   3rd Qu.:0.21271   3rd Qu.:4.318   3rd Qu.:1.199e-03
                    Max.   :0.9193   Max.   :0.27495   Max.   :6.410   Max.   :5.291e-03
>

but plot(fits) not. I receive:

> plot(fits)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In data.matrix(x) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

Also coef(fits) seems not to work, I just get "NULL". What is the matter? What do I should go after?

edit: Added the summary info and I've a further question, maybe connected to the issue. I want to fit all the grouped data separately (am I doing this right now?) so by trying to plot it is not specified what shall be plotted exactly (which of the subsets)?

I guess my problem can be reduced to cirumstance that I do not know how I can apply regular r commands to the grouped data/subsets generated via do.call()? In the end I need a specific value out of the fit. I know fitted() can do this but how to do now for each group? E.g. I need the corresponding voltage of an amplification of 150 and the slope at this point.

Data (only a part shown):

Grouped & fitted by do.call() (only a part shown):

Body:
The second issue (from the edit) is not connected, so I'll focus on the initial one. You are getting the error, because you are trying to plot a character() class, which doesn't work. In general, it's not the best idea to try to call plot the whole dataframe anyway - you probably want to plot some specific columns against one another, right? plot is kind of smart though, so it tries to plot something usually. Here's a reporducible example:

plot(data.frame(letters[1:10], 1:10, stringsAsFactors = F))   # error
plot(data.frame(1:10, sample(1:10,10), stringsAsFactors = F)) # sees two columns, makes a scatterplot
plot(data.frame(1:10, sample(1:10,10), sample(1:10,10), stringsAsFactors = F)) # sees 2+ columns, makes a scatterplot matrix
plot(data.frame(letters[1:5], 1:10, stringsAsFactors = T)) # if using factors (not character), plot wrangles data into a boxplot (recycling values!)
boxplot(data.frame(runif(10), runif(10)*2, runif(10)^2 )) # what I suspect you were after

In short, it's better to figure out what you want to plot and then plot that.

Edit to reply to comment/edit. To subset, you could either just limit the plot boundaries

plot(sample(1:100, 100), ylim=c(0,50), xlim=c(2,10))

or do a subset using logic operators, e.g.,

x = 1:10
x2 = x[which(x>5 & x < 10)]
plot(x2)