问:
two functions are not calling synchronously on typeahead-on-select()
There are three functions in my directive:-

```<code>scope.fetchDetails = function(){
        scope.a.data1 = scope.margin1;
        scope.a.data2 = scope.margin2;
       scope.getMargin(scope.a.data1,scope.a.data2);
   }

    scope.getMargin = function(data1,data2 {
        ApiServices.getMargin(data1,data2).then(function (response) {
            scope.selected = response.data;
            scope.a.allValues = scope.selected.Values;
        });
    }

    scope.getUser = function(){
        if(!scope.a.allValues){
            scope.a.allValues = "NULL";
        }
            ApiServices.getUser(scope.a.allValues).then(function (response){
                 scope.user= response.data;
            });
    }
</code>```

I am calling this function in my textbox:-

```<code><input type="text" class="form-control" ng-model="a.prod" typeahead="s for s in prods | filter:$viewValue" typeahead-on-select="fetchDetails();getUser()"/>
</code>```

What I want is first to call fetchDetails which will give me allValues and then it calls getUser which gives me rest of data.
    But its calling getUser first and fetchDetails after that, which is why I am not able to fetch data.If I run that code again for different scope.a.allValues. It is calling for previous scope.a.allValues.
    Can anyone tell me how to solve this issue?

答:
It actually first calls fetchDetails and then getUser, but since they're asynchronous, getUser may finish before fetchDetails and vice versa.

To make them execute and finish in sequence, you need to chain your promises, so when fetchDetails() resolves, it calls getUser().

To do that you'd have to change your code to something this:

```<code>scope.fetchDetails = function(){
    scope.a.data1 = scope.margin1;
    scope.a.data2 = scope.margin2;
    return scope.getMargin(scope.a.data1,scope.a.data2)
        .then(scope.getUser);
}

scope.getMargin = function(data1,data2) {
    return ApiServices.getMargin(data1,data2).then(function (response) {
        scope.selected = response.data;
        scope.a.allValues = scope.selected.Values;
    });
}

scope.getUser = function(){
    if(!scope.a.allValues){
        scope.a.allValues = "NULL";
    }
    return ApiServices.getUser(scope.a.allValues).then(function (response){
        scope.user = response.data;
    });
}
</code>```

Then in your view, you only call fetchDetails():

```<code><input type="text" class="form-control" ng-model="a.prod" typeahead="s for s in prods | filter:$viewValue" typeahead-on-select="fetchDetails()"/>
</code>```

Body:
There are three functions in my directive:-

scope.fetchDetails = function(){
        scope.a.data1 = scope.margin1;
        scope.a.data2 = scope.margin2;
       scope.getMargin(scope.a.data1,scope.a.data2);
   }

    scope.getMargin = function(data1,data2 {
        ApiServices.getMargin(data1,data2).then(function (response) {
            scope.selected = response.data;
            scope.a.allValues = scope.selected.Values;
        });
    }

    scope.getUser = function(){
        if(!scope.a.allValues){
            scope.a.allValues = "NULL";
        }
            ApiServices.getUser(scope.a.allValues).then(function (response){
                 scope.user= response.data;
            });
    }

I am calling this function in my textbox:-

<input type="text" class="form-control" ng-model="a.prod" typeahead="s for s in prods | filter:$viewValue" typeahead-on-select="fetchDetails();getUser()"/>

What I want is first to call fetchDetails which will give me allValues and then it calls getUser which gives me rest of data.
    But its calling getUser first and fetchDetails after that, which is why I am not able to fetch data.If I run that code again for different scope.a.allValues. It is calling for previous scope.a.allValues.
    Can anyone tell me how to solve this issue?

Body:
It actually first calls fetchDetails and then getUser, but since they're asynchronous, getUser may finish before fetchDetails and vice versa.

To make them execute and finish in sequence, you need to chain your promises, so when fetchDetails() resolves, it calls getUser().

To do that you'd have to change your code to something this:

scope.fetchDetails = function(){
    scope.a.data1 = scope.margin1;
    scope.a.data2 = scope.margin2;
    return scope.getMargin(scope.a.data1,scope.a.data2)
        .then(scope.getUser);
}

scope.getMargin = function(data1,data2) {
    return ApiServices.getMargin(data1,data2).then(function (response) {
        scope.selected = response.data;
        scope.a.allValues = scope.selected.Values;
    });
}

scope.getUser = function(){
    if(!scope.a.allValues){
        scope.a.allValues = "NULL";
    }
    return ApiServices.getUser(scope.a.allValues).then(function (response){
        scope.user = response.data;
    });
}

Then in your view, you only call fetchDetails():

<input type="text" class="form-control" ng-model="a.prod" typeahead="s for s in prods | filter:$viewValue" typeahead-on-select="fetchDetails()"/>


来源: stackexchange

问:
Can't mount Android Things image file in OS X to tweak config files
Some tutorials recommend making modifications to files such as wpa_supplicant.conf within the Android Things image file, as per this answer https://stackoverflow.com/a/41732035/766115. I'm trying with the Android Things developer preview 4.1 image file.

However, I've had no luck mounting this file for editing purposes on OS X. Various attempts to use os x Disk Utility or the mount command from the terminal all result in some type of error message telling me the file format is not compatible. I can see in Disk Util, or through terminal mount, that the ISO image has 15 sectors (or partitions), but I can't access them.

I've even tried spinning up an Ubuntu in AWS, uploading and mounting from there. No dice.

```<code>   mount: wrong fs type, bad option, bad superblock on /dev/loop0,
   missing codepage or helper program, or other error

   In some cases useful info is found in syslog - try
   dmesg | tail or so.
</code>```

Any advice? What am I missing.

答: hdiutil attach [file] is the macOS command to treat an image file as a disk device. If the image file contains a filesystem macOS can read, it should also mount any volumes contained in the file. If your image contains a volume not supported by macOS (e.g., ext4), you also need to install an appropriate driver before you can mount the volume.

ContentLicense: CC BY-SA 3.0

Body:
Some tutorials recommend making modifications to files such as wpa_supplicant.conf within the Android Things image file, as per this answer https://stackoverflow.com/a/41732035/766115. I'm trying with the Android Things developer preview 4.1 image file.

However, I've had no luck mounting this file for editing purposes on OS X. Various attempts to use os x Disk Utility or the mount command from the terminal all result in some type of error message telling me the file format is not compatible. I can see in Disk Util, or through terminal mount, that the ISO image has 15 sectors (or partitions), but I can't access them.

I've even tried spinning up an Ubuntu in AWS, uploading and mounting from there. No dice.

   mount: wrong fs type, bad option, bad superblock on /dev/loop0,
   missing codepage or helper program, or other error

   In some cases useful info is found in syslog - try
   dmesg | tail or so.

Any advice? What am I missing.


问:
Recording music and Sending it to ftp server using iphone
Hi
 I have a plan to develop an iPhone application which records my drum playing sound and uploads it to a ftp server.

I want to know is to possible to upload to ftp server while recording?. Because if i decide to record and save then upload later, there is a chance of memory full. I want to avoid that .

Can i send music files by splitting into small piece ?

Please suggest me any good solution for this.

Thanks in advance.

答:
You could stream the audio to a webserver, written in whatever language you choose.

The server code could then create small files on the FTP server while the recording is still taking place, and possibly even stitch them together after recording is complete.

This is, however, very advanced for a first project, and would make sense to do the 'splitting' on the device before hand (possibly record multiple 10 second tracks), and transmit them to FTP after recording is complete.

ContentLicense: CC BY-SA 2.5


问:
Adding CloudQueueMessage as a parameter type throws exception
I have a Queue Trigger in Azure function Function, Right now it has method signature as :
Run([QueueTrigger("listner")]string myQueueItem, TraceWriter log)

I want to add one more parameter of type CloudQueueMessage. So when i added it. it throws an error like Message  ->

(QueueTriggerForFileProcessing) Error: Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.QueueTriggerForFileProcessing'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'msg' to type CloudQueueMessage. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).

Does anyone come across similar requirement ? any workable solution to this?

Thanks in advance

Ravi

答:
Please ensure you're targeting the same storage package version as what the storage binding currently uses (currently, 7.2.1).

You can use different versions if using those types from within your function (not relying on bindings), but when binding to types from the package, you'll need to use the version expected by the runtime.


问:
Summing in a for loop in R
I'm struggling to work out how to code this sum in R; I'm guessing we can use a for loop somehow but can't get my head around it.

The equation I am trying to code is:

n-\sum_{k=0}^{n-1}choose(n-1,k)beta_kexp(kLn-k) for n=1,2,..

where:

beta_k is a vector I already have

L is a constant.

I've coded this manually but would like to put it into some kind of for loop.

```<code>mu3<-3-choose(2,1)*beta1*exp(-1*lambdaL*(3-1))-choose(2,2)*beta2*exp(-2*lambdaL*(3-2))
mu4<-4-choose(3,1)*beta1*exp(-1*lambdaL*(4-1))-choose(3,2)*beta2*exp(-2*lambdaL*(4-2))-choose(3,3)*beta3*exp(-3*lambdaL*(4-3))
mu5<-5-choose(4,1)*beta1*exp(-1*lambdaL*(5-1))-choose(4,2)*beta2*exp(-2*lambdaL*(5-2))-choose(4,3)*beta3*exp(-3*lambdaL*(5-3))-choose(4,4)*beta4*exp(-4*lambdaL*(5-4))
</code>```

etc

```<code>lambdaL<-0.5
</code>```

This is my list of beta's

```<code>betarec(10,0.5)
 [1] 0.0000000 1.0000000 0.7869387 1.0278660 1.5510843 2.3702034 3.4694342
4.7718938
 [9] 6.1685468 7.5667952 8.9154479
</code>```

Thank you!

Title: Summing in a for loop in R

Body:
I'm struggling to work out how to code this sum in R; I'm guessing we can use a for loop somehow but can't get my head around it.

The equation I am trying to code is:

n-\sum_{k=0}^{n-1}choose(n-1,k)beta_kexp(kLn-k) for n=1,2,..

where:

beta_k is a vector I already have

L is a constant.

I've coded this manually but would like to put it into some kind of for loop.

mu3<-3-choose(2,1)*beta1*exp(-1*lambdaL*(3-1))-choose(2,2)*beta2*exp(-2*lambdaL*(3-2))
mu4<-4-choose(3,1)*beta1*exp(-1*lambdaL*(4-1))-choose(3,2)*beta2*exp(-2*lambdaL*(4-2))-choose(3,3)*beta3*exp(-3*lambdaL*(4-3))
mu5<-5-choose(4,1)*beta1*exp(-1*lambdaL*(5-1))-choose(4,2)*beta2*exp(-2*lambdaL*(5-2))-choose(4,3)*beta3*exp(-3*lambdaL*(5-3))-choose(4,4)*beta4*exp(-4*lambdaL*(5-4))

etc

lambdaL<-0.5

This is my list of beta's

betarec(10,0.5)
 [1] 0.0000000 1.0000000 0.7869387 1.0278660 1.5510843 2.3702034 3.4694342
4.7718938
 [9] 6.1685468 7.5667952 8.9154479

Thank you!

Body:
Consider a nested apply call with mapply iteratively passing n and k args to an embedded sapply to loop through all successive betas from 1 to current k and iteratively sum the results.

Input

lambdaL <- 0.5
beta <- c(0.0000000,1.0000000,0.7869387,1.0278660,1.5510843,2.3702034,
          3.4694342,4.7718938,6.1685468,7.5667952,8.9154479)

Current version

mu3<-3-choose(2,1)*beta[1]*exp(-1*lambdaL*(3-1))-choose(2,2)*beta[2]*exp(-2*lambdaL*(3-2))
mu3
# [1] 2.632121
mu4<-4-choose(3,1)*beta[1]*exp(-1*lambdaL*(4-1))-choose(3,2)*beta[2]*exp(-2*lambdaL*(4-2))-choose(3,3)*beta[3]*exp(-3*lambdaL*(4-3))
mu4
# [1] 3.418404
mu5<-5-choose(4,1)*beta[1]*exp(-1*lambdaL*(5-1))-choose(4,2)*beta[2]*exp(-2*lambdaL*(5-2))-choose(4,3)*beta[3]*exp(-3*lambdaL*(5-3))-choose(4,4)*beta[4]*exp(-4*lambdaL*(5-4))
mu5
# [1] 4.405454

Loop version  (output equivalent to previous version)

mu_formula <- function(n,k) {
   n + sum(sapply(seq(k), function(i)
           -choose((n-1),i)*beta[i]*exp(-i*lambdaL*(n-i))))
}

mu_vector <- setNames(mapply(mu_formula, 3:5, 2:4), paste0("mu", 3:5))
mu_vector
#      mu3      mu4      mu5
# 2.632121 3.418404 4.405454

mu_list <- setNames(Map(mu_formula, 3:5, 2:4),paste0("mu", 3:5))
mu_list
# $mu3
# [1] 2.632121

# $mu4
# [1] 3.418404

# $mu5
# [1] 4.405454

Generalized Loop (for all betas)

mu_list <- setNames(Map(mu_formula,seq_along(beta)[-1]+1,seq_along(beta)[-1]),
                    paste0("mu",seq_along(beta)[-1]+1))
mu_list

# $mu3
# [1] 2.632121

# $mu4
# [1] 3.418404

# $mu5
# [1] 4.405454

# $mu6
# [1] 5.507972

# $mu7
# [1] 6.640989

# $mu8
# [1] 7.756735

# $mu9
# [1] 8.840919

# $mu10
# [1] 9.896983

# $mu11
# [1] 10.93315

# $mu12
# [1] 11.95646


问:
check if checkbox is checked before submit form in MVC C# and jQuery
at first I had this MVC View that show a list of specific records from database, this is the code and as you can see there is a checkbox column

```<code> <tbody>
                                    @foreach (var item in Model)
                                    {
                                        <tr>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.numero_documento)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_empresa)
                                            </td>
                                            <td>
                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />
                                            </td>
                                        </tr>
                                    }
                                </tbody>
</code>```

and when press the submit button it makes a validation that at least one checkbox has to be checked, like this

```<code>$("#btn-agrupar").click(function (e) {
    if ($("input[type='checkbox']").is(':checked') === true)
        $("#FormAgrupar").submit();
    else {
        if (e.preventDefault) {
            e.preventDefault();
            $("#mostrarmodal").modal("show");
        }
        else {
            e.returnValue = false;
            $("#mostrarmodal").modal("show");
        }
    }
});
</code>```

and used to work but now I do have to added another checkbox column and use jQuery to send to a specific controller the info in the form, this is the code of the view

```<code><tbody>
                                    @foreach (var item in Model)
                                    {
                                        <tr>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.numero_documento)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_empresa)
                                            </td>
                                            <td>
                                                <input type="checkbox" name="delete" value="@item.numero_documento" +"a" />
                                            </td>
                                            <td>
                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />
                                            </td>
                                        </tr>
                                    }
                                </tbody>
</code>```

and this is the code of my jQuery, the problem is that now it doesn´t validate if at least one checkbox is checked for none of the checkbox columns, could you help me and tell me the problem?

```<code> $("#btn-agrupar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("RealizarAgrupacion","Home")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

        $("#btn-eliminar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("Index","Contact")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });
</code>```

this is the code of the buttons in my form

```<code><input type="button" value="Cancelar" id="btn-cancelar" class="btn btn-danger" />
                        <input type="button" value="Eliminar Solicitudes" id="btn-eliminar" class="btn btn-danger" />
                        <input type="button" value="Agrupar Solicitudes" id="btn-agrupar" class="btn btn-primary pull-right" />
</code>```

答:
If I understood your question correctly, you seem to have an issue in differentiating the two check box.You can try referencing the checkbox using it's name and see it that helps.

For example:

```<code>if ($("input[name='delete']").is(':checked') === true) {
    //Do something
}
if ($("input[name='code']").is(':checked') === true) {
    //Do something
}
</code>```

To check all the checkboxes in the view, use prop function

```<code>$('input:checkbox').prop('checked', true);
</code>```

Body:
at first I had this MVC View that show a list of specific records from database, this is the code and as you can see there is a checkbox column

                                    @foreach (var item in Model)
                                    {

                                                @Html.DisplayFor(modelItem => item.numero_documento)

                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)

                                                @Html.DisplayFor(modelItem => item.nombre_empresa)

                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />

                                    }

