问:
How can the interface-driven serialization framework be improved?
I am developing an interface-driven serialization framework for use with interfaces for data XML serialization.

The ultimate goal is, that that framework is capable of save/load the state of the object (or a part of it, visible thought interface prism) using interfaces as an abstraction.

While thinking of the design, I have found, that using C# attributes, I can provide framework with required info to
save and load state of the object, and the way, how to perform a serialization/deserialization. As an advantages, I discovered that no solution exits, capable of partial object save/restore. If i describe the XML data in terms of an interface with data attributes, i have found that it is not requred anymore to have a dependency to that interface form the class (so that class does not require anymore to implement the given interface for the XML data).

I have a question about the usage of XmlObjectSerializer class, due to some usability issues. Here the example of the interface declaration, being tested:

Here is a primer:

```<code>    interface IPersonRoot
    {
        string Name { get; set; }
    }

    [XmlRootSerializer("Body")]
    interface IPersonCustomRoot
    {
        string Name { get; set; }
    }

    interface IPersonAttribute
    {
        [XmlAttributeRuntimeSerializer]
        string Name { get; set; }
    }

    interface IPersonCustomAttribute
    {
        [XmlAttributeRuntimeSerializer("Id")]
        string Name { get; set; }
    }

    interface IPersonElement
    {
        [XmlElementRuntimeSerializer]
        string Name { get; set; }
    }

    interface IPersonCustomElement
    {
        [XmlElementRuntimeSerializer("Head")]
        string Name { get; set; }
    }

    interface IPersonCustomElementString
    {
        [XmlElementRuntimeSerializer("Head", typeof(string))]
        string Name { get; set; }
    }

    interface IVeryImportantPersonRoot : IPersonRoot
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomRoot : IPersonCustomRoot
    {
        Guid Id { get; set; }
    }

    [XmlRootSerializer("Spirit")]
    interface IVeryImportantPersonCustomRootOverride : IPersonCustomRoot
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonAttribute : IPersonAttribute
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomAttribute : IPersonCustomAttribute
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonElement : IPersonElement
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomElement : IPersonCustomElement
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomElementOverride : IPersonCustomElement
    {
        [XmlElementRuntimeSerializer("Guid")]
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomElementOverrideGuid : IPersonCustomElement
    {
        [XmlElementRuntimeSerializer("Guid", typeof(Guid))]
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomRuntimeSerializer : IPersonCustomElement
    {
        Guid Id { get; set; }

        [XmlColorRuntimeSerializer]
        Color Color { get; set; }
    }

    interface IVeryImportantPersonColor
    {
        string Name { get; set; }

        Guid Id { get; set; }

        [XmlColorRuntimeSerializer]
        Color Color { get; set; }
    }
</code>```

Here is the XmlObjectSerializer class definition:

```<code>public class XmlObjectSerializer
{
        //...
        public static void Load<T>(string xml, Type type, object value)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                XDocument root = XDocument.Load(XmlReader.Create(ms));
                string rootName = GetRootName(typeof(T), root.Root.Name.ToString());
                IXmlObjectSerializer serializer = Load(root.Root, CreateInternal(null, rootName));
                serializer.Deserialize(type, value);
            }
        }
        public static void Load<T>(string xml, object value)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                XDocument root = XDocument.Load(XmlReader.Create(ms));
                string rootName = GetRootName(typeof(T), root.Root.Name.ToString());
                IXmlObjectSerializer serializer = Load(root.Root, CreateInternal(null, rootName));
                serializer.Deserialize(typeof(T), value);
            }
        }
        public static string Save<T>(Type type, object value)
        {
            string rootName = GetRootName(typeof(T), value.GetType().Name);
            XmlObjectSerializer result = CreateInternal(null, rootName);
            IXmlRuntimeSerializer serializer = result;
            serializer.Serialize(type, value);
            XDocument root = new XDocument();
            return result.ToXmlString();
        }
        public static string Save<T>(object value)
        {
            string rootName = GetRootName(typeof(T), value.GetType().Name);
            XmlObjectSerializer result = CreateInternal(null, rootName);
            IXmlRuntimeSerializer serializer = result;
            serializer.Serialize(typeof(T), value);
            return result.ToXmlString();
        }
        public static void Load(Stream data, Type type, object value)
        {
            XDocument document = XDocument.Load(XmlReader.Create(data));
            string rootName = GetRootName(type, document.Root.Name.ToString());
            IXmlObjectSerializer serializer = Load(document.Root, CreateInternal(null, rootName));
            serializer.Deserialize(type, value);
        }
        public static void Save(Stream data, Type type, object value)
        {
            string rootName = GetRootName(type, value.GetType().Name);
            XmlObjectSerializer serializer = CreateInternal(null, rootName);
            serializer.Save(type, data, value);
        }
}
</code>```

Then, here is a question:

Is is better to change XmlObjectSerializer class to be more generic, like XmlObjectSerializer, or just hide all public methods, which uses an Type as as argument? I have the compiler static analyzer warning, saying that using a generic methods, (i.e. Load(...), Save(...)) in a non-generic class is a bad practices and should be changed to the method, accepting Type as an argument.

The problem is, should i change the design of a XmlObjectSerializer class following that rule (in this case, i will loose generic approach) and use object and Type as an arguments, or keep the methods intact.

Can you give me an advice to follow on, and code samples related to posted code sample?

Phanx,

答:
I think that particular compiler warning in the general case is garbage; you should always look at the specific case.

Having written a few such frameworks, I would agree that it is important to include a Type based API, since there are many scenarios for such libraries where generics are a nuisance. By optimising for the non-generic case (rather than using MakeGenericMethod) you can do the other very simply:

```<code>Foo(Type type, ...) {...}
Foo<T>(...) { Foo(typeof(T), ...); }
</code>```

This coming from someone currently re-writing a library to move the optimised case to Type rather than <T>. This is especially important for compact framework etc, where otherwise you can start getting missing-method exceptions when it runs out of space.

Re the interfaces; looks messy and complex - tl;dr; on that. But as long as you're happy...

Body:
I am developing an interface-driven serialization framework for use with interfaces for data XML serialization.

The ultimate goal is, that that framework is capable of save/load the state of the object (or a part of it, visible thought interface prism) using interfaces as an abstraction.

While thinking of the design, I have found, that using C# attributes, I can provide framework with required info to
save and load state of the object, and the way, how to perform a serialization/deserialization. As an advantages, I discovered that no solution exits, capable of partial object save/restore. If i describe the XML data in terms of an interface with data attributes, i have found that it is not requred anymore to have a dependency to that interface form the class (so that class does not require anymore to implement the given interface for the XML data).

I have a question about the usage of XmlObjectSerializer class, due to some usability issues. Here the example of the interface declaration, being tested:

Here is a primer:

    interface IPersonRoot
    {
        string Name { get; set; }
    }

    [XmlRootSerializer("Body")]
    interface IPersonCustomRoot
    {
        string Name { get; set; }
    }

    interface IPersonAttribute
    {
        [XmlAttributeRuntimeSerializer]
        string Name { get; set; }
    }

    interface IPersonCustomAttribute
    {
        [XmlAttributeRuntimeSerializer("Id")]
        string Name { get; set; }
    }

    interface IPersonElement
    {
        [XmlElementRuntimeSerializer]
        string Name { get; set; }
    }

    interface IPersonCustomElement
    {
        [XmlElementRuntimeSerializer("Head")]
        string Name { get; set; }
    }

    interface IPersonCustomElementString
    {
        [XmlElementRuntimeSerializer("Head", typeof(string))]
        string Name { get; set; }
    }

    interface IVeryImportantPersonRoot : IPersonRoot
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomRoot : IPersonCustomRoot
    {
        Guid Id { get; set; }
    }

    [XmlRootSerializer("Spirit")]
    interface IVeryImportantPersonCustomRootOverride : IPersonCustomRoot
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonAttribute : IPersonAttribute
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomAttribute : IPersonCustomAttribute
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonElement : IPersonElement
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomElement : IPersonCustomElement
    {
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomElementOverride : IPersonCustomElement
    {
        [XmlElementRuntimeSerializer("Guid")]
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomElementOverrideGuid : IPersonCustomElement
    {
        [XmlElementRuntimeSerializer("Guid", typeof(Guid))]
        Guid Id { get; set; }
    }

    interface IVeryImportantPersonCustomRuntimeSerializer : IPersonCustomElement
    {
        Guid Id { get; set; }

        [XmlColorRuntimeSerializer]
        Color Color { get; set; }
    }

    interface IVeryImportantPersonColor
    {
        string Name { get; set; }

        Guid Id { get; set; }

        [XmlColorRuntimeSerializer]
        Color Color { get; set; }
    }

Here is the XmlObjectSerializer class definition:

public class XmlObjectSerializer
{
        //...
        public static void Load<T>(string xml, Type type, object value)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                XDocument root = XDocument.Load(XmlReader.Create(ms));
                string rootName = GetRootName(typeof(T), root.Root.Name.ToString());
                IXmlObjectSerializer serializer = Load(root.Root, CreateInternal(null, rootName));
                serializer.Deserialize(type, value);
            }
        }
        public static void Load<T>(string xml, object value)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                XDocument root = XDocument.Load(XmlReader.Create(ms));
                string rootName = GetRootName(typeof(T), root.Root.Name.ToString());
                IXmlObjectSerializer serializer = Load(root.Root, CreateInternal(null, rootName));
                serializer.Deserialize(typeof(T), value);
            }
        }
        public static string Save<T>(Type type, object value)
        {
            string rootName = GetRootName(typeof(T), value.GetType().Name);
            XmlObjectSerializer result = CreateInternal(null, rootName);
            IXmlRuntimeSerializer serializer = result;
            serializer.Serialize(type, value);
            XDocument root = new XDocument();
            return result.ToXmlString();
        }
        public static string Save<T>(object value)
        {
            string rootName = GetRootName(typeof(T), value.GetType().Name);
            XmlObjectSerializer result = CreateInternal(null, rootName);
            IXmlRuntimeSerializer serializer = result;
            serializer.Serialize(typeof(T), value);
            return result.ToXmlString();
        }
        public static void Load(Stream data, Type type, object value)
        {
            XDocument document = XDocument.Load(XmlReader.Create(data));
            string rootName = GetRootName(type, document.Root.Name.ToString());
            IXmlObjectSerializer serializer = Load(document.Root, CreateInternal(null, rootName));
            serializer.Deserialize(type, value);
        }
        public static void Save(Stream data, Type type, object value)
        {
            string rootName = GetRootName(type, value.GetType().Name);
            XmlObjectSerializer serializer = CreateInternal(null, rootName);
            serializer.Save(type, data, value);
        }
}

