问:
How to trigger a late import of another module only when a certain object is needed from my module?

The Situation

I want to have a module that roughly works like the following:

```<code># my_module.py

my_number = 17

from other_module import foo
my_object = foo(23)
</code>```

However, there is a problem: Installing other_module causes problems for some users and is only required for those who want to use my_object – which in turn is only a small fraction of users. I want to spare those users who do not need my_object from installing other_module.

I therefore want the import of other_module to happen only if my_object is imported from my_module. With other words, the user should be able to run the following without having installed other_module:

```<code>from my_module import my_number
</code>```

My best solution so far

I could provide my_object via a function that contains the import:

```<code># in my_module.py

def get_my_object():
    from other_module import foo
    my_object = foo(23)
    return my_object
</code>```

The user would then have to do something like:

```<code>from my_module import get_my_object
my_object = get_my_object()
</code>```

Question

Is there a better way to conditionally trigger the import of other_module? I am mostly interested in keeping things as simple as possible for the users.

答:
This is a common hack to be done:

```<code>import sys

class MockModule:
    def __init__(self, module):
        self.module = module

    def __getattr__(self, attr):
        if attr == 'dependency_required_var':
            try:
                import foo
                return self.module.dependency_required_var
            except ImportError:
                raise Exception('foo library is required to use dependency_required_var')
        else:
            return getattr(self.module, attr)

MockModule.__name__ = __name__
sys.modules[__name__] = MockModule(sys.modules[__name__])

dependency_required_var = 0
</code>```

With this PEP, we can simply do (we should be able to but I couldn't get it to work) the following in Python 3.7 and higher:

```<code>def __getattr__(attr):
    if attr == 'dependency_required_var':
        try:
            import foo
            return dependency_required_var
        except ImportError:
            raise Exception('foo library is required to use dependency_required_var')
    else:
        return globals()[attr]
</code>```

The PEP seems to be accepted, but the relevant pull request from the PEP seems to be closed, I'm actually not sure if it has been implemented or not.

Body:
The Situation

I want to have a module that roughly works like the following:

# my_module.py

my_number = 17

from other_module import foo
my_object = foo(23)

However, there is a problem: Installing other_module causes problems for some users and is only required for those who want to use my_object – which in turn is only a small fraction of users. I want to spare those users who do not need my_object from installing other_module.

I therefore want the import of other_module to happen only if my_object is imported from my_module. With other words, the user should be able to run the following without having installed other_module:

from my_module import my_number

My best solution so far

I could provide my_object via a function that contains the import:

# in my_module.py

def get_my_object():
    from other_module import foo
    my_object = foo(23)
    return my_object

The user would then have to do something like:

from my_module import get_my_object
my_object = get_my_object()

Question

Is there a better way to conditionally trigger the import of other_module? I am mostly interested in keeping things as simple as possible for the users.

Body:
This is a common hack to be done:

import sys

class MockModule:
    def __init__(self, module):
        self.module = module

    def __getattr__(self, attr):
        if attr == 'dependency_required_var':
            try:
                import foo
                return self.module.dependency_required_var
            except ImportError:
                raise Exception('foo library is required to use dependency_required_var')
        else:
            return getattr(self.module, attr)

MockModule.__name__ = __name__
sys.modules[__name__] = MockModule(sys.modules[__name__])

dependency_required_var = 0

With this PEP, we can simply do (we should be able to but I couldn't get it to work) the following in Python 3.7 and higher:

def __getattr__(attr):
    if attr == 'dependency_required_var':
        try:
            import foo
            return dependency_required_var
        except ImportError:
            raise Exception('foo library is required to use dependency_required_var')
    else:
        return globals()[attr]

The PEP seems to be accepted, but the relevant pull request from the PEP seems to be closed, I'm actually not sure if it has been implemented or not.


来源: stackexchange

问:
Checking multiple array elements and return true if all matched
I wanted to find if all emement of below array matched to each other:

```<code>val a = Array(1,1,1)
val b = Array(1,0,1)
val c = Array(0,1,1)

</code>```

here output should be

```<code>Array(0,0,1)
</code>```

as all the value of a(2),b(2) and c(2) is 1 however for all cases it's 0. Is there any functional way of solving this in Scala?

答:
If the arrays are all the same size, then one approach is to transpose the arrays, then map-and-reduce the result with Java's bitwise AND operator &:

```<code>val a = Array(1, 1, 1)
val b = Array(1, 0, 1)
val c = Array(0, 1, 1)

val result = Array(a, b, c).transpose.map(_.reduce(_ & _)) // Array(0, 0, 1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wanted to find if all emement of below array matched to each other:

val a = Array(1,1,1)
val b = Array(1,0,1)
val c = Array(0,1,1)

here output should be

Array(0,0,1)

as all the value of a(2),b(2) and c(2) is 1 however for all cases it's 0. Is there any functional way of solving this in Scala?

Body:
If the arrays are all the same size, then one approach is to transpose the arrays, then map-and-reduce the result with Java's bitwise AND operator &:

val a = Array(1, 1, 1)
val b = Array(1, 0, 1)
val c = Array(0, 1, 1)

val result = Array(a, b, c).transpose.map(_.reduce(_ & _)) // Array(0, 0, 1)


问:
Finding and running a file
I am creating a script where it searches through a bunch of nested folders to find the newest version of a software, which are in .msi form. My code currently can find the file and output it, but is not able to run the file.

I can use Select in the last line for the ForEach to output the correct file but when I change it to Start-Process, I get bombarded by errors.

```<code> $path="S:\\Releases\\Program"
 $NoOfDirs=Get-ChildItem $path -Directory

 ForEach($dir in $NoOfDirs){
     Get-ChildItem  "$path\$($dir.name)" -File -Recurse |
     Where-Object {$_.LastWriteTime -gt ([DateTime]::Now.Adddays(-1))} |
     Select-Object @{l='Folder';e={$dir.Name}},Name,LastWriteTime |
     Sort-Object  -pro LastWriteTime -Descending |
     Start-Process -First 1
 }
</code>```

Is there a different command I should be using when running .msi files?

答:
Since your code has to "search through a bunch of nested folders", I'd recommend using the -Recurse switch on Get-ChildItem.
Also use the -Filter parameter to have the search limited to .MSI files.

Something like this:

```<code>$path    = "S:\Releases\Program"
$refDate = (Get-Date).Adddays(-1)

Get-ChildItem -Path $path -Filter '*.msi' -File -Recurse |
    Where-Object {$_.LastWriteTime -gt $refDate} |
    ForEach-Object {
        # create the arguments for msiexec.exe.
        # to find out more switches, open a commandbox and type msiexec /?
        $msiArgs  = '/i', ('"{0}"' -f $_.FullName), '/qn', '/norestart'
        $exitCode = Start-Process 'msiexec.exe' -ArgumentList $msiArgs -NoNewWindow -Wait -PassThru
        if ($exitCode -ne 0) {
            # something went wrong. see http://www.msierrors.com/tag/msiexec-return-codes/
            # to find out what the error was.
            Write-Warning "MsiExec.exe returned error code $exitCode"
        }
    }
</code>```

Title: Finding and running a file

Body:
I am creating a script where it searches through a bunch of nested folders to find the newest version of a software, which are in .msi form. My code currently can find the file and output it, but is not able to run the file.

I can use Select in the last line for the ForEach to output the correct file but when I change it to Start-Process, I get bombarded by errors.

 $path="S:\\Releases\\Program"
 $NoOfDirs=Get-ChildItem $path -Directory

 ForEach($dir in $NoOfDirs){
     Get-ChildItem  "$path\$($dir.name)" -File -Recurse |
     Where-Object {$_.LastWriteTime -gt ([DateTime]::Now.Adddays(-1))} |
     Select-Object @{l='Folder';e={$dir.Name}},Name,LastWriteTime |
     Sort-Object  -pro LastWriteTime -Descending |
     Start-Process -First 1
 }

Is there a different command I should be using when running .msi files?

Body:
Since your code has to "search through a bunch of nested folders", I'd recommend using the -Recurse switch on Get-ChildItem.
Also use the -Filter parameter to have the search limited to .MSI files.

Something like this:

$path    = "S:\Releases\Program"
$refDate = (Get-Date).Adddays(-1)

Get-ChildItem -Path $path -Filter '*.msi' -File -Recurse |
    Where-Object {$_.LastWriteTime -gt $refDate} |
    ForEach-Object {
        # create the arguments for msiexec.exe.
        # to find out more switches, open a commandbox and type msiexec /?
        $msiArgs  = '/i', ('"{0}"' -f $_.FullName), '/qn', '/norestart'
        $exitCode = Start-Process 'msiexec.exe' -ArgumentList $msiArgs -NoNewWindow -Wait -PassThru
        if ($exitCode -ne 0) {
            # something went wrong. see http://www.msierrors.com/tag/msiexec-return-codes/
            # to find out what the error was.
            Write-Warning "MsiExec.exe returned error code $exitCode"
        }
    }


问:
Confused about debounce function in javascript and " Cannot read property 'clientX' of undefined"
I'm trying to learn to implement debouncing in javascript, however I got an error of "Uncaught TypeError: Cannot read property 'clientX' of undefined". May I know how to fix it?

Also, I'm still so confused about:

```<code>function debounce (func, wait) {
  var timeoutID;
  return function () {
    clearTimeout(timeoutID);
    timeoutID = setTimeout(func, wait);
  }
}
</code>```

I know the main idea of debounce is to trigger the function when we haven't move the mouse for 2 seconds, if we moved inside the 2 seconds, the counter will be clear and re count from the start again, but I'm still confused about the code. Why we set the timeoutID variable at the beginning of the function? How does this be identified as the timeoutID we set inside the returned function? why we then "return" the timer function?
When it's first called, var timeoutID just initiate this variable with no value, then how can the clearTimeout(timeoutID) use this variable with no value?
Thank you so much!

```<code>function debounce (func, wait) {
  var timeoutID;
  return function () {
    clearTimeout(timeoutID);
    timeoutID = setTimeout(func, wait);
  }
}
function test(e) {
  console.log(e.clientX);
}

document.addEventListener('mousemove', debounce(test,2000));
</code>```

答:
You need to make sure to call the callback with the arguments the event gets.  So it is transparent to the event handler if it was called directly or from a debounce.

function debounce (callback, delay) {
  var timeout;

  return function () {
    var originalArguments = arguments;

    clearTimeout(timeout);
    timeout = setTimeout(() => callback.apply(this, originalArguments), delay);
  }
}

function test(e) {
  console.log(this);
  console.log(e.target);
}

document.getElementById('thing').addEventListener('click', debounce(test, 2000));```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Click Me Repeatedly</code>```

Body:
I'm trying to learn to implement debouncing in javascript, however I got an error of "Uncaught TypeError: Cannot read property 'clientX' of undefined". May I know how to fix it?

Also, I'm still so confused about:

function debounce (func, wait) {
  var timeoutID;
  return function () {
    clearTimeout(timeoutID);
    timeoutID = setTimeout(func, wait);
  }
}

I know the main idea of debounce is to trigger the function when we haven't move the mouse for 2 seconds, if we moved inside the 2 seconds, the counter will be clear and re count from the start again, but I'm still confused about the code. Why we set the timeoutID variable at the beginning of the function? How does this be identified as the timeoutID we set inside the returned function? why we then "return" the timer function?
When it's first called, var timeoutID just initiate this variable with no value, then how can the clearTimeout(timeoutID) use this variable with no value?
Thank you so much!

function debounce (func, wait) {
  var timeoutID;
  return function () {
    clearTimeout(timeoutID);
    timeoutID = setTimeout(func, wait);
  }
}
function test(e) {
  console.log(e.clientX);
}

document.addEventListener('mousemove', debounce(test,2000));

Body:
You need to make sure to call the callback with the arguments the event gets.  So it is transparent to the event handler if it was called directly or from a debounce.

function debounce (callback, delay) {
  var timeout;

  return function () {
    var originalArguments = arguments;

    clearTimeout(timeout);
    timeout = setTimeout(() => callback.apply(this, originalArguments), delay);
  }
}

function test(e) {
  console.log(this);
  console.log(e.target);
}

document.getElementById('thing').addEventListener('click', debounce(test, 2000));

<a href="#" id="thing" data-thing="test">Click Me Repeatedly</a>


问:
LZ complexity algorithm
Could you please explain me the thing: how does LZ complexity algorithm incorporate with data compression? Does it (or meant to) compress data or it only estimates the number of unique substrings in vocabulary?

Thanks!

答: You can calculate LZ complexity without actually doing any compression, although the calculation will look a lot like what happens when LZ-compressing the input data. See, e.g., calculating Lempel-Ziv (LZ) complexity (aka sequence complexity) of a binary string where one of the answers has (non-compressing) code for calculating LZ complexity.</p>

ContentLicense: CC BY-SA 3.0

Title: LZ complexity algorithm


问:
Github pages still shows README after deploying React app
I have a create-react-app project (https://github.com/khpeek/beomaps/tree/master) which I'd like to deploy to Github pages using gh-pages. Following this tutorial, https://medium.com/@serverlessguru/deploy-reactjs-app-with-s3-static-hosting-f640cb49d7e6, I've added the following to my package.json:

However, if I run npm run deploy, it is published,

but the Github page, https://khpeek.github.io/beomaps/, still shows default content based on the README.md. Do I perhaps need to change the deploy directory?

答:
In the Options page of the repository, I had to select the gh-pages branch instead of the master branch:

(I also re-installed gh-pages as a normal dependency, not a development one (i.e. npm install gh-pages --save instead of npm install gh-pages --save-dev), though I'm not sure whether this was important).

Now the page is visible on Github pages:


问:
How to send an automated message to a skype group chat using python
Even though i am able to send messages to an individual skype contact using skpy module. i am unable to send to a group chat.

Below is the simple code i've used to send:

```<code>from skpy import Skype
sk = Skype("myskypeID", "pwd") # connect to Skype
content="the message i wanna send"
ch = sk.contacts["SkypeID_in_contacts"].chat
ch.sendMsg(content)
</code>```

I cannot find any skype group ID for my group chats. Is there anyway of finding a skype group ID or some other method to append with python code i have used.
Please help

答:
All Group Chart in Skype have an ID like

```<code>19:<random>@thread.skype
</code>```

Here you can find a simple script to found all your groups IDs
How to get Skype Group Chat ID

End then you can found your chat with that id

```<code>ch = sk.chats["19:0b85483d2d634415993bb9daf58e7891@thread.skype"]
ch.sendMsg(msg)
</code>```

Body:
Even though i am able to send messages to an individual skype contact using skpy module. i am unable to send to a group chat.

Below is the simple code i've used to send:

from skpy import Skype
sk = Skype("myskypeID", "pwd") # connect to Skype
content="the message i wanna send"
ch = sk.contacts["SkypeID_in_contacts"].chat
ch.sendMsg(content)

I cannot find any skype group ID for my group chats. Is there anyway of finding a skype group ID or some other method to append with python code i have used.
Please help

Body:
All Group Chart in Skype have an ID like

19:<random>@thread.skype

Here you can find a simple script to found all your groups IDs
How to get Skype Group Chat ID

End then you can found your chat with that id

ch = sk.chats["19:0b85483d2d634415993bb9daf58e7891@thread.skype"]
ch.sendMsg(msg)


问:
How to export csv in CanvasJS in Javascript?
I want to load a csv file to my html file to plot some data.
I have figured out how to plot in html but the next challenge is to import data from a csv file. I am new to html and javascript and would appreciate inputs or even other modules aside from CanvasJS.</p>

```<code><!DOCTYPE HTML>
<html>
<head>
<meta charset ="UTF-8">
<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    theme: "light2",
    title:{
        text: "DOE TEST Chart"
    },
    axisY:{
        includeZero: false
    },
    data: [{
        type: "line",
        dataPoints: dataPoints
    }]
});