and when press the submit button it makes a validation that at least one checkbox has to be checked, like this

$("#btn-agrupar").click(function (e) {
    if ($("input[type='checkbox']").is(':checked') === true)
        $("#FormAgrupar").submit();
    else {
        if (e.preventDefault) {
            e.preventDefault();
            $("#mostrarmodal").modal("show");
        }
        else {
            e.returnValue = false;
            $("#mostrarmodal").modal("show");
        }
    }
});

and used to work but now I do have to added another checkbox column and use jQuery to send to a specific controller the info in the form, this is the code of the view

                                    @foreach (var item in Model)
                                    {

                                                @Html.DisplayFor(modelItem => item.numero_documento)

                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)

                                                @Html.DisplayFor(modelItem => item.nombre_empresa)

                                                <input type="checkbox" name="delete" value="@item.numero_documento" +"a" />

                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />

                                    }

and this is the code of my jQuery, the problem is that now it doesn´t validate if at least one checkbox is checked for none of the checkbox columns, could you help me and tell me the problem?

 $("#btn-agrupar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("RealizarAgrupacion","Home")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

        $("#btn-eliminar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("Index","Contact")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

this is the code of the buttons in my form

<input type="button" value="Cancelar" id="btn-cancelar" class="btn btn-danger" />
                        <input type="button" value="Eliminar Solicitudes" id="btn-eliminar" class="btn btn-danger" />
                        <input type="button" value="Agrupar Solicitudes" id="btn-agrupar" class="btn btn-primary pull-right" />

Body:
If I understood your question correctly, you seem to have an issue in differentiating the two check box.You can try referencing the checkbox using it's name and see it that helps.

For example:

if ($("input[name='delete']").is(':checked') === true) {
    //Do something
}
if ($("input[name='code']").is(':checked') === true) {
    //Do something
}

To check all the checkboxes in the view, use prop function

$('input:checkbox').prop('checked', true);


问:
Why do I need __init__.py at every level?
Given that I have the following directory structure with . being the current working directory

```<code>.
\---foo
    \---bar
        \---__init__.py
        \---baz.py
</code>```

When I run python -c "import foo.bar.baz" I get

```<code>Traceback (most recent call last):
  File "<string>", line 1
ImportError: No module named foo.bar.baz
</code>```

If I echo "" > foo/__init__.py, the above command works.

Am I doing something wrong or do I  misunderstand the point of __init__.py?  I thought it was to stop modules existing where they shouldn't, e.g. a directory named string, but if you replace foo with string in my example, I'm seemingly forced to create the module that should never be used, just so I can reference a file deeper in the hierarchy.

Update

I'm working with a build system that's generating the __init__.py's for me and is enforcing the directory structure and while I could mess with the hierarchy, I'd prefer to just add the __init__.py myself. To change the question slightly, why do I need a python package at every level instead of just at the top? Is it just a rule that you can only import modules from the python path or from a chain of packages off of the python path?

答:
Yes, this file is required if you want directory to be treated as a module.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

https://docs.python.org/3/tutorial/modules.html#packages

In a __init__.py file you have great possibility to document module, to get rid of the nested imports for a user/developer by providing the most useful objects(classes/functions) at the first level... ...actually to be as simple in use as possible.

Edit after question update

The default importer/finder (examine the sys.meta_path) is:

BuiltinImporter - searches for/load a built-in module

FrozenImporter - searches for/loads frozen module (e.g. *.pyc)

PathFinder - the one you are interested in, allow to search for/loads a module based on the file system

The third is the __init__.py thing (actually the FrozenImporter as well).

ThePathFinder searches for a module in the paths from sys.path (and in __path__ defined in a package). The module could be either a standalone python file (if it is in the root of the search path) or a directory with __init__.py.

Referring to your example:

```<code>foo/
  bar/
    __init__.py
    baz.py
</code>```

If you create __init__.py in foo/, foo.bar.baz will be available (as you said).

If you add foo/ to sys.path or pass it through PYTHONPATH=foo/, bar.baz will be available (note without parent module foo).

If you write your own finder (and loader) you can load for example any file you want despite where it is. That gives you great power. For example take a look on stack-overflow-import, exposes code based on SO's search results.

Body:
Given that I have the following directory structure with . being the current working directory

.
\---foo
    \---bar
        \---__init__.py
        \---baz.py

When I run python -c "import foo.bar.baz" I get

Traceback (most recent call last):
  File "<string>", line 1
ImportError: No module named foo.bar.baz

If I echo "" > foo/__init__.py, the above command works.

Am I doing something wrong or do I  misunderstand the point of __init__.py?  I thought it was to stop modules existing where they shouldn't, e.g. a directory named string, but if you replace foo with string in my example, I'm seemingly forced to create the module that should never be used, just so I can reference a file deeper in the hierarchy.

Update

I'm working with a build system that's generating the __init__.py's for me and is enforcing the directory structure and while I could mess with the hierarchy, I'd prefer to just add the __init__.py myself. To change the question slightly, why do I need a python package at every level instead of just at the top? Is it just a rule that you can only import modules from the python path or from a chain of packages off of the python path?

Body:
Yes, this file is required if you want directory to be treated as a module.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

https://docs.python.org/3/tutorial/modules.html#packages

In a __init__.py file you have great possibility to document module, to get rid of the nested imports for a user/developer by providing the most useful objects(classes/functions) at the first level... ...actually to be as simple in use as possible.

Edit after question update

The default importer/finder (examine the sys.meta_path) is:

BuiltinImporter - searches for/load a built-in module

FrozenImporter - searches for/loads frozen module (e.g. *.pyc)

PathFinder - the one you are interested in, allow to search for/loads a module based on the file system

The third is the __init__.py thing (actually the FrozenImporter as well).

ThePathFinder searches for a module in the paths from sys.path (and in __path__ defined in a package). The module could be either a standalone python file (if it is in the root of the search path) or a directory with __init__.py.

Referring to your example:

foo/
  bar/
    __init__.py
    baz.py

If you create __init__.py in foo/, foo.bar.baz will be available (as you said).

If you add foo/ to sys.path or pass it through PYTHONPATH=foo/, bar.baz will be available (note without parent module foo).

If you write your own finder (and loader) you can load for example any file you want despite where it is. That gives you great power. For example take a look on stack-overflow-import, exposes code based on SO's search results.

ContentLicense: CC BY-SA 4.0


问:
Location of test automation sources
I'm busy with orientating myself on test automation. Think about Fitnesse, Cucumber or Robot Now I'm doubting where to put my tests. Roughly there are three options.

1) Same project as the application under test
2) In a separate project in the same (Git) repo
3) Seperate project in a seperate (Git) repo.