Then, here is a question:

Is is better to change XmlObjectSerializer class to be more generic, like XmlObjectSerializer, or just hide all public methods, which uses an Type as as argument? I have the compiler static analyzer warning, saying that using a generic methods, (i.e. Load(...), Save(...)) in a non-generic class is a bad practices and should be changed to the method, accepting Type as an argument.

The problem is, should i change the design of a XmlObjectSerializer class following that rule (in this case, i will loose generic approach) and use object and Type as an arguments, or keep the methods intact.

Can you give me an advice to follow on, and code samples related to posted code sample?

Phanx,

Body:
I think that particular compiler warning in the general case is garbage; you should always look at the specific case.

Having written a few such frameworks, I would agree that it is important to include a Type based API, since there are many scenarios for such libraries where generics are a nuisance. By optimising for the non-generic case (rather than using MakeGenericMethod) you can do the other very simply:

Foo(Type type, ...) {...}
Foo<T>(...) { Foo(typeof(T), ...); }

This coming from someone currently re-writing a library to move the optimised case to Type rather than <T>. This is especially important for compact framework etc, where otherwise you can start getting missing-method exceptions when it runs out of space.

Re the interfaces; looks messy and complex - tl;dr; on that. But as long as you're happy...


来源: stackexchange

问:
Travis CI: PHP 7.2 don't support Argon2i
I've an error in my project with Travis CI:

Argon2i algorithm is not supported. Please install the libsodium extension

    or upgrade to PHP 7.2+.

But, Argon2i is present in the PHP 7.2 version and Travis CI install the PHP 7.2 version:

```<code>$ phpenv global 7.2 2>/dev/null

7.2 is not pre-installed; installing
Downloading archive: https://s3.amazonaws.com/travis-php-archives/binaries/ubuntu/14.04/x86_64/php-7.2.tar.bz2
$ curl -s -o archive.tar.bz2 $archive_url && tar xjf archive.tar.bz2 --directory /

$ phpenv global 7.2

$ php --version
PHP 7.2.0 (cli) (built: Dec  2 2017 17:12:55) ( ZTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.2.0, Copyright (c) 1999-2017, by Zend Technologies
    with Xdebug v2.6.0-dev, Copyright (c) 2002-2017, by Derick Rethans
</code>```

Someone have an idea ?

答:
I faced the same problem recently in a Symfony 4 project and posted an issue on Travis' Github.

However, the problem does not seem to come from Travis but from PHP 7.2 default build itself.

Quoting myself:

I was locally using a pre-configured PHP, so to be sure I just compiled PHP 7.2 from sources.

```<code>$ ./php -v
PHP 7.2.0 (cli) (built: Dec  6 2017 15:26:29) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2017 Zend Technologies
</code>```

Then I tryed to use the ARGON2I algorithm such as described in official docs:

```<code>$ ./php -r 'echo password_hash("test", PASSWORD_ARGON2I) . "\n";'
Warning: Use of undefined constant PASSWORD_ARGON2I - assumed
'PASSWORD_ARGON2I' (this will throw an Error in a future version of PHP) in Command line code on line 1
Warning: password_hash() expects parameter 2 to be integer, string given in Command line code on line 1
</code>```

While not having any problem with BCRYPT:

```<code>$ ./php -r 'echo password_hash("test", PASSWORD_BCRYPT) . "\n";'
$2y$10$wsWe3BhyzenVqDs6JV/fPOB0XKh0oTuGdrgLp61MnUPzOUdw4jZey
</code>```

This is strange. I would have expected this algorithm to be part of the default PHP 7.2 build, just as other hash algorithms. And nothing seems to indicate the opposite in the docs. I'll investigate. Maybe I understood something wrong... but this looks like a bug to me, since they say here that PASSWORD_ARGON2I is part of PHP core.

Edit:

In the light of Sheppard's comment, it appears indeed that 7.2 does not implement the PASSWORD_AGRON2Ialgorithm in its default build. PHP has to be compiled with option -with-password-argon2, such as described in https://wiki.php.net/rfc/argon2_password_hash.

ContentLicense: CC BY-SA 3.0

Body:
I've an error in my project with Travis CI:

Argon2i algorithm is not supported. Please install the libsodium extension

    or upgrade to PHP 7.2+.

But, Argon2i is present in the PHP 7.2 version and Travis CI install the PHP 7.2 version:

$ phpenv global 7.2 2>/dev/null

7.2 is not pre-installed; installing
Downloading archive: https://s3.amazonaws.com/travis-php-archives/binaries/ubuntu/14.04/x86_64/php-7.2.tar.bz2
$ curl -s -o archive.tar.bz2 $archive_url && tar xjf archive.tar.bz2 --directory /

$ phpenv global 7.2