$.get("file:////C:/Users/TestDev/Documents/html_files/js_plots/Sample/zpw.csv", getDataPointsFromCSV);

function getDataPointsFromCSV(csv) {
        var csvLines = points = [];
        csvLines = csv.split(/[\r?\n]\r|\n]+/);
        for (var i = 0; i < csvLines.length; i++) {
                if (csvLines[i].length > 0){
                        points = csvLines[i].split(",");
                        dataPoints.push({
                                label: points[0],
                                y: parseFloat(points[1])
                        });

                }
        }
        chart.render();
}

}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; max-width: 920px; margin: 0px auto;"></div>
<script src="../../canvasjs.min.js"></script>
</body>
</html>

</code>```

答: Try moving the Sample folder containing the csv file into your project and use a relative url like "Sample/zpw.csv"</p>

Body:
I want to load a csv file to my html file to plot some data.
I have figured out how to plot in html but the next challenge is to import data from a csv file. I am new to html and javascript and would appreciate inputs or even other modules aside from CanvasJS.

<!DOCTYPE HTML>

<meta charset ="UTF-8">


问:
Azure ARM template - set application settings and diagnostic log setitngs
I ran into an issue running arm template for an app service where II want to configure application settings and diagnostic log settings.

```<code>{

            "type": "Microsoft.Web/sites",
            "name": "[parameters('azureWebsiteName')]",
            "apiVersion": "[variables('appServiceApiVersion')]",
            "location": "[variables('location')]",
            "tags": {
                "Solution": "[parameters('solutionType')]",
                "Sku": "[parameters('solutionSku')]"
            },
            "properties": {
                "enabled": true,
                "clientAffinityEnabled": false,
                "serverFarmId": "[variables('hostingPlanName')]",
                "siteConfig": {
                    "alwaysOn": true,
                    "siteAuthEnabled": true,
                    "siteAuthSettings": {
                        "clientId": "[parameters('aadClientId')]",
                        "clientSecret": "[parameters('aadClientSecret')]",
                        "unauthenticatedClientAction": "[parameters('apiSiteUnauthenticatedClientAction')]",
                        "defaultProvider": "[parameters('apiSiteDefaultProvider')]",
                        "allowedAudiences": [
                            "[parameters('aadAppIdUri')]"
                        ]
                    },
                    "appSettings": [ ]
                }
            },
            "identity": {
                "type": "SystemAssigned"
            },
            "dependsOn": [
                "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
            ],
            "resources": [
                {
                    "type": "config",
                    "name": "appsettings",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                        "[resourceId('Microsoft.Web/sites/config/', parameters('azureWebsiteName'), 'logs')]",
                        "[resourceId('microsoft.insights/components/', parameters('appInsightsName'))]",
                        "Microsoft.ApplicationInsights.AzureWebSites",
                        "[resourceId('Microsoft.KeyVault/vaults/', parameters('keyVaultName'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), variables('storageAccountConnectionString'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), variables('documentDBAccessKey'))]"
                    ],
                    "properties": {
                        "AzureWebJobsStorage": "[concat('@Microsoft.KeyVault(SecretUri=', reference(variables('storageAccountConnectionString')).secretUriWithVersion, ')')]"
                }
                },
                {
                    "type": "config",
                    "name": "logs",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                        "[resourceId('Microsoft.Storage/storageAccounts/', parameters('storageName'))]",
                        "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('appLogsContainerName'))]",
                        "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('webServerLogsContainerName'))]"
                    ],
                    "properties": {
                        "httpLogs": {
                            "azureBlobStorage": {
                                "sasUrl": "[concat('https://',parameters('storageName'),'.blob.core.windows.net/',variables('webServerLogsContainerName'),'?',listServiceSas(parameters('storageName'), '2018-11-01', variables('webServerLogsSasProperties')).serviceSasToken)]",
                                "retentionInDays": "[parameters('diagnosticsLogsRetentionInDays')]",
                                "enabled": true
                            }
                        },
                        "failedRequestsTracing": {
                            "enabled": true
                        },
                        "detailedErrorMessages": {
                            "enabled": true
                        }
                    }
                },
                {
                    "type": "siteextensions",
                    "name": "Microsoft.ApplicationInsights.AzureWebSites",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/Sites', parameters('azureWebsiteName'))]"
                    ],
                    "properties": {}
                }
            ]
        }