What is, if there is, common to do? And why?

答:
I would not consider anything else than keeping production code and test code in the same repository.

My main arguments are

I want the tests to be executed each time the production code changes and my CI server picks up the change

Test code and production code is maintained at the same time and by the same people, keeping them in separated repositories just makes life hard

Title: Location of test automation sources


问:
Not getting dynamic variable names PHP
I want to print the values of variable but it prints 12 only</p>

```<code>$str1="abhishek";
$str2="ashish";
for($i=1;$i<=2;$i++)
{
echo $str.$i;
}
</code>```

Title: Not getting dynamic variable names PHP

Body:
I want to print the values of variable but it prints 12 only

$str1="abhishek";
$str2="ashish";
for($i=1;$i<=2;$i++)
{
echo $str.$i;
}

Body:
Do this:

$str1="abhishek";
$str2="ashish";
for($i=1;$i<=2;$i++){
    echo ${"str".$i};
}


问:
How to make md-sidenav-container full height of div in an angular4 app?
I have an angular4 app and am using the angular materials framework https://material.angular.io/components/sidenav/examples. I want to make the md-sidenav-container stretch the whole height of the div without covering up the header. I have attached the fullscreen directive, which causes the sidenav to fill the whole height of the screen thus covering up the header component. This is not what I want. The images show the sidenav stretch above the header, as well as another attempt where it stops at the header but does not stretch to the bottom. I want it to stretch all the way up to the header and all the way down to the bottom of the screen. How do I accomplish this?
Thanks!

Html

```<code><div class="bar">
  <md-sidenav-container class="example-sidenav-fab-container">
  <md-sidenav #sidenav mode="side" opened="true" align="end">
    <!--<button md-mini-fab class="example-fab" (click)="sidenav.toggle()">-->
      <!--<md-icon>add</md-icon>-->
    <!--</button>-->
    <div class="example-scrolling-content">
      <ul>
        <li>Recommendations</li>
        <li>Events</li>
        <li>Settings</li>
      </ul>
    </div>
  </md-sidenav>
  <button md-mini-fab class="example-fab" (click)="sidenav.toggle()">
    <md-icon>add</md-icon>
  </button>
</md-sidenav-container>
</div>
</code>```

Css

```<code>md-sidenav-container
  :background-color white
  :float right
  :width 300px
  :height 400px

md-sidenav
  :background-color $light-blue

//.example-sidenav-fab-container
//  width: 300px
//  height: 400px
  //border: 1px solid rgba(0, 0, 0, 0.5)

.example-sidenav-fab-container md-sidenav
  max-width: 300px

.example-sidenav-fab-container md-sidenav
  display: flex
  overflow: visible

.example-scrolling-content
  overflow: auto

.example-fab
  position: absolute
  right: 20px
  bottom: 10px

.bar
  :height 100%
</code>```

答:
I have found this workaround that works ok

HTML

```<code><md-sidenav-container id="container" fullscreen >
</code>```

CSS

```<code>#container {
 top: 64px !important;
}

@media(max-width: 599px) {
  #container {
    top: 56px !important;
  }
}
</code>```

top has to have the same height of your toolbar. Remember that the standard Angular Material toolbar height becomes smaller when the width is less than 600px .

Body:
I have an angular4 app and am using the angular materials framework https://material.angular.io/components/sidenav/examples. I want to make the md-sidenav-container stretch the whole height of the div without covering up the header. I have attached the fullscreen directive, which causes the sidenav to fill the whole height of the screen thus covering up the header component. This is not what I want. The images show the sidenav stretch above the header, as well as another attempt where it stops at the header but does not stretch to the bottom. I want it to stretch all the way up to the header and all the way down to the bottom of the screen. How do I accomplish this?
Thanks!

Html

  <md-sidenav-container class="example-sidenav-fab-container">
  <md-sidenav #sidenav mode="side" opened="true" align="end">

Recommendations

Events

Settings

  </md-sidenav>
  <button md-mini-fab class="example-fab" (click)="sidenav.toggle()">
    <md-icon>add</md-icon>
  </button>
</md-sidenav-container>

Css

md-sidenav-container
  :background-color white
  :float right
  :width 300px
  :height 400px

md-sidenav
  :background-color $light-blue

//.example-sidenav-fab-container
//  width: 300px
//  height: 400px
  //border: 1px solid rgba(0, 0, 0, 0.5)

.example-sidenav-fab-container md-sidenav
  max-width: 300px

.example-sidenav-fab-container md-sidenav
  display: flex
  overflow: visible

.example-scrolling-content
  overflow: auto

.example-fab
  position: absolute
  right: 20px
  bottom: 10px

.bar
  :height 100%

Body:
I have found this workaround that works ok

HTML

<md-sidenav-container id="container" fullscreen >

CSS

#container {
 top: 64px !important;
}

@media(max-width: 599px) {
  #container {
    top: 56px !important;
  }
}

top has to have the same height of your toolbar. Remember that the standard Angular Material toolbar height becomes smaller when the width is less than 600px .


问:
Not able to plug-in a custom cache manager via shared library to Spring Boot Service
I am trying to add caching behaviour to the services using Spring @cacheable annotation and by using a custom cachemanager as part of configuration to enable/disable caching at runtime.

My custom configuration class works fine when used within the service project. But, when I make it part of a shared library and reference it in the service the caching behaviour does not work.

So, I have a shared library which is now referenced by my service. I want to use the shared library to so that I can change the cacheManager strategy by changing to some other cache manager without impacting the service client.

But, now caching does not work.Within the same service it works, but not as a shared library.

I am not sure if some other cache configuration is getting configured automatically or not.

I want to understand if I need to exclude some cache configuration classes or configure my configuration before some other configuration is getting created.

My configuration class is as below. I am using a string object delimited by (,) to create the caches in the class from application configuration.

```<code>@Configuration
@EnableCaching
@RefreshScope
@AutoConfigureBefore(CacheAutoConfiguration.class)
public class MyCustomCacheConfig {

/* Flag to Determine if Cache should be Enabled or not for the service */
    @Value("${cacheEnabled}")
    private boolean cacheEnabled;

    /* Name of the caches to be created */
    @Value("${caches}")
    private String caches;

    @Bean
    @Primary
    @RefreshScope
    CacheManager cacheManager() {

        //If Cache is Enabled then swap the cacheManager for SimpleCacheManager
        if (cacheEnabled) {
        List<String> cacheNameList = Arrays.asList(caches.split(","));
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        List<ConcurrentMapCache> conMapList = new ArrayList<>();
        for (int i = 0; i < cacheNameList.size(); i++) {
            conMapList.add(new ConcurrentMapCache(cacheNameList.get(i)));
        }

        cacheManager.setCaches(conMapList);

        return cacheManager;
        }else{
            CacheManager cacheManager = new NoOpCacheManager();
            return cacheManager;
        }

    }
}
</code>```

I am using the standard spring boot autoconfiguration approach by having the below entry in path src/main/resources/META-INF/spring.factories of my shared library component.

```<code>**org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.demo.autoconfigure.MyCustomCacheConfig**
</code>```

And so, I expect the configuration will be picked up on startup when the service starts up. I have the library added as a dependency to the service pom.xml

Since I have multiple services to which I want to have this feature of switching cache on/off  at run-time,I thought I can make the configuration as a shared library.

I also have shared the complete repository including the service, the caching-component,demo config service and the file base repo in the git repo below,

https://github.com/bsridhar123/cache-demo-repo

Can someone help me in identifying the cause of the issue.

答:
I got the solution to my issue.

When I added an entry as below in application.properties in the shared library component and built it and referenced it in my service it worked fine.

```<code>spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
</code>```

I also removed the @AutoConfigureBefore annotation I had earlier in my configuration class ins shared library.

Seems like explicitly excluding the autoconfiguration class rather than using the annotatio works,  though I had to add a application.properties to my library.

Body:
I am trying to add caching behaviour to the services using Spring @cacheable annotation and by using a custom cachemanager as part of configuration to enable/disable caching at runtime.

My custom configuration class works fine when used within the service project. But, when I make it part of a shared library and reference it in the service the caching behaviour does not work.

So, I have a shared library which is now referenced by my service. I want to use the shared library to so that I can change the cacheManager strategy by changing to some other cache manager without impacting the service client.

But, now caching does not work.Within the same service it works, but not as a shared library.

I am not sure if some other cache configuration is getting configured automatically or not.

I want to understand if I need to exclude some cache configuration classes or configure my configuration before some other configuration is getting created.

My configuration class is as below. I am using a string object delimited by (,) to create the caches in the class from application configuration.

@Configuration
@EnableCaching
@RefreshScope
@AutoConfigureBefore(CacheAutoConfiguration.class)
public class MyCustomCacheConfig {

/* Flag to Determine if Cache should be Enabled or not for the service */
    @Value("${cacheEnabled}")
    private boolean cacheEnabled;

    /* Name of the caches to be created */
    @Value("${caches}")
    private String caches;