$ php --version
PHP 7.2.0 (cli) (built: Dec  2 2017 17:12:55) ( ZTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.2.0, Copyright (c) 1999-2017, by Zend Technologies
    with Xdebug v2.6.0-dev, Copyright (c) 2002-2017, by Derick Rethans

Someone have an idea ?

Body:
I faced the same problem recently in a Symfony 4 project and posted an issue on Travis' Github.

However, the problem does not seem to come from Travis but from PHP 7.2 default build itself.

Quoting myself:

I was locally using a pre-configured PHP, so to be sure I just compiled PHP 7.2 from sources.

$ ./php -v
PHP 7.2.0 (cli) (built: Dec  6 2017 15:26:29) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2017 Zend Technologies

Then I tryed to use the ARGON2I algorithm such as described in official docs:

$ ./php -r 'echo password_hash("test", PASSWORD_ARGON2I) . "\n";'
Warning: Use of undefined constant PASSWORD_ARGON2I - assumed
'PASSWORD_ARGON2I' (this will throw an Error in a future version of PHP) in Command line code on line 1
Warning: password_hash() expects parameter 2 to be integer, string given in Command line code on line 1

While not having any problem with BCRYPT:

$ ./php -r 'echo password_hash("test", PASSWORD_BCRYPT) . "\n";'
$2y$10$wsWe3BhyzenVqDs6JV/fPOB0XKh0oTuGdrgLp61MnUPzOUdw4jZey

This is strange. I would have expected this algorithm to be part of the default PHP 7.2 build, just as other hash algorithms. And nothing seems to indicate the opposite in the docs. I'll investigate. Maybe I understood something wrong... but this looks like a bug to me, since they say here that PASSWORD_ARGON2I is part of PHP core.

Edit:

In the light of Sheppard's comment, it appears indeed that 7.2 does not implement the PASSWORD_AGRON2Ialgorithm in its default build. PHP has to be compiled with option -with-password-argon2, such as described in https://wiki.php.net/rfc/argon2_password_hash.


问:
How to center align text in a HTML table cell, without considering other elements in the cell

How do I center text in a div in a column without counting other element in same div, please?

td {
  border: 1px solid black;
  width: 150px;
  text-align: center;
}

button {
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>text1</td>
  </tr>
    <td>text2<button>ok</button></td>
  <tr>
    <td>text3</td>
  </tr>
</table></code>```

答:
Give a class to your text and add the below

```<code>.yourclass{
    text-align: center;
}
</code>```

in your css

Body:
How do I center text in a div in a column without counting other element in same div, please?

td {
  border: 1px solid black;
  width: 150px;
  text-align: center;
}

button {
  float: right;
}

    text1

    text2<button>ok</button>

    text3

Body:
Give a class to your text and add the below

.yourclass{
    text-align: center;
}

in your css


问:
How to replace comma with space in text file using VBA
I have data in a text file (input.jpg). I want to replace the comma with the space and align the data in one line.Please see the output text file (output.jpg).

how to do this in VBA.
Please help me.

[input data]

答:
This should do the trick:</p>

```<code>Sub foo()
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Test.txt" 'change the path to whatever yours ought to be
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)

Do While Not objTS.AtEndOfStream
    strContents = strContents & " " & objTS.ReadLine 'Read line by line and store all lines in strContents
Loop

strContents = Replace(strContents, ",", " ")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
End Sub
</code>```

Body:
This should do the trick:

Sub foo()
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Test.txt" 'change the path to whatever yours ought to be
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)

Do While Not objTS.AtEndOfStream
    strContents = strContents & " " & objTS.ReadLine 'Read line by line and store all lines in strContents
Loop

strContents = Replace(strContents, ",", " ")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
End Sub


问:
Cross-Platform iOS/Mac OS X Objective-C development?
I'll be starting  medium-sized iOS project soon, a document-centric app.

Later, the software might get ported to Mac OS X. Of course, the whole UI will need to change; that's not what I'm asking.

Is it possible to write the core logic in such a way that it's cross-platform (Mac/iOS only), or more easily ported? Has anybody done this before, or is the usual way to just write different code for both platforms?

I'm thankful for any tips regarding this, be they about Code, Frameworks, Version Control - anything. I'd hate to realize I've painted myself into a corner only after the fact, so I want to start as well as possible.

答:
Any pure logic and "model" level classes you create will, in the main, work on both iOS and Mac OS X, as long as you stick to the Cocoa classes, and SQLite/Core Data, etc. methods that are common to both systems. That said, the iOS file system is heavily sandboxed, which isn't a restriction on OS X and that's something you'll also need to deal with in a "document centric" app.

However, as you state the UI level classes are completely different on both systems, with iOS using the various UIKit classes in comparison to the various NS classes on OS X. As such, it's unlikely you'll be able to share much at that level.

In terms of sharing the code between the two projects, you could create a "common" project of lower level objects, etc., add and this as a reference within the iOS and Mac OS X projects, although this may end up proving somewhat painful if things diverge (which I suspect they might). Irrespective, there's a good blog post on this topic called "Easy, Modular Code Sharing Across iPhone Apps: Static Libraries and Cross-Project References" by Clint Harris which is worth a read, although it does focus primarily on the iOS side of things.

ContentLicense: CC BY-SA 2.5


问:
VSTS Task - Azure RM Service Reference
I'm working on VSTS Task which will populate input data from AzureRM. Anyone know help to find out the data binding reference (marked as xxxxxxx)? I would like to get data about automation account, but i wasn't able to find it. Many thanks.</p>

```<code>"inputs":[
    {
        "name": "ConnectedServiceName",
        "type": "connectedService:AzureRM",
        "label": "Azure RM Subscription",
        "required": true,
        "helpMarkDown": "Azure Resource Manager subscription",
    },
    {
        "name": "ResourceGroupName",
        "label": "Resource Group",
        "type": "pickList",
        "required": true,
        "helpMarkDown": "Provide the name of a resource group.",
        "properties": {
        "EditableOptions": "True"
    },
    {
        "name": "AutomationAccount",
        "type": "pickList",
        "label": "Automation Account Name",
        "required": true,
        "helpMarkDown": "Select or Type Automation Account Name",
        "properties": {
            "EditableOptions": "True"
        }
    }
],
"dataSourceBindings": [
    {
        "target": "ResourceGroupName",
        "endpointId": "$(ConnectedServiceName)",
        "dataSourceName": "AzureResourceGroups"
    },
    {
        "target": "AutomationAccount",
        "endpointId": "$(ConnectedServiceName)",
        "dataSourceName": "xxxxxxxxxxxxxxxxx"
    },
]
</code>```

答:
There is actually a blog post on service endpoints available: Service endpoints – Data sources

Looks like you can also perform the same Rest call as the service endpoint to retrieve the entire structure with

```<code>https://YourVSTSSubscription.visualstudio.com/defaultcollection/_apis/distributedtask/serviceendpointtypes?type=AzureRM
</code>```

Title: VSTS Task - Azure RM Service Reference

Body:
I'm working on VSTS Task which will populate input data from AzureRM. Anyone know help to find out the data binding reference (marked as xxxxxxx)? I would like to get data about automation account, but i wasn't able to find it. Many thanks.

"inputs":[
    {
        "name": "ConnectedServiceName",
        "type": "connectedService:AzureRM",
        "label": "Azure RM Subscription",
        "required": true,
        "helpMarkDown": "Azure Resource Manager subscription",
    },
    {
        "name": "ResourceGroupName",
        "label": "Resource Group",
        "type": "pickList",
        "required": true,
        "helpMarkDown": "Provide the name of a resource group.",
        "properties": {
        "EditableOptions": "True"
    },
    {
        "name": "AutomationAccount",
        "type": "pickList",
        "label": "Automation Account Name",
        "required": true,
        "helpMarkDown": "Select or Type Automation Account Name",
        "properties": {
            "EditableOptions": "True"
        }
    }
],
"dataSourceBindings": [
    {
        "target": "ResourceGroupName",
        "endpointId": "$(ConnectedServiceName)",
        "dataSourceName": "AzureResourceGroups"
    },
    {
        "target": "AutomationAccount",
        "endpointId": "$(ConnectedServiceName)",
        "dataSourceName": "xxxxxxxxxxxxxxxxx"
    },
]

Body:
There is actually a blog post on service endpoints available: Service endpoints – Data sources

Looks like you can also perform the same Rest call as the service endpoint to retrieve the entire structure with

https://YourVSTSSubscription.visualstudio.com/defaultcollection/_apis/distributedtask/serviceendpointtypes?type=AzureRM


问:
Overload operator<< for a vector struct of pointer?
I am currently trying to make a overload operator<<  to my  vector of structs, such that I will print the content of the vector in a matrix format..

this is what I've tried so far

```<code>// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

struct element
{
    std::vector<int> keys;
    std::string item;

    element(std::vector <int> key, std::string item)
    {
        keys = key;
        this->item = item;
    }

};

inline std::stream operator << (std::ostream &stream, const std::vector<element*> _element)
{
    for (auto elements: _element)
    {
        for(auto item : elements)
        {
            std::stream << item.key << " "
        }
    }

}

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;
    std::vector<element> storage;
    std::vector<int> test(10);
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    std::string name = "test";
    storage.push_back(element(test,name));
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    storage.push_back(element(test,name));
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    storage.push_back(element(test,name));

    std::vector<element*> copy_of_storage;
    for(auto elements: storage)
    {
        copy_of_storage.push_back(&(elements));
    }

    std::cout << copy_of_storage << std::endl;

}
</code>```

but for some reason it is not working, and can't seem to understand what is going wrong?

https://wandbox.org/permlink/BQpqmz0HwoXgyS7t

答:
There are a lot of things that are wrong in your operator<<.

First, your return type should be std::ostream& thus you must return stream. In your second loop :

```<code>    for(auto item : elements)
</code>```

elements is a pointer of element (the value type of your vector) so you can't iterate other it, you might want to iterate other elements->keys

Here is your fixed function :

```<code>inline std::ostream& operator<< (std::ostream &stream, const  std::vector<element*> _element)
{
    for (auto elements: _element)
        for(auto item : elements->keys)
            stream << item << " ";
    return stream;
}
</code>```

https://wandbox.org/permlink/qNYVx2yMg7L76NWe

Body:
I am currently trying to make a overload operator<<  to my  vector of structs, such that I will print the content of the vector in a matrix format..

this is what I've tried so far

// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

struct element
{
    std::vector<int> keys;
    std::string item;

    element(std::vector <int> key, std::string item)
    {
        keys = key;
        this->item = item;
    }

};

inline std::stream operator << (std::ostream &stream, const std::vector<element*> _element)
{
    for (auto elements: _element)
    {
        for(auto item : elements)
        {
            std::stream << item.key << " "
        }
    }

}

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;
    std::vector<element> storage;
    std::vector<int> test(10);
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    std::string name = "test";
    storage.push_back(element(test,name));
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    storage.push_back(element(test,name));
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    storage.push_back(element(test,name));

    std::vector<element*> copy_of_storage;
    for(auto elements: storage)
    {
        copy_of_storage.push_back(&(elements));
    }

    std::cout << copy_of_storage << std::endl;

}

but for some reason it is not working, and can't seem to understand what is going wrong?

https://wandbox.org/permlink/BQpqmz0HwoXgyS7t

Body:
There are a lot of things that are wrong in your operator<<.

First, your return type should be std::ostream& thus you must return stream. In your second loop :

    for(auto item : elements)

elements is a pointer of element (the value type of your vector) so you can't iterate other it, you might want to iterate other elements->keys

Here is your fixed function :

inline std::ostream& operator<< (std::ostream &stream, const  std::vector<element*> _element)
{
    for (auto elements: _element)
        for(auto item : elements->keys)
            stream << item << " ";
    return stream;
}

https://wandbox.org/permlink/qNYVx2yMg7L76NWe


问:
How can I run sails console without a webserver (using any ports)?
I have a Sails server running, and I want to execute some commands from inside of lifted Sails.

The problem is, then I run sails console - it bootstraps another instance of Sails, and trying to load another webserver next to existing, by default using the same ports.

By some environment limits, I can use only one port at the time. So I cannot load another webserver on the same machine.

Is there a way how to run sails console without using any ports?

Thank you.

答: There is an option. Use sails console --dontLift


问:
Basemap - Values must be between -90, 90 Degrees
OBJECTIVE

Upload a GIS, shapefile (county boundaries) into Basemap

Use Basemap to plot county boundaries

Determine whether or not a location falls within Boundaries

Assign a weight to a point, depending on which boundary they fall into

Use DBSCAN to discover cluster centriod based on coordinates and weight

APPROACH

Using this tutorial on Basemap, upload a shapefile for mapping.

```<code>#First, we have to import our datasets.
#These datasets include store locations, existing distribution locations, county borders, and real estate by county
walmartStores = pd.read_csv("data/walmart-stores.csv",header=0, encoding='latin1')
propertyValues = pd.read_csv("data/property values.csv")
shp = fiona.open('data/boundaries/Counties.shp')

#We need to create a workable array with Walmart Stores
longitude = walmartStores.longitude
latitude = walmartStores.latitude
stores = np.column_stack((longitude, latitude))

#We also need to load the shape file for county boundaries
extra = 0.1
bds = shp.bounds
shp.close()

#We need to assign the lower-left bound and upper-right bound
ll = (bds[0], bds[1])
ur = (bds[2], bds[3])

#concatenate the lower left and upper right into a variable called coordinates
coords = list(chain(ll, ur))
print(coords)

#define variables for the width and the height of the map
w, h = coords[2] - coords[0], coords[3] - coords[1]
</code>```

with print(coords) = [105571.4206781257, 4480951.235680977, 779932.0626624253, 4985476.422250552]

All is well thus far, however I run into a problem below:

```<code>m = Basemap(
    #set projection to 'tmerc' to minimize map distortion
    projection='tmerc',

    #set longitude as average of lower, upper longitude bounds
    lon_0 = np.average([bds[0],bds[2]]),

    #set latitude as average of lower,upper latitude bounds
    lat_0 = np.average([bds[1],bds[3]]),

    #string describing ellipsoid (‘GRS80’ or ‘WGS84’, for example).
    #Not sure what this does...
    ellps = 'WGS84',

    #set the map boundaries. Note that we use the extra variable to provide a 10% buffer around the map
    llcrnrlon=coords[0] - extra * w,
    llcrnrlat=coords[1] - extra + 0.01 * h,
    urcrnrlon=coords[2] + extra * w,
    urcrnrlat=coords[3] + extra + 0.01 * h,

    #provide latitude of 'true scale.'
    #check the Basemap API
    lat_ts=0,

    #resolution of boundary database to use. Can be c (crude), l (low), i (intermediate), h (high), f (full) or None.
    resolution='i',

    #don't show the axis ticks automatically
    suppress_ticks = False)

m.readshapefile(
    #provide the path to the shapefile, but leave off the .shp extension
    'data/boundaries/Counties.shp',

    #name your map something useful (I named this 'srilanka')
    'nyCounties',

    #set the default shape boundary coloring (default is black) and the zorder (layer order)
    color='none',
    zorder=2)
</code>```

Error: lat_0 must be between -90.000000 and 90.000000

QUESTIONS

lat_0 and lon_0 aren't between -90 and 90. However, lon_0 doesn't throw an error. Why is this the case?

I've looked online for others facing a similar issue and have come up empty handed. Is there something unique with my notebook? (NOTE: conda list shows `basemap 1.0.7, so I know that it's installed and running)

Thanks!

答:
Latitude can only be between -90 and 90 - anything else doesn't makes sense. The North pole is +90 and the South pole is -90, with the equator at 0. There are no other acceptable values!

Regarding longtitude, it can only be between -180 and 180. 0 is at the Prime Meridian and going to -180 (westward) and +180 (eastward)

Body:
OBJECTIVE

Upload a GIS, shapefile (county boundaries) into Basemap

Use Basemap to plot county boundaries

Determine whether or not a location falls within Boundaries

Assign a weight to a point, depending on which boundary they fall into

Use DBSCAN to discover cluster centriod based on coordinates and weight

APPROACH

Using this tutorial on Basemap, upload a shapefile for mapping.

#First, we have to import our datasets.
#These datasets include store locations, existing distribution locations, county borders, and real estate by county
walmartStores = pd.read_csv("data/walmart-stores.csv",header=0, encoding='latin1')
propertyValues = pd.read_csv("data/property values.csv")
shp = fiona.open('data/boundaries/Counties.shp')

#We need to create a workable array with Walmart Stores
longitude = walmartStores.longitude
latitude = walmartStores.latitude
stores = np.column_stack((longitude, latitude))

#We also need to load the shape file for county boundaries
extra = 0.1
bds = shp.bounds
shp.close()

#We need to assign the lower-left bound and upper-right bound
ll = (bds[0], bds[1])
ur = (bds[2], bds[3])

#concatenate the lower left and upper right into a variable called coordinates
coords = list(chain(ll, ur))
print(coords)

#define variables for the width and the height of the map
w, h = coords[2] - coords[0], coords[3] - coords[1]

with print(coords) = [105571.4206781257, 4480951.235680977, 779932.0626624253, 4985476.422250552]

All is well thus far, however I run into a problem below:

m = Basemap(
    #set projection to 'tmerc' to minimize map distortion
    projection='tmerc',

    #set longitude as average of lower, upper longitude bounds
    lon_0 = np.average([bds[0],bds[2]]),

    #set latitude as average of lower,upper latitude bounds
    lat_0 = np.average([bds[1],bds[3]]),

    #string describing ellipsoid (‘GRS80’ or ‘WGS84’, for example).
    #Not sure what this does...
    ellps = 'WGS84',

    #set the map boundaries. Note that we use the extra variable to provide a 10% buffer around the map
    llcrnrlon=coords[0] - extra * w,
    llcrnrlat=coords[1] - extra + 0.01 * h,
    urcrnrlon=coords[2] + extra * w,
    urcrnrlat=coords[3] + extra + 0.01 * h,

    #provide latitude of 'true scale.'
    #check the Basemap API
    lat_ts=0,

    #resolution of boundary database to use. Can be c (crude), l (low), i (intermediate), h (high), f (full) or None.
    resolution='i',

    #don't show the axis ticks automatically
    suppress_ticks = False)

m.readshapefile(
    #provide the path to the shapefile, but leave off the .shp extension
    'data/boundaries/Counties.shp',

    #name your map something useful (I named this 'srilanka')
    'nyCounties',

    #set the default shape boundary coloring (default is black) and the zorder (layer order)
    color='none',
    zorder=2)

Error: lat_0 must be between -90.000000 and 90.000000

QUESTIONS

lat_0 and lon_0 aren't between -90 and 90. However, lon_0 doesn't throw an error. Why is this the case?

I've looked online for others facing a similar issue and have come up empty handed. Is there something unique with my notebook? (NOTE: conda list shows `basemap 1.0.7, so I know that it's installed and running)