</code>```

The problem is when I deploy this, the logs config is set temporarily set then somehow gets un-set.
I believe it has something to do with multiple config objects(one for app-settings and one for logs) f I were to remove the app-settings config, the logs are correctly set and remain set.

Can someone help me understand what is happening?
Thanks!

答:
Just merge properties of both configs into a single entity and apply that entity and it would work.

This happens because you overwrite the first write with the second write.

Body:
I ran into an issue running arm template for an app service where II want to configure application settings and diagnostic log settings.

{

            "type": "Microsoft.Web/sites",
            "name": "[parameters('azureWebsiteName')]",
            "apiVersion": "[variables('appServiceApiVersion')]",
            "location": "[variables('location')]",
            "tags": {
                "Solution": "[parameters('solutionType')]",
                "Sku": "[parameters('solutionSku')]"
            },
            "properties": {
                "enabled": true,
                "clientAffinityEnabled": false,
                "serverFarmId": "[variables('hostingPlanName')]",
                "siteConfig": {
                    "alwaysOn": true,
                    "siteAuthEnabled": true,
                    "siteAuthSettings": {
                        "clientId": "[parameters('aadClientId')]",
                        "clientSecret": "[parameters('aadClientSecret')]",
                        "unauthenticatedClientAction": "[parameters('apiSiteUnauthenticatedClientAction')]",
                        "defaultProvider": "[parameters('apiSiteDefaultProvider')]",
                        "allowedAudiences": [
                            "[parameters('aadAppIdUri')]"
                        ]
                    },
                    "appSettings": [ ]
                }
            },
            "identity": {
                "type": "SystemAssigned"
            },
            "dependsOn": [
                "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
            ],
            "resources": [
                {
                    "type": "config",
                    "name": "appsettings",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                        "[resourceId('Microsoft.Web/sites/config/', parameters('azureWebsiteName'), 'logs')]",
                        "[resourceId('microsoft.insights/components/', parameters('appInsightsName'))]",
                        "Microsoft.ApplicationInsights.AzureWebSites",
                        "[resourceId('Microsoft.KeyVault/vaults/', parameters('keyVaultName'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), variables('storageAccountConnectionString'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), variables('documentDBAccessKey'))]"
                    ],
                    "properties": {
                        "AzureWebJobsStorage": "[concat('@Microsoft.KeyVault(SecretUri=', reference(variables('storageAccountConnectionString')).secretUriWithVersion, ')')]"
                }
                },
                {
                    "type": "config",
                    "name": "logs",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                        "[resourceId('Microsoft.Storage/storageAccounts/', parameters('storageName'))]",
                        "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('appLogsContainerName'))]",
                        "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('webServerLogsContainerName'))]"
                    ],
                    "properties": {
                        "httpLogs": {
                            "azureBlobStorage": {
                                "sasUrl": "[concat('https://',parameters('storageName'),'.blob.core.windows.net/',variables('webServerLogsContainerName'),'?',listServiceSas(parameters('storageName'), '2018-11-01', variables('webServerLogsSasProperties')).serviceSasToken)]",
                                "retentionInDays": "[parameters('diagnosticsLogsRetentionInDays')]",
                                "enabled": true
                            }
                        },
                        "failedRequestsTracing": {
                            "enabled": true
                        },
                        "detailedErrorMessages": {
                            "enabled": true
                        }
                    }
                },
                {
                    "type": "siteextensions",
                    "name": "Microsoft.ApplicationInsights.AzureWebSites",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/Sites', parameters('azureWebsiteName'))]"
                    ],
                    "properties": {}
                }
            ]
        }

The problem is when I deploy this, the logs config is set temporarily set then somehow gets un-set.
I believe it has something to do with multiple config objects(one for app-settings and one for logs) f I were to remove the app-settings config, the logs are correctly set and remain set.

Can someone help me understand what is happening?
Thanks!


问:
Structuremap addalltypesof constructed by a specific constructor
I really like StructureMap as an IOC-framework especially the convention based registration. Now I try to do the following: I want to add all types that implement a specific interface when the class has a default (no parameters) constructor. And the types must be created using this constructor.

This is what I have untill now, which registers the correct types, but how do I specify that the default constructor should be used when creating an instance.

```<code>public class MyRegistry : Registry
{
    public MyRegistry()
    {
        Scan(
           x =>
           {
               x.AssemblyContainingType<IUseCase>();
               x.Exclude(t => !HasDefaultConstructor(t));
               x.AddAllTypesOf<IUseCase>();
           });
    }
    private static bool HasDefaultConstructor(Type type)
    {
        var _constructors = type.GetConstructors();
        return _constructors.Any(c => IsDefaultConstructor(c));
    }

    private static bool IsDefaultConstructor(ConstructorInfo constructor)
    {
        return !constructor.GetParameters().Any();
    }
}
</code>```

答:
There are a few ways to force StructureMap to use a specific constructor.  The simplest is to put the DefaultConstructor attribute on the constructor you want to use.  Assuming you don't want to do that, you would have to create a custom RegistrationConvention.

```<code>public class UseCaseRegistrationConvention : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        if (type.IsAbstract || type.IsInterface || type.IsEnum)
            return;

        var useCaseInterface = type.GetInterface("IUseCase");
        if (useCaseInterface == null)
            return;

        var constructor = type.GetConstructors().FirstOrDefault(c => !c.GetParameters().Any());
        if (constructor != null)
        {
            registry.For(useCaseInterface).Add(c => constructor.Invoke(new object[0]));
        }
    }
}
</code>```

Then use it in your Scan call:

```<code>Scan(x =>
   {
       x.AssemblyContainingType<IUseCase>();
       x.With(new UseCaseRegistrationConvention());
   });
</code>```

Body:
I really like StructureMap as an IOC-framework especially the convention based registration. Now I try to do the following: I want to add all types that implement a specific interface when the class has a default (no parameters) constructor. And the types must be created using this constructor.

This is what I have untill now, which registers the correct types, but how do I specify that the default constructor should be used when creating an instance.

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        Scan(
           x =>
           {
               x.AssemblyContainingType<IUseCase>();
               x.Exclude(t => !HasDefaultConstructor(t));
               x.AddAllTypesOf<IUseCase>();
           });
    }
    private static bool HasDefaultConstructor(Type type)
    {
        var _constructors = type.GetConstructors();
        return _constructors.Any(c => IsDefaultConstructor(c));
    }

    private static bool IsDefaultConstructor(ConstructorInfo constructor)
    {
        return !constructor.GetParameters().Any();
    }
}

Body:
There are a few ways to force StructureMap to use a specific constructor.  The simplest is to put the DefaultConstructor attribute on the constructor you want to use.  Assuming you don't want to do that, you would have to create a custom RegistrationConvention.

public class UseCaseRegistrationConvention : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        if (type.IsAbstract || type.IsInterface || type.IsEnum)
            return;

        var useCaseInterface = type.GetInterface("IUseCase");
        if (useCaseInterface == null)
            return;

        var constructor = type.GetConstructors().FirstOrDefault(c => !c.GetParameters().Any());
        if (constructor != null)
        {
            registry.For(useCaseInterface).Add(c => constructor.Invoke(new object[0]));
        }
    }
}

Then use it in your Scan call:

Scan(x =>
   {
       x.AssemblyContainingType<IUseCase>();
       x.With(new UseCaseRegistrationConvention());
   });


问:
How to merge two data frames together with no common ID?
I am trying to run the sample code from here:

https://www.dataquest.io/blog/k-nearest-neighbors-in-python/

The sample data is available here:

https://www.dropbox.com/s/b3nv38jjo5dxcl6/nba_2013.csv?dl=0

I'm getting an error here:

lebron_normalized = nba_normalized[nba["player"] == "LeBron James"]

Error: KeyError: 'player'

When I look at the data set, I see that nba_normalized doesn't have a field named player because nba_normalized is only numeric. How can I find the normalized vector for Lebron James, and based on that, find euclidean_distances?

答:
Yeah, I'm pretty sure OP just overwrote nba at some point due to the KeyError.

To expound a bit, the masking operation isn't a merge but a True/False vector performed on a subset of a dataframe so you're less worried about joining on a key and more interested in ensuring that your dataframes are similar in composition.

```<code>import pandas as pd

nba = pd.read_csv('nba_2013.csv')
distance_columns = ['age', 'g', 'gs', 'mp', 'fg', 'fga', 'fg.', 'x3p', 'x3pa', 'x3p.', 'x2p', 'x2pa', 'x2p.', 'efg.', 'ft', 'fta', 'ft.', 'orb', 'drb', 'trb', 'ast', 'stl', 'blk', 'tov', 'pf', 'pts']

nba_numeric = nba[distance_columns]

nba_normalized = (nba_numeric - nba.mean()) / nba_numeric.std()

def lebron(x):
    if "lebron" in x.lower():
        return True
    return False

lebron_normalized = nba_normalized[nba.player.isin(set(filter(lebron, nba.player)))]

# Heh
print(lebron_normalized.head(4))
</code>```

Body:
Yeah, I'm pretty sure OP just overwrote nba at some point due to the KeyError.

To expound a bit, the masking operation isn't a merge but a True/False vector performed on a subset of a dataframe so you're less worried about joining on a key and more interested in ensuring that your dataframes are similar in composition.

import pandas as pd

nba = pd.read_csv('nba_2013.csv')
distance_columns = ['age', 'g', 'gs', 'mp', 'fg', 'fga', 'fg.', 'x3p', 'x3pa', 'x3p.', 'x2p', 'x2pa', 'x2p.', 'efg.', 'ft', 'fta', 'ft.', 'orb', 'drb', 'trb', 'ast', 'stl', 'blk', 'tov', 'pf', 'pts']

nba_numeric = nba[distance_columns]

nba_normalized = (nba_numeric - nba.mean()) / nba_numeric.std()

def lebron(x):
    if "lebron" in x.lower():
        return True
    return False

lebron_normalized = nba_normalized[nba.player.isin(set(filter(lebron, nba.player)))]

# Heh
print(lebron_normalized.head(4))


问:
Add private key to ssh-agent in docker file
I am trying to write a docker file for angular cli project but I have an external dependency which is a private repo on BitBucket so I need to pass my ssh key. I am trying to pass ssh keys using --build-arg

Now issues is, It's not adding those keys to ssh-agent and ask for the password instead.

I am using this command to run
docker build -t ng-2-docker/client --build-arg ssh_prv_key="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa)" .

and this is my docker file

```<code>ARG ssh_prv_key
ARG ssh_pub_key

# Use an official Node runtime as a parent image
FROM node:8.9.4

# Specify working directory in docker container
WORKDIR /app

# Authorize SSH Host
RUN mkdir -p /ssh/
RUN chmod 0700 /ssh

# Add the keys and set permissions
RUN echo "$ssh_prv_key" > /ssh/id_rsa && echo "$ssh_pub_key" > /ssh/id_rsa.pub && chmod 600 /ssh/id_rsa && chmod 600 /ssh/id_rsa.pub

# add bitbucket to known hosts
RUN ssh-keyscan bitbucket.org > /ssh/known_hosts

# Copy SSH key to temp folder to pull new code
# ADD ~/.ssh/id_rsa /tmp/
# RUN ssh-agent /tmp
RUN ls -la /ssh