    @Bean
    @Primary
    @RefreshScope
    CacheManager cacheManager() {

        //If Cache is Enabled then swap the cacheManager for SimpleCacheManager
        if (cacheEnabled) {
        List<String> cacheNameList = Arrays.asList(caches.split(","));
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        List<ConcurrentMapCache> conMapList = new ArrayList<>();
        for (int i = 0; i < cacheNameList.size(); i++) {
            conMapList.add(new ConcurrentMapCache(cacheNameList.get(i)));
        }

        cacheManager.setCaches(conMapList);

        return cacheManager;
        }else{
            CacheManager cacheManager = new NoOpCacheManager();
            return cacheManager;
        }

    }
}

I am using the standard spring boot autoconfiguration approach by having the below entry in path src/main/resources/META-INF/spring.factories of my shared library component.

**org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.demo.autoconfigure.MyCustomCacheConfig**

And so, I expect the configuration will be picked up on startup when the service starts up. I have the library added as a dependency to the service pom.xml

Since I have multiple services to which I want to have this feature of switching cache on/off  at run-time,I thought I can make the configuration as a shared library.

I also have shared the complete repository including the service, the caching-component,demo config service and the file base repo in the git repo below,

https://github.com/bsridhar123/cache-demo-repo

Can someone help me in identifying the cause of the issue.

Body:
I got the solution to my issue.

When I added an entry as below in application.properties in the shared library component and built it and referenced it in my service it worked fine.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration

I also removed the @AutoConfigureBefore annotation I had earlier in my configuration class ins shared library.

Seems like explicitly excluding the autoconfiguration class rather than using the annotatio works,  though I had to add a application.properties to my library.


问:
How to use navigator.app.exitApp() to exit application in cordova on iOS platform?
I have an application built using cordova but I don't know how to add exit/stop function to exit the application.After looking around in google and other sites I got clue to use navigator.app.exitApp() but it didn't work for me. How can I solve this?

here is my code:

```<code>function onDeviceReady() {
            var network = navigator.connection.type;

            if (network === 'none') {

                    $cordovaDialogs.confirm('Attention' + '\n' + 'You have no internet connection', '', ['Review Settings', 'Exit'])
                        .then(function(buttonIndex) {
                            // no button = 0, 'OK' = 1, 'Cancel' = 2
                            var btnIndex = buttonIndex;
                            if (btnIndex == 1) {
                                $state.go('register');
                            } else {
                                navigator.device.exitApp();
                            }
                        });
</code>```

答:
cordova plugin add https://github.com/FRD49/iOS-ExitApp.git

use this plugin and simply call
navigator.app.exitApp();

Body:
I have an application built using cordova but I don't know how to add exit/stop function to exit the application.After looking around in google and other sites I got clue to use navigator.app.exitApp() but it didn't work for me. How can I solve this?

here is my code:

function onDeviceReady() {
            var network = navigator.connection.type;

            if (network === 'none') {

                    $cordovaDialogs.confirm('Attention' + '\n' + 'You have no internet connection', '', ['Review Settings', 'Exit'])
                        .then(function(buttonIndex) {
                            // no button = 0, 'OK' = 1, 'Cancel' = 2
                            var btnIndex = buttonIndex;
                            if (btnIndex == 1) {
                                $state.go('register');
                            } else {
                                navigator.device.exitApp();
                            }
                        });


问:
Lock a div in place after you have selected it
So I have the hover state figured out. I'd like to keep the card at it's translated stated once I click on it though. I've tried using pseudo class :focus and :active but it didn't work. Or I'm just not putting the right values in.

$('.wrapper').on('click', function() {
  $(this).addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper:hover {
    transform: translateY(5px);
}

.wrapper:active {
    transform: translateY(5px);
    position: fixed;
}</code>```

Featured

Big Baby Swing

Does he look like hes stupid.  Did he drive well?  No.  Then is he stupid? He's a good kid that's like the devil behind a wheel. That's all you need to know about him..

              More

```

codepen to my question

答: You assign a active class on click so .wrapper.active instead of .wrapper:active should work

Body:
So I have the hover state figured out. I'd like to keep the card at it's translated stated once I click on it though. I've tried using pseudo class :focus and :active but it didn't work. Or I'm just not putting the right values in.

$('.wrapper').on('click', function() {
  $(this).addClass('active');
});

.wrapper:hover {
    transform: translateY(5px);
}

.wrapper:active {
    transform: translateY(5px);
    position: fixed;
}

Featured

Big Baby Swing

Does he look like hes stupid.  Did he drive well?  No.  Then is he stupid? He's a good kid that's like the devil behind a wheel. That's all you need to know about him..

              More

codepen to my question


问:
Creating a fancy search bar with Swing components
I'm trying to come up with an elegant recreation of the search bar component in Thunderbird. The clear button doesn't appear until there is text in the box, so that screen-shot is a bit inaccurate.

Should I use a layered pane and get some buttons to float above the box? (but then getting the text to not appear below the buttons would be hacky)

Maybe just put buttons at the ends of the search bar and have it somehow blend in?

Any ideas or maybe a style reconsideration is welcome, thank you.

答:
Check out JideSoft's Common Layer and the Overlayable class.

Demos


问:
parsed values are getting truncated on unix platform while parsing xml using dom4j and jdk 7
I am using dom4j to parse xml. Parsing is going smooth on windows platform(jdk 7) and when I deploy same code on UNIX having jdk 7 over there, its truncating the parsed values on random basis. Sometimes it don't parse few values at all.

Issue is not producible on window and as its random on UNIX, I am not able to trace the root cause. Code is running in batch mode at both places. Can anyone help me on this?

答:
When you get random corruptions in the data from the XML parser that's shipped with the JDK, the first thing to do is to try it with Apache Xerces instead. This often solves the problem. The JDK parser, although it's based on some version of Apache Xerces, has some nasty bugs. I think they finally got fixed in JDK 8, but I wouldn't swear to it.</p>

<p>(You'll have to look up the details of how to configure DOM4J to use a different SAX parser underneath). </p>

Body:
When you get random corruptions in the data from the XML parser that's shipped with the JDK, the first thing to do is to try it with Apache Xerces instead. This often solves the problem. The JDK parser, although it's based on some version of Apache Xerces, has some nasty bugs. I think they finally got fixed in JDK 8, but I wouldn't swear to it.

(You'll have to look up the details of how to configure DOM4J to use a different SAX parser underneath).


问:
How to parse a file matching all the lines for a string and keep track of count?
We have a file with following lines in it,
we need to find all the lines with "Error" message type..
save the message and its count and print the messages in the descending order of count,can anyone provide guidance on how to do this?

file.txt

```<code><TIMESTAMP><MESSAGETYPE><MESSAGE>
<4:02><ERROR><Error message1>
<14:13><Error><Error message2>
<10:03><Warning><Warning message1>
<12:03><Warning><Warning message2>
</code>```

CODE:-

答:
For similar task, I used next trick:

```<code>fname = "summary.log"
with open(fname) as f:
    content = f.readlines()
content = [x.strip() for x in content]
commits = []

def onHeader(obj):
    date = obj.group(1)
    time = obj.group(2)
    commits.append(CCommitInfo(date, time))

def onFile(obj):
    added = int(obj.group(1))
    removed = int(obj.group(2))
    commits[-1].changed(added, removed)

matchers = []
matchers.append((re.compile(r"(.+?)\s(.+?)\s\+\d+$"), onHeader))
matchers.append((re.compile(r"^(\d+)\t(\d+).+\.(php|pas)"), onFile))

def match(s):
    for x in matchers:
        r = x[0].search(s)
        if r:
            x[1](r)
            break

for x in content:
    match(x)
</code>```

Sorry for code "as is". As you can see, I just add to matchers pairs regexp-callback  and match them to each line. Simple and  powerful.

Body:
We have a file with following lines in it,
we need to find all the lines with "Error" message type..
save the message and its count and print the messages in the descending order of count,can anyone provide guidance on how to do this?

file.txt

<TIMESTAMP><MESSAGETYPE><MESSAGE>
<4:02><ERROR><Error message1>
<14:13><Error><Error message2>
<10:03><Warning><Warning message1>
<12:03><Warning><Warning message2>

CODE:-

Body:
For similar task, I used next trick:

fname = "summary.log"
with open(fname) as f:
    content = f.readlines()
content = [x.strip() for x in content]
commits = []

def onHeader(obj):
    date = obj.group(1)
    time = obj.group(2)
    commits.append(CCommitInfo(date, time))

def onFile(obj):
    added = int(obj.group(1))
    removed = int(obj.group(2))
    commits[-1].changed(added, removed)

matchers = []
matchers.append((re.compile(r"(.+?)\s(.+?)\s\+\d+$"), onHeader))
matchers.append((re.compile(r"^(\d+)\t(\d+).+\.(php|pas)"), onFile))

def match(s):
    for x in matchers:
        r = x[0].search(s)
        if r:
            x[1](r)
            break

for x in content:
    match(x)

Sorry for code "as is". As you can see, I just add to matchers pairs regexp-callback  and match them to each line. Simple and  powerful.


问:
simple preg_replace() not working right for me :/
```<code>$str = "{Controller}/{Action}";
$str = preg_replace("/\//","\\/",$str);
$str = preg_replace("/(\{\w+\})\\/(\{\w+\})/","\\1 slash \\2",$str);
echo $str;
</code>```

So the third line doesn't do anything for me, could anyone say where i was wrong? It works if i put something else instead of \/
thanks in advance;)

答:
This will work:

```<code>$str = "{Controller}/{Action}";
$str = preg_replace('#(\{\w+\})/(\{\w+\})#', '\1 slash \2', $str);

echo $str;
</code>```

Output: {Controller} slash {Action}

Remarks:

You should use single quotes to reduce the need for escaping and therefore much better readability.

You also should consider using another delimiter if you are matching literal slashes (eg #, but anything works)

Body:
$str = "{Controller}/{Action}";
$str = preg_replace("/\//","\\/",$str);
$str = preg_replace("/(\{\w+\})\\/(\{\w+\})/","\\1 slash \\2",$str);
echo $str;

So the third line doesn't do anything for me, could anyone say where i was wrong? It works if i put something else instead of \/
thanks in advance;)

Body:
This will work:

$str = "{Controller}/{Action}";
$str = preg_replace('#(\{\w+\})/(\{\w+\})#', '\1 slash \2', $str);

echo $str;

Output: {Controller} slash {Action}

Remarks:

You should use single quotes to reduce the need for escaping and therefore much better readability.

You also should consider using another delimiter if you are matching literal slashes (eg #, but anything works)


问:
How to use sometimes rule in Laravel 5 request class
I have the following request class:

```<code><?php namespace App\Http\Requests\User;

use App\Http\Requests\Request;
use Validator;
use Session;
use Auth;
use App\User;

class RegisterStep1Request extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Set up the validation rules
     */
    public function rules()
    {
        Validator::extend('valid_date', function($attribute, $value, $parameters)
        {
            $pieces = explode('/', $value);
            if(strpos($value, '/')===FALSE) {
                return false;
            } else {
                if(checkdate($pieces[1], $pieces[0], $pieces[2])) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        return [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|email|unique:users,email',
            'dob' => 'required|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/|valid_date',
            'mobile' => 'required',
            'password' => 'required|confirmed'
        ];
    }

    public function messages()
    {
        return [
            'first_name.required' => 'The first name field is required.',
            'last_name.required' => 'The last name field is required.',
            'email.required' => 'The email address field is required.',
            'email.email' => 'The email address specified is not a valid email address.',
            'email.unique' => 'The email address is already registered with this website.',
            'dob.required' => 'The date of birth field is required.',
            'dob.regex' => 'The date of birth is invalid. Please use the following format: DD/MM/YYYY.',
            'dob.valid_date' => 'The date of birth is invalid. Please check and try again.',
            'mobile.required' => 'The mobile number field is required.',
            'password.required' => 'The password field is required.',
            'password.confirmed' => 'The confirm password field does not match the password field.'
        ];
    }

}
</code>```

I want to add the following sometimes rule:

```<code>Validator::sometimes('dob', 'valid_date', function($input)
{
    return apply_regex($input->dob) === true;
});
</code>```

How would I add this to my request class?

I have amended my rules method to the following:

```<code>public function rules()
{
    Validator::extend('valid_date', function($attribute, $value, $parameters)
    {
        $pieces = explode('/', $value);
        if(strpos($value, '/')===FALSE) {
            return false;
        } else {
            if(checkdate($pieces[1], $pieces[0], $pieces[2])) {
                return true;
            } else {
                return false;
            }
        }
    });

    Validator::sometimes('dob', 'valid_date', function($input)
    {
        return apply_regex($input->dob) === true;
    });

    return [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required|email|unique:users,email',
        'dob' => 'sometimes|required|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/|valid_date',
        'mobile' => 'required',
        'password' => 'required|confirmed'
    ];
}
</code>```

But I now get the following error when I submit the form:

```<code>FatalErrorException in Facade.php line 216:
Call to undefined method Illuminate\Validation\Factory::sometimes()
</code>```

答:
There is a documented way to make changes to the request's validator instance in Laravel 5.4. You should implement the withValidator method for that.

Based on the example from @lukasgeiter's answer, you may add the following to your request class:

```<code>/**
 * Configure the validator instance.
 *
 * @param  \Illuminate\Validation\Validator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->sometimes('dob', 'valid_date', function ($input) {
        return apply_regex($input->dob) === true;
    });
}
</code>```

By doing this you don't have to worry about overriding internal methods. Besides, this seems to be the official way for configuring the validator.

Body:
I have the following request class:

<?php namespace App\Http\Requests\User;

use App\Http\Requests\Request;
use Validator;
use Session;
use Auth;
use App\User;

class RegisterStep1Request extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Set up the validation rules
     */
    public function rules()
    {
        Validator::extend('valid_date', function($attribute, $value, $parameters)
        {
            $pieces = explode('/', $value);
            if(strpos($value, '/')===FALSE) {
                return false;
            } else {
                if(checkdate($pieces[1], $pieces[0], $pieces[2])) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        return [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|email|unique:users,email',
            'dob' => 'required|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/|valid_date',
            'mobile' => 'required',
            'password' => 'required|confirmed'
        ];
    }

    public function messages()
    {
        return [
            'first_name.required' => 'The first name field is required.',
            'last_name.required' => 'The last name field is required.',
            'email.required' => 'The email address field is required.',
            'email.email' => 'The email address specified is not a valid email address.',
            'email.unique' => 'The email address is already registered with this website.',
            'dob.required' => 'The date of birth field is required.',
            'dob.regex' => 'The date of birth is invalid. Please use the following format: DD/MM/YYYY.',
            'dob.valid_date' => 'The date of birth is invalid. Please check and try again.',
            'mobile.required' => 'The mobile number field is required.',
            'password.required' => 'The password field is required.',
            'password.confirmed' => 'The confirm password field does not match the password field.'
        ];
    }

}

I want to add the following sometimes rule:

Validator::sometimes('dob', 'valid_date', function($input)
{
    return apply_regex($input->dob) === true;
});

How would I add this to my request class?

I have amended my rules method to the following:

public function rules()
{
    Validator::extend('valid_date', function($attribute, $value, $parameters)
    {
        $pieces = explode('/', $value);
        if(strpos($value, '/')===FALSE) {
            return false;
        } else {
            if(checkdate($pieces[1], $pieces[0], $pieces[2])) {
                return true;
            } else {
                return false;
            }
        }
    });

    Validator::sometimes('dob', 'valid_date', function($input)
    {
        return apply_regex($input->dob) === true;
    });

    return [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required|email|unique:users,email',
        'dob' => 'sometimes|required|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/|valid_date',
        'mobile' => 'required',
        'password' => 'required|confirmed'
    ];
}

But I now get the following error when I submit the form:

FatalErrorException in Facade.php line 216:
Call to undefined method Illuminate\Validation\Factory::sometimes()

Body:
There is a documented way to make changes to the request's validator instance in Laravel 5.4. You should implement the withValidator method for that.

Based on the example from @lukasgeiter's answer, you may add the following to your request class:

/**
 * Configure the validator instance.
 *
 * @param  \Illuminate\Validation\Validator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->sometimes('dob', 'valid_date', function ($input) {
        return apply_regex($input->dob) === true;
    });
}

By doing this you don't have to worry about overriding internal methods. Besides, this seems to be the official way for configuring the validator.


问:
Is there "FloatingToggleButton" or something like that in Android?
I want to use FloatingActionButton for "like" action, but there should be two states for this, liked and unliked. So ToggleButton is suitable for this, but is there anything that combines the feature of these two kinds of button?</p>

答: You can use the checkbox with checked and unchecked images. so that you can able to manage it for like and like within same button action. this link will help you to get the checkbox selector which use icons for different state.</p>


问:
Running distributed Tensorflow on Google Cloud ML engine ClusterSpec
I am trying to run a large distributed tensorflow model on Google Cloud's ML engine and am having trouble understanding what should go on tf.train.ClusterSpec.

When you run a job on Google Cloud you can select the scale tier from BASIC, STANDARD_1, PREMIUM_1, BASIC_GPU or CUSTOM, each giving you access to different types of clusters. However, I can't find the name/addresses of the machines in these clusters.

答:
Please take a look at the documentation and sample here. You should set ClusterSpec using the environment variable TF_CONFIG; e.g.</p>

```<code>  tf_config = os.environ.get('TF_CONFIG')

  # If TF_CONFIG is not available run local
  if not tf_config:
    return run('', True, *args, **kwargs)

  tf_config_json = json.loads(tf_config)
  cluster = tf_config_json.get('cluster')
  ...
  cluster_spec = tf.train.ClusterSpec(cluster)
</code>```

Body:
Please take a look at the documentation and sample here. You should set ClusterSpec using the environment variable TF_CONFIG; e.g.

  tf_config = os.environ.get('TF_CONFIG')

  # If TF_CONFIG is not available run local
  if not tf_config:
    return run('', True, *args, **kwargs)

  tf_config_json = json.loads(tf_config)
  cluster = tf_config_json.get('cluster')
  ...
  cluster_spec = tf.train.ClusterSpec(cluster)


问:
Setting tab order with javascript
I have a page which has multiple forms. I'm using Mootools sliding tabs so each of the buttons on the menu slide along to the next form. There are 3 forms which are technically on the same HTML page. See an example of the technique at http://creativepony.com/archive/demos/sliding-tabs/

My problem is when a user presses the tab key and tabs through to the last field I want the tab order so it goes back to the first field. This is so the user does not accidentally tab to the next form. The user would end up looping back around the same form fields. For the user to reach the next form they use the menu so I don't want them to be able to tab to the next form.

I am aware of setting tab order with 'tabindex' but this doesn't help me make the user return to the first field of that form.

Any ideas how to achieve this with javascript?

答: I would do this by making the fields in the forms that aren't visible disabled, so the browser knows to skip them, regardless of navigation mechanism (think accessibility aids).

Title: Setting tab order with javascript


问:
Find max and second max salary for a employee table MySQL
Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary:

```<code>  Employee
  Employee ID    Salary
   3            200
   4            800
   7            450
</code>```

I wish to write a query select max(salary) as max_salary, 2nd_max_salary from employee

then it should return

```<code>  max_salary   2nd_max_salary
   800             450
</code>```

i know how to find 2nd highest salary

```<code>   SELECT MAX(Salary) FROM Employee
  WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )
</code>```

or to find the nth

```<code>  SELECT FROM Employee Emp1 WHERE (N-1) = ( SELECT COUNT(DISTINCT(Emp2.Salary)) FROM Employee Emp2
  WHERE Emp2.Salary > Emp1.Salary)
</code>```

but i am unable to figureout how to join these 2 results for the desired result

答:
```<code>select * from emp where sal =(select max(sal) from emp where eno in(select eno from emp where sal <(select max(sal)from emp )));
</code>```

try the above code ....

if you want the third max record then add another nested query "select max(sal)from emp" inside the bracket of the last query and give less than operator in front of it.

Body:
Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary:

  Employee
  Employee ID    Salary
   3            200
   4            800
   7            450

I wish to write a query select max(salary) as max_salary, 2nd_max_salary from employee

then it should return

  max_salary   2nd_max_salary
   800             450

i know how to find 2nd highest salary

   SELECT MAX(Salary) FROM Employee
  WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )

or to find the nth

  SELECT FROM Employee Emp1 WHERE (N-1) = ( SELECT COUNT(DISTINCT(Emp2.Salary)) FROM Employee Emp2
  WHERE Emp2.Salary > Emp1.Salary)

but i am unable to figureout how to join these 2 results for the desired result

Body:
select * from emp where sal =(select max(sal) from emp where eno in(select eno from emp where sal <(select max(sal)from emp )));

try the above code ....

if you want the third max record then add another nested query "select max(sal)from emp" inside the bracket of the last query and give less than operator in front of it.


问:
How "this" got binded in the React component method
I have abstracted my React code here. I have not binded "this" to method A(). That is , in the constructor I didnot do
        this.A = this.A.bind(this);
nor used any arrow syntax for binding.
So the compiler cannot know what's the value of this inside A().
Since I have used this.map inside A(), the compiler should have thrown error for this usage. When inspecting the code in Chrome Dev Tools, I found the compiler seems to correctly assign the value of this automatically by var _this2 = this. I couldnt understand the behaviour. Can somebody explain this pls. (I am new to React. Kindly bear if this question sounds silly)

```<code>class Test extends React.Component{
    constructor(props){
     super(props);
     this.map = [];
     this.state = { a: 1};
    }

    A(){
     // some complex logic
     this.map = Complexlogic() ;
    }

    componentWillMount(){
     this.A();
    }
}
</code>```

答:
React has created class constructs partially for this purpose. By design, anything created within a class construct is bound to the object context, as it would in any other language's class.

Why you often see functions being 'bound' inside class constructs is for when they have to be passed outside the class context, but you wish to maintain the context of the object for that function. Such as when you pass a function to a component in the render call.

As for why you see "_this2" - its just a way that react manages several different "this" contexts being available at a given time.

Body:
I have abstracted my React code here. I have not binded "this" to method A(). That is , in the constructor I didnot do
        this.A = this.A.bind(this);
nor used any arrow syntax for binding.
So the compiler cannot know what's the value of this inside A().
Since I have used this.map inside A(), the compiler should have thrown error for this usage. When inspecting the code in Chrome Dev Tools, I found the compiler seems to correctly assign the value of this automatically by var _this2 = this. I couldnt understand the behaviour. Can somebody explain this pls. (I am new to React. Kindly bear if this question sounds silly)

class Test extends React.Component{
    constructor(props){
     super(props);
     this.map = [];
     this.state = { a: 1};
    }

    A(){
     // some complex logic
     this.map = Complexlogic() ;
    }

    componentWillMount(){
     this.A();
    }
}


问:
In html, how to stretch an image in only one dimension?
Let's say that I want to fit an 10*60 image into a 15*15 container. That is to say, I want to stretch my image so that the width correspond (so that would be an image of 15*90), but I do not want the height to stretch more than the width, so the bottom of my image will not appear.

When I define my html image, I put an width=100% to stretch the width, but what do I say to the height?

Thank  you !

答: If I understood the question correctly, you don't have to specify any value on the height property. Just set overflow:hidden on your container if you don't want the overflowing part of the image to show. Hope this helps.


问:
prestashop 1.7 how to edit the "add product" page in backoffice
I am trying without any success, to edit the page in the subject, because I have added 7 more fields in the product table that I would like to manage in the backoffice.

I have seen that the 1.6 version of Prestoshop had a specific view for that page and that it was pretty simple to add fields to the form. As to the 1.7 I'm going literally crazy, because I cannot find any view that manages the "add product" page.

Any hint? I know that it could probably have something to do with the introduction of Symfony in Prestashop, but I don't get how.

Thanks

EDIT

Solution found here. Great answer: https://stackoverflow.com/a/44861846/1873501

答:
Actually it is related to the Symfony / Twig part, like Module admin controllers, so you have to take a look here :  /src/PrestaShopBundle/Form/Admin/Product

Best way to debug this part is to use debug mode on 1.7 with Symfony bar, you can track what is happening with Twig !

All bundles are stored in ./src/ like in a classic Symfony installation.

Edit : A better way to achieve things would actually to make a module (https://validator.prestashop.com/generator) with displayAdminProductsExtra hook !


问:
Twisted.web.server does not notify if a connection is cancelled by client
The documentation implies that the Deferred at request.notifyFinish() should be notified if the connection drops for any reason.  I loaded similar code below:

```<code>from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import reactor
from twisted.logger import Logger

log = Logger()

class DelayedResource(Resource):
    isLeaf = 1

    def _delayedRender(self, request):
        log.info("Rendered!")
        request.write("<html><body>Sorry to keep you waiting.</body></html>")
        request.finish()

    def _responseFailed(self, err, call):
        call.cancel()
        log.info("No. Wait. Stop")

    def render_GET(self, request):
        log.info("Lets try this!")
        call = reactor.callLater(5, self._delayedRender, request)
        request.notifyFinish().addErrback(self._responseFailed, call)
        return NOT_DONE_YET
</code>```

If I cancel the connection from the client, _responseFailed does not get called. The log statement "No. Wait. Stop" is never printed and the "Rendered!" statement is printed.

This is important, because in my real use case the I am allocating resources that need to be deallocated if the connection drops. After upgrading to twisted 17.1.0, these stopped getting cleaned up.

Am I doing this wrong? Or is this a bug in twisted?

答: This was due to a bug (or an accidentally introduced feature - you be the judge!) introduced by http://tm.tl/8320 but recently fixed by http://tm.tl/8692.  Therefore, Twisted 16.3 through Twisted 17.5 will not fire notifyFinish() with a Failure (though it seems it still fires in the success case).  Due to complexities in the HTTP implementation and the underlying features of TCP, even versions of Twisted outside that range may not always fire notifyFinish() with a Failure in cases where the HTTP client observes some kind of error.  Bear this in mind and make sure that any processing that must occur at the end of a request does not rely on an errback on this Deferred (ie, attach a callback as well or ensure that processing runs as part of the response generation code).

Body:
The documentation implies that the Deferred at request.notifyFinish() should be notified if the connection drops for any reason.  I loaded similar code below:

from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import reactor
from twisted.logger import Logger

log = Logger()

class DelayedResource(Resource):
    isLeaf = 1

    def _delayedRender(self, request):
        log.info("Rendered!")
        request.write("Sorry to keep you waiting.")
        request.finish()

    def _responseFailed(self, err, call):
        call.cancel()
        log.info("No. Wait. Stop")

    def render_GET(self, request):
        log.info("Lets try this!")
        call = reactor.callLater(5, self._delayedRender, request)
        request.notifyFinish().addErrback(self._responseFailed, call)
        return NOT_DONE_YET

If I cancel the connection from the client, _responseFailed does not get called. The log statement "No. Wait. Stop" is never printed and the "Rendered!" statement is printed.

This is important, because in my real use case the I am allocating resources that need to be deallocated if the connection drops. After upgrading to twisted 17.1.0, these stopped getting cleaned up.

Am I doing this wrong? Or is this a bug in twisted?


问:
R crashing when running a for loop
I am a r-beginner and have a code in which I am trying to do the average silhouette method. When I try to run a for loop, R stops with the error: R for Windows GUI front-end has stopped working. The code that I use is:

```<code>data_no_demographics<-read.csv(file.choose(),row.names=1)
data_no_demographics <- na.omit(data_no_demographics)
library(cluster)
k_max<-20
sil<-rep(0,k_max)
for(i in 2:k_max){
  km.res <- kmeans(scale(data_no_demographics), centers = i, nstart = 50)
  ss <- silhouette(km.res$cluster, scale(data_no_demographics))
  sil[i] <- mean(ss[, 3])
}
plot(1:k_max, sil, type = "b", pch = 20,col="black",frame = FALSE, xlab ="Number of clusters (k)", ylab="Average silhouette width (fit of data within its cluster)", main="Optimal number of clusters")
abline(v = which.max(sil), lty = 2, col="red")
</code>```

Any help will be appreciated.

```<code>dput(data_no_demographics[1:4,])
</code>```

Output: (data_structure(list(DRY.FOOD.MEAL.PREPARATION = c(0, 0, 0, 0),BASMATI.RICE =c(0.106274747, 0.086781763, 0.066892377, 0.039564525), JASMINE.RICE = c(0.037947215, 0.101672855, 0.025094901, 0.026354222), ITALIAN.RICE = c(0, 0.006335413, 0, 0), ORG.SIDE.DISHES = c(0, 0, 0, 0), COUSCOUS = c(0.014091056,  0.013493856, 0.009541397, 0.006704727), QUINOA = c(0.013921964, 0.020977683, 0.011593311, 0.006638343), FLAVOURED.RICE = c(0.322163823, 0.225682349, 0.378639581, 0.340580191), INSTANT.RICE = c(0.063184297, 0.044711557, 0.092459218, 0.152615507), PARBOILED.RICE = c(0.065396593, 0.089652796, 0.048548271, 0.032295539), RTH.SPECIALTY = c(0.010371018, 0.011771236, 0.009418283, 0.007833245), RTH.RICE = c(0.307790945,
0.286375991, 0.29621422, 0.336331652), OTHER.RICE = c(0.013020136, 0.019484745, 0.010382682, 0.006737918), REGULAR.DRY.RICE = c(0.045838206, 0.093059756, 0.051215759, 0.044344132), READY.TO.EAT = c(0, 0, 0, 0)), .Names = c("DRY.FOOD.MEAL.PREPARATION", "BASMATI.RICE", "JASMINE.RICE", "ITALIAN.RICE", "ORG.SIDE.DISHES", "COUSCOUS", "QUINOA", "FLAVOURED.RICE", "INSTANT.RICE", "PARBOILED.RICE", "RTH.SPECIALTY", "RTH.RICE", "OTHER.RICE", "REGULAR.DRY.RICE",
"READY.TO.EAT"), row.names = c(1000L, 1004L, 1007L, 1008L), class = "data.frame")

答:
I just had a test run with the data you provided and found some warnings because of the usage of silhouette. Changing silhouette(km.res$cluster, scale(data_no_demographics)) to silhouette(km.res$cluster, dist(data_no_demographics)) removed the warnings.

```<code>data_no_demographics <- data.frame(
  DRY.FOOD.MEAL.PREPARATION = c(0, 0, 0, 0),
  BASMATI.RICE =c(0.106274747, 0.086781763, 0.066892377, 0.039564525),
  JASMINE.RICE = c(0.037947215, 0.101672855, 0.025094901, 0.026354222),
  ITALIAN.RICE = c(0, 0.006335413, 0, 0),
  ORG.SIDE.DISHES = c(0, 0, 0, 0),
  COUSCOUS = c(0.014091056, 0.013493856, 0.009541397, 0.006704727),
  QUINOA = c(0.013921964, 0.020977683, 0.011593311, 0.006638343),
  FLAVOURED.RICE = c(0.322163823, 0.225682349, 0.378639581, 0.340580191),
  INSTANT.RICE = c(0.063184297, 0.044711557, 0.092459218, 0.152615507),
  PARBOILED.RICE = c(0.065396593, 0.089652796, 0.048548271, 0.032295539),
  RTH.SPECIALTY = c(0.010371018, 0.011771236, 0.009418283, 0.007833245),
  RTH.RICE = c(0.307790945, 0.286375991, 0.29621422, 0.336331652),
  OTHER.RICE = c(0.013020136, 0.019484745, 0.010382682, 0.006737918),
  REGULAR.DRY.RICE = c(0.045838206, 0.093059756, 0.051215759, 0.044344132),
  READY.TO.EAT = c(0, 0, 0, 0),
  row.names = c(1000L, 1004L, 1007L, 1008L)
)
# omit columns that are just zeros
data_no_demographics <- data_no_demographics[-c(1,5,15)]

library(cluster)
k_max<-3
sil<-rep(0,k_max)
distance_matrix <- dist(data_no_demographics)
for(i in 2:k_max){
  km.res <- kmeans(scale(data_no_demographics), centers = i, nstart = 1)
  ss <- silhouette(km.res$cluster, distance_matrix)
  sil[i] <- mean(ss[, 3])
}
plot(1:k_max, sil, type = "b", pch = 20,col="black",frame = FALSE,
  xlab ="Number of clusters (k)",
  ylab="Average silhouette width (fit of data within its cluster)",
  main="Optimal number of clusters")
abline(v = which.max(sil), lty = 2, col="red")
</code>```

EDIT

I just moved the computation of the distance matrix (dist) outside of the loop. This should speed up computations if more rows are used.

Title: R crashing when running a for loop

Body:
I am a r-beginner and have a code in which I am trying to do the average silhouette method. When I try to run a for loop, R stops with the error: R for Windows GUI front-end has stopped working. The code that I use is:

data_no_demographics<-read.csv(file.choose(),row.names=1)
data_no_demographics <- na.omit(data_no_demographics)
library(cluster)
k_max<-20
sil<-rep(0,k_max)
for(i in 2:k_max){
  km.res <- kmeans(scale(data_no_demographics), centers = i, nstart = 50)
  ss <- silhouette(km.res$cluster, scale(data_no_demographics))
  sil[i] <- mean(ss[, 3])
}
plot(1:k_max, sil, type = "b", pch = 20,col="black",frame = FALSE, xlab ="Number of clusters (k)", ylab="Average silhouette width (fit of data within its cluster)", main="Optimal number of clusters")
abline(v = which.max(sil), lty = 2, col="red")

Any help will be appreciated.

dput(data_no_demographics[1:4,])

Output: (data_structure(list(DRY.FOOD.MEAL.PREPARATION = c(0, 0, 0, 0),BASMATI.RICE =c(0.106274747, 0.086781763, 0.066892377, 0.039564525), JASMINE.RICE = c(0.037947215, 0.101672855, 0.025094901, 0.026354222), ITALIAN.RICE = c(0, 0.006335413, 0, 0), ORG.SIDE.DISHES = c(0, 0, 0, 0), COUSCOUS = c(0.014091056,  0.013493856, 0.009541397, 0.006704727), QUINOA = c(0.013921964, 0.020977683, 0.011593311, 0.006638343), FLAVOURED.RICE = c(0.322163823, 0.225682349, 0.378639581, 0.340580191), INSTANT.RICE = c(0.063184297, 0.044711557, 0.092459218, 0.152615507), PARBOILED.RICE = c(0.065396593, 0.089652796, 0.048548271, 0.032295539), RTH.SPECIALTY = c(0.010371018, 0.011771236, 0.009418283, 0.007833245), RTH.RICE = c(0.307790945,
0.286375991, 0.29621422, 0.336331652), OTHER.RICE = c(0.013020136, 0.019484745, 0.010382682, 0.006737918), REGULAR.DRY.RICE = c(0.045838206, 0.093059756, 0.051215759, 0.044344132), READY.TO.EAT = c(0, 0, 0, 0)), .Names = c("DRY.FOOD.MEAL.PREPARATION", "BASMATI.RICE", "JASMINE.RICE", "ITALIAN.RICE", "ORG.SIDE.DISHES", "COUSCOUS", "QUINOA", "FLAVOURED.RICE", "INSTANT.RICE", "PARBOILED.RICE", "RTH.SPECIALTY", "RTH.RICE", "OTHER.RICE", "REGULAR.DRY.RICE",
"READY.TO.EAT"), row.names = c(1000L, 1004L, 1007L, 1008L), class = "data.frame")

Body:
I just had a test run with the data you provided and found some warnings because of the usage of silhouette. Changing silhouette(km.res$cluster, scale(data_no_demographics)) to silhouette(km.res$cluster, dist(data_no_demographics)) removed the warnings.

data_no_demographics <- data.frame(
  DRY.FOOD.MEAL.PREPARATION = c(0, 0, 0, 0),
  BASMATI.RICE =c(0.106274747, 0.086781763, 0.066892377, 0.039564525),
  JASMINE.RICE = c(0.037947215, 0.101672855, 0.025094901, 0.026354222),
  ITALIAN.RICE = c(0, 0.006335413, 0, 0),
  ORG.SIDE.DISHES = c(0, 0, 0, 0),
  COUSCOUS = c(0.014091056, 0.013493856, 0.009541397, 0.006704727),
  QUINOA = c(0.013921964, 0.020977683, 0.011593311, 0.006638343),
  FLAVOURED.RICE = c(0.322163823, 0.225682349, 0.378639581, 0.340580191),
  INSTANT.RICE = c(0.063184297, 0.044711557, 0.092459218, 0.152615507),
  PARBOILED.RICE = c(0.065396593, 0.089652796, 0.048548271, 0.032295539),
  RTH.SPECIALTY = c(0.010371018, 0.011771236, 0.009418283, 0.007833245),
  RTH.RICE = c(0.307790945, 0.286375991, 0.29621422, 0.336331652),
  OTHER.RICE = c(0.013020136, 0.019484745, 0.010382682, 0.006737918),
  REGULAR.DRY.RICE = c(0.045838206, 0.093059756, 0.051215759, 0.044344132),
  READY.TO.EAT = c(0, 0, 0, 0),
  row.names = c(1000L, 1004L, 1007L, 1008L)
)
# omit columns that are just zeros
data_no_demographics <- data_no_demographics[-c(1,5,15)]

library(cluster)
k_max<-3
sil<-rep(0,k_max)
distance_matrix <- dist(data_no_demographics)
for(i in 2:k_max){
  km.res <- kmeans(scale(data_no_demographics), centers = i, nstart = 1)
  ss <- silhouette(km.res$cluster, distance_matrix)
  sil[i] <- mean(ss[, 3])
}
plot(1:k_max, sil, type = "b", pch = 20,col="black",frame = FALSE,
  xlab ="Number of clusters (k)",
  ylab="Average silhouette width (fit of data within its cluster)",
  main="Optimal number of clusters")
abline(v = which.max(sil), lty = 2, col="red")

EDIT

I just moved the computation of the distance matrix (dist) outside of the loop. This should speed up computations if more rows are used.


问:
Creating URLs in php
I have a basic understanding on PHP. My question is, i'm developing my first project and my sample directory structure is [localhost/plugins/feed/index.php]. In accessing index.php in /plugins/feed/index.php file, I need at the browser address bar the Url to be localhost/feed instead of localhost/plugins/feed/index.php
Please i need your help</p>

答:
Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

```<code>Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^ plugins/(.*)$ /$1 [L,NC,R]
</code>```

Explanation: Above rules is matching URL patter that starts with plugins and have somthing like /plugins/feed/index.php and puts feed/index.php in $1. It makes an external redirection to /$1 i.e. /feed/index.php.

As server automatically loads index.php file so you don't need to worry about that. Which means, localhost/feed is equal to localhost/feed/index.php

These are the flags used:

```<code>L  - Last
NC - Ignore (No) Case comparison
R  - External redirection (with 302) -- can be changed to R=301
</code>```

For more information about .htaccess

Title: Creating URLs in php

Body:
Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^ plugins/(.*)$ /$1 [L,NC,R]

Explanation: Above rules is matching URL patter that starts with plugins and have somthing like /plugins/feed/index.php and puts feed/index.php in $1. It makes an external redirection to /$1 i.e. /feed/index.php.

As server automatically loads index.php file so you don't need to worry about that. Which means, localhost/feed is equal to localhost/feed/index.php

These are the flags used:

L  - Last
NC - Ignore (No) Case comparison
R  - External redirection (with 302) -- can be changed to R=301

For more information about .htaccess


问:
pass value to next page
I have a php page (search.php) which has a link to another php page. (reserve.php). I want to

```<code>  1. pass the link text to the next page
  2. display that link text in a input box
</code>```

Please tell me how should I write the proper coding for the above tasks.

search.php

```<code><a href="Reserve.php"><?php echo $row['AccNo'];?></a>
</code>```

答:
Your Search.php have

">Go to Reserve Page

Now On Reserve.php
Get that AccNo using GET

$AccNo=$_GET['AccNo'];

and then just echo the $AccNo Variable in your Input Text field

<input type="text" value="<?php echo $AccNo; ?>" >

Hope this helps

Title: pass value to next page

Body:
I have a php page (search.php) which has a link to another php page. (reserve.php). I want to

  1. pass the link text to the next page
  2. display that link text in a input box

Please tell me how should I write the proper coding for the above tasks.

search.php

<?php echo $row['AccNo'];?>

Body:
Your Search.php have

<a href="Reserve.php?AccNo=<?php echo $row['AccNo']; ?>">Go to Reserve Page</a>

Now On Reserve.php
Get that AccNo using GET

$AccNo=$_GET['AccNo'];

and then just echo the $AccNo Variable in your Input Text field

<input type="text" value="<?php echo $AccNo; ?>" >

Hope this helps


问:
What SQL magic do I need to turn one column into several?
I need to print some tickets, each of which has enough room to hold one set of customer details along with codes for up to five items ordered by that customer. Customers who have ordered more than five items get multiple tickets. So from an orders table like this,

```
Customer | Item
---------|------
Bob      | FTMCH
Bob      | ZORP
Bob      | KLUGE
Carol    | FTMCH
Carol    | MEEP
Carol    | ZORP
Ted      | FOON
Ted      | SMOCK
Alice    | ORGO
Carol    | SQICK
Carol    | BLECH
Carol    | KLUGE
Carol    | GLURP
```

I need a query that returns this:

```
Customer | Item1 | Item2 | Item3 | Item4 | Item5
---------|-------|-------|-------|-------|------
Alice    | ORGO  | null  | null  | null  | null
Bob      | FTMCH | ZORP  | KLUGE | null  | null
Carol    | FTMCH | MEEP  | ZORP  | SQICK | BLECH
Carol    | KLUGE | GLURP | null  | null  | null
Ted      | FOON  | SMOCK | null  | null  | null
```

Can some kind soul help me with the SQL for this? HSQL embedded database in OpenOffice.org Base, if it makes a difference.

答:
OK, this works well enough:

```
SELECT
    "Customer",
    MAX(CASE WHEN "Slot" = 0 THEN "Item" END) AS "Item1",
    MAX(CASE WHEN "Slot" = 1 THEN "Item" END) AS "Item2",
    MAX(CASE WHEN "Slot" = 2 THEN "Item" END) AS "Item3",
    MAX(CASE WHEN "Slot" = 3 THEN "Item" END) AS "Item4",
    MAX(CASE WHEN "Slot" = 4 THEN "Item" END) AS "Item5"
FROM (
    SELECT
        l."Customer" AS "Customer",
        l."Item" AS "Item",
        COUNT(r."Item") / 5 AS "Ticket",
        MOD(COUNT(r."Item"), 5) AS "Slot"
    FROM "Orders" AS l
    LEFT JOIN "Orders" AS r
    ON r."Customer" = l."Customer" AND r."Item" < l."Item"
    GROUP BY "Customer", "Item"
)
GROUP BY "Customer", "Ticket"
ORDER BY "Customer", "Ticket"
```

It makes this:

```
Customer | Item1 | Item2 | Item3 | Item4 | Item5
---------|-------|-------|-------|-------|-------
Alice    | ORGO  |       |       |       |
Bob      | FTMCH | KLUGE | ZORP  |       |
Carol    | BLECH | FTMCH | GLURP | KLUGE | MEEP
Carol    | SQICK | ZORP  |       |       |
Ted      | FOON  | SMOCK |       |       |
```

Thanks to all who helped, both here and at Ask Metafilter.

(Followup edit:)

Jesus, this just gets worse :-(

Turns out the business rules allow the same customer to order the same item on multiple occasions, and that all outstanding orders are to be included on the one set of tickets. So my toy table should have looked more like this:

```
ID  | Customer | Item
159 | Bob      | FTMCH
264 | Bob      | ZORP
265 | Bob      | KLUGE
288 | Carol    | FTMCH
314 | Carol    | MEEP
323 | Carol    | ZORP
327 | Ted      | FOON
338 | Ted      | SMOCK
358 | Alice    | ORGO
419 | Carol    | SQICK
716 | Carol    | MEEP
846 | Carol    | BLECH
939 | Carol    | MEEP
950 | Carol    | GLURP
979 | Carol    | KLUGE
```

Carol's multiple MEEPs bugger the ranking logic in the original solution, and I've ended up with the following hideous monster:

```
SELECT
    "Customer",
    MAX(CASE WHEN "Slot" = 0 THEN "Item" END) AS "Item0",
    MAX(CASE WHEN "Slot" = 1 THEN "Item" END) AS "Item1",
    MAX(CASE WHEN "Slot" = 2 THEN "Item" END) AS "Item2",
    MAX(CASE WHEN "Slot" = 3 THEN "Item" END) AS "Item3",
    MAX(CASE WHEN "Slot" = 4 THEN "Item" END) AS "Item4",
    MAX(CASE WHEN "Slot" = 0 THEN "Quantity" END) AS "Qty0",
    MAX(CASE WHEN "Slot" = 1 THEN "Quantity" END) AS "Qty1",
    MAX(CASE WHEN "Slot" = 2 THEN "Quantity" END) AS "Qty2",
    MAX(CASE WHEN "Slot" = 3 THEN "Quantity" END) AS "Qty3",
    MAX(CASE WHEN "Slot" = 4 THEN "Quantity" END) AS "Qty4"
FROM (
    SELECT
        "Customer",
        "Item",
        COUNT("ID") AS "Quantity",
        "Rank" / 5 AS "Ticket",
        MOD("Rank", 5) AS "Slot"
    FROM (
        SELECT
            main."ID" AS "ID",
            main."Customer" AS "Customer",
            main."Item" AS "Item",
            COUNT(less."Item") AS "Rank"
        FROM "Orders" AS main
        LEFT JOIN (
            SELECT DISTINCT
                "Customer",
                "Item"
            FROM "Orders") AS less
        ON less."Customer" = main."Customer" AND less."Item" < main."Item"
        GROUP BY "ID", "Customer", "Item"
    )
    GROUP BY "Customer", "Item", "Rank"
)
GROUP BY "Customer", "Ticket"
```

which makes this:

```
Customer | Item0 | Item1 | Item2 | Item3 | Item4 | Qty0 | Qty1 | Qty2 | Qty3 | Qty3 | Qty4
Bob      | FTMCH | KLUGE | ZORP  |       |       | 1    | 1    | 1    |      |      |
Carol    | BLECH | FTMCH | GLURP | KLUGE | MEEP  | 1    | 1    | 1    | 1    | 1    | 3
Carol    | SQICK | ZORP  |       |       |       | 1    | 1    |      |      |      |
Ted      | FOON  | SMOCK |       |       |       | 1    | 1    |      |      |      |
Alice    | ORGO  |       |       |       |       | 1    |      |      |      |      |
```

It does the job, I guess, but I'm feeling pretty lucky that the database involved is always going to be quite small (a few thousand rows).

Spiritually I'm an embedded-systems guy, not a database guy. Can anybody who does this for a living tell me whether this kind of nonsense is common? Would a query with four nested SELECTs and a LEFT JOIN merit a mention on the Daily WTF?

Body:
I need to print some tickets, each of which has enough room to hold one set of customer details along with codes for up to five items ordered by that customer. Customers who have ordered more than five items get multiple tickets. So from an orders table like this,

Customer | Item
---------|------
Bob      | FTMCH
Bob      | ZORP
Bob      | KLUGE
Carol    | FTMCH
Carol    | MEEP
Carol    | ZORP
Ted      | FOON
Ted      | SMOCK
Alice    | ORGO
Carol    | SQICK
Carol    | BLECH
Carol    | KLUGE
Carol    | GLURP

I need a query that returns this:

Customer | Item1 | Item2 | Item3 | Item4 | Item5
---------|-------|-------|-------|-------|------
Alice    | ORGO  | null  | null  | null  | null
Bob      | FTMCH | ZORP  | KLUGE | null  | null
Carol    | FTMCH | MEEP  | ZORP  | SQICK | BLECH
Carol    | KLUGE | GLURP | null  | null  | null
Ted      | FOON  | SMOCK | null  | null  | null

Can some kind soul help me with the SQL for this? HSQL embedded database in OpenOffice.org Base, if it makes a difference.

Body:
OK, this works well enough:

SELECT
    "Customer",
    MAX(CASE WHEN "Slot" = 0 THEN "Item" END) AS "Item1",
    MAX(CASE WHEN "Slot" = 1 THEN "Item" END) AS "Item2",
    MAX(CASE WHEN "Slot" = 2 THEN "Item" END) AS "Item3",
    MAX(CASE WHEN "Slot" = 3 THEN "Item" END) AS "Item4",
    MAX(CASE WHEN "Slot" = 4 THEN "Item" END) AS "Item5"
FROM (
    SELECT
        l."Customer" AS "Customer",
        l."Item" AS "Item",
        COUNT(r."Item") / 5 AS "Ticket",
        MOD(COUNT(r."Item"), 5) AS "Slot"
    FROM "Orders" AS l
    LEFT JOIN "Orders" AS r
    ON r."Customer" = l."Customer" AND r."Item" < l."Item"
    GROUP BY "Customer", "Item"
)
GROUP BY "Customer", "Ticket"
ORDER BY "Customer", "Ticket"

It makes this:

Customer | Item1 | Item2 | Item3 | Item4 | Item5
---------|-------|-------|-------|-------|-------
Alice    | ORGO  |       |       |       |
Bob      | FTMCH | KLUGE | ZORP  |       |
Carol    | BLECH | FTMCH | GLURP | KLUGE | MEEP
Carol    | SQICK | ZORP  |       |       |
Ted      | FOON  | SMOCK |       |       |

Thanks to all who helped, both here and at Ask Metafilter.

(Followup edit:)

Jesus, this just gets worse :-(

Turns out the business rules allow the same customer to order the same item on multiple occasions, and that all outstanding orders are to be included on the one set of tickets. So my toy table should have looked more like this:

ID  | Customer | Item
159 | Bob      | FTMCH
264 | Bob      | ZORP
265 | Bob      | KLUGE
288 | Carol    | FTMCH
314 | Carol    | MEEP
323 | Carol    | ZORP
327 | Ted      | FOON
338 | Ted      | SMOCK
358 | Alice    | ORGO
419 | Carol    | SQICK
716 | Carol    | MEEP
846 | Carol    | BLECH
939 | Carol    | MEEP
950 | Carol    | GLURP
979 | Carol    | KLUGE

Carol's multiple MEEPs bugger the ranking logic in the original solution, and I've ended up with the following hideous monster:

SELECT
    "Customer",
    MAX(CASE WHEN "Slot" = 0 THEN "Item" END) AS "Item0",
    MAX(CASE WHEN "Slot" = 1 THEN "Item" END) AS "Item1",
    MAX(CASE WHEN "Slot" = 2 THEN "Item" END) AS "Item2",
    MAX(CASE WHEN "Slot" = 3 THEN "Item" END) AS "Item3",
    MAX(CASE WHEN "Slot" = 4 THEN "Item" END) AS "Item4",
    MAX(CASE WHEN "Slot" = 0 THEN "Quantity" END) AS "Qty0",
    MAX(CASE WHEN "Slot" = 1 THEN "Quantity" END) AS "Qty1",
    MAX(CASE WHEN "Slot" = 2 THEN "Quantity" END) AS "Qty2",
    MAX(CASE WHEN "Slot" = 3 THEN "Quantity" END) AS "Qty3",
    MAX(CASE WHEN "Slot" = 4 THEN "Quantity" END) AS "Qty4"
FROM (
    SELECT
        "Customer",
        "Item",
        COUNT("ID") AS "Quantity",
        "Rank" / 5 AS "Ticket",
        MOD("Rank", 5) AS "Slot"
    FROM (
        SELECT
            main."ID" AS "ID",
            main."Customer" AS "Customer",
            main."Item" AS "Item",
            COUNT(less."Item") AS "Rank"
        FROM "Orders" AS main
        LEFT JOIN (
            SELECT DISTINCT
                "Customer",
                "Item"
            FROM "Orders") AS less
        ON less."Customer" = main."Customer" AND less."Item" < main."Item"
        GROUP BY "ID", "Customer", "Item"
    )
    GROUP BY "Customer", "Item", "Rank"
)
GROUP BY "Customer", "Ticket"

which makes this:

Customer | Item0 | Item1 | Item2 | Item3 | Item4 | Qty0 | Qty1 | Qty2 | Qty3 | Qty3 | Qty4
Bob      | FTMCH | KLUGE | ZORP  |       |       | 1    | 1    | 1    |      |      |
Carol    | BLECH | FTMCH | GLURP | KLUGE | MEEP  | 1    | 1    | 1    | 1    | 1    | 3
Carol    | SQICK | ZORP  |       |       |       | 1    | 1    |      |      |      |
Ted      | FOON  | SMOCK |       |       |       | 1    | 1    |      |      |      |
Alice    | ORGO  |       |       |       |       | 1    |      |      |      |      |

It does the job, I guess, but I'm feeling pretty lucky that the database involved is always going to be quite small (a few thousand rows).

Spiritually I'm an embedded-systems guy, not a database guy. Can anybody who does this for a living tell me whether this kind of nonsense is common? Would a query with four nested SELECTs and a LEFT JOIN merit a mention on the Daily WTF?