Thanks!


问:
NUnit GUI runner command line args
In looking at the available command line arguments for the nunit.exe, I haven't been able to find a way to specify the path and filename of the TestResults.xml file (it always ends up in the same folder as the test fixture).  I know this can be specified when using nunit-console.exe via the /xml argument, but is there there any way to specify this for nunit.exe?

Thanks.

答: Looks like what I'm trying to do isn't possible.  No biggie.</p>

Title: NUnit GUI runner command line args


问:
Rails: "except" vs "slice" to take out certain parameter?
I am trying to create a class instance with one particular key extracted out and save for later

consider this is the type of param:

```<code>Parameters: {"p1": "foo", "p2": "bar", "p3":"param that i want to extract" >
</code>```

I would do something like:

```<code>@my_class = MyClass.new(whiteList_function.except(:p3))
</code>```

or something like

```<code>@my_class = MyClass.new(whiteList_function)
@my_class_key = @my_class.slice(:p3)
</code>```

My whiteList_function:

```<code>def whiteList_function
    params.require(:my_class).permit(:p1,:p2,p3)
end
</code>```

My concern is that, I have searched on SO and some have mentioned the security risk of using except.

So my question is, in this particular usage(take out certain key and use them for later), should I use except or slice?

答:
I'm no Rails user and maybe I misunderstand your question but in plain Ruby here is what I would do</p>

```<code>class MyClass
  attr_reader :params
  def initialize params
    @params = whiteList_function params
  end
  def whiteList_function params
    whiteList = [:p1, :p2]
    params.select{|key| whiteList.include? key }
  end
end

MyClass.new({"p1": "foo", "p2": "bar", "p3":"param that i want to extract"})
# #<MyClass:0x00000002802a58 @params={:p1=>"foo", :p2=>"bar"}>
</code>```

Body:
I am trying to create a class instance with one particular key extracted out and save for later

consider this is the type of param:

Parameters: {"p1": "foo", "p2": "bar", "p3":"param that i want to extract" >

I would do something like:

@my_class = MyClass.new(whiteList_function.except(:p3))

or something like

@my_class = MyClass.new(whiteList_function)
@my_class_key = @my_class.slice(:p3)

My whiteList_function:

def whiteList_function
    params.require(:my_class).permit(:p1,:p2,p3)
end

My concern is that, I have searched on SO and some have mentioned the security risk of using except.

So my question is, in this particular usage(take out certain key and use them for later), should I use except or slice?

Body:
I'm no Rails user and maybe I misunderstand your question but in plain Ruby here is what I would do

class MyClass
  attr_reader :params
  def initialize params
    @params = whiteList_function params
  end
  def whiteList_function params
    whiteList = [:p1, :p2]
    params.select{|key| whiteList.include? key }
  end
end

MyClass.new({"p1": "foo", "p2": "bar", "p3":"param that i want to extract"})
# #<MyClass:0x00000002802a58 @params={:p1=>"foo", :p2=>"bar"}>


问:
Creating a Column-Vector in Python Numpy in Fortran order

I need a numpy array with 3-rows and 1 Column (for pyCGNS when creating a Zone).

And This Must be true when asking if it is NPY.isfortran(X).

I tried several ways, but none worked.

e.g.

```<code>a1 = NPY.zeros((3,1),order='F')
print NPY.isfortran(a1)
->False
</code>```

答:
The function is obsolete. it  returns:

True if the array is Fortran contiguous BUT not C contiguous.

```<code>In [421]: np.isfortran(a1)
Out[421]: False

In [422]: a1.flags
Out[422]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False
</code>```

Your array is fortran contiguous AND C contiguous.

Body:
I need a numpy array with 3-rows and 1 Column (for pyCGNS when creating a Zone).

And This Must be true when asking if it is NPY.isfortran(X).

I tried several ways, but none worked.

e.g.

a1 = NPY.zeros((3,1),order='F')
print NPY.isfortran(a1)
->False

Body:
The function is obsolete. it  returns:

True if the array is Fortran contiguous BUT not C contiguous.

In [421]: np.isfortran(a1)
Out[421]: False

In [422]: a1.flags
Out[422]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

Your array is fortran contiguous AND C contiguous.


问:
Redis error in node.js
I am using Redis in Node.js and when deployed on live server it started to crash with below error message:

The no of requests are more per second.

```<code>at Object.replyToObject [as reply_to_object] (/home/ubuntu/webservices/node_modules/redis/lib/utils.js:7:15)
at RedisClient.handle_reply (/home/ubuntu/webservices/node_modules/redis/index.js:319:23)
at multi_callback (/home/ubuntu/webservices/node_modules/redis/lib/multi.js:79:43)
at Command.callback (/home/ubuntu/webservices/node_modules/redis/lib/multi.js:116:9)
at normal_reply (/home/ubuntu/webservices/node_modules/redis/index.js:726:21)
at RedisClient.return_reply (/home/ubuntu/webservices/node_modules/redis/index.js:824:9)
at JavascriptRedisParser.returnReply (/home/ubuntu/webservices/node_modules/redis/index.js:192:18)
at JavascriptRedisParser.execute (/home/ubuntu/webservices/node_modules/redis/node_modules/redis-parser/lib/parser.js:553:10)
Socket.<anonymous> (/home/ubuntu/webservices/node_modules/redis/index.js:274:27)
emitOne (events.js:116:13)
Socket.emit (events.js:211:7)
addChunk (_stream_readable.js:263:12)
readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:594:20)
</code>```

I have written common code to open and close the Redis connections and try to reuse connections. (not sure is it correct way of reusing it).

I am using Redis "^2.7.1" and installed Redis locally on Ubuntu.

I am able to enter Redis console and see the keys stored. But not sure why its giving the above error messages very frequently. I am using pm2 module so it restarts once it crashes.

Below is Redis Code in Node.js

```<code>var Promise = require('bluebird');
var Redis = Promise.promisifyAll(require('redis'));

// Global (Avoids Duplicate Connections)
var redisClient = null;
var redisMultiClient = null;

// Make the below functions as private
function openRedisConnection() {
    if (redisClient && redisClient.connected)
        return redisClient;

    if (redisClient)
        redisClient.end(); // End and open once more

    redisClient = Redis.createClient(6379,process.env.REDIS_URL);
    redisClient.selected_db = 1;
    return redisClient;
}

function openMultiRedisConnection() {
    if (redisMultiClient && redisMultiClient._client.connected) {
        redisMultiClient._client.selected_db = 0;
        return redisMultiClient;
    }

    if (redisMultiClient)
        redisMultiClient.quit(); // End and open once more

    redisMultiClient = Redis.createClient(6379,process.env.REDIS_URL).multi();
    redisMultiClient._client.selected_db = 0;
    return redisMultiClient;
}

function getExpiryTime(key) {
    return 120; // testing
}

module.exports = {
    /**
     * Get Key-Value Pair
     */
    getRedisValue: function (keys) {
        return openRedisConnection().mgetAsync(keys);
    },
    /**
     * Set Key-Value Pair
     */
    setRedisValue: function (key, value) {
        return openRedisConnection()
            .setAsync(key, value, 'EX', getExpiryTime(key))
            .then(function (result) {
                return Promise.resolve(result);
            });
    },

    getV2MultiRedisValue: function (keyList) {
        let redisMultiClientObj = openMultiRedisConnection();
        redisMultiClientObj._client.selected_db = 2;

        redisMultiClientObj.hgetallAsync(keyList);

        return redisMultiClientObj.execAsync()
            .then(function (results) {
                return Promise.resolve(results);
            });
    },

    setV2MultiRedisValue: function (key, redisList) {
        let expiryTime = getExpiryTime(key);
        let redisMultiClientObj = openMultiRedisConnection();
        redisMultiClientObj._client.selected_db = 2;

        for (let item of redisList) {
            redisMultiClientObj.hmsetAsync(item.key, item.value);
            redisMultiClientObj.expireAsync(item.key, expiryTime);
        }
        return redisMultiClientObj.execAsync()
        .then(function (results) {
            return Promise.resolve(results);
        });
    }
};
</code>```

答:
client.multi([commands]) doen't open multi connections, just pointing out because function openMultiRedisConnection is misleading.

You use mulit wrong, per reference

client.multi([commands])

MULTI commands are queued up until an EXEC is issued, and then all
  commands are run atomically by Redis. The interface in node_redis is
  to return an individual Multi object by calling client.multi(). If any
  command fails to queue, all commands are rolled back and none is going
  to be executed (For further information look at transactions).

Multi returns an individual Object and its not very good to use it again after .exec is called.

I don't know why you need more that one database but you are changing database with selected_db and on a global client variable and this is BAD! and could cause many problems!(data inconsistency, conflict, etc).
You can use client.select(callback) to changed database but again it seems like a bad idea.

There is no reason for this part of code its exactly the same as not doing that.

```<code> .then(function (result) {
    return Promise.resolve(result);
  });
</code>```

You should be ok with only one database.

```<code>   var Promise = require('bluebird');
var Redis = Promise.promisifyAll(require('redis'));

// Global (Avoids Duplicate Connections)
var redisClient = [];

// Make the below functions as private
function openRedisConnection( {
    if (redisClient && redisClient.connected)
        return redisClient;

    if (redisClient)
        redisClient.end(); // End and open once more

    redisClient = Redis.createClient(6379,process.env.REDIS_URL,{"db":1});

    return redisClient;
}

function getExpiryTime(key) {
    return 120; // testing
}

module.exports = {
    /**
     * Get Key-Value Pair
     */
    getRedisValue: function (keys) {
        return openRedisConnection().mgetAsync(keys);
    },
    /**
     * Set Key-Value Pair
     */
    setRedisValue: function (key, value) {
        return openRedisConnection()
            .setAsync(key, value, 'EX', getExpiryTime(key));

    },

    getV2MultiRedisValue: function (keyList) {

         let redisClient = openRedisConnection();

        //no need to open multi here....
        let multi = redisClient.multi();

        multi.hgetallAsync(keyList);

        return multi.execAsync();

    },

    setV2MultiRedisValue: function (key, redisList) {
        let expiryTime = getExpiryTime(key);
        let redisClient = openRedisConnection();

        let multi = redisClient.multi();

        for (let item of redisList) {
            multi.hmsetAsync(item.key, item.value);
            multi.expireAsync(item.key, expiryTime);
        }

        return multi.execAsync();

    }
};
</code>```

Title: Redis error in node.js

Body:
I am using Redis in Node.js and when deployed on live server it started to crash with below error message:

The no of requests are more per second.

at Object.replyToObject [as reply_to_object] (/home/ubuntu/webservices/node_modules/redis/lib/utils.js:7:15)
at RedisClient.handle_reply (/home/ubuntu/webservices/node_modules/redis/index.js:319:23)
at multi_callback (/home/ubuntu/webservices/node_modules/redis/lib/multi.js:79:43)
at Command.callback (/home/ubuntu/webservices/node_modules/redis/lib/multi.js:116:9)
at normal_reply (/home/ubuntu/webservices/node_modules/redis/index.js:726:21)
at RedisClient.return_reply (/home/ubuntu/webservices/node_modules/redis/index.js:824:9)
at JavascriptRedisParser.returnReply (/home/ubuntu/webservices/node_modules/redis/index.js:192:18)
at JavascriptRedisParser.execute (/home/ubuntu/webservices/node_modules/redis/node_modules/redis-parser/lib/parser.js:553:10)
Socket.<anonymous> (/home/ubuntu/webservices/node_modules/redis/index.js:274:27)
emitOne (events.js:116:13)
Socket.emit (events.js:211:7)
addChunk (_stream_readable.js:263:12)
readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:594:20)