# check if ssh agent is running or not, if not, run
RUN eval `ssh-agent -s` && ssh-add /ssh/id_rsa

# Copy local files into the containers working directory
COPY package.json /app

# Install dependencies inside container
RUN npm i

# Copy local files into the containers working directory
COPY . /app

# Execute Process
CMD ["npm", "docker:rogers:local"]

# Remove ssh key from temp
# RUN rm /tmp/id_rsa
RUN rm -rf /ssh

# expose port
EXPOSE 4200
</code>```

and here is the output if I run the command mentioned above.

答:
I spent several days going through the same issue. ssh-keygen -p ensured the passphrase was empty, but I needed to ssh-agent and ssh-add in my Dockerfile to be able to pull from a private repo. Several of my peers told me they were able to make it work; I would copy what they had and still be asked for a passphrase. Finally I came across this issue. After manually inputting in the rsa key line by line and seeing it succeed, I realized it was because I was building the image and passing in the key via a make target, and the Makefile was processing the newlines as whitespaces. Ultimately it was just a matter of updating how the key was being cat as an argument so that it ran as bash instead to preserve the newlines.

Here was the build command inside my Makefile:

```<code>make container:
    docker build --rm \
    --build-arg ssh_prv_key="$$(cat ~/.ssh/id_rsa)" \
    --squash -f Dockerfile -t $(DOCKER_IMAGE) .
</code>```

I will also note that I needed to include

```<code>echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config
</code>```

to one of my Dockerfile RUN commands as well

Body:
I am trying to write a docker file for angular cli project but I have an external dependency which is a private repo on BitBucket so I need to pass my ssh key. I am trying to pass ssh keys using --build-arg

Now issues is, It's not adding those keys to ssh-agent and ask for the password instead.

I am using this command to run
docker build -t ng-2-docker/client --build-arg ssh_prv_key="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa)" .

and this is my docker file

ARG ssh_prv_key
ARG ssh_pub_key

# Use an official Node runtime as a parent image
FROM node:8.9.4

# Specify working directory in docker container
WORKDIR /app

# Authorize SSH Host
RUN mkdir -p /ssh/
RUN chmod 0700 /ssh

# Add the keys and set permissions
RUN echo "$ssh_prv_key" > /ssh/id_rsa && echo "$ssh_pub_key" > /ssh/id_rsa.pub && chmod 600 /ssh/id_rsa && chmod 600 /ssh/id_rsa.pub

# add bitbucket to known hosts
RUN ssh-keyscan bitbucket.org > /ssh/known_hosts

# Copy SSH key to temp folder to pull new code
# ADD ~/.ssh/id_rsa /tmp/
# RUN ssh-agent /tmp
RUN ls -la /ssh

# check if ssh agent is running or not, if not, run
RUN eval `ssh-agent -s` && ssh-add /ssh/id_rsa

# Copy local files into the containers working directory
COPY package.json /app

# Install dependencies inside container
RUN npm i

# Copy local files into the containers working directory
COPY . /app

# Execute Process
CMD ["npm", "docker:rogers:local"]

# Remove ssh key from temp
# RUN rm /tmp/id_rsa
RUN rm -rf /ssh

# expose port
EXPOSE 4200

and here is the output if I run the command mentioned above.

Body:
I spent several days going through the same issue. ssh-keygen -p ensured the passphrase was empty, but I needed to ssh-agent and ssh-add in my Dockerfile to be able to pull from a private repo. Several of my peers told me they were able to make it work; I would copy what they had and still be asked for a passphrase. Finally I came across this issue. After manually inputting in the rsa key line by line and seeing it succeed, I realized it was because I was building the image and passing in the key via a make target, and the Makefile was processing the newlines as whitespaces. Ultimately it was just a matter of updating how the key was being cat as an argument so that it ran as bash instead to preserve the newlines.

Here was the build command inside my Makefile:

make container:
    docker build --rm \
    --build-arg ssh_prv_key="$$(cat ~/.ssh/id_rsa)" \
    --squash -f Dockerfile -t $(DOCKER_IMAGE) .

I will also note that I needed to include

echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config

to one of my Dockerfile RUN commands as well


问:
Accessing a variable in another object of the same class
I'm trying to access an array in the object "other," but I can't figure out how to access the variable. This is what I have so far:

```<code>public void union(DataSet other)
{
  DataSet temp = new newdataexp();
  temp = other;
}
</code>```

I haven't been able to figure out how to access the variable, even when I create a method in the class that returns the variable and then trying to call it from this method union.

I have this method, and am trying to do: String[][] temp = other.getdata(), but the compiler says that it cannot find symbol: method getdata().

public String[][] getdata()
{

return filedata;

}

答:
I don't know if I good understand you question but to access a variable in another object of the same class just try this:

```<code>class MyClass {
   private int[] myArray = new int[10];

   public void myMethod(MyClass myClass) {
       // you can in this way:
       // int[] tempArray = myClass.myArray
       // but this is better:
       int[] tempArray = myClass.getMyArray();
   }

   public int[] getMyArray() {
       return myArray;
   }

}
</code>```

Edited:

But if you want to make union better extract union method outside class, create method:

```<code>public static MyObject union(MyObject myObjectFirst, MyObject myObjectSecond) {
   ...
}
</code>```

Body:
I'm trying to access an array in the object "other," but I can't figure out how to access the variable. This is what I have so far:

public void union(DataSet other)
{
  DataSet temp = new newdataexp();
  temp = other;
}

I haven't been able to figure out how to access the variable, even when I create a method in the class that returns the variable and then trying to call it from this method union.

I have this method, and am trying to do: String[][] temp = other.getdata(), but the compiler says that it cannot find symbol: method getdata().

public String[][] getdata()
{

return filedata;

}

Body:
I don't know if I good understand you question but to access a variable in another object of the same class just try this:

class MyClass {
   private int[] myArray = new int[10];

   public void myMethod(MyClass myClass) {
       // you can in this way:
       // int[] tempArray = myClass.myArray
       // but this is better:
       int[] tempArray = myClass.getMyArray();
   }

   public int[] getMyArray() {
       return myArray;
   }

}

Edited:

But if you want to make union better extract union method outside class, create method:

public static MyObject union(MyObject myObjectFirst, MyObject myObjectSecond) {
   ...
}


问:
Can't access variable (array) from another function (defined in global scope)
I'd like to use a variable (array) from another function. I already defined it in global scope, but it doesn't work..

Here is my code for better understanding:

```<code>var globalData = '';
var data = '';

$.getJSON('https://...' + data[x].id + '.json', function(data) {

    globalData = data;
    data = globalData.name;

    console.log(data); // works just fine

    if (condition === 1) {
        function2(); // calls this function
    } else {
        function3();
    }
});

function function2() {
    console.log(data); // just an empty line
    console.log(globalData); // UPDATE: works just fine
}
</code>```

答:
The problem is that you have two variables with name data one is local to call back and other is global. So when the following line

```<code>data = globalData.name;
</code>```

doesn't change the global variable it just changes the local variable.

One solution is to have different name for global variable.

```<code>var globalData = '';
var data2 = '';

$.getJSON('https://...' + data[x].id + '.json', function(data) {

    globalData = data;
    data2 = globalData.name;

    console.log(data2); // works just fine

    if (condition === 1) {
        function2(); // calls this function
    } else {
        function3();
    }
});

function function2() {
    console.log(data2); // just an empty line
}
</code>```

Body:
I'd like to use a variable (array) from another function. I already defined it in global scope, but it doesn't work..

Here is my code for better understanding:

var globalData = '';
var data = '';

$.getJSON('https://...' + data[x].id + '.json', function(data) {

    globalData = data;
    data = globalData.name;

    console.log(data); // works just fine

    if (condition === 1) {
        function2(); // calls this function
    } else {
        function3();
    }
});

function function2() {
    console.log(data); // just an empty line
    console.log(globalData); // UPDATE: works just fine
}

Body:
The problem is that you have two variables with name data one is local to call back and other is global. So when the following line

data = globalData.name;

doesn't change the global variable it just changes the local variable.

One solution is to have different name for global variable.

var globalData = '';
var data2 = '';

$.getJSON('https://...' + data[x].id + '.json', function(data) {

    globalData = data;
    data2 = globalData.name;

    console.log(data2); // works just fine

    if (condition === 1) {
        function2(); // calls this function
    } else {
        function3();
    }
});

function function2() {
    console.log(data2); // just an empty line
}


问:
Adafruit NeoPixel library doesn't work when addressing more than 7 LED strips
As of my last question on SO I'm working on an interactive 14x14 LED table which is being controlled by an Arduino Mega (for further information about the setup and code have a look here.
After fixing the problem with data arriving at the Arduino in the wrong order I'm now facing this problem:

In order to control the colours of each pixel on the LED table using Adafruit's NeoPixel library I read in an array of the form int[14][14][3]. This works fine now, but when I try to set the RGB values for MORE than 7 LED strips regarding to the corresponding data nothing happens. I also have several Serial.println() calls to check what data is read and if I'm running more than 7 LED strips 0 is printed for every possible value.

The basic functionality of controlling the LEDs works perfectly - I can also process and output the data described above correctly to the LED strips as long as I don't use more than 7 strips. The problem is that it doesn't matter if I declare more than these 7 strips alltogether in one array or split them. Also initializing them seperately doesn't work as well as creating one instance of the strip and reassigning the pin for it every time I want to use a different strip.

My code currently looks like this and I'm literally clueless what could be the reason for this problem or how I could solve it.

```<code>#include <ArduinoJson.h>
#include <Adafruit_NeoPixel.h>

#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

#define PINROW0 0
#define PINROW1 1
#define PINROW2 2
#define PINROW3 3
#define PINROW4 4
#define PINROW5 5
#define PINROW6 6
#define PINROW7 7
#define PINROW8 8
#define PINROW9 26
#define PINROW10 28
#define PINROW11 30
#define PINROW12 32
#define PINROW13 34

#define NUMPIXELS 14 //Anzahl der Pixel pro Reihe