I have written common code to open and close the Redis connections and try to reuse connections. (not sure is it correct way of reusing it).

I am using Redis "^2.7.1" and installed Redis locally on Ubuntu.

I am able to enter Redis console and see the keys stored. But not sure why its giving the above error messages very frequently. I am using pm2 module so it restarts once it crashes.

Below is Redis Code in Node.js

var Promise = require('bluebird');
var Redis = Promise.promisifyAll(require('redis'));

// Global (Avoids Duplicate Connections)
var redisClient = null;
var redisMultiClient = null;

// Make the below functions as private
function openRedisConnection() {
    if (redisClient && redisClient.connected)
        return redisClient;

    if (redisClient)
        redisClient.end(); // End and open once more

    redisClient = Redis.createClient(6379,process.env.REDIS_URL);
    redisClient.selected_db = 1;
    return redisClient;
}

function openMultiRedisConnection() {
    if (redisMultiClient && redisMultiClient._client.connected) {
        redisMultiClient._client.selected_db = 0;
        return redisMultiClient;
    }

    if (redisMultiClient)
        redisMultiClient.quit(); // End and open once more

    redisMultiClient = Redis.createClient(6379,process.env.REDIS_URL).multi();
    redisMultiClient._client.selected_db = 0;
    return redisMultiClient;
}

function getExpiryTime(key) {
    return 120; // testing
}

module.exports = {
    /**
     * Get Key-Value Pair
     */
    getRedisValue: function (keys) {
        return openRedisConnection().mgetAsync(keys);
    },
    /**
     * Set Key-Value Pair
     */
    setRedisValue: function (key, value) {
        return openRedisConnection()
            .setAsync(key, value, 'EX', getExpiryTime(key))
            .then(function (result) {
                return Promise.resolve(result);
            });
    },

    getV2MultiRedisValue: function (keyList) {
        let redisMultiClientObj = openMultiRedisConnection();
        redisMultiClientObj._client.selected_db = 2;

        redisMultiClientObj.hgetallAsync(keyList);

        return redisMultiClientObj.execAsync()
            .then(function (results) {
                return Promise.resolve(results);
            });
    },

    setV2MultiRedisValue: function (key, redisList) {
        let expiryTime = getExpiryTime(key);
        let redisMultiClientObj = openMultiRedisConnection();
        redisMultiClientObj._client.selected_db = 2;

        for (let item of redisList) {
            redisMultiClientObj.hmsetAsync(item.key, item.value);
            redisMultiClientObj.expireAsync(item.key, expiryTime);
        }
        return redisMultiClientObj.execAsync()
        .then(function (results) {
            return Promise.resolve(results);
        });
    }
};

Body:
client.multi([commands]) doen't open multi connections, just pointing out because function openMultiRedisConnection is misleading.

You use mulit wrong, per reference

client.multi([commands])

MULTI commands are queued up until an EXEC is issued, and then all
  commands are run atomically by Redis. The interface in node_redis is
  to return an individual Multi object by calling client.multi(). If any
  command fails to queue, all commands are rolled back and none is going
  to be executed (For further information look at transactions).

Multi returns an individual Object and its not very good to use it again after .exec is called.

I don't know why you need more that one database but you are changing database with selected_db and on a global client variable and this is BAD! and could cause many problems!(data inconsistency, conflict, etc).
You can use client.select(callback) to changed database but again it seems like a bad idea.

There is no reason for this part of code its exactly the same as not doing that.

 .then(function (result) {
    return Promise.resolve(result);
  });

You should be ok with only one database.

   var Promise = require('bluebird');
var Redis = Promise.promisifyAll(require('redis'));

// Global (Avoids Duplicate Connections)
var redisClient = [];