/*Adafruit_NeoPixel row0 = Adafruit_NeoPixel(NUMPIXELS, PINROW0, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row1 = Adafruit_NeoPixel(NUMPIXELS, PINROW1, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row2 = Adafruit_NeoPixel(NUMPIXELS, PINROW2, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row3 = Adafruit_NeoPixel(NUMPIXELS, PINROW3, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row4 = Adafruit_NeoPixel(NUMPIXELS, PINROW4, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row5 = Adafruit_NeoPixel(NUMPIXELS, PINROW5, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row6 = Adafruit_NeoPixel(NUMPIXELS, PINROW6, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row7 = Adafruit_NeoPixel(NUMPIXELS, PINROW7, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row8 = Adafruit_NeoPixel(NUMPIXELS, PINROW8, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row9 = Adafruit_NeoPixel(NUMPIXELS, PINROW9, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row10 = Adafruit_NeoPixel(NUMPIXELS, PINROW10, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row11 = Adafruit_NeoPixel(NUMPIXELS, PINROW11, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row12 = Adafruit_NeoPixel(NUMPIXELS, PINROW12, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row13 = Adafruit_NeoPixel(NUMPIXELS, PINROW13, NEO_GRB + NEO_KHZ800);
*/

//Adafruit_NeoPixel currentStrip = Adafruit_NeoPixel(NUMPIXELS, pins[0], NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel row[] = { //Initialisieren des Arrays, das die addressierbaren LED Streifen im Adafruit Format enthält
  Adafruit_NeoPixel(NUMPIXELS, PINROW0, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW1, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW2, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW3, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW4, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW5, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW6, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW7, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW8, NEO_GRB + NEO_KHZ800)/*,
  Adafruit_NeoPixel(NUMPIXELS, PINROW9, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW10, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW11, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW12, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW13, NEO_GRB + NEO_KHZ800)*/
};

#define DELAY 1000 //Refresh Zyklus auf 10 Millisekunden setzen
#define NUMSTRIPS 9/*(sizeof(row)/sizeof(row[0]))*/ //Anzahl der verbundenen LED Streifen definieren

int values[14][14][3];
String matrixAsString = "";

void setup() {

#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif

  /*Seriellen Port über den der Pi sich mit dem Arduino verbindet einrichten*/
  Serial.begin(115200); //setzen der Bitrate auf 115200 Bit pro Sekunde
  Serial.setTimeout(100000);

  /*NeoPixel Library initialisieren*/
  for (int i = 0; i < NUMSTRIPS; i++) {
    row[i].begin();
    row[i].show();
  }
}

void process(String matrixAsString) {
  DynamicJsonDocument doc(4372);
  Serial.println(matrixAsString);
  deserializeJson(doc, matrixAsString);

  Serial.println((int)(doc[2][10][0]));
  Serial.println((int)(doc[2][10][0]));
  Serial.println((int)(doc[5][10][0]));
  Serial.println((int)(doc[0][1][2]));
  Serial.println((int)(doc[0][0][1]));

  for (int i = 0; i < NUMSTRIPS; i++) {
    for (int j = 0; j < NUMPIXELS; j++) {
      for (int k = 0; k < 3; k++) {
        values[i][j][k] = (int)(doc[i][j][k]);
      }
    }
  }
}

void paint() {
  int r = 0;
  int g = 0;
  int b = 0;
  for (int i = 0; i < NUMSTRIPS; i++) {
    for (int j = 0; j < NUMPIXELS; j++) {
      r = values[i][j][0];
      g = values[i][j][1];
      b = values[i][j][2];
      row[i].setPixelColor(j, row[i].Color(r, g, b));
      row[i].show();
    }
  }
}