// Make the below functions as private
function openRedisConnection( {
    if (redisClient && redisClient.connected)
        return redisClient;

    if (redisClient)
        redisClient.end(); // End and open once more

    redisClient = Redis.createClient(6379,process.env.REDIS_URL,{"db":1});

    return redisClient;
}

function getExpiryTime(key) {
    return 120; // testing
}

module.exports = {
    /**
     * Get Key-Value Pair
     */
    getRedisValue: function (keys) {
        return openRedisConnection().mgetAsync(keys);
    },
    /**
     * Set Key-Value Pair
     */
    setRedisValue: function (key, value) {
        return openRedisConnection()
            .setAsync(key, value, 'EX', getExpiryTime(key));

    },

    getV2MultiRedisValue: function (keyList) {

         let redisClient = openRedisConnection();

        //no need to open multi here....
        let multi = redisClient.multi();

        multi.hgetallAsync(keyList);

        return multi.execAsync();

    },

    setV2MultiRedisValue: function (key, redisList) {
        let expiryTime = getExpiryTime(key);
        let redisClient = openRedisConnection();

        let multi = redisClient.multi();

        for (let item of redisList) {
            multi.hmsetAsync(item.key, item.value);
            multi.expireAsync(item.key, expiryTime);
        }

        return multi.execAsync();

    }
};


问:
Sort Linked List based on dynamic field from user
My objective is to Dynamically insert values in to the Linked List. And thereafter, I want to perform sorting or search algorithms on the List.

In addition to it, I am creating class at runtime (based on user input) using Reflection.

Thereafter, I use data provided by the user in JSON Array, to create instances of the class, and then I insert the instances in to the GenericList.

Following is the code for the Generic Linked List.

```<code>public class LinkedListNode<T> implements Serializable {
    private T value;
    private LinkedListNode<T> next;

    public LinkedListNode(T value) {
        this.value = value;
    }
    public void setNext(LinkedListNode<T> next) {
        this.next = next;
    }
    public LinkedListNode<T> getNext() {
        return next;
    }
    public T getValue() {
        return value;
    }
}

public class GenericList<T>  implements Serializable {
    private LinkedListNode<T> first = null;
    public void insert(LinkedListNode<T> node) {
        node.setNext(first);
        first = node;
    }
    public void emptyList(){
        first = null;
    }
    public void remove(){
        if(first.getNext()!=null)
            first = first.getNext();
        else first = null;
    }
}
</code>```

And this is how I create instances of the class and insert it to the GenericList.

```<code>//dataToInsert => is the JSONArray. =>  [{field1:"value1",field2:"value1"},{field1:"value2",field2:"value2"},{field1:"value3",field2:"value3"}]
//classLoaded =>  package com.LinkedAnalyzerAdapter.saveTestClasses; public class order implements java.io.Serializable  {public String field1;public String field2;}
Class<?> classLoaded = classLoader.loadClass("com.LinkedAnalyzerAdapter.saveTestClasses.order");
GenericList<Object> list = new GenericList<Object>();
for (int i = 0; i < dataToInsert.length(); i++) {
    JSONObject jsonObj = new JSONObject();
    jsonObj = dataToInsert.getJSONObject(i);
    Object obj = classLoaded.newInstance();
    Field[] fs = classLoaded.getDeclaredFields();
    for (Field field : fs)
    {
        field.setAccessible(true);
        Object fieldValue = jsonObj.get(field.getName());
        field.set(obj, fieldValue);
    }
    list.insert(new LinkedListNode<Object>(obj));
}
</code>```

I am successfully able to insert data in to GenericList, but after inserting I later want to sort the data based on field1, in the ascending order.

I have spent hours to solve it but unable to successfully accomplish sorting.

答:
You should really use java.util.LinkedList instead of your own GenericList, to take advantage of the built in Collections</p>

```<code>LinkedList<LinkedListNode<?>> list = new LinkedList<>();
Collections.sort(list, new Comparator<String>() {
     @Override
     public int compare(String o1, String o2) {
         return ...
     }
 }
</code>```

Body:
My objective is to Dynamically insert values in to the Linked List. And thereafter, I want to perform sorting or search algorithms on the List.

In addition to it, I am creating class at runtime (based on user input) using Reflection.

Thereafter, I use data provided by the user in JSON Array, to create instances of the class, and then I insert the instances in to the GenericList.

Following is the code for the Generic Linked List.

public class LinkedListNode<T> implements Serializable {
    private T value;
    private LinkedListNode<T> next;

    public LinkedListNode(T value) {
        this.value = value;
    }
    public void setNext(LinkedListNode<T> next) {
        this.next = next;
    }
    public LinkedListNode<T> getNext() {
        return next;
    }
    public T getValue() {
        return value;
    }
}

public class GenericList<T>  implements Serializable {
    private LinkedListNode<T> first = null;
    public void insert(LinkedListNode<T> node) {
        node.setNext(first);
        first = node;
    }
    public void emptyList(){
        first = null;
    }
    public void remove(){
        if(first.getNext()!=null)
            first = first.getNext();
        else first = null;
    }
}

And this is how I create instances of the class and insert it to the GenericList.

//dataToInsert => is the JSONArray. =>  [{field1:"value1",field2:"value1"},{field1:"value2",field2:"value2"},{field1:"value3",field2:"value3"}]
//classLoaded =>  package com.LinkedAnalyzerAdapter.saveTestClasses; public class order implements java.io.Serializable  {public String field1;public String field2;}
Class<?> classLoaded = classLoader.loadClass("com.LinkedAnalyzerAdapter.saveTestClasses.order");
GenericList<Object> list = new GenericList<Object>();
for (int i = 0; i < dataToInsert.length(); i++) {
    JSONObject jsonObj = new JSONObject();
    jsonObj = dataToInsert.getJSONObject(i);
    Object obj = classLoaded.newInstance();
    Field[] fs = classLoaded.getDeclaredFields();
    for (Field field : fs)
    {
        field.setAccessible(true);
        Object fieldValue = jsonObj.get(field.getName());
        field.set(obj, fieldValue);
    }
    list.insert(new LinkedListNode<Object>(obj));
}

I am successfully able to insert data in to GenericList, but after inserting I later want to sort the data based on field1, in the ascending order.

I have spent hours to solve it but unable to successfully accomplish sorting.

Body:
You should really use java.util.LinkedList instead of your own GenericList, to take advantage of the built in Collections

LinkedList<LinkedListNode<?>> list = new LinkedList<>();
Collections.sort(list, new Comparator<String>() {
     @Override
     public int compare(String o1, String o2) {
         return ...
     }
 }


问:
Vertically centering text in square (flex) divs
I'm building a game with a grid of cells with some specific constraints but I can't get the CSS right to do all that:

There should be 9 cells in each row (so width: 11.11%).

Each cell should have square size (managed with div:before { content: ''; float: left; padding-top: 100%; }).

Each cell contains one digit horizontally and vertically centered within the cell.

The game should be responsive, so cell's can shrink together with the text on mobile (I'm currently playing with font-size and media queries).

I got up to the point where all of these are ok, except the vertically centering of the text within a cell. Anyone knows what the trick is or if that just isn't possible and I should create images for that?

答:
in flex container use:

```<code>justify-content:center
align-items: center
</code>```

look also on this guide

Body:
in flex container use:

justify-content:center
align-items: center

look also on this guide


问:
Home Button in Header in R shiny Dashboard
I am trying to add a home button in the header of my Shiny app so that whenever anyone clicks it from any tab, it will redirect to the first page. Currently I am using one actionButton in every tab with observeEvent to go back to first page.

I am not able to add any actionButton in the header section of Shiny app. Is there any way around for this feature?

It is something like this:
Sample Shiny Look

Reproducible Code:

```<code>library(shiny)
library(shinydashboard)
library(shinyjs)
options(shiny.maxRequestSize=1000*1024^2)

app <- shinyApp(
  a <- dashboardPage(
    dashboardHeader(title = "Sample Shiny", titleWidth=1450),
    dashboardSidebar(sidebarMenu(id='tabs',
                                 menuItem("Welcome", tabName = "welcome"),
                                 menuItem("Tab1", tabName = "tab1"),
                                 menuItem("Tab2",
                                      menuSubItem("Tab2_1", tabName = "tab2_1"),
                                      menuSubItem("Tab2_2", tabName = "tab2_2"))
    )
    ),
    dashboardBody(  shinyjs::useShinyjs(),
                    tabItems(
                      tabItem(tabName="welcome", tabPanel(title = "Score",fluidRow(valueBoxOutput("box_01"),valueBoxOutput("box_02")))),
                      # First tab content
                      tabItem(tabName = "tab1",actionButton("homeButton1", "Home")),
                      # Second tab content
                      tabItem(tabName = "tab2_1",tabsetPanel(id = "test",tabPanel(title = "tab2_1",actionButton("homeButton2", "Home"),actionButton("NextButton2", "Tab3")))),
                      tabItem(tabName = "tab2_2",tabsetPanel(id = "outputTabset",tabPanel(title = "Tab 3",actionButton("homeButton3", "Home"))))
    )
  )),

  b<-shinyServer(function(input, output, session) {

    ##########Links from first page
    output$box_01 <- renderValueBox({
      box1<-valueBox(value=01,
                 icon = icon("database",lib="font-awesome")
                 ,width=NULL
                 ,color = "blue"
                 ,href="#"
                 ,subtitle=HTML("<b>Tab 1</b>")
      )
      box1$children[[1]]$attribs$class<-"action-button"
      box1$children[[1]]$attribs$id<-"button_box_01"
      return(box1)

    })

    output$box_02 <- renderValueBox({
      box2<-valueBox(value=02,
                 icon = icon("user-secret",lib="font-awesome")
                 ,width=NULL
                 ,color = "yellow"
                 ,href="#"
                 ,subtitle=HTML("<b>Tab 2</b>")
      )
      box2$children[[1]]$attribs$class<-"action-button"
      box2$children[[1]]$attribs$id<-"button_box_02"
      return(box2)

    })

    observeEvent(input$button_box_01,{
      if(input$button_box_01[1]>0){
        newtab <- switch(input$tabs,
                     "welcome" = "tab1",
                     "tab1" = "welcome"
        )
        updateTabItems(session, "tabs", newtab)
      }  })

    observeEvent(input$button_box_02,{
      if(input$button_box_02[1]>0){
        newtab <- switch(input$tabs,
                     "welcome" = "tab2_1",
                     "tab2_1" = "welcome"
    )
    updateTabItems(session, "tabs", newtab)
  }  })

### HomeButtons

observeEvent(input$homeButton1,{
  newtab <- switch(input$tabs,
                   "welcome" = "tab1",
                   "tab1" = "welcome"
  )
  updateTabItems(session, "tabs", newtab)
})
observeEvent(input$homeButton2,{
  newtab <- switch(input$tabs,
                   "welcome" = "tab2_1",
                   "tab2_1" = "welcome"
  )
  updateTabItems(session, "tabs", newtab)
    })

    observeEvent(input$NextButton2,{
      newtab <- switch(input$tabs,
                   "tab2_2" = "tab2_1",
                   "tab2_1" = "tab2_2"
      )
      updateTabItems(session, "tabs", newtab)
    })

    observeEvent(input$homeButton3,{
      newtab <- switch(input$tabs,
                   "welcome" = "tab2_2",
                   "tab2_2" = "welcome"
      )
      updateTabItems(session, "tabs", newtab)
    })

#######SideBar Disable

    addClass(selector = "body", class = "sidebar-collapse")

    })
        )

shiny::runApp(app,launch.browser=TRUE,host="0.0.0.0",port=6105)
</code>```

答:
Here's an option using javascript and a home icon which fits into the header nicely:

```<code>dashboardHeader(title = "Your Title",
               tags$li(a(onclick = "openTab('home')",
                        href = NULL,
                        icon("home"),
                        title = "Homepage",
                        style = "cursor: pointer;"),
                      class = "dropdown",
                      tags$script(HTML("
                                       var openTab = function(tabName){
                                       $('a', $('.sidebar')).each(function() {
                                       if(this.getAttribute('data-value') == tabName) {
                                       this.click()
                                       };
                                       });
                                       }")))
)
</code>```

Change home in the openTab('home') part to whatever your home tab is called and it will switch to that tab when clicked.

Body:
I am trying to add a home button in the header of my Shiny app so that whenever anyone clicks it from any tab, it will redirect to the first page. Currently I am using one actionButton in every tab with observeEvent to go back to first page.

I am not able to add any actionButton in the header section of Shiny app. Is there any way around for this feature?

It is something like this:
Sample Shiny Look

Reproducible Code:

library(shiny)
library(shinydashboard)
library(shinyjs)
options(shiny.maxRequestSize=1000*1024^2)

app <- shinyApp(
  a <- dashboardPage(
    dashboardHeader(title = "Sample Shiny", titleWidth=1450),
    dashboardSidebar(sidebarMenu(id='tabs',
                                 menuItem("Welcome", tabName = "welcome"),
                                 menuItem("Tab1", tabName = "tab1"),
                                 menuItem("Tab2",
                                      menuSubItem("Tab2_1", tabName = "tab2_1"),
                                      menuSubItem("Tab2_2", tabName = "tab2_2"))
    )
    ),
    dashboardBody(  shinyjs::useShinyjs(),
                    tabItems(
                      tabItem(tabName="welcome", tabPanel(title = "Score",fluidRow(valueBoxOutput("box_01"),valueBoxOutput("box_02")))),
                      # First tab content
                      tabItem(tabName = "tab1",actionButton("homeButton1", "Home")),
                      # Second tab content
                      tabItem(tabName = "tab2_1",tabsetPanel(id = "test",tabPanel(title = "tab2_1",actionButton("homeButton2", "Home"),actionButton("NextButton2", "Tab3")))),
                      tabItem(tabName = "tab2_2",tabsetPanel(id = "outputTabset",tabPanel(title = "Tab 3",actionButton("homeButton3", "Home"))))
    )
  )),

  b<-shinyServer(function(input, output, session) {

    ##########Links from first page
    output$box_01 <- renderValueBox({
      box1<-valueBox(value=01,
                 icon = icon("database",lib="font-awesome")
                 ,width=NULL
                 ,color = "blue"
                 ,href="#"
                 ,subtitle=HTML("Tab 1")
      )
      box1$children[[1]]$attribs$class<-"action-button"
      box1$children[[1]]$attribs$id<-"button_box_01"
      return(box1)

    })

    output$box_02 <- renderValueBox({
      box2<-valueBox(value=02,
                 icon = icon("user-secret",lib="font-awesome")
                 ,width=NULL
                 ,color = "yellow"
                 ,href="#"
                 ,subtitle=HTML("Tab 2")
      )
      box2$children[[1]]$attribs$class<-"action-button"
      box2$children[[1]]$attribs$id<-"button_box_02"
      return(box2)

    })

    observeEvent(input$button_box_01,{
      if(input$button_box_01[1]>0){
        newtab <- switch(input$tabs,
                     "welcome" = "tab1",
                     "tab1" = "welcome"
        )
        updateTabItems(session, "tabs", newtab)
      }  })

    observeEvent(input$button_box_02,{
      if(input$button_box_02[1]>0){
        newtab <- switch(input$tabs,
                     "welcome" = "tab2_1",
                     "tab2_1" = "welcome"
    )
    updateTabItems(session, "tabs", newtab)
  }  })

### HomeButtons

observeEvent(input$homeButton1,{
  newtab <- switch(input$tabs,
                   "welcome" = "tab1",
                   "tab1" = "welcome"
  )
  updateTabItems(session, "tabs", newtab)
})
observeEvent(input$homeButton2,{
  newtab <- switch(input$tabs,
                   "welcome" = "tab2_1",
                   "tab2_1" = "welcome"
  )
  updateTabItems(session, "tabs", newtab)
    })

    observeEvent(input$NextButton2,{
      newtab <- switch(input$tabs,
                   "tab2_2" = "tab2_1",
                   "tab2_1" = "tab2_2"
      )
      updateTabItems(session, "tabs", newtab)
    })

    observeEvent(input$homeButton3,{
      newtab <- switch(input$tabs,
                   "welcome" = "tab2_2",
                   "tab2_2" = "welcome"
      )
      updateTabItems(session, "tabs", newtab)
    })

#######SideBar Disable

    addClass(selector = "body", class = "sidebar-collapse")

    })
        )

shiny::runApp(app,launch.browser=TRUE,host="0.0.0.0",port=6105)

Body:
Here's an option using javascript and a home icon which fits into the header nicely:

dashboardHeader(title = "Your Title",
               tags$li(a(onclick = "openTab('home')",
                        href = NULL,
                        icon("home"),
                        title = "Homepage",
                        style = "cursor: pointer;"),
                      class = "dropdown",
                      tags$script(HTML("
                                       var openTab = function(tabName){
                                       $('a', $('.sidebar')).each(function() {
                                       if(this.getAttribute('data-value') == tabName) {
                                       this.click()
                                       };
                                       });
                                       }")))
)

Change home in the openTab('home') part to whatever your home tab is called and it will switch to that tab when clicked.


问:
unable to edit letters in textbox on adding space after three letters in textbox in jQuery
How to re-edit letter from the following textbox

$('.zip-code').on('keypress change', function () {
  $(this).val(function (index, value) {
    return value.replace(/\W/gi, '').replace(/(.{3})/g, '$1 ');
  });
}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label" for="credit-card">zip Code</label>
<input type="text" maxlength="7" class="zip-code" value="" autocomplete="off"  /></code>```

The above code gives space after 3 letters but unable to re-edit the letter

following are the issues faced :

should remove entire zip-code to edit a letter in textbox

If the zip-code entered wrong and if needed to edit it , unable to edit the letter/letters in zip-code field.

after editing the zip-code the letter moves to the end.

答:
Your problem here is a few issues. First, you want to use keyup to get the value otherwise it will fire before the key value is set and not give an accurate value when called. Second, your regex is running while you are potentially still typing which forces the cursor to the end. You can overcome this using a timer (Borrowed from this answer).

Try the snippet below, I believe this accomplishes what you are after.

var typingTimer;                //timer identifier
var doneTypingInterval = 1000;  //time in ms, 1 second for example
var $input = $('.zip-code');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(formatZip, doneTypingInterval);
}).on('keydown', function () {
  clearTimeout(typingTimer);
});

function formatZip () {
  $input.val(function (index, value) {;
    var str = value.replace(/\W/gi, ''),
        newVal = [str.slice(0, 3), ' ', str.slice(3,6)].join('');
    return newVal;
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label" for="credit-card">zip Code</label>
<input type="text" maxlength="7" class="zip-code" value="" autocomplete="off"  /></code>```

Body:
How to re-edit letter from the following textbox

$('.zip-code').on('keypress change', function () {
  $(this).val(function (index, value) {
    return value.replace(/\W/gi, '').replace(/(.{3})/g, '$1 ');
  });
});

zip Code
<input type="text" maxlength="7" class="zip-code" value="" autocomplete="off"  />

The above code gives space after 3 letters but unable to re-edit the letter

following are the issues faced :

should remove entire zip-code to edit a letter in textbox

If the zip-code entered wrong and if needed to edit it , unable to edit the letter/letters in zip-code field.

after editing the zip-code the letter moves to the end.

Body:
Your problem here is a few issues. First, you want to use keyup to get the value otherwise it will fire before the key value is set and not give an accurate value when called. Second, your regex is running while you are potentially still typing which forces the cursor to the end. You can overcome this using a timer (Borrowed from this answer).

Try the snippet below, I believe this accomplishes what you are after.

var typingTimer;                //timer identifier
var doneTypingInterval = 1000;  //time in ms, 1 second for example
var $input = $('.zip-code');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(formatZip, doneTypingInterval);
}).on('keydown', function () {
  clearTimeout(typingTimer);
});

function formatZip () {
  $input.val(function (index, value) {;
    var str = value.replace(/\W/gi, ''),
        newVal = [str.slice(0, 3), ' ', str.slice(3,6)].join('');
    return newVal;
  });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label" for="credit-card">zip Code</label>
<input type="text" maxlength="7" class="zip-code" value="" autocomplete="off"  />


问:
How to extend convoy volume?
Environment:

CentOS 7.4.1708

Docker 17.09.0-ce, build afdb6d4

convoy v0.5.0 (docker-convoy: Docker volume plugin) with devicemapper

Phase 1: Created convoy volume

```<code>sudo convoy create data-test --size 100M
</code>```

Phase 2: Tried to extend convoy volume

Backup original convoy volume

Restore volume with --size option
Then, I got an error that Volume must be same size.

Is there way to extend convoy volume?

答:
Docker-convoy uses devicemapper(default) that user could visible to block-device(try lsblk).

Create new volume with --size option:

sudo convoy create new-volume-name --size 1000G

Transfer data from volume-name to new-volume-name:

sudo dd if=/dev/mapper/volume-name of=/dev/mapper/new-volume-name

Resize new-volume-name:

sudo resize2fs /dev/mapper/new-volume-name

If it warn need to check by e2fsck, run sudo e2fsck /dev/mapper/new-volume-name

Check volume that it is readable:

sudo convoy mount new-volume-name

sudo ls -l /var/lib/rancher/convoy/devicemapper/mounts/new-volume-name

sudo convoy umount new-volume-name

Remove original volume:

sudo convoy delete volume-name

Switch from volume-name to new-volume-name at the container.

Note:
This process is for offline migration. I could not find out incremental backup in this time. Before you run this, the docker containers should be stopped.
And, there is no way to rename volume name.

Title: How to extend convoy volume?

Body:
Environment:

CentOS 7.4.1708

Docker 17.09.0-ce, build afdb6d4

convoy v0.5.0 (docker-convoy: Docker volume plugin) with devicemapper

Phase 1: Created convoy volume

sudo convoy create data-test --size 100M

Phase 2: Tried to extend convoy volume

Backup original convoy volume

Restore volume with --size option
Then, I got an error that Volume must be same size.

Is there way to extend convoy volume?


问:
Combining two arrays in JS/Jquery
Hello everybody i got a question regarding arrays in javascript, so lets get started, my question is "Can i use an array let's say it's called 'food' and it has all kinda types of food(burgers,pizza,fish), so when i get result via random function that my other function can use that result let's say it's "pizza" to get my other array that has "name, adress for places where you can eat pizza")

So it's two buttons, one input type="text" for results of first random function and span for  items for the second one that will have adresses and names of places, javascript/jquery, i can provide you with basic code which i tried

So my first thought here is to get something like switch with bunch of cases so if result of random function is "pizza" that it goes into switch - case for pizza and there it would be all info

```<code>"https://codepen.io/nikolamilovac/pen/yPWaxz"
</code>```

答:
Here is an improved version of my previous deleted answer. You don't need 2 arrays, you just need to store the value returned from the random function in order to use it when needed.

var placesWhereYouCanEat = [{
  what: 'gencive de porc',
  locations: ['Paris']
}, {
  what: 'fish',
  locations: ['London']
}, {
  what: 'burger',
  locations: ['Berlin']
}],
selectedPlace;

function getRandomIndex() {
  return Math.floor(Math.random() * placesWhereYouCanEat.length);
}

document.getElementById('what').addEventListener('click', function () {
  selectedPlace = placesWhereYouCanEat[getRandomIndex()];

  document.getElementById('food').value = selectedPlace.what;
  document.getElementById('locations').innerHTML = '';
});

document.getElementById('where').addEventListener('click', function () {
  var locationsElement = document.getElementById('locations');
  locationsElement.innerHTML = '';

  selectedPlace.locations.forEach(function (location) {
    var li = document.createElement('li');
    li.innerText = location;
    locationsElement.appendChild(li);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="what">What do I eat ?</button>
<input id="food" type="text" />
<button id="where">Where do I eat ?</button>
<ul id="locations">
</ul></code>```

Title: Combining two arrays in JS/Jquery

Body:
Hello everybody i got a question regarding arrays in javascript, so lets get started, my question is "Can i use an array let's say it's called 'food' and it has all kinda types of food(burgers,pizza,fish), so when i get result via random function that my other function can use that result let's say it's "pizza" to get my other array that has "name, adress for places where you can eat pizza")

So it's two buttons, one input type="text" for results of first random function and span for  items for the second one that will have adresses and names of places, javascript/jquery, i can provide you with basic code which i tried

So my first thought here is to get something like switch with bunch of cases so if result of random function is "pizza" that it goes into switch - case for pizza and there it would be all info

"https://codepen.io/nikolamilovac/pen/yPWaxz"

Body:
Here is an improved version of my previous deleted answer. You don't need 2 arrays, you just need to store the value returned from the random function in order to use it when needed.

var placesWhereYouCanEat = [{
  what: 'gencive de porc',
  locations: ['Paris']
}, {
  what: 'fish',
  locations: ['London']
}, {
  what: 'burger',
  locations: ['Berlin']
}],
selectedPlace;

function getRandomIndex() {
  return Math.floor(Math.random() * placesWhereYouCanEat.length);
}

document.getElementById('what').addEventListener('click', function () {
  selectedPlace = placesWhereYouCanEat[getRandomIndex()];

  document.getElementById('food').value = selectedPlace.what;
  document.getElementById('locations').innerHTML = '';
});

document.getElementById('where').addEventListener('click', function () {
  var locationsElement = document.getElementById('locations');
  locationsElement.innerHTML = '';

  selectedPlace.locations.forEach(function (location) {
    var li = document.createElement('li');
    li.innerText = location;
    locationsElement.appendChild(li);
  });
});

<button id="what">What do I eat ?</button>
<input id="food" type="text" />
<button id="where">Where do I eat ?</button>
<ul id="locations">
</ul>


问:
Cannot read property '1' of null on my WordPress plugin
I am running a new plugin on a client's WooCommerce/WordPress webshop, but it isn't working as supposed. The browser console is giving me this error:

```<code>Uncaught TypeError: Cannot read property '1' of null
    at Object.success (yith-wcp-frontend.min.js:1)
    at i (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at y (jquery.js:4)
    at XMLHttpRequest.c (jquery.js:4)
</code>```

I have 'pretty printed' that error, which will give me the proper lines:

```<code>Uncaught TypeError: Cannot read property '1' of null
    at Object.success (yith-wcp-frontend.min.js:formatted:206)
    at i (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at y (jquery.js:4)
    at XMLHttpRequest.c (jquery.js:4)
</code>```

This is what line 206 looks like:

I've never really understood these 'Cannot read property '1' of null' errors, especially this one. Does anybody know what is going wrong here?

This is a link to the specific page: http://wqd.nl/3IFd

The error pops up when selecting something in the select list below 'Kleurkeuze'.

答: Try updating YITH Composite Products plugin that you are using. I wonder if it has been resolved, and you are just using an incompatible version of WordPress, WooCommerce, or Yith.</p>

Body:
I am running a new plugin on a client's WooCommerce/WordPress webshop, but it isn't working as supposed. The browser console is giving me this error:

Uncaught TypeError: Cannot read property '1' of null
    at Object.success (yith-wcp-frontend.min.js:1)
    at i (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at y (jquery.js:4)
    at XMLHttpRequest.c (jquery.js:4)

I have 'pretty printed' that error, which will give me the proper lines:

Uncaught TypeError: Cannot read property '1' of null
    at Object.success (yith-wcp-frontend.min.js:formatted:206)
    at i (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at y (jquery.js:4)
    at XMLHttpRequest.c (jquery.js:4)

This is what line 206 looks like:

I've never really understood these 'Cannot read property '1' of null' errors, especially this one. Does anybody know what is going wrong here?

This is a link to the specific page: http://wqd.nl/3IFd

The error pops up when selecting something in the select list below 'Kleurkeuze'.


问:
How to run CasperJS from cron inside AWS EC2
I am having difficulties running my CasperJS script as a cron job on my AWS EC2 server.

The crontab:

```<code>0 13 * * * PHANTOMJS_EXECUTABLE=/home/ec2-user/local/bin/phantomjs /home/ec2-user/local/bin/casperjs /home/ec2-user/code/scraptest.js
</code>```

The script runs fine when I run it manually but cron emails me with the following:

```<code>(...)
X-Cron-Env: <LANG=en_US.UTF-8>
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/ec2-user>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=ec2-user>
X-Cron-Env: <USER=ec2-user>

/usr/bin/env: node: No such file or directory
</code>```

I've tried everything I could think of and I am running out of ideas. Any advice?

答:
cron and your session do not share the environment variables, it looks like you discovered that.

Frankly there is a much better way to deal with this, and that is to define your PATH and other ENV vars globally within your crontab, that way if you add another cron entry you're not writing your ENV into every command!

Your cron will work fine this this, plus you can add a MAILTO= and get cron to e-mail most any address any errors or STDOUT you want

```<code>PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/ec2-user/local/bin"

55 08 * * * /home/ec2-user/local/bin/casperjs /home/ec2-user/code/scraptest.js
</code>```

Body:
I am having difficulties running my CasperJS script as a cron job on my AWS EC2 server.

The crontab:

0 13 * * * PHANTOMJS_EXECUTABLE=/home/ec2-user/local/bin/phantomjs /home/ec2-user/local/bin/casperjs /home/ec2-user/code/scraptest.js

The script runs fine when I run it manually but cron emails me with the following:

(...)
X-Cron-Env: <LANG=en_US.UTF-8>
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/ec2-user>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=ec2-user>
X-Cron-Env: <USER=ec2-user>

/usr/bin/env: node: No such file or directory

I've tried everything I could think of and I am running out of ideas. Any advice?

Body:
cron and your session do not share the environment variables, it looks like you discovered that.

Frankly there is a much better way to deal with this, and that is to define your PATH and other ENV vars globally within your crontab, that way if you add another cron entry you're not writing your ENV into every command!

Your cron will work fine this this, plus you can add a MAILTO= and get cron to e-mail most any address any errors or STDOUT you want

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/ec2-user/local/bin"

55 08 * * * /home/ec2-user/local/bin/casperjs /home/ec2-user/code/scraptest.js


答:
Quoting the isfortran documentation (emphasis mine):

Returns True if the array is Fortran contiguous but not C contiguous.

This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if an array is Fortran contiguous use a.flags.f_contiguous instead.

There are a few things to note here:

Your vector is both Fortran and C contiguous, so the function returns false.

The function is obsolete

There is an alternative way to check the array, that should work for your case:

```<code>a = np.zeros((3, 1), order='F')
print(a.flags)
# C_CONTIGUOUS : True
# F_CONTIGUOUS : True
# OWNDATA : True
# WRITEABLE : True
# ALIGNED : True
# UPDATEIFCOPY : False

print(a.flags.f_contiguous)
# True
</code>```

You cannot edit flags. However, there are a few tricks. For example, you can use transpose to turn a 2D C array into an F array (albeit with swapped dimensions):

```<code>print(np.ones((3, 2), order='C').flags)
#  C_CONTIGUOUS : True
#  F_CONTIGUOUS : False
# ....

print(np.ones((3, 2), order='C').T.flags)
#  C_CONTIGUOUS : False
#  F_CONTIGUOUS : True
# ....
</code>```

Title: Creating a Column-Vector in Python Numpy in Fortran order

Body:
I need a numpy array with 3-rows and 1 Column (for pyCGNS when creating a Zone).

And This Must be true when asking if it is NPY.isfortran(X).

I tried several ways, but none worked.

e.g.

a1 = NPY.zeros((3,1),order='F')
print NPY.isfortran(a1)
->False

Body:
Quoting the isfortran documentation (emphasis mine):

Returns True if the array is Fortran contiguous but not C contiguous.

This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if an array is Fortran contiguous use a.flags.f_contiguous instead.

There are a few things to note here:

Your vector is both Fortran and C contiguous, so the function returns false.

The function is obsolete

There is an alternative way to check the array, that should work for your case:

a = np.zeros((3, 1), order='F')
print(a.flags)
# C_CONTIGUOUS : True
# F_CONTIGUOUS : True
# OWNDATA : True
# WRITEABLE : True
# ALIGNED : True
# UPDATEIFCOPY : False

print(a.flags.f_contiguous)
# True

You cannot edit flags. However, there are a few tricks. For example, you can use transpose to turn a 2D C array into an F array (albeit with swapped dimensions):

print(np.ones((3, 2), order='C').flags)
#  C_CONTIGUOUS : True
#  F_CONTIGUOUS : False
# ....

print(np.ones((3, 2), order='C').T.flags)
#  C_CONTIGUOUS : False
#  F_CONTIGUOUS : True
# ....