//infinite loop refreshing the matrix
void loop() {

  while (Serial.available()) {
    char c = Serial.read();
    matrixAsString += c;
    if (c == '\n') {
      process(matrixAsString);
      paint();
      matrixAsString = "";
    }

  }

}
</code>```

As of the official Adafruit Documentation the library is designed to have as many strips connected as the Arduino is able to support so there has to be a solution.

To test my code I'm using this data which is a String representation of a randomly generated 14x14 RGB matrix:

[[[0,0,0],[1,0,0],[1,1,0],[2,1,0],[2,2,0],[3,2,0],[3,3,0],[3,3,1],[3,3,2],[3,3,3],[4,3,3],[4,4,3],[5,4,3],[5,4,4]],[[6,4,4],[7,4,4],[7,5,4],[7,6,4],[7,7,4],[7,7,5],[7,7,6],[7,7,7],[7,7,8],[8,7,8],[8,8,8],[8,9,8],[8,10,8],[8,11,8]],[[8,11,9],[8,11,10],[9,11,10],[9,11,11],[9,12,11],[9,12,12],[9,13,12],[10,13,12],[10,13,13],[10,13,14],[10,13,15],[11,13,15],[11,14,15],[11,15,15]],[[12,15,15],[12,15,16],[12,15,17],[13,15,17],[13,16,17],[13,16,18],[14,16,18],[14,17,18],[15,17,18],[15,17,19],[15,18,19],[15,18,20],[15,19,20],[15,19,21]],[[15,20,21],[15,21,21],[16,21,21],[17,21,21],[17,22,21],[18,22,21],[19,22,21],[19,23,21],[20,23,21],[20,23,22],[20,23,23],[20,24,23],[20,25,23],[20,26,23]],[[21,26,23],[22,26,23],[22,27,23],[23,27,23],[23,27,24],[24,27,24],[24,27,25],[24,28,25],[24,28,26],[24,29,26],[24,29,27],[24,29,28],[24,30,28],[25,30,28]],[[25,30,29],[25,31,29],[25,31,30],[26,31,30],[27,31,30],[27,32,30],[27,32,31],[27,33,31],[27,34,31],[27,35,31],[27,35,32],[28,35,32],[28,36,32],[29,36,32]],[[29,37,32],[29,37,33],[29,38,33],[29,38,34],[30,38,34],[31,38,34],[32,38,34],[33,38,34],[33,39,34],[33,39,35],[33,39,36],[33,40,36],[33,40,37],[33,41,37]],[[33,42,37],[33,42,38],[33,42,39],[33,42,40],[33,43,40],[33,43,41],[33,43,42],[33,44,42],[33,45,42],[33,45,43],[33,46,43],[34,46,43],[34,47,43],[35,47,43]],[[36,47,43],[37,47,43],[38,47,43],[38,47,44],[39,47,44],[39,47,45],[39,48,45],[40,48,45],[40,48,46],[40,49,46],[41,49,46],[41,50,46],[41,51,46],[41,51,47]],[[42,51,47],[42,51,48],[43,51,48],[43,51,49],[43,52,49],[43,53,49],[43,54,49],[43,54,50],[44,54,50],[44,55,50],[45,55,50],[45,55,51],[46,55,51],[47,55,51]],[[48,55,51],[48,56,51],[48,57,51],[48,58,51],[48,58,52],[48,58,53],[48,59,53],[48,59,54],[48,60,54],[48,60,55],[48,60,56],[48,60,57],[49,60,57],[49,61,57]],[[49,62,57],[49,62,58],[49,63,58],[49,63,59],[50,63,59],[50,64,59],[50,65,59],[51,65,59],[52,65,59],[53,65,59],[54,65,59],[54,66,59],[54,66,60],[54,67,60]],[[55,67,60],[56,67,60],[57,67,60],[58,67,60],[59,67,60],[59,67,61],[59,68,61],[59,69,61],[60,69,61],[61,69,61],[61,69,62],[61,69,63],[61,70,63],[61,71,63]]]

Thank you in advance for your help and I'm very grateful for any tip or suggestion provided.

答:
You've got only 8kB of ram and you are using:

int values[14][14][3]; => 1176 bytes on this array (instead of half, if you'd use byte/uint8_t instead of int)

Freaking String matrixAsString = ""; and += operator on it. That'd seriously messes up memory (in a terms of memory fragmentation).

DynamicJsonDocument doc(4372); allocates another huge amount of memory

not to mention, each strip has it's own pixel memory so values array is little bit extraneous

maybe it's possible to use the same buffer for reading and json parser? That might save a lots

So according to that, you have to be out of memory

Anyway, I'd use some decent ARM and DMA magic (for example 16 channels at once on STM32 MCUs) without much interaction of CPU for sending it out. Or existing solution like OctoWS2811 LED Library

Body:
As of my last question on SO I'm working on an interactive 14x14 LED table which is being controlled by an Arduino Mega (for further information about the setup and code have a look here.
After fixing the problem with data arriving at the Arduino in the wrong order I'm now facing this problem:

In order to control the colours of each pixel on the LED table using Adafruit's NeoPixel library I read in an array of the form int[14][14][3]. This works fine now, but when I try to set the RGB values for MORE than 7 LED strips regarding to the corresponding data nothing happens. I also have several Serial.println() calls to check what data is read and if I'm running more than 7 LED strips 0 is printed for every possible value.

The basic functionality of controlling the LEDs works perfectly - I can also process and output the data described above correctly to the LED strips as long as I don't use more than 7 strips. The problem is that it doesn't matter if I declare more than these 7 strips alltogether in one array or split them. Also initializing them seperately doesn't work as well as creating one instance of the strip and reassigning the pin for it every time I want to use a different strip.

My code currently looks like this and I'm literally clueless what could be the reason for this problem or how I could solve it.

#include <ArduinoJson.h>
#include <Adafruit_NeoPixel.h>

#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

#define PINROW0 0
#define PINROW1 1
#define PINROW2 2
#define PINROW3 3
#define PINROW4 4
#define PINROW5 5
#define PINROW6 6
#define PINROW7 7
#define PINROW8 8
#define PINROW9 26
#define PINROW10 28
#define PINROW11 30
#define PINROW12 32
#define PINROW13 34

#define NUMPIXELS 14 //Anzahl der Pixel pro Reihe

/*Adafruit_NeoPixel row0 = Adafruit_NeoPixel(NUMPIXELS, PINROW0, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row1 = Adafruit_NeoPixel(NUMPIXELS, PINROW1, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row2 = Adafruit_NeoPixel(NUMPIXELS, PINROW2, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row3 = Adafruit_NeoPixel(NUMPIXELS, PINROW3, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row4 = Adafruit_NeoPixel(NUMPIXELS, PINROW4, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row5 = Adafruit_NeoPixel(NUMPIXELS, PINROW5, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row6 = Adafruit_NeoPixel(NUMPIXELS, PINROW6, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row7 = Adafruit_NeoPixel(NUMPIXELS, PINROW7, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row8 = Adafruit_NeoPixel(NUMPIXELS, PINROW8, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row9 = Adafruit_NeoPixel(NUMPIXELS, PINROW9, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row10 = Adafruit_NeoPixel(NUMPIXELS, PINROW10, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row11 = Adafruit_NeoPixel(NUMPIXELS, PINROW11, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row12 = Adafruit_NeoPixel(NUMPIXELS, PINROW12, NEO_GRB + NEO_KHZ800);
  Adafruit_NeoPixel row13 = Adafruit_NeoPixel(NUMPIXELS, PINROW13, NEO_GRB + NEO_KHZ800);
*/

//Adafruit_NeoPixel currentStrip = Adafruit_NeoPixel(NUMPIXELS, pins[0], NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel row[] = { //Initialisieren des Arrays, das die addressierbaren LED Streifen im Adafruit Format enthält
  Adafruit_NeoPixel(NUMPIXELS, PINROW0, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW1, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW2, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW3, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW4, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW5, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW6, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW7, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW8, NEO_GRB + NEO_KHZ800)/*,
  Adafruit_NeoPixel(NUMPIXELS, PINROW9, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW10, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW11, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW12, NEO_GRB + NEO_KHZ800),
  Adafruit_NeoPixel(NUMPIXELS, PINROW13, NEO_GRB + NEO_KHZ800)*/
};

#define DELAY 1000 //Refresh Zyklus auf 10 Millisekunden setzen
#define NUMSTRIPS 9/*(sizeof(row)/sizeof(row[0]))*/ //Anzahl der verbundenen LED Streifen definieren

int values[14][14][3];
String matrixAsString = "";

void setup() {

#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif

  /*Seriellen Port über den der Pi sich mit dem Arduino verbindet einrichten*/
  Serial.begin(115200); //setzen der Bitrate auf 115200 Bit pro Sekunde
  Serial.setTimeout(100000);

  /*NeoPixel Library initialisieren*/
  for (int i = 0; i < NUMSTRIPS; i++) {
    row[i].begin();
    row[i].show();
  }
}

void process(String matrixAsString) {
  DynamicJsonDocument doc(4372);
  Serial.println(matrixAsString);
  deserializeJson(doc, matrixAsString);

  Serial.println((int)(doc[2][10][0]));
  Serial.println((int)(doc[2][10][0]));
  Serial.println((int)(doc[5][10][0]));
  Serial.println((int)(doc[0][1][2]));
  Serial.println((int)(doc[0][0][1]));

  for (int i = 0; i < NUMSTRIPS; i++) {
    for (int j = 0; j < NUMPIXELS; j++) {
      for (int k = 0; k < 3; k++) {
        values[i][j][k] = (int)(doc[i][j][k]);
      }
    }
  }
}

void paint() {
  int r = 0;
  int g = 0;
  int b = 0;
  for (int i = 0; i < NUMSTRIPS; i++) {
    for (int j = 0; j < NUMPIXELS; j++) {
      r = values[i][j][0];
      g = values[i][j][1];
      b = values[i][j][2];
      row[i].setPixelColor(j, row[i].Color(r, g, b));
      row[i].show();
    }
  }
}

//infinite loop refreshing the matrix
void loop() {

  while (Serial.available()) {
    char c = Serial.read();
    matrixAsString += c;
    if (c == '\n') {
      process(matrixAsString);
      paint();
      matrixAsString = "";
    }

  }

}

As of the official Adafruit Documentation the library is designed to have as many strips connected as the Arduino is able to support so there has to be a solution.

To test my code I'm using this data which is a String representation of a randomly generated 14x14 RGB matrix:

[[[0,0,0],[1,0,0],[1,1,0],[2,1,0],[2,2,0],[3,2,0],[3,3,0],[3,3,1],[3,3,2],[3,3,3],[4,3,3],[4,4,3],[5,4,3],[5,4,4]],[[6,4,4],[7,4,4],[7,5,4],[7,6,4],[7,7,4],[7,7,5],[7,7,6],[7,7,7],[7,7,8],[8,7,8],[8,8,8],[8,9,8],[8,10,8],[8,11,8]],[[8,11,9],[8,11,10],[9,11,10],[9,11,11],[9,12,11],[9,12,12],[9,13,12],[10,13,12],[10,13,13],[10,13,14],[10,13,15],[11,13,15],[11,14,15],[11,15,15]],[[12,15,15],[12,15,16],[12,15,17],[13,15,17],[13,16,17],[13,16,18],[14,16,18],[14,17,18],[15,17,18],[15,17,19],[15,18,19],[15,18,20],[15,19,20],[15,19,21]],[[15,20,21],[15,21,21],[16,21,21],[17,21,21],[17,22,21],[18,22,21],[19,22,21],[19,23,21],[20,23,21],[20,23,22],[20,23,23],[20,24,23],[20,25,23],[20,26,23]],[[21,26,23],[22,26,23],[22,27,23],[23,27,23],[23,27,24],[24,27,24],[24,27,25],[24,28,25],[24,28,26],[24,29,26],[24,29,27],[24,29,28],[24,30,28],[25,30,28]],[[25,30,29],[25,31,29],[25,31,30],[26,31,30],[27,31,30],[27,32,30],[27,32,31],[27,33,31],[27,34,31],[27,35,31],[27,35,32],[28,35,32],[28,36,32],[29,36,32]],[[29,37,32],[29,37,33],[29,38,33],[29,38,34],[30,38,34],[31,38,34],[32,38,34],[33,38,34],[33,39,34],[33,39,35],[33,39,36],[33,40,36],[33,40,37],[33,41,37]],[[33,42,37],[33,42,38],[33,42,39],[33,42,40],[33,43,40],[33,43,41],[33,43,42],[33,44,42],[33,45,42],[33,45,43],[33,46,43],[34,46,43],[34,47,43],[35,47,43]],[[36,47,43],[37,47,43],[38,47,43],[38,47,44],[39,47,44],[39,47,45],[39,48,45],[40,48,45],[40,48,46],[40,49,46],[41,49,46],[41,50,46],[41,51,46],[41,51,47]],[[42,51,47],[42,51,48],[43,51,48],[43,51,49],[43,52,49],[43,53,49],[43,54,49],[43,54,50],[44,54,50],[44,55,50],[45,55,50],[45,55,51],[46,55,51],[47,55,51]],[[48,55,51],[48,56,51],[48,57,51],[48,58,51],[48,58,52],[48,58,53],[48,59,53],[48,59,54],[48,60,54],[48,60,55],[48,60,56],[48,60,57],[49,60,57],[49,61,57]],[[49,62,57],[49,62,58],[49,63,58],[49,63,59],[50,63,59],[50,64,59],[50,65,59],[51,65,59],[52,65,59],[53,65,59],[54,65,59],[54,66,59],[54,66,60],[54,67,60]],[[55,67,60],[56,67,60],[57,67,60],[58,67,60],[59,67,60],[59,67,61],[59,68,61],[59,69,61],[60,69,61],[61,69,61],[61,69,62],[61,69,63],[61,70,63],[61,71,63]]]

Thank you in advance for your help and I'm very grateful for any tip or suggestion provided.


问:
Why is the positive lookahead in my pcregrep Regex not working?
I wrote a Regex using pcregrep, and everything behaved as expected until I added a positive lookahead.

Scenario:

I have the following text file:

```<code>a
b
c
a
c
</code>```

Goal:

I want to use a Regex with pcregrep to return a line containing a and a line containing c with a line containing b between them that is not captured. So it would capture the first three lines (a, b, c) and return the first (a) and third (c) line. It would not capture the fourth and fifth line because there is no b line between them. So the output would be:

```<code>a
c
</code>```

What I've tried

If I run pcregrep -M 'a\nb\nc\n' (command 1), this captures and returns:

```<code>a
b
c
</code>```

as expected. So I now want to modify this to capture the b line with a positive lookahead. I tried this: pcregrep -M 'a\n(?=(b\n))c\n' (command 2). However, this returns nothing.

My question:

Why does command 2 not return the expected output, where command 1 does? How can I return the desired result? I know there are ways to do this other than pcregrep, but please note that I want to use pcregrep because I'll be extending the functionality to solve similar problems.

答:
You can use 2 capture groups with -o option:

```<code>pcregrep -M -o1 -o2 '(a\n)b\n(c)\n' file
</code>```

```<code>a
c
</code>```

Details:

(...): In regex it is used for capturing groups

-o1 -o2: prints only capture group #1 and #2

Note that your regex a\n(?=(b\n))c\n won't work because lookahead is just assertion with zero-width match. Your regex asserts presence of b\n after a\n which is fine but it attempts to match c\n right after a\n and this is where matching fails.

Body:
I wrote a Regex using pcregrep, and everything behaved as expected until I added a positive lookahead.

Scenario:

I have the following text file:

a
b
c
a
c

Goal:

I want to use a Regex with pcregrep to return a line containing a and a line containing c with a line containing b between them that is not captured. So it would capture the first three lines (a, b, c) and return the first (a) and third (c) line. It would not capture the fourth and fifth line because there is no b line between them. So the output would be:

a
c

What I've tried

If I run pcregrep -M 'a\nb\nc\n' (command 1), this captures and returns:

a
b
c

as expected. So I now want to modify this to capture the b line with a positive lookahead. I tried this: pcregrep -M 'a\n(?=(b\n))c\n' (command 2). However, this returns nothing.

My question:

Why does command 2 not return the expected output, where command 1 does? How can I return the desired result? I know there are ways to do this other than pcregrep, but please note that I want to use pcregrep because I'll be extending the functionality to solve similar problems.

Body:
You can use 2 capture groups with -o option:

pcregrep -M -o1 -o2 '(a\n)b\n(c)\n' file

a
c

Details:

(...): In regex it is used for capturing groups

-o1 -o2: prints only capture group #1 and #2

Note that your regex a\n(?=(b\n))c\n won't work because lookahead is just assertion with zero-width match. Your regex asserts presence of b\n after a\n which is fine but it attempts to match c\n right after a\n and this is where matching fails.


问:
Thymeleaf th:block condition
I want to set up some conditions on Thymeleaf templates like this, but it doesn't work.

 Identifiant

 Nom Formation
 Descirption Formation
 Adresse Formation
Status Formation
 Chef Projet
 Formateur
Ressource Humain
Update
Liste Devellopeur

```

the erros is
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "${StatusFormation}} =='Traitement' }" (template: "ChefProjetFormationHome" - line 29, col 11) at org.thymeleaf.standard.expression.StandardExpressionParser.parseExpression(StandardExpressionParser.java:131)

答:
The problem is you add one extra brace in this line:

```<code><th:block th:if="${StatusFormation}} =='Traitement' }">
</code>```

you should change it to:

```<code><th:block th:if="${StatusFormation} == 'Traitement'">
</code>```

Title: Thymeleaf th:block condition

Body:
I want to set up some conditions on Thymeleaf templates like this, but it doesn't work.

 Identifiant

 Nom Formation
 Descirption Formation
 Adresse Formation
Status Formation
 Chef Projet
 Formateur
Ressource Humain
Update
Liste Devellopeur

the erros is
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "${StatusFormation}} =='Traitement' }" (template: "ChefProjetFormationHome" - line 29, col 11) at org.thymeleaf.standard.expression.StandardExpressionParser.parseExpression(StandardExpressionParser.java:131)

Body:
The problem is you add one extra brace in this line:

<th:block th:if="${StatusFormation}} =='Traitement' }">

you should change it to:

<th:block th:if="${StatusFormation} == 'Traitement'">


问:
Group a Ruby Array of Dates by Month and Year into a Hash
Let's say I had a Ruby Array of Dates like:

```<code>2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21
</code>```

What would be an easy and Ruby-esque way of creating a Hash that groups the Date elements by year and then month, like:

```<code>{
    2011 => {
        1   => [2011-01-20, 2011-01-23],
        2   => [2011-02-01, 2011-02-15],
        3  => [2011-03-21],
    }
}
</code>```

I can do this by iterating over everything and extracting years, months and so on, then comining them.

Ruby offers so many methods and blocks for Arrays and Hashes, there must be an easier way?

答:
```<code>require 'date'

dates = [
  '2011-01-20',
  '2011-01-23',
  '2011-02-01',
  '2011-02-15',
  '2011-03-21'
].map{|sd| Date.parse(sd)}

Hash[
  dates.group_by(&:year).map{|y, items|
    [y, items.group_by{|d| d.strftime('%B')}]
  }
]
#=> {2011=>{"January"=>[#<Date: 2011-01-20 (4911163/2,0,2299161)>, #<Date: 2011-01-23 (4911169/2,0,2299161)>], "February"=>[#<Date: 2011-02-01 (4911187/2,0,2299161)>, #<Date: 2011-02-15 (4911215/2,0,2299161)>], "March"=>[#<Date: 2011-03-21 (4911283/2,0,2299161)>]}}
</code>```

I noticed you have changed month names into numbers, so you may want to replace d.strftime('%B') above with d.month or whatever else.

Here's a step-by-step explanation:

You essentially want two-level grouping: first level by year, second by month. Ruby has very useful method group_by, which groups elements by given expression (a block). So: first part is grouping original array by year:

```<code>hash_by_year = dates.group_by(&:year)
# => {2011=>[#<Date: 2011-01-20 (4911163/2,0,2299161)>, #<Date: 2011-01-23 (4911169/2,0,2299161)>, #<Date: 2011-02-01 (4911187/2,0,2299161)>, #<Date: 2011-02-15 (4911215/2,0,2299161)>, #<Date: 2011-03-21 (4911283/2,0,2299161)>]}
</code>```

That gives us first level: keys are years, values arrays of dates with given year. But we still need to group the second level: that's why we map by-year hash - to group its values by month. Let's for start forget strftime and say that we're grouping by d.month:

```<code>hash_by_year.map{|year, dates_in_year|
  [year, dates_in_year.group_by(&:month)]
}
# => [[2011, {1=>[#<Date: 2011-01-20 (4911163/2,0,2299161)>, #<Date: 2011-01-23 (4911169/2,0,2299161)>], 2=>[#<Date: 2011-02-01 (4911187/2,0,2299161)>, #<Date: 2011-02-15 (4911215/2,0,2299161)>], 3=>[#<Date: 2011-03-21 (4911283/2,0,2299161)>]}]]
</code>```

That way we got our second level grouping. Instead of array of all dates in a year, now we have hash whose keys are months, and values arrays of dates for a given month.

The only problem we have is that map returns an array and not a hash. Thats why we "surround" whole expression by Hash[], which makes a hash out of array of pairs, in our case pairs [year, hash_of_dates_by_month].

Sorry if the explanation sounds confusing, I found harder to explain functional expressions than imperative, because of the nesting. :(

Body:
Let's say I had a Ruby Array of Dates like:

2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21

What would be an easy and Ruby-esque way of creating a Hash that groups the Date elements by year and then month, like:

{
    2011 => {
        1   => [2011-01-20, 2011-01-23],
        2   => [2011-02-01, 2011-02-15],
        3  => [2011-03-21],
    }
}

I can do this by iterating over everything and extracting years, months and so on, then comining them.

Ruby offers so many methods and blocks for Arrays and Hashes, there must be an easier way?

Body:
require 'date'

dates = [
  '2011-01-20',
  '2011-01-23',
  '2011-02-01',
  '2011-02-15',
  '2011-03-21'
].map{|sd| Date.parse(sd)}

Hash[
  dates.group_by(&:year).map{|y, items|
    [y, items.group_by{|d| d.strftime('%B')}]
  }
]
#=> {2011=>{"January"=>[#<Date: 2011-01-20 (4911163/2,0,2299161)>, #<Date: 2011-01-23 (4911169/2,0,2299161)>], "February"=>[#<Date: 2011-02-01 (4911187/2,0,2299161)>, #<Date: 2011-02-15 (4911215/2,0,2299161)>], "March"=>[#<Date: 2011-03-21 (4911283/2,0,2299161)>]}}

I noticed you have changed month names into numbers, so you may want to replace d.strftime('%B') above with d.month or whatever else.

Here's a step-by-step explanation:

You essentially want two-level grouping: first level by year, second by month. Ruby has very useful method group_by, which groups elements by given expression (a block). So: first part is grouping original array by year:

hash_by_year = dates.group_by(&:year)
# => {2011=>[#<Date: 2011-01-20 (4911163/2,0,2299161)>, #<Date: 2011-01-23 (4911169/2,0,2299161)>, #<Date: 2011-02-01 (4911187/2,0,2299161)>, #<Date: 2011-02-15 (4911215/2,0,2299161)>, #<Date: 2011-03-21 (4911283/2,0,2299161)>]}

That gives us first level: keys are years, values arrays of dates with given year. But we still need to group the second level: that's why we map by-year hash - to group its values by month. Let's for start forget strftime and say that we're grouping by d.month:

hash_by_year.map{|year, dates_in_year|
  [year, dates_in_year.group_by(&:month)]
}
# => [[2011, {1=>[#<Date: 2011-01-20 (4911163/2,0,2299161)>, #<Date: 2011-01-23 (4911169/2,0,2299161)>], 2=>[#<Date: 2011-02-01 (4911187/2,0,2299161)>, #<Date: 2011-02-15 (4911215/2,0,2299161)>], 3=>[#<Date: 2011-03-21 (4911283/2,0,2299161)>]}]]

That way we got our second level grouping. Instead of array of all dates in a year, now we have hash whose keys are months, and values arrays of dates for a given month.

The only problem we have is that map returns an array and not a hash. Thats why we "surround" whole expression by Hash[], which makes a hash out of array of pairs, in our case pairs [year, hash_of_dates_by_month].

Sorry if the explanation sounds confusing, I found harder to explain functional expressions than imperative, because of the nesting. :(


问:
Flutter: webview_flutter update url in same webview widget
Hey I am trying to create a screen which shows a webview with a bottomappbar.
So you load the webview and when tapping on a item in the bottomappbar a other website should loaded in the same webview...

I cant figure out how to open another website other than I originaly parsed.
I tried to update the url by using «setState» but it only updates the appbar title and the webview still shows the original website

Here is my current code:

```<code>class _WebviewContainer extends State<WebviewContainer> {
var url;
final key = UniqueKey();

_WebviewContainer(this.url);

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text(url),
    actions: <Widget>[
      IconButton(
        icon: Icon(
          Icons.home,
          size: 40.0,
          color: Colors.white,
        ),
        onPressed: () => {
          //-> Here I set the new url but the webview always shows the origin website

          setState(() {
            url = 'https://stackoverflow.com/';
          })
        },
      )
    ],
  ),
  body: Column(
    children: <Widget>[
      Expanded(
        child: WebView(
          key: key,
          javascriptMode: JavascriptMode.unrestricted,
          initialUrl: url,
        ),
      ),
    ],
  ),
);
}
}
</code>```

I took the code from a tutorial on YouTube and the creator also stated that the webview will reload if the state of the url changes, but unfortunately he did not show how to do it

If anybody could help me out?

答:
So I had a similar situation except i wanted a new url to be loaded in my webview when i selected an item from a dropdownmenu.
How I did this was create an instance of WebViewController

```<code>WebViewController controller;
</code>```

Then set this controller when the webview is created with the onWebViewCreated parameter

```<code>child: WebView(
      key: _key,
      javascriptMode: JavascriptMode.unrestricted,
      initialUrl: url,
    onWebViewCreated: (WebViewController webViewController) {
    controller = webViewController;}
</code>```

Now you have the controller set, you can use its loadUrl method in setState() to change the displayed Url

```<code>setState(() {
            controller.loadUrl(newUrl_here);
</code>```

I just started with Flutter so could be a better way of course but this worked for me

Body:
Hey I am trying to create a screen which shows a webview with a bottomappbar.
So you load the webview and when tapping on a item in the bottomappbar a other website should loaded in the same webview...

I cant figure out how to open another website other than I originaly parsed.
I tried to update the url by using «setState» but it only updates the appbar title and the webview still shows the original website

Here is my current code:

class _WebviewContainer extends State<WebviewContainer> {
var url;
final key = UniqueKey();

_WebviewContainer(this.url);

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text(url),
    actions: <Widget>[
      IconButton(
        icon: Icon(
          Icons.home,
          size: 40.0,
          color: Colors.white,
        ),
        onPressed: () => {
          //-> Here I set the new url but the webview always shows the origin website

          setState(() {
            url = 'https://stackoverflow.com/';
          })
        },
      )
    ],
  ),
  body: Column(
    children: <Widget>[
      Expanded(
        child: WebView(
          key: key,
          javascriptMode: JavascriptMode.unrestricted,
          initialUrl: url,
        ),
      ),
    ],
  ),
);
}
}

I took the code from a tutorial on YouTube and the creator also stated that the webview will reload if the state of the url changes, but unfortunately he did not show how to do it

If anybody could help me out?

Body:
So I had a similar situation except i wanted a new url to be loaded in my webview when i selected an item from a dropdownmenu.
How I did this was create an instance of WebViewController

WebViewController controller;

Then set this controller when the webview is created with the onWebViewCreated parameter

child: WebView(
      key: _key,
      javascriptMode: JavascriptMode.unrestricted,
      initialUrl: url,
    onWebViewCreated: (WebViewController webViewController) {
    controller = webViewController;}

Now you have the controller set, you can use its loadUrl method in setState() to change the displayed Url

setState(() {
            controller.loadUrl(newUrl_here);

I just started with Flutter so could be a better way of course but this worked for me


问:
'Field required a bean of type that could not be found.' error spring restful API using mongodb
So I've been learning Spring in the couples of week, been following this tutorial

Building a RESTful Web Service

All was well until I tried to integrate it to mongodb. So I follow this tutorial.

Accessing Data with MongoDB

But my practice is partially still using the first one. So my project directory structure is like this.

```<code>src/
├── main/
│   └── java/
|       ├── model/
|       |   └── User.java
|       ├── rest/
|       |   ├── Application.java
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── service/
|           └── UserService.java
└── resources/
    └── application.properties
</code>```

This is my model/User.java file

package main.java.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="user")
public class User {

    private int age;
    private String country;
    @Id
    private String id;
    private String name;

    public User() {
        super();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}
```

<p>This is my <strong>rest/UsersController.java</strong> file</p>

<pre class="lang-java prettyprint-override"><code>package main.java.rest;

import java.util.List;
import main.java.service.UserService;
import main.java.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/users")
public class UsersController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public List<User> getAllUsers() {
        return userService.findAll();
    }
}
</code>```

This is my service/UserService.java file

package main.java.service;

import java.util.List;
import main.java.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserService extends MongoRepository<User, String> {
    public List<User> findAll();
}
```

I could compile them (I'm using gradle for compilation because I'm following the tutorial), but when I run the jar file it was throwing this error.

APPLICATION FAILED TO START

Description:

Field userService in main.java.rest.UsersController required a bean of
  type 'main.java.service.UserService' that could not be found.

Action:

Consider defining a bean of type 'main.java.service.UserService' in
  your configuration.

Not sure what is wrong I start googling around and found that I need to include Beans.xml file and register the userService in it. I did that but it's not working. I'm really new to this so I really have no clue on what's going on.

答: You have to add the <code>@Service</code> annotation to the implementation of your service. </p>

Body:
So I've been learning Spring in the couples of week, been following this tutorial

Building a RESTful Web Service

All was well until I tried to integrate it to mongodb. So I follow this tutorial.

Accessing Data with MongoDB

But my practice is partially still using the first one. So my project directory structure is like this.

src/
├── main/
│   └── java/
|       ├── model/
|       |   └── User.java
|       ├── rest/
|       |   ├── Application.java
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── service/
|           └── UserService.java
└── resources/
    └── application.properties

This is my model/User.java file

package main.java.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="user")
public class User {

    private int age;
    private String country;
    @Id
    private String id;
    private String name;

    public User() {
        super();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

This is my rest/UsersController.java file

package main.java.rest;

import java.util.List;
import main.java.service.UserService;
import main.java.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/users")
public class UsersController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public List<User> getAllUsers() {
        return userService.findAll();
    }
}

This is my service/UserService.java file

package main.java.service;

import java.util.List;
import main.java.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserService extends MongoRepository<User, String> {
    public List<User> findAll();
}

I could compile them (I'm using gradle for compilation because I'm following the tutorial), but when I run the jar file it was throwing this error.

APPLICATION FAILED TO START

Description:

Field userService in main.java.rest.UsersController required a bean of
  type 'main.java.service.UserService' that could not be found.

Action:

Consider defining a bean of type 'main.java.service.UserService' in
  your configuration.

Not sure what is wrong I start googling around and found that I need to include Beans.xml file and register the userService in it. I did that but it's not working. I'm really new to this so I really have no clue on what's going on.

Body: You have to add the @Service annotation to the implementation of your service.


问:
Oracle - object order - how does it work?
Oracle doc says as follows: "As with map methods, an order method, if one is defined, is called automatically whenever two objects of that type need to be compared."

So I assume it will sort when using 'order by' clausule.

Lets say, I have following object:

```<code>create or replace type height as object
(
    val number,

    constructor function height return self as result,
    constructor function height (val number) return self as result,

    order member function compare (other height) RETURN INTEGER
);
</code>```

and its body implementation:

```<code>create or replace type body height is
    constructor function height return self as result is
         begin
            self.val := null;
         end;

    constructor function height (val number) return self as result is
         begin
            self.val := val;
            return;
         end;

    order member function compare (other height) return integer is
        begin
            if self.val > self.val then return 1;
            elsif self.val < self.val then return -1;
            else return 0;
            end if;
        end;
end;
</code>```

Then my table looks like this:

```<code>CREATE TABLE people (
    name varchar2(50),
    height height
);
</code>```

And some records ...

```<code>insert into people values ('Foo', height(150));
insert into people values ('Bar', height(130));
insert into people valueS ('Baz', height(180));
</code>```

Then I want to sort it:

```<code>select p.height.val from people p order by height ASC;
select p.height.val from people p order by height DESC;
</code>```

But result is the same for 2 queries, no matter if order is asc or desc.

答:
I experimented with your code and found a solution.

The solution that works looks like this

I have added a second compare function with two parameters

```<code>create or replace type height as object
(
    val number,

    constructor function height return self as result,
    constructor function height (val number) return self as result,

    order member function compare2 (other height) return integer,
    member function compare (o1 height,o2 height) return integer
);
/
</code>```

```<code>create or replace type body height is
    constructor function height return self as result is
         begin
            self.val := null;
         end;

    constructor function height (val number) return self as result is
         begin
            self.val := val;
            return;
         end;

    order member function compare2 (other height) return integer is
       begin
            RETURN compare(SELF,other);
        end;
     member function compare (o1 height,o2 height) return integer is
        begin
          if o1.val > o2.val then return 1;
            elsif o1.val < o2.val then return -1;
            else return 0;
            end if;
        end;

end;
/
</code>```

```<code>select p.height.val from people p order by height ASC;
</code>```

```
| HEIGHT.VAL |
| ---------: |
|        130 |
|        150 |
|        180 |
```

```<code>select p.height.val from people p order by height DESC;
</code>```

```
| HEIGHT.VAL |
| ---------: |
|        180 |
|        150 |
|        130 |
```

db<>fiddle here

Body:
Oracle doc says as follows: "As with map methods, an order method, if one is defined, is called automatically whenever two objects of that type need to be compared."

So I assume it will sort when using 'order by' clausule.

Lets say, I have following object:

create or replace type height as object
(
    val number,

    constructor function height return self as result,
    constructor function height (val number) return self as result,

    order member function compare (other height) RETURN INTEGER
);

and its body implementation:

create or replace type body height is
    constructor function height return self as result is
         begin
            self.val := null;
         end;

    constructor function height (val number) return self as result is
         begin
            self.val := val;
            return;
         end;

    order member function compare (other height) return integer is
        begin
            if self.val > self.val then return 1;
            elsif self.val < self.val then return -1;
            else return 0;
            end if;
        end;
end;

Then my table looks like this:

CREATE TABLE people (
    name varchar2(50),
    height height
);

And some records ...

insert into people values ('Foo', height(150));
insert into people values ('Bar', height(130));
insert into people valueS ('Baz', height(180));

Then I want to sort it:

select p.height.val from people p order by height ASC;
select p.height.val from people p order by height DESC;

But result is the same for 2 queries, no matter if order is asc or desc.

Body:
I experimented with your code and found a solution.

The solution that works looks like this

I have added a second compare function with two parameters

create or replace type height as object
(
    val number,

    constructor function height return self as result,
    constructor function height (val number) return self as result,

    order member function compare2 (other height) return integer,
    member function compare (o1 height,o2 height) return integer
);
/

create or replace type body height is
    constructor function height return self as result is
         begin
            self.val := null;
         end;

    constructor function height (val number) return self as result is
         begin
            self.val := val;
            return;
         end;

    order member function compare2 (other height) return integer is
       begin
            RETURN compare(SELF,other);
        end;
     member function compare (o1 height,o2 height) return integer is
        begin
          if o1.val > o2.val then return 1;
            elsif o1.val < o2.val then return -1;
            else return 0;
            end if;
        end;

end;
/

select p.height.val from people p order by height ASC;

| HEIGHT.VAL |
| ---------: |
|        130 |
|        150 |
|        180 |

select p.height.val from people p order by height DESC;

| HEIGHT.VAL |
| ---------: |
|        180 |
|        150 |
|        130 |

db<>fiddle here


问:
Augmented reality in mono touch
I'm developing a typical "Windows GUI" based app for iPhone using MONO technologies. I need to add a little AR based functionality to it. It is just about opening up the camera, and showing information to the user regarding nearby businesses.

How can I do this using mono?

答:
Of course it is possible. I have created a project and works very nice. It is quite complicated and I would need three pages to explain it and, the time to do it which I do not have.

In general, you need to look into:

CLLocationManager for location and
compass.

MapKit, if you want to provide
reverse geocoding information.

Implement an overlay    view over the
UIImagePickerController    which will
act as your canvas.

And of    course, drawing.

I hope these guidelines will get you started.

Title: Augmented reality in mono touch


问:
Round time(7) column values no nearest 15 minutes
I have columns of type time(7)[nulls allowed], some of the values need to be to be adjusted to the nearest 15 minute mark and the seconds set to zero.

Example:

```<code>09:00:40.0000000 -> 09:00:00.0000000
12:50:00.0000000 -> 12:45:00.0000000
12:59:37.0000000 -> 13:00:00.0000000
</code>```

答:
Try this-</p>

```<code>SELECT
CAST
(
    DATEADD(MINUTE, ROUND(DATEDIFF(MINUTE, 0,
    CAST('2015-11-24  ' -- Add any day for converting to DateTime
    +LEFT('09:00:40.0000000',LEN('09:00:40.0000000') - 4) -- Removing last four zero from your data to convert to date time
    AS DATETIME)) / 15.0, 0) * 15, 0)
    AS TIME
);
</code>```

Body:
I have columns of type time(7)[nulls allowed], some of the values need to be to be adjusted to the nearest 15 minute mark and the seconds set to zero.

Example:

09:00:40.0000000 -> 09:00:00.0000000
12:50:00.0000000 -> 12:45:00.0000000
12:59:37.0000000 -> 13:00:00.0000000

Body:
Try this-

SELECT
CAST
(
    DATEADD(MINUTE, ROUND(DATEDIFF(MINUTE, 0,
    CAST('2015-11-24  ' -- Add any day for converting to DateTime
    +LEFT('09:00:40.0000000',LEN('09:00:40.0000000') - 4) -- Removing last four zero from your data to convert to date time
    AS DATETIME)) / 15.0, 0) * 15, 0)
    AS TIME
);