问:
Bazel build, protobuf and code completion
When using Bazel to build a project that contains .proto files, we can use, for example, go_binary and go_proto_library rules to create a binary. The generated binary will work as expected, but the code generated from the .proto files is not in the working directory.

As a result, code completion in editors and IDEs will not work. Even worse, they will often print errors about invalid import statements.

This is an example using protocol buffers, but there are probably other similar cases, such as using third party dependencies.

How is this usually handled?

答:
I'm one of the engineers working on the Go rules for Bazel. Unfortunately, I don't have a good answer for you right now, but this issue is on our radar, and the Go team is working on a general long-term solution. I've filed bazelbuild/rules_go#512 on our GitHub repo to track this issue, and I'll update this answer when we have a better solution.

The problem is Bazel stores generated code and other artifacts in its own internal directory that editors aren't aware of. We're designing and building a new workspace abstraction mechanism that will allow tools (editors, IDEs, tools like guru) to understand all of sources, generated files, packages, imports, and other metadata in a repository without needing to integrate directly with Bazel or other build systems.

As a temporary workaround, try generating the .pb.go files manually with protoc. You can check those files into your repository but not include them in your BUILD files. This should make editors and IDEs aware of the generated files, but you'll still produce new, up-to-date versions of them when you compile.


来源: stackexchange

问:
Reading Email using Pop3 in C#
I am looking for a method of reading emails using Pop3 in C# 2.0. Currently, I am using code found in CodeProject. However, this solution is less than ideal. The biggest problem is that it doesn't support emails written in unicode.</p>

答: I've successfully used OpenPop.NET to access emails via POP3.  </p>

OwnerDisplayName: Eldila

ContentLicense: CC BY-SA 2.5

Title: Reading Email using Pop3 in C#

OwnerDisplayName: VanOrman

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Jarrod Dixon


问:
What database tests should I write so that refactoring database is easy
Are there any guidelines on writing database tests so that you can refactor database "without fear" while doing evolutionary database design?

What aspects of database should be put to test while developing it? Any example would be great..

答:
Always fear every change you make to a database. This will compel you to double check every thing you change and narrow down the possible errors.

Keep in mind that databases are usually the backbone of one or more application, so every change you make must be planned carefully and properly tested.

OwnerDisplayName: StackUnderflow

LastEditorDisplayName: StackUnderflow

OwnerDisplayName: Sergio


问:
How to retrieve multiple inherited types from a collection in C++?
Say you have a std::vector class that holds type Item, and you store inherited types of items: Weapon, Potion, Armor, etc. How do you retrieve the item as the inherited class and not the base?</p>

答:
How do you retrieve the item as the inherited class and not the base?

This suggests that you need closed-set polymorphism, which is provided by std::variant or boost::variant.

```<code>using Entity = std::variant<Weapon, Potion, Armor>;
// An `Entity` is either a `Weapon`, a `Potion`, or an `Armor`.

std::vector<Entity> entities;

struct EntityVisitor
{
    void operator()(Weapon&);
    void operator()(Potion&);
    void operator()(Armor&);
};

for(auto& e : entities)
{
    std::visit(EntityVisitor{}, e);
    // Call the correct overload depending on what `e` is.
}
</code>```

Body:
How do you retrieve the item as the inherited class and not the base?

This suggests that you need closed-set polymorphism, which is provided by std::variant or boost::variant.

using Entity = std::variant<Weapon, Potion, Armor>;
// An `Entity` is either a `Weapon`, a `Potion`, or an `Armor`.

std::vector<Entity> entities;

struct EntityVisitor
{
    void operator()(Weapon&);
    void operator()(Potion&);
    void operator()(Armor&);
};

for(auto& e : entities)
{
    std::visit(EntityVisitor{}, e);
    // Call the correct overload depending on what `e` is.
}


问:
regex for soundcloud social media profiles/urls
I´m looking to extract the FACEBOOK or other social media profiles URLS form the site SOUNDCLOUD.

example url:
https://soundcloud.com/netztherapie

There is the link to that profiles social media profile.
When using regular expressions for facebook it doesn't catch it.

I wonder what a adequate regex for this code would be:

CODE:

```<code>a href="https://exit.sc?url=https%3A%2F%2Fwww.facebook.com%2FNetztherapie-641177919313762%2F" target="_blank" rel="me nofollow" class="web-profile sc-link-light sc-social-logo-interactive">
  <span class="sc-social-logo sc-social-logo-facebook"></span>
  Wir auf Facebook!
</a
</code>```

I'm looking to extract:

```<code>https://www.facebook.com/Netztherapie/
</code>```

答:
Something along these lines is what you'll probably want to do:

```<code>regex = "www\.facebook\.com%2F([^-]+)-"
</code>```

You probably don't actually have to capture the www.facebook.com or https:// because you know that.  Easier to just try and grab the name and then make the string.  Here is an easy to read (although the string concatenation is not proper Python) example:

```<code>import re

regex = "www\.facebook\.com%2F([^-]+)-"

match = re.search(regex, """a href="https://exit.sc?url=https%3A%2F%2Fwww.facebook.com%2FNetztherapie-641177919313762%2F" target="_blank" rel="me nofollow" class="web-profile sc-link-light sc-social-logo-interactive"> Wir auf Facebook!""")
if match:
    print ("yep")
    thename = match.group(1)
    print ("https://www.facebook.com/" + thename + "/")

else:
    print ("nope")
</code>```

The regex is just grabbing all non - after the base URL.  That should at least get you headed in the right direction.  You probably need to tweak the regex after you run some tests, maybe you don't want the www. in there for example, I'm not sure how uniform all the soundcloud URLs really are.

Body:
I´m looking to extract the FACEBOOK or other social media profiles URLS form the site SOUNDCLOUD.

example url:
https://soundcloud.com/netztherapie

There is the link to that profiles social media profile.
When using regular expressions for facebook it doesn't catch it.

I wonder what a adequate regex for this code would be:

CODE:

a href="https://exit.sc?url=https%3A%2F%2Fwww.facebook.com%2FNetztherapie-641177919313762%2F" target="_blank" rel="me nofollow" class="web-profile sc-link-light sc-social-logo-interactive">

  Wir auf Facebook!
</a

I'm looking to extract:

https://www.facebook.com/Netztherapie/

Body:
Something along these lines is what you'll probably want to do:

regex = "www\.facebook\.com%2F([^-]+)-"

You probably don't actually have to capture the www.facebook.com or https:// because you know that.  Easier to just try and grab the name and then make the string.  Here is an easy to read (although the string concatenation is not proper Python) example:

import re

regex = "www\.facebook\.com%2F([^-]+)-"

match = re.search(regex, """a href="https://exit.sc?url=https%3A%2F%2Fwww.facebook.com%2FNetztherapie-641177919313762%2F" target="_blank" rel="me nofollow" class="web-profile sc-link-light sc-social-logo-interactive"> Wir auf Facebook!""")
if match:
    print ("yep")
    thename = match.group(1)
    print ("https://www.facebook.com/" + thename + "/")

else:
    print ("nope")

The regex is just grabbing all non - after the base URL.  That should at least get you headed in the right direction.  You probably need to tweak the regex after you run some tests, maybe you don't want the www. in there for example, I'm not sure how uniform all the soundcloud URLs really are.


问:
How to call a user defined function with NULL values for one of its input parameter?
My UDF's body has the following HAVING class.

```<code>HAVING
         Company.Description            = @Company       AND
         SystemCustomerType.Description = @CustomerType
</code>```

I tried to call this by this following syntax.

```<code>SELECT * FROM FunctionName('ABC_Company',NULL)
</code>```

And also tried to set default value as NULL for @CustomerType parameter. And called the function by

```<code>SELECT * FROM FunctionName('ABC_Company',default)
</code>```

答:
'something' = NULL always returns false. To check if something is NULL use 'is'.</p>

```<code>HAVING
     Company.Description            = @Company       AND
     (SystemCustomerType.Description = @CustomerType
     or (SystemCustomerType.Description is null and @CustomerType  is null))
</code>```

Body:
My UDF's body has the following HAVING class.

HAVING
         Company.Description            = @Company       AND
         SystemCustomerType.Description = @CustomerType

I tried to call this by this following syntax.

SELECT * FROM FunctionName('ABC_Company',NULL)

And also tried to set default value as NULL for @CustomerType parameter. And called the function by

SELECT * FROM FunctionName('ABC_Company',default)

Body:
'something' = NULL always returns false. To check if something is NULL use 'is'.

HAVING
     Company.Description            = @Company       AND
     (SystemCustomerType.Description = @CustomerType
     or (SystemCustomerType.Description is null and @CustomerType  is null))


问:
Failed to load a dll in the Temp Directory on a Windows Server
I have developed an C# application that run very well in local.

But there is a problem when i put on the server.

The application use a DLL library (A.dll) in a point of the execution, this A.dll copy (or is create at the first execution) another DLL (B.dll) in the AppData/Local/TEMP directory. But when the A.dll try to load the B.dll an exception is threw:

```<code>system.invalidoperationexception: failed to load B.dll
</code>```

I have tried to run as Administrator the main exe, but with no results. And i think that the permissions are ok, after all is the TEMP directory.

I have not access at the DLLs source, are libraries.

Anyone can suggest me any solution? Would i check better? Where?

Thank You All.

答:
Have you checked that the system does not restrict execution of code from within the temp directory, e.g. using SRP or AppLocker?

This is usually set in group policy and is generally a sensible restriction these days to prevent things such as drive-by installers and cryptolocker malware.

You can verify this by trying to run an executable from %TEMP% and seeing if you get an access denied error.

If this is the case you can try relocating TEMP (as SRP usually defaults to locking you out of %USERPROFILE%\AppData\Local\Temp and moving the Temp folder will have the desired effect.

Hope this helps!

Body:
I have developed an C# application that run very well in local.

But there is a problem when i put on the server.

The application use a DLL library (A.dll) in a point of the execution, this A.dll copy (or is create at the first execution) another DLL (B.dll) in the AppData/Local/TEMP directory. But when the A.dll try to load the B.dll an exception is threw:

system.invalidoperationexception: failed to load B.dll

I have tried to run as Administrator the main exe, but with no results. And i think that the permissions are ok, after all is the TEMP directory.

I have not access at the DLLs source, are libraries.

Anyone can suggest me any solution? Would i check better? Where?

Thank You All.


问:
Manipulate the java class path of an Eclipse plugin?
I am working on a plugin that consist of a homemade view to Eclipse.
When I run the plugin and display the classpath using  System.getProperty("java.class.path")
I get this as output : D:\Programs\eclipse\plugins\org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar

I would like to add some .jar files for the proper functioning of my view, but I can't figure out how... I guess you can do it by adding some specifications to the MANIFEST.MF of the plugin but I don't know how to do it propely.
any ideas ?

答:
The best approach I've found is to create a lib directory in your Eclipse project (where your view is contained). Place your .jar files in said lib directory.

Then using the editor on the MANIFEST.MF, you add the .jar files to the classpath. If you wish to export the packages, you then add to the Exported Packages as well.

Depending upon what you are doing, you may wish/need to also update the Build Configuration.

If you examine the MANIFEST.MF file itself, you will then see an entry for Bundle-ClassPath. It will list your entries. Here it has the standard "." for the project, a resources/ directory that we export, and a couple of .jar files.

```<code>Bundle-ClassPath: .,
resources/,
lib/aopalliance-1.0.jar,
lib/apccore-client-2.11.8.jar,
lib/cglib-nodep-2.2.2.jar,
lib/ehcache-2.10.3.jar,
...
</code>```

Note that in our experience, it is also necessary to adjust the Java Build Path from the Properties of the project itself. A user commented that this step may not be necessary. We are on an older version of Eclipse due to our product, so YMMV, If needed (usually compile failures are the indicator), you then need to add, via the properties context menu on the project, the .jar files to the "Java Build Path" (you can do the same with a resources directory).

This will allow you to properly build using the .jar files.

Body:
The best approach I've found is to create a lib directory in your Eclipse project (where your view is contained). Place your .jar files in said lib directory.

Then using the editor on the MANIFEST.MF, you add the .jar files to the classpath. If you wish to export the packages, you then add to the Exported Packages as well.

Depending upon what you are doing, you may wish/need to also update the Build Configuration.

If you examine the MANIFEST.MF file itself, you will then see an entry for Bundle-ClassPath. It will list your entries. Here it has the standard "." for the project, a resources/ directory that we export, and a couple of .jar files.

Bundle-ClassPath: .,
resources/,
lib/aopalliance-1.0.jar,
lib/apccore-client-2.11.8.jar,
lib/cglib-nodep-2.2.2.jar,
lib/ehcache-2.10.3.jar,
...

Note that in our experience, it is also necessary to adjust the Java Build Path from the Properties of the project itself. A user commented that this step may not be necessary. We are on an older version of Eclipse due to our product, so YMMV, If needed (usually compile failures are the indicator), you then need to add, via the properties context menu on the project, the .jar files to the "Java Build Path" (you can do the same with a resources directory).

This will allow you to properly build using the .jar files.


问:
Transform CSS { ul li:hover a } in JQUERY .hover
I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.

CSS:

```<code>ul li:hover a {
    color: #FFF;
}
</code>```

Can anyone Help ?

EDIT:

My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.

JQuery:

```<code>$("ul li").hover(function () {
    $(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
    $(this).stop().animate({ backgroundColor: "black"}, 400);
});
</code>```

To animate background color on hover in menu and submenu.

For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)

```<code>$('ul.submenu li a').hover(function () {
    $(this).css({color:'#FFFFFF'});
}, function () {
    $(this).css({color:'#00FF00'});
});
</code>```

All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.

HTML Structure:

```<code><ul class="menu">

      <li><a href="#">text</a></li>

      <li><a href="#">text</a>

        <ul class="submenu">
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
        </ul>

      </li>

      <li><a href="#">text</a></li>

</ul>
</code>```

答:
Try this (now tested: http://jsfiddle.net/nathan/J7HLV/):</p>

```<code>$('ul li a, ul li').hover(function () {
  $(this).add($(this).children('a')).filter('a').css('color','#fff');
},function () {
  $(this).add($(this).children('a')).filter('a').css('color','');
});
</code>```

Body:
I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.

CSS:

ul li:hover a {
    color: #FFF;
}

Can anyone Help ?

EDIT:

My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.

JQuery:

$("ul li").hover(function () {
    $(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
    $(this).stop().animate({ backgroundColor: "black"}, 400);
});

To animate background color on hover in menu and submenu.

For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)

$('ul.submenu li a').hover(function () {
    $(this).css({color:'#FFFFFF'});
}, function () {
    $(this).css({color:'#00FF00'});
});

All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.

HTML Structure:

text

text

text

text

text

text

Body:
Try this (now tested: http://jsfiddle.net/nathan/J7HLV/):

$('ul li a, ul li').hover(function () {
  $(this).add($(this).children('a')).filter('a').css('color','#fff');
},function () {
  $(this).add($(this).children('a')).filter('a').css('color','');
});


问:
Preserve order of dictionary items as declared in Swift?
When creating a key/value dictionary, it is returned as randomly sorted. I was hoping that they would be in the same order as it was created.

For example, see this code:

```<code>var dict = [
    "kg": 1,
    "g": 2,
    "mg": 3,
    "lb": 4,
    "oz": 5,
    "t": 6
]

println(dict)
</code>```

This returns the following:

```<code>[kg: 1, oz: 5, g: 2, mg: 3, lb: 4, t: 6]
</code>```

How do I preserve the order in which the dictionary was declared?

答:
Sadly, Apple has only built in three collection datastructures in to Swift out of the box. These is the Array, Dictionary and Set. Luckily, Apple has introduced a very extensive and powerful hierarchy of protocols that support defining your own collection classes easily and elegantly.

So, if you do not mind the additional space- (and perhaps time-) complexity of your solution, you might want to opt for building your own Swift collection class/struct that resembles a Dictionary that preserves the order in which elements were added to it, by relating indexes to keys and vice versa. See the documentation for more information on creating your own collection datastructures: https://developer.apple.com/documentation/swift/collection.

I'll give you a little something to get you going:

Disclaimer: This code is not tested, and I have not spent a great deal of thought on matters of algorithmic complexity. Please determine the requirements of your solution and check for yourself whether the following code complies.

```<code>public struct KeepOrderDictionary<Key, Value> where Key : Hashable
{
    public private(set) var values: [Value]

    fileprivate var keyToIndexMap: [Key:Int]
    fileprivate var indexToKeyMap: [Int:Key]

    public init()
    {
        self.values = [Value]()
        self.keyToIndexMap = [Key:Int]()
        self.indexToKeyMap = [Int:Key]()
    }

    public var count: Int
    {   return values.count}

    public mutating func add(key: Key, _ value: Value)
    {
        if let index = keyToIndexMap[key]
        {   values[index] = value}
        else
        {
            values.append(value)
            keyToIndexMap[key] = values.count - 1
            indexToKeyMap[values.count - 1] = key
        }
    }

    public mutating func add(index: Int, _ value: Value) -> Bool
    {
        if let key = indexToKeyMap[index]
        {
            add(key: key, value)
            return true
        }

        return false
    }

    public func get(key: Key) -> (Key, Value)?
    {
        if let index = keyToIndexMap[key]
        {   return (key, values[index])}

        return nil
    }

    public func get(index: Int) -> (Key, Value)?
    {
        if let key = indexToKeyMap[index]
        {   return (key, values[index])}

        return nil
    }

    public mutating func removeValue(forKey key: Key) -> Bool
    {
        guard let index = keyToIndexMap[key] else
        {   return false}

        values.remove(at: index)

        keyToIndexMap.removeValue(forKey: key)
        indexToKeyMap.removeValue(forKey: index)

        return true
    }

    public mutating func removeValue(at index: Int) -> Bool
    {
        guard let key = indexToKeyMap[index] else
        {   return false}

        values.remove(at: index)

        keyToIndexMap.removeValue(forKey: key)
        indexToKeyMap.removeValue(forKey: index)

        return true
    }
}

extension KeepOrderDictionary
{
    public subscript(key: Key) -> Value?
        {
        get
        {   return get(key: key)?.1}

        set
        {
            if let newValue = newValue
            {   add(key: key, newValue)}
            else
            {   let _ = removeValue(forKey: key)}
        }
    }

    public subscript(index: Int) -> Value?
        {
        get
        {   return get(index: index)?.1}

        set
        {
            if let newValue = newValue
            {   let _ = add(index: index, newValue)}
        }
    }
}

extension KeepOrderDictionary : ExpressibleByDictionaryLiteral
{
    public init(dictionaryLiteral elements: (Key, Value)...)
    {
        self.init()
        for entry in elements
        {   add(key: entry.0, entry.1)}
    }
}

extension KeepOrderDictionary : Sequence
{
    public typealias Iterator = IndexingIterator<[(key: Key, value: Value)]>

    public func makeIterator() -> KeepOrderDictionary.Iterator
    {
        var content = [(key: Key, value: Value)]()

        for i in 0 ..< count
        {
            if let value: Value = self[i], let key: Key = indexToKeyMap[i]
            {     content.append((key: key, value: value))}
        }

        return content.makeIterator()
    }
}
</code>```

Body:
When creating a key/value dictionary, it is returned as randomly sorted. I was hoping that they would be in the same order as it was created.

For example, see this code:

var dict = [
    "kg": 1,
    "g": 2,
    "mg": 3,
    "lb": 4,
    "oz": 5,
    "t": 6
]

println(dict)

This returns the following:

[kg: 1, oz: 5, g: 2, mg: 3, lb: 4, t: 6]

How do I preserve the order in which the dictionary was declared?

Body:
Sadly, Apple has only built in three collection datastructures in to Swift out of the box. These is the Array, Dictionary and Set. Luckily, Apple has introduced a very extensive and powerful hierarchy of protocols that support defining your own collection classes easily and elegantly.

So, if you do not mind the additional space- (and perhaps time-) complexity of your solution, you might want to opt for building your own Swift collection class/struct that resembles a Dictionary that preserves the order in which elements were added to it, by relating indexes to keys and vice versa. See the documentation for more information on creating your own collection datastructures: https://developer.apple.com/documentation/swift/collection.

I'll give you a little something to get you going:

Disclaimer: This code is not tested, and I have not spent a great deal of thought on matters of algorithmic complexity. Please determine the requirements of your solution and check for yourself whether the following code complies.

public struct KeepOrderDictionary<Key, Value> where Key : Hashable
{
    public private(set) var values: [Value]

    fileprivate var keyToIndexMap: [Key:Int]
    fileprivate var indexToKeyMap: [Int:Key]

    public init()
    {
        self.values = [Value]()
        self.keyToIndexMap = [Key:Int]()
        self.indexToKeyMap = [Int:Key]()
    }

    public var count: Int
    {   return values.count}

    public mutating func add(key: Key, _ value: Value)
    {
        if let index = keyToIndexMap[key]
        {   values[index] = value}
        else
        {
            values.append(value)
            keyToIndexMap[key] = values.count - 1
            indexToKeyMap[values.count - 1] = key
        }
    }

    public mutating func add(index: Int, _ value: Value) -> Bool
    {
        if let key = indexToKeyMap[index]
        {
            add(key: key, value)
            return true
        }

        return false
    }

    public func get(key: Key) -> (Key, Value)?
    {
        if let index = keyToIndexMap[key]
        {   return (key, values[index])}

        return nil
    }

    public func get(index: Int) -> (Key, Value)?
    {
        if let key = indexToKeyMap[index]
        {   return (key, values[index])}

        return nil
    }

    public mutating func removeValue(forKey key: Key) -> Bool
    {
        guard let index = keyToIndexMap[key] else
        {   return false}

        values.remove(at: index)

        keyToIndexMap.removeValue(forKey: key)
        indexToKeyMap.removeValue(forKey: index)

        return true
    }

    public mutating func removeValue(at index: Int) -> Bool
    {
        guard let key = indexToKeyMap[index] else
        {   return false}

        values.remove(at: index)

        keyToIndexMap.removeValue(forKey: key)
        indexToKeyMap.removeValue(forKey: index)

        return true
    }
}

extension KeepOrderDictionary
{
    public subscript(key: Key) -> Value?
        {
        get
        {   return get(key: key)?.1}

        set
        {
            if let newValue = newValue
            {   add(key: key, newValue)}
            else
            {   let _ = removeValue(forKey: key)}
        }
    }

    public subscript(index: Int) -> Value?
        {
        get
        {   return get(index: index)?.1}

        set
        {
            if let newValue = newValue
            {   let _ = add(index: index, newValue)}
        }
    }
}

extension KeepOrderDictionary : ExpressibleByDictionaryLiteral
{
    public init(dictionaryLiteral elements: (Key, Value)...)
    {
        self.init()
        for entry in elements
        {   add(key: entry.0, entry.1)}
    }
}

extension KeepOrderDictionary : Sequence
{
    public typealias Iterator = IndexingIterator<[(key: Key, value: Value)]>

    public func makeIterator() -> KeepOrderDictionary.Iterator
    {
        var content = [(key: Key, value: Value)]()

        for i in 0 ..< count
        {
            if let value: Value = self[i], let key: Key = indexToKeyMap[i]
            {     content.append((key: key, value: value))}
        }

        return content.makeIterator()
    }
}


问:
Selenium3.4.0-Python3.6.1 : In Selenium-Python binding using unittest how do I decide when to use self.assertIn or assert
I am working with Selenium 3.4.0 with Python 3.6.1. I have written a script following the Python documentation through unittest module which is a built-in Python based on Java’s JUnit using geckodriver 0.16.1 and Mozilla Firefox 57.0 on Windows 8 Pro machine, 64 bit OS, x-64 processor. In my test method test_search_in_python_org() I have the following lines which works well:

```<code>    def test_search_in_python_org(self):
      driver = self.driver
      driver.get("http://www.python.org")
      self.assertIn("Python", driver.title)
      elem = driver.find_element_by_name("q")
      elem.send_keys("pycon")
      elem.send_keys(Keys.RETURN)
      assert "No results found." not in driver.page_source
</code>```

When I am asserting the "page title" I am using: self.assertIn("Python", driver.title)

But, when I am asserting a string (my assumption), within the page source I am using: assert "No results found." not in driver.page_source

My question is what are the factors/conditions which decides whether I should use  self.assertIn or simply assert?

Any suggestions or pointers will be helpful.

答:
Looking at the Python unittest documentation and also recalling from the bunch of Django unittests that I once had to do here, are my findings.

USE CASE:

First thing that is the most simple thing and in my opinion the biggest difference between the two, is the cases where you can use each command. They are both interchangeably usable in the case of a test class, however, in order to use the assertIn command, you need to import the unittest library.
So, say I want to know if h is in hello. A simple way to do it through the assertIn command is:

```<code>class MyTestCase(unittest.TestCase):
    def is_h_in_hello(self):
        self.assertIn("h", "hello")
</code>```

and then I need to run tests, that is through unittest.main() in this example, in order to get my answer.
But using the assert command, it is much easier to see if h is in hello. Which is very simply done like so:

```<code>assert "h" in "hello"
</code>```

But essentially, both will give me the same answer. However, what distinguishes the two methods is the simplicity of use in the second method.

RESULTS:

The second difference I found was the readability of the results on Python Shell. The unittest library is designed so that the commands are very specific. So if a test fails, you will receive a very clear message saying what went wrong. Say now you want to see if b is in hello. Doing it through the class method (simply changing "h" to "b"), the message we get after running the test is:

```<code>AssertionError: 'b' not found in 'hello'

----------------------------------------------------------------------
Ran 1 test in 0.038s

FAILED (failures=1)
</code>```

So it very clearly tells you: 'b' not found in 'hello', which makes it very convenient to see what exactly is the problem. But say you do the same process through the assert command. The error message generated is something like:

```<code>Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    assert "b" in "hello"
AssertionError
</code>```

Although it tells you the error type (AssertionError), and the traceback, it does not specifically tell you that "b" is NOT in "hello". In this simple case, it is very easy to look at the traceback and say oh, there's no b in hello! However in more complicated cases, it might be tricky to see why this error message was generated.

Overall, the two methods are very similar and will get you the result you want, but essentially it comes down to the little differences here and there, having less lines of code and how straight-forward the Shell messages are.

Body:
I am working with Selenium 3.4.0 with Python 3.6.1. I have written a script following the Python documentation through unittest module which is a built-in Python based on Java’s JUnit using geckodriver 0.16.1 and Mozilla Firefox 57.0 on Windows 8 Pro machine, 64 bit OS, x-64 processor. In my test method test_search_in_python_org() I have the following lines which works well:

    def test_search_in_python_org(self):
      driver = self.driver
      driver.get("http://www.python.org")
      self.assertIn("Python", driver.title)
      elem = driver.find_element_by_name("q")
      elem.send_keys("pycon")
      elem.send_keys(Keys.RETURN)
      assert "No results found." not in driver.page_source

When I am asserting the "page title" I am using: self.assertIn("Python", driver.title)

But, when I am asserting a string (my assumption), within the page source I am using: assert "No results found." not in driver.page_source

My question is what are the factors/conditions which decides whether I should use  self.assertIn or simply assert?

Any suggestions or pointers will be helpful.

Body:
Looking at the Python unittest documentation and also recalling from the bunch of Django unittests that I once had to do here, are my findings.

USE CASE:

First thing that is the most simple thing and in my opinion the biggest difference between the two, is the cases where you can use each command. They are both interchangeably usable in the case of a test class, however, in order to use the assertIn command, you need to import the unittest library.
So, say I want to know if h is in hello. A simple way to do it through the assertIn command is:

class MyTestCase(unittest.TestCase):
    def is_h_in_hello(self):
        self.assertIn("h", "hello")

and then I need to run tests, that is through unittest.main() in this example, in order to get my answer.
But using the assert command, it is much easier to see if h is in hello. Which is very simply done like so:

assert "h" in "hello"

But essentially, both will give me the same answer. However, what distinguishes the two methods is the simplicity of use in the second method.

RESULTS:

The second difference I found was the readability of the results on Python Shell. The unittest library is designed so that the commands are very specific. So if a test fails, you will receive a very clear message saying what went wrong. Say now you want to see if b is in hello. Doing it through the class method (simply changing "h" to "b"), the message we get after running the test is:

AssertionError: 'b' not found in 'hello'

----------------------------------------------------------------------
Ran 1 test in 0.038s

FAILED (failures=1)

So it very clearly tells you: 'b' not found in 'hello', which makes it very convenient to see what exactly is the problem. But say you do the same process through the assert command. The error message generated is something like:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    assert "b" in "hello"
AssertionError

Although it tells you the error type (AssertionError), and the traceback, it does not specifically tell you that "b" is NOT in "hello". In this simple case, it is very easy to look at the traceback and say oh, there's no b in hello! However in more complicated cases, it might be tricky to see why this error message was generated.

Overall, the two methods are very similar and will get you the result you want, but essentially it comes down to the little differences here and there, having less lines of code and how straight-forward the Shell messages are.


问:
UIPickerView Delegate Method return nil
I am using a UIPickerView instance to determine certain setting in my project.

In my viewDidLoad(), I initialise an array which includes all my data:

```<code>pickerData = ["5 Minutes", "6 Minutes","7 Minutes","8 Minutes","9 Minutes","10 Minutes","11 Minutes","12 Minutes","13 Minutes","14 Minutes","15 Minutes","16 Minutes","17 Minutes","18 Minutes","19 Minutes","20 Minutes","21 Minutes","22 Minutes","23 Minutes","24 Minutes","25 Minutes","26 Minutes","27 Minutes","28 Minutes","29 Minutes","30 Minutes","31 Minutes","32 Minutes","33 Minutes","34 Minutes","35 Minutes","36 Minutes","37 Minutes","38 Minutes","39 Minutes","40 Minutes","41 Minutes","42 Minutes","43 Minutes","44 Minutes","45 Minutes","46 Minutes","47 Minutes","48 Minutes","49 Minutes","50 Minutes","51 Minutes","52 Minutes","53 Minutes","54 Minutes","55 Minutes","56 Minutes","57 Minutes","58 Minutes","59 Minutes","60 Minutes",]
</code>```

In UIPickerView delegate method, I need to retrieve the one element at certain index then convert it into an Integer.

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        let minuteIndex = Int(pickerData[row])
        print(minuteIndex)
    }
</code>```

When I start to make my selection in the UIPickView,
Xcode console print every selection as nil.

I am quite confuse what's wrong? How to resolve this, thanks in advance.

答:
You could use row + 5, ignore the string/contents. </p>

```<code>let minuteIndex = row + 5
</code>```

<p>No casts or conversions. </p>

Title: UIPickerView Delegate Method return nil

Body:
I am using a UIPickerView instance to determine certain setting in my project.

In my viewDidLoad(), I initialise an array which includes all my data:

pickerData = ["5 Minutes", "6 Minutes","7 Minutes","8 Minutes","9 Minutes","10 Minutes","11 Minutes","12 Minutes","13 Minutes","14 Minutes","15 Minutes","16 Minutes","17 Minutes","18 Minutes","19 Minutes","20 Minutes","21 Minutes","22 Minutes","23 Minutes","24 Minutes","25 Minutes","26 Minutes","27 Minutes","28 Minutes","29 Minutes","30 Minutes","31 Minutes","32 Minutes","33 Minutes","34 Minutes","35 Minutes","36 Minutes","37 Minutes","38 Minutes","39 Minutes","40 Minutes","41 Minutes","42 Minutes","43 Minutes","44 Minutes","45 Minutes","46 Minutes","47 Minutes","48 Minutes","49 Minutes","50 Minutes","51 Minutes","52 Minutes","53 Minutes","54 Minutes","55 Minutes","56 Minutes","57 Minutes","58 Minutes","59 Minutes","60 Minutes",]

In UIPickerView delegate method, I need to retrieve the one element at certain index then convert it into an Integer.

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        let minuteIndex = Int(pickerData[row])
        print(minuteIndex)
    }

When I start to make my selection in the UIPickView,
Xcode console print every selection as nil.

I am quite confuse what's wrong? How to resolve this, thanks in advance.

Body:
You could use row + 5, ignore the string/contents.

let minuteIndex = row + 5

No casts or conversions.


问:
foreach for mybatis returns Null results
My mapper xml is like this.

```<code><mapper namespace="EmployeeDaoMapper">
<resultMap id="employeeResultMap" type="Employee">
    <result property="employeeName" column="name"/>
    <result property="employeeId" column="employee_id"/>
</resultMap>

<select id="getEmployees" parameterType="list" resultMap="employeeResultMap">
<!--<select id="getEmployees" resultType="Employee">-->
    SELECT
    <foreach item="item" index="index" collection="list" separator="," >
        #{item}
    </foreach>
    FROM employees
    WHERE LOWER (name) LIKE LOWER(#{searchQuery} +'%') OR
    LOWER(login) LIKE LOWER(#{searchQuery} +'%') OR
    LOWER( employee_id ) LIKE LOWER(#{searchQuery} + '%')
    LIMIT #{resultsLimit}

</select>
</code>```

EmployeeMapper Interface

```<code>List<Employee> getEmployees(@Param("searchQuery") String searchQuery, @Param("resultsLimit") int
        resultsLimit, @Param("list") List<String> attributes);
</code>```

query returns list of null.

Instead of foreach, if i directly add column names then it works fine.

I am not sure what mistake i am making. I checked query, it is building query correctly, still unable to fetch results.

答:
I agree with Jeff Butler.

I would add change parameterType="list" to parameterType="map" as named parameters are provided through a Map

Body:
My mapper xml is like this.

<mapper namespace="EmployeeDaoMapper">
<resultMap id="employeeResultMap" type="Employee">
    <result property="employeeName" column="name"/>
    <result property="employeeId" column="employee_id"/>
</resultMap>

<select id="getEmployees" parameterType="list" resultMap="employeeResultMap">

    SELECT
    <foreach item="item" index="index" collection="list" separator="," >
        #{item}
    </foreach>
    FROM employees
    WHERE LOWER (name) LIKE LOWER(#{searchQuery} +'%') OR
    LOWER(login) LIKE LOWER(#{searchQuery} +'%') OR
    LOWER( employee_id ) LIKE LOWER(#{searchQuery} + '%')
    LIMIT #{resultsLimit}

</select>

EmployeeMapper Interface

List<Employee> getEmployees(@Param("searchQuery") String searchQuery, @Param("resultsLimit") int
        resultsLimit, @Param("list") List<String> attributes);

query returns list of null.

Instead of foreach, if i directly add column names then it works fine.

I am not sure what mistake i am making. I checked query, it is building query correctly, still unable to fetch results.


答:
Sure, simply use the hover binding.

```<code>$("ul li a").bind("hover", function () {
    $(this).css("color", "#FFF");
});
$("ul li").bind("hover", function () {
    $(this).children("a").css("color", "#FFF");
});
</code>```

Note that this code won't reset the CSS properties when you mouse out. To do that you would need to store the original color values.

It is probably worth it to set that a element to display: block so it expands to the entire parent li element. Then you only need to hover on one of them.

Title: Transform CSS { ul li:hover a } in JQUERY .hover

Body:
Sure, simply use the hover binding.

$("ul li a").bind("hover", function () {
    $(this).css("color", "#FFF");
});
$("ul li").bind("hover", function () {
    $(this).children("a").css("color", "#FFF");
});

Note that this code won't reset the CSS properties when you mouse out. To do that you would need to store the original color values.

It is probably worth it to set that a element to display: block so it expands to the entire parent li element. Then you only need to hover on one of them.


问:
Cannot find control with unspecified name attribute on formArrays
I am trying to iterate over a formArray in my component but I get the following error

Error: Cannot find control with unspecified name attribute

Here is what the logic looks like on my class file

export class AreasFormComponent implements OnInit {
    public initialState: any;
    public areasForm: FormGroup;

    constructor(private fb: FormBuilder) { }

    private area(): any {
      return this.fb.group({
          name: ['', [Validators.required]],
          latLong: ['', [Validators.required]],
          details: ['', [Validators.required]]
      });
    }

    public ngOnInit(): void {
        this.areasForm = this.fb.group({
            name: ['', [Validators.required]],
            areas: this.fb.array([this.area()])
        });
    }
}
```

<p>and my template file </p>

<pre class="lang-xml prettyprint-override"><code><form class="areas-form" [formGroup]="areasForm" (ngSubmit)="onSubmit(areasForm.values)">
    <md-input-container class="full-width">
        <input mdInput placeholder="Location Name" type="text" formControlName="name" required>
        <md-error *ngIf="areasForm.get('name').hasError('required')">Please enter the locationName</md-error>
    </md-input-container>
    <md-grid-list cols="1" [formArrayName]="areas">
        <md-grid-tile formGroupName="i"  colspan="1" rowHeight="62px" *ngFor="let area of areasForm.controls.areas.controls; let i = index ">
            <md-grid-list cols="3" rowHeight="60px">
                <md-grid-tile colspan="1">
                    <md-input-container class="full-width">
                        <input mdInput placeholder="Area Name" type="text" formControlName="name" required>
                        <md-error *ngIf="areasForm.get('areas').controls[i].name.hasError('required')">Please enter the area name</md-error>
                    </md-input-container>
                </md-grid-tile>
                <md-grid-tile colspan="1">
                    <md-input-container class="full-width">
                        <input mdInput placeholder="details" type="text" formControlName="details" required>
                        <md-error *ngIf="areasForm.get('areas').controls[i].name.hasError('required')">Please enter the locationName</md-error>
                    </md-input-container>
                </md-grid-tile>
                <md-grid-tile colspan="1">
                    <button md-fab (click)="remove(i)"><md-icon>subtract</md-icon>Remove Area</button>
                </md-grid-tile>
            </md-grid-list>
        </md-grid-tile>
    </md-grid-list>
    <button type="submit" [disabled]="areasForm.invalid" md-raised-button color="primary">Submit</button>
</form>
</code>```

答:
In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:

```<code>[formControlName]="'familyName'"
</code>```

similar to below:

```<code>formControlName="familyName"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to iterate over a formArray in my component but I get the following error

Error: Cannot find control with unspecified name attribute

Here is what the logic looks like on my class file

export class AreasFormComponent implements OnInit {
    public initialState: any;
    public areasForm: FormGroup;

    constructor(private fb: FormBuilder) { }

    private area(): any {
      return this.fb.group({
          name: ['', [Validators.required]],
          latLong: ['', [Validators.required]],
          details: ['', [Validators.required]]
      });
    }

    public ngOnInit(): void {
        this.areasForm = this.fb.group({
            name: ['', [Validators.required]],
            areas: this.fb.array([this.area()])
        });
    }
}

and my template file

<form class="areas-form" [formGroup]="areasForm" (ngSubmit)="onSubmit(areasForm.values)">
    <md-input-container class="full-width">
        <input mdInput placeholder="Location Name" type="text" formControlName="name" required>
        <md-error *ngIf="areasForm.get('name').hasError('required')">Please enter the locationName</md-error>
    </md-input-container>
    <md-grid-list cols="1" [formArrayName]="areas">
        <md-grid-tile formGroupName="i"  colspan="1" rowHeight="62px" *ngFor="let area of areasForm.controls.areas.controls; let i = index ">
            <md-grid-list cols="3" rowHeight="60px">
                <md-grid-tile colspan="1">
                    <md-input-container class="full-width">
                        <input mdInput placeholder="Area Name" type="text" formControlName="name" required>
                        <md-error *ngIf="areasForm.get('areas').controls[i].name.hasError('required')">Please enter the area name</md-error>
                    </md-input-container>
                </md-grid-tile>
                <md-grid-tile colspan="1">
                    <md-input-container class="full-width">
                        <input mdInput placeholder="details" type="text" formControlName="details" required>
                        <md-error *ngIf="areasForm.get('areas').controls[i].name.hasError('required')">Please enter the locationName</md-error>
                    </md-input-container>
                </md-grid-tile>
                <md-grid-tile colspan="1">
                    <button md-fab (click)="remove(i)"><md-icon>subtract</md-icon>Remove Area</button>
                </md-grid-tile>
            </md-grid-list>
        </md-grid-tile>
    </md-grid-list>
    <button type="submit" [disabled]="areasForm.invalid" md-raised-button color="primary">Submit</button>
</form>

Body:
In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:

[formControlName]="'familyName'"

similar to below:

formControlName="familyName"


问:
Where in OpenCart's code does it send invoice emails off?
I'm trying to disable the firing of the invoice email for certain order statuses but can't find where the email->send is that does this.
I've commented out all email->sends in  catalog->model->checkout->order.php and have cleared the cache but still I get an invoice email through.
Thanks in advance.

答:
The emails are sent from file:
catalog/model/checkout/order.php as you are saying.

Let's say the order_status_id of the order you want to send the email is: 7 (usually the default order complete status id)

Find the code:

```<code>$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

$mail->setTo($order_info['email']);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender(html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
$mail->setHtml($this->load->view('mail/order', $data));
$mail->setText($text);
$mail->send();
</code>```

and wrap it with an if statement like this:

```<code>if($order_status_id == 7){
    $mail = new Mail();
    $mail->protocol = $this->config->get('config_mail_protocol');
    $mail->parameter = $this->config->get('config_mail_parameter');
    $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
    $mail->smtp_username = $this->config->get('config_mail_smtp_username');
    $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
    $mail->smtp_port = $this->config->get('config_mail_smtp_port');
    $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

    $mail->setTo($order_info['email']);
    $mail->setFrom($this->config->get('config_email'));
    $mail->setSender(html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
    $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
    $mail->setHtml($this->load->view('mail/order', $data));
    $mail->setText($text);
    $mail->send();
}
</code>```

This change will construct and send the email only if the order has status_id = 7. Change this order_status_id to yours.

Important Information:
1) If you are using any opencart extension that changes this code, you need to adjust your code ...
2) If you order_status_id is the default order_status_id of your eshop, then you will never get email. Be careful.

Hope I helped. Cheers.

Body:
The emails are sent from file:
catalog/model/checkout/order.php as you are saying.

Let's say the order_status_id of the order you want to send the email is: 7 (usually the default order complete status id)

Find the code:

$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

$mail->setTo($order_info['email']);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender(html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
$mail->setHtml($this->load->view('mail/order', $data));
$mail->setText($text);
$mail->send();

and wrap it with an if statement like this:

if($order_status_id == 7){
    $mail = new Mail();
    $mail->protocol = $this->config->get('config_mail_protocol');
    $mail->parameter = $this->config->get('config_mail_parameter');
    $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
    $mail->smtp_username = $this->config->get('config_mail_smtp_username');
    $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
    $mail->smtp_port = $this->config->get('config_mail_smtp_port');
    $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

    $mail->setTo($order_info['email']);
    $mail->setFrom($this->config->get('config_email'));
    $mail->setSender(html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
    $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
    $mail->setHtml($this->load->view('mail/order', $data));
    $mail->setText($text);
    $mail->send();
}

This change will construct and send the email only if the order has status_id = 7. Change this order_status_id to yours.

Important Information:
1) If you are using any opencart extension that changes this code, you need to adjust your code ...
2) If you order_status_id is the default order_status_id of your eshop, then you will never get email. Be careful.

Hope I helped. Cheers.


问:
Changing functionality of back button on android
I want to change the functionality of back button for a particular bunch of code being active. Once its done how do i reset it to default.

I am using following piece of code:

```<code>@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode== KeyEvent.KEYCODE_BACK && issearchopen)
        {
            searchView.closeSearch();
        }

        else{

        }
        return true;
    }
</code>```

boolean issearchopen is true whenever my 'bunch' of code is active.

Thanks in advance

答:
To do it you need to override onBackPressed() method.
Your code will looks like this

```<code>@Override
public void onBackPressed() {
   if(issearchopen){
      searchView.closeSearch();
      issearchopen = false;
   } else {
      super.onBackPressed(); // default back press behaviour
   }
}
</code>```

Also don't forget to change issearchopen to true when open searchView.

Body:
I want to change the functionality of back button for a particular bunch of code being active. Once its done how do i reset it to default.

I am using following piece of code:

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode== KeyEvent.KEYCODE_BACK && issearchopen)
        {
            searchView.closeSearch();
        }

        else{

        }
        return true;
    }

boolean issearchopen is true whenever my 'bunch' of code is active.

Thanks in advance

Body:
To do it you need to override onBackPressed() method.
Your code will looks like this

@Override
public void onBackPressed() {
   if(issearchopen){
      searchView.closeSearch();
      issearchopen = false;
   } else {
      super.onBackPressed(); // default back press behaviour
   }
}

Also don't forget to change issearchopen to true when open searchView.


问:
Using a created extension method
Here's the method I created:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            ProyectoFinalEntities x = new ProyectoFinalEntities();
            var categories = x.Categories;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Category c in categories)
            {
                stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
            }

            return stringBuilder.ToString();
        }
    }
}
</code>```

I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:

```<code>@Html.MyMenu //doesn't appears to be in the available method selection.
</code>```

What's the reason why I can't call this method like that? Thanks for the help.

答:
Update you web.config:

```<code>  <system.web>
    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
        <add namespace="System.Web.Helpers" />
        ...
        <add namespace="MvcApplication1.HelperMethods" /><!-- Add this line -->
      </namespaces>
    </pages>
  </system.web>
</code>```

This way you won't need to use the using directive for MvcApplicatin1.HelperMethods in each View. And you can put multiple helper classes in that namespace.

OwnerDisplayName: delete

Title: Using a created extension method

Body:
Here's the method I created:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            ProyectoFinalEntities x = new ProyectoFinalEntities();
            var categories = x.Categories;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (Category c in categories)
            {
                stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
            }

            return stringBuilder.ToString();
        }
    }
}

I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:

@Html.MyMenu //doesn't appears to be in the available method selection.

What's the reason why I can't call this method like that? Thanks for the help.

Body:
Update you web.config:

  <system.web>
    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
        <add namespace="System.Web.Helpers" />
        ...
        <add namespace="MvcApplication1.HelperMethods" /><!-- Add this line -->
      </namespaces>
    </pages>
  </system.web>

This way you won't need to use the using directive for MvcApplicatin1.HelperMethods in each View. And you can put multiple helper classes in that namespace.


问:
Embedding the last video published on a Youtube channel
I've been getting some mixed information while trying to embed an iframe that contains the most recently uploaded Youtube video of a certain channel.

I'm unsuccessfully trying to use the below format:

src="https://www.youtube.com/feeds/videos.xml?channel_id=CHANNEL_ID&orderby=published&maxResults=1"

Any help would be appreciated.

答:
This will give you step by step directions:
https://support.google.com/youtube/answer/171780?hl=en</p>


问:
c++ algorithm to select two random numbers from a range, with minimal distance
I have an std::vector initialized with numbers from 1 to 100

```<code>std::vector<int> vec;
for(int i = 1; i < 101; i++)
  vec.push_back(i);
</code>```

I want to select two random integers that have a minimal distance (for example minimal distance can be 10).

If num1, num2 are the numbers:

num2 - num1 > distance

I am using the following method to select a random integer between ranges:

```<code>int getRandomValue(int from, int to)
        {
                std::random_device seeder;
                std::mt19937 engine(seeder());
                std::uniform_int_distribution<int> dist(from, to);
                return dist(engine);
        }
</code>```

How can I generate num2 and num1?

答:
```<code>#include <cstdlib>

a = rand() % 90;
b = a + 10;
</code>```

a is the smaller , b is the bigger

Body:
I have an std::vector initialized with numbers from 1 to 100

std::vector<int> vec;
for(int i = 1; i < 101; i++)
  vec.push_back(i);

I want to select two random integers that have a minimal distance (for example minimal distance can be 10).

If num1, num2 are the numbers:

num2 - num1 > distance

I am using the following method to select a random integer between ranges:

int getRandomValue(int from, int to)
        {
                std::random_device seeder;
                std::mt19937 engine(seeder());
                std::uniform_int_distribution<int> dist(from, to);
                return dist(engine);
        }

How can I generate num2 and num1?

Body:
#include <cstdlib>

a = rand() % 90;
b = a + 10;

a is the smaller , b is the bigger


问:
How to use ng-if or ng-show to make md-select removed(hide)?
I am trying to make a md-select removed or hide when a checkbox is not checked.
I have tired both ng-if or ng-show, but once the md-select is displayed, it cannot be removed or hide. My code is as follows:

Using ng-if:

```<code><md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
Add Dependency
</md-checkbox>

<p>Checkbox value: {{ checked }}</p>
<md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-if ="checked">
<md-option>testOption1</md-option>
<md-option>testOption2</md-option>
<md-option>testOption3</md-option>
</md-select>
</code>```

Using ng-show

```<code><md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
Add Dependency
</md-checkbox>

<p>Checkbox value: {{ checked }}</p>
<md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-show ="checked">
<md-option>testOption1</md-option>
<md-option>testOption2</md-option>
<md-option>testOption3</md-option>
</md-select>
</code>```

Where did I do wrong? Thank you.

答:
Make it simple, ng-model is enough to handle this. No need of ng-true-value\ng-false-value,  It's generally required when you need custom flag like Yes\No

So : <md-checkbox ng-model="checked"> will do it for you.

See this working fiddle

Body:
I am trying to make a md-select removed or hide when a checkbox is not checked.
I have tired both ng-if or ng-show, but once the md-select is displayed, it cannot be removed or hide. My code is as follows:

Using ng-if:

<md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
Add Dependency
</md-checkbox>

Checkbox value: {{ checked }}

<md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-if ="checked">
<md-option>testOption1</md-option>
<md-option>testOption2</md-option>
<md-option>testOption3</md-option>
</md-select>

Using ng-show

<md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
Add Dependency
</md-checkbox>

Checkbox value: {{ checked }}

<md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-show ="checked">
<md-option>testOption1</md-option>
<md-option>testOption2</md-option>
<md-option>testOption3</md-option>
</md-select>

Where did I do wrong? Thank you.


问:
Error Cannot access memory at address in linked list
I'm creating a linked list with some insert functions.

This method work fine :

```<code>void insert_before(){
    struct node *new_node, *ptr, *preptr;
    int pivot;

    new_node = (struct node*)malloc(sizeof(struct node));
    ptr = link;
    preptr = link;

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    printf("\n Enter the value before which the data has to be inserted : ");
    scanf("%d", &pivot);

    while(ptr->data != pivot){
        preptr = ptr;
        ptr = ptr->next;
    }

    preptr->next = new_node;
    new_node->next = ptr;
}
</code>```

However, I got Cannot access memory at address 0x8 in this method :

```<code>void insert_after(){
    struct node *new_node, *ptr, *preptr;
    int pivot;

    new_node = (struct node*)malloc(sizeof(struct node));
    ptr = link;
    preptr = link;

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    printf("\n Enter the value after which the data has to be inserted : ");
    scanf("%d", &pivot);

    while(preptr->data != pivot){
        preptr = ptr;
        ptr = ptr->next;
    }

    preptr->next = new_node;
    new_node->next = ptr;
}
</code>```

Note that both of the method use the same struct* link, and the only difference is on the looping while(preptr->data != pivot).

Why does the first code working fine, but the second one broken?

Thanks for your help

PS : This is my whole project (very short), in case you need it : https://pastebin.com/wsMEicGv

答:
You have a lot of bad practice:

You use global without reason!

You use global without reason!!

You use global without reason!!!

You cast malloc() without reason.

You don't check return value of function like scanf() or malloc().

You code several time the same feature.

fflush(stdin); is undefined behavior.

You don't initialize your variable when you could.

You declare all your variable at the beginning of the function.

For example, display() could look like this:

```<code>void display(struct node *head) { // no global it's better, isn't it ?
    printf("List:");
    while (head != NULL) {
        printf(" %d", head->data);
        head = head->next;
    }
    printf("\n");
}
</code>```

More, in your create_ll() function, why don't you use insert beginning and reverse the list after ?

```<code>int create_ll(struct node **head) {
    *head = NULL;
    while (insert_beginning(head) != ERROR) {
    }
    return reverse_ll(head);
}
</code>```

Use example:

```<code>int main(void) {
    struct node *head;
    if (create_ll(&head) == ERROR) {
        return 1;
    }
    display(head);
    free_ll(head);
}
</code>```

For the problem of your both function, read the answer of stephan-lechner. But I make you an example:

```<code>int insert_after(struct node **head) {
    printf("\n Enter the data : ");
    int data;
    if (scanf("%d", &data) != 1) { // If the input has no been parse.
        // data is invalid here
        return ERROR;
    }
    // data is valid here

    printf("\n Enter the value after which the data has to be inserted : ");
    int pivot;
    if (scanf("%d", &pivot) != 1) {
        return ERROR;
    }

    for (struct node *node = *head; node != NULL; node = node->next) {
        if (node->data == pivot) {
            struct node *new_node = malloc(sizeof *new_node);
            if (new_node == NULL) {
                return ERROR;
            }
            new_node->data = data;
            new_node->next = node->next;
            node->next = new_node;

            return OK;
        }
    }
    return ERROR;
}
</code>```

Be aware that: If you use global your list functions will be:

Not thread safe.

Only usable for one list.

More info here.

Body:
I'm creating a linked list with some insert functions.

This method work fine :

void insert_before(){
    struct node *new_node, *ptr, *preptr;
    int pivot;

    new_node = (struct node*)malloc(sizeof(struct node));
    ptr = link;
    preptr = link;

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    printf("\n Enter the value before which the data has to be inserted : ");
    scanf("%d", &pivot);

    while(ptr->data != pivot){
        preptr = ptr;
        ptr = ptr->next;
    }

    preptr->next = new_node;
    new_node->next = ptr;
}

However, I got Cannot access memory at address 0x8 in this method :

void insert_after(){
    struct node *new_node, *ptr, *preptr;
    int pivot;

    new_node = (struct node*)malloc(sizeof(struct node));
    ptr = link;
    preptr = link;

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    printf("\n Enter the value after which the data has to be inserted : ");
    scanf("%d", &pivot);

    while(preptr->data != pivot){
        preptr = ptr;
        ptr = ptr->next;
    }

    preptr->next = new_node;
    new_node->next = ptr;
}

Note that both of the method use the same struct* link, and the only difference is on the looping while(preptr->data != pivot).

Why does the first code working fine, but the second one broken?

Thanks for your help

PS : This is my whole project (very short), in case you need it : https://pastebin.com/wsMEicGv

Body:
You have a lot of bad practice:

You use global without reason!

You use global without reason!!

You use global without reason!!!

You cast malloc() without reason.

You don't check return value of function like scanf() or malloc().

You code several time the same feature.

fflush(stdin); is undefined behavior.

You don't initialize your variable when you could.

You declare all your variable at the beginning of the function.

For example, display() could look like this:

void display(struct node *head) { // no global it's better, isn't it ?
    printf("List:");
    while (head != NULL) {
        printf(" %d", head->data);
        head = head->next;
    }
    printf("\n");
}

More, in your create_ll() function, why don't you use insert beginning and reverse the list after ?

int create_ll(struct node **head) {
    *head = NULL;
    while (insert_beginning(head) != ERROR) {
    }
    return reverse_ll(head);
}

Use example:

int main(void) {
    struct node *head;
    if (create_ll(&head) == ERROR) {
        return 1;
    }
    display(head);
    free_ll(head);
}

For the problem of your both function, read the answer of stephan-lechner. But I make you an example:

int insert_after(struct node **head) {
    printf("\n Enter the data : ");
    int data;
    if (scanf("%d", &data) != 1) { // If the input has no been parse.
        // data is invalid here
        return ERROR;
    }
    // data is valid here

    printf("\n Enter the value after which the data has to be inserted : ");
    int pivot;
    if (scanf("%d", &pivot) != 1) {
        return ERROR;
    }

    for (struct node *node = *head; node != NULL; node = node->next) {
        if (node->data == pivot) {
            struct node *new_node = malloc(sizeof *new_node);
            if (new_node == NULL) {
                return ERROR;
            }
            new_node->data = data;
            new_node->next = node->next;
            node->next = new_node;

            return OK;
        }
    }
    return ERROR;
}

Be aware that: If you use global your list functions will be:

Not thread safe.

Only usable for one list.

More info here.


问:
Why does my array not have the right length after initializing it?
I want to initialize an array of variable length with random zeros and ones. My problem is that the array I created seems to only have a length of 4 elements.
Why is that?</p>

```<code>int main()
{
    int i, j;
    int length = 20;
    int *array = (int *) calloc(length, sizeof(int));
    for (i = 1; i < length; i++) {
        array[i] = 1;
        printf("%d", array[i]);
    }
    printf("\n");
    for (j = 0; j < sizeof(array); j++) {
        printf("%d", array[j]);
    }
    getchar();
}
</code>```

答:
Solution is, instead of the the sizeof operator in for (j = 0; j < sizeof(array); j++), use for (j = 0; j < length; j++).

Also, i presume you want 20 elements of 0s and 1s in the array. So you might want to change

in the line for (i = 1; i < length; i++)

use for (i = 0; i < length; i++) instead.

Now for the explanation, the primary bug in the code is in the line

for (j = 0; j < sizeof(array); j++)

The sizeof operator returns size in bytes of the object representation of type. In your case the type is int, hence for a 32 bit machine, the sizeof operator will return 4 and for a 64 bit machine it will return 8. So in the second loop, runtime length is returned as 4(your machine is 32bit).

To explore all the elements you have input in the first loop, just use the same length variable to point to each index of the array instead of the sizeof operator.

Body:
I want to initialize an array of variable length with random zeros and ones. My problem is that the array I created seems to only have a length of 4 elements.
Why is that?

int main()
{
    int i, j;
    int length = 20;
    int *array = (int *) calloc(length, sizeof(int));
    for (i = 1; i < length; i++) {
        array[i] = 1;
        printf("%d", array[i]);
    }
    printf("\n");
    for (j = 0; j < sizeof(array); j++) {
        printf("%d", array[j]);
    }
    getchar();
}


问:
Scroll view scrolls the list view not the layout
I am developing a layout which contains two listviews. when the listviews expand beyond the layout size, I want to scroll the layout but its scrolls the listview.

How to scrolls the layout instead of the listviews.

My Code:

fragment_one.xml

```<code>        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="10dip" >

                <ListView
                    android:id="@+id/list_nation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#B29090" >
                </ListView>

                <ListView
                    android:id="@+id/list_regional"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#4A9C67" >
                </ListView>
            </LinearLayout>

        </ScrollView>
</code>```

答:
try this, remove the LinearLayout use RelativeLayout

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true" >

  <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ListView
        android:id="@+id/list_nation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:background="#B29090" >
         </ListView>

         <ListView
        android:id="@+id/list_regional"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:background="#4A9C67"  >
        </ListView>
  </RelativeLayout>
</ScrollView>
</code>```

Body:
I am developing a layout which contains two listviews. when the listviews expand beyond the layout size, I want to scroll the layout but its scrolls the listview.

How to scrolls the layout instead of the listviews.

My Code:

fragment_one.xml

        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="10dip" >

                <ListView
                    android:id="@+id/list_nation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#B29090" >
                </ListView>

                <ListView
                    android:id="@+id/list_regional"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#4A9C67" >
                </ListView>
            </LinearLayout>

        </ScrollView>

Body:
try this, remove the LinearLayout use RelativeLayout

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true" >

  <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ListView
        android:id="@+id/list_nation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:background="#B29090" >
         </ListView>

         <ListView
        android:id="@+id/list_regional"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:background="#4A9C67"  >
        </ListView>
  </RelativeLayout>
</ScrollView>


问:
Search Results by specified site
I'm wondering if there is a way to limit the Bing Web Search API to return only results for a specific website. I'm migrating from Google Custom Search to Bing Web Search API. I would like to limit all search queries to the website URL.

If I search for cars on the coolcars.com site it only returns results for coolcars.com and not anothersite.com.

Here's a link to the Bing Web Search API: https://azure.microsoft.com/en-us/services/cognitive-services/bing-web-search-api/

答:
A next Q: how to include subdomains in the search?
Example:
site:startpagina.nl "coaching" -prikbord
should give back subdomains like: (in Google search)

http://coaching.startpagina.nl/

http://coaching-counselling.startpagina.nl/

http://wandelcoach.startpagina.nl/

but it only gives back www. results like:
https://www.startpagina.nl
https://www.startpagina.nl/v/maatschappij/onderwijs/vraag/371779/
https://www.startpagina.nl/v/financien-werk/carriere-werk/vraag/

Title: Search Results by specified site


问:
How does this reinterpret_cast work? (Porting C++ to Java)
I have some C++ code I'm trying to port to Java, that looks like this:

```<code>struct foostruct {
    unsigned char aa : 3;
    bool ab : 1;
    unsigned char ba : 3;
    bool bb : 1;
};

static void foo(const unsigned char* buffer, int length)
{

    const unsigned char *end = buffer + length;

    while (buffer < end)
    {
        const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
        //read some values from struct and act accordingly
    }

}
</code>```

What is the reinterpret_cast doing?

答: It does what a classic C-style (const foostruct *)buffer would do at worst: tells C++ to ignore all safety and that you really know what you are doing. In this case, that the buffer actually consists of foostructs, which in turn are bit fields overlain on single 8 bit characters. Essentially, you can do the same in Java by just getting the bytes and doing the shift and mask operations yourself.

Body:
I have some C++ code I'm trying to port to Java, that looks like this:

struct foostruct {
    unsigned char aa : 3;
    bool ab : 1;
    unsigned char ba : 3;
    bool bb : 1;
};

static void foo(const unsigned char* buffer, int length)
{

    const unsigned char *end = buffer + length;

    while (buffer < end)
    {
        const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
        //read some values from struct and act accordingly
    }

}

What is the reinterpret_cast doing?


问:
How to post objects in ViewModel?
I've got this viewmodel class with an integer Id and an object type.

```<code>public class MyViewModel
{
    [Required]
    public int MyId { get; set; }

    public MyObject MyObject { get; set; }
}
</code>```

MyObject Model is:

```<code>public class MyObject
{
    [Key]
    public int ObjId { get; set; }

    public int Number { get; set; }
    public string Name { get; set; }

}
</code>```

This controller:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MyId, MyObject.Number, MyObject.Name")]MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
//do something!
}
</code>```

The view is:

```<code>@model MyProject.Models.MyViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-group">
        @Html.LabelFor(model => model.MyId , htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("MyId", null, "Select", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.MyId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.MyObject.Number, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.MyObject.Number, new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Number, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.MyObject.Name , htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.MyObject.Name , new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Name , "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" formaction="@Url.Action("Create")" />
        </div>
    </div>
}
</code>```

When I post data to controller, it recognize the MyId value but don't fill MyObject parameter. Any suggests to how to post an object with ViewModel?

答:
Assuming that you have @model MyViewModel at the top of the view, there's no need to complicate it.

Make your submit on the view

```<code><input type="submit" value="Create" class="btn btn-default" />
</code>```

and change the signature of the post method

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
//do something!
}
</code>```

The view model should then be bound.

Title: How to post objects in ViewModel?

Body:
I've got this viewmodel class with an integer Id and an object type.

public class MyViewModel
{
    [Required]
    public int MyId { get; set; }

    public MyObject MyObject { get; set; }
}

MyObject Model is:

public class MyObject
{
    [Key]
    public int ObjId { get; set; }

    public int Number { get; set; }
    public string Name { get; set; }

}

This controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MyId, MyObject.Number, MyObject.Name")]MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
//do something!
}

The view is:

@model MyProject.Models.MyViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.LabelFor(model => model.MyId , htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("MyId", null, "Select", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.MyId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.MyObject.Number, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.TextBoxFor(model => model.MyObject.Number, new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Number, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.MyObject.Name , htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.TextBoxFor(model => model.MyObject.Name , new { @class = "form-control", type = "number", min = "1", max = "3", step = "1" })
            @Html.ValidationMessageFor(model => model.MyObject.Name , "", new { @class = "text-danger" })

            <input type="submit" value="Create" class="btn btn-default" formaction="@Url.Action("Create")" />

}

When I post data to controller, it recognize the MyId value but don't fill MyObject parameter. Any suggests to how to post an object with ViewModel?

Body:
Assuming that you have @model MyViewModel at the top of the view, there's no need to complicate it.

Make your submit on the view

<input type="submit" value="Create" class="btn btn-default" />

and change the signature of the post method

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MyViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
//do something!
}

The view model should then be bound.


问:
Re-read environment variables from VBScript
I'm running a VBScript from a MSI installer (created using WiX toolset). This script checks using the PATH environment variable whether another software
is installed or not. The installer also offers a retry button which runs the script again.

Now the problem is this: If the PATH environment variable is changed while my installer is running, my script will not detect that change. My script only uses the new value of the PATH environmental variable after a re-start of the installer.

So the question is this: How can I force the installer process to update its copy of the environment variables using VBScript?

Edit:

It looks like this article explains how to solve the problem with PowerScript. But I need a solution for VBScript.

答:
```<code>With WScript.CreateObject("WScript.Shell")
    .Environment("PROCESS")("PATH") = .ExpandEnvironmentStrings(Replace( _
        .Environment("USER")("PATH") & ";" & .Environment("SYSTEM")("PATH"), ";;", ";" _
    ))
End With
</code>```

This will overwrite the in memory current process PATH environment variable with the information retrieved from registry for the user and system environment variables.

note: Previous code only updates the environment copy of the [c|w]script process that executes the code. It does not update the installer's copy of the environment (you can not update another process environment).

Body:
With WScript.CreateObject("WScript.Shell")
    .Environment("PROCESS")("PATH") = .ExpandEnvironmentStrings(Replace( _
        .Environment("USER")("PATH") & ";" & .Environment("SYSTEM")("PATH"), ";;", ";" _
    ))
End With

This will overwrite the in memory current process PATH environment variable with the information retrieved from registry for the user and system environment variables.

note: Previous code only updates the environment copy of the [c|w]script process that executes the code. It does not update the installer's copy of the environment (you can not update another process environment).


问:
CSS On hover Ease/ fade triangle in
I am trying to ease the triangle in on hover, e.g. have the opacity lighter and make it to opacity = 1 after like 4 seconds or something. Is this possible? If so how?

```<code>nav a:hover:after {
    content: "";
    display: block;
    border: 8px solid #405580;
    border-bottom-color: #fff;
    position: absolute;
    left:33%;
    margin-top: 23px;

}
</code>```

I have attached my code pen. Please advise: https://codepen.io/anon/pen/awOZZz

答:
You can add this code, as written by @Santi.

```<code>nav a::after {
  content: "";
  display: block;
  opacity: 0;
  transition: opacity 4s;
}
</code>```

* {
  margin: 0;
  border: 0;
  padding: 0;
}
body {
  background: #f0f0f0;
  font: 14px/20px Arial, San-Serif;
  color: #555 margin: 0;
}
a {
  color: #FFF;
  text-decoration: none;
  font-weight: bold;
  position: relative;
}
a:hover {
  color: #FFF;
  text-decoration: underline;
}
header {
  background: #405580;
  width: 100%;
  height: 86px;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  opacity: 0.90;
}
nav {
  float: right;
  padding: 35px 20px 0 0;
}
nav ul li {
  display: inline-block;
  float: left;
  padding: 10px;
}
nav a::after {
  content: "";
  display: block;
  opacity: 0;
  transition: opacity 4s;
}
nav a:hover::after {
  content: "";
  display: block;
  border: 8px solid #405580;
  border-bottom-color: #fff;
  position: absolute;
  left: 33%;
  margin-top: 23px;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Adatia.co.uk</title>
  <meta content="width=divice-width, initial-scale=1.0" name="viewport">
  <link href="NewFile.css" rel="stylesheet">
</head>
<body>
  <header>
    <nav>

      <ul>
        <li>
          Home
        </li>
        <li>
          Page1
        </li>
        <li>
          Page2
        </li>
        <li>
          Page3
        </li>
        <li>
          Page4
        </li>
        <li>
          Page5
        </li>
      </ul>
    </nav>
  </header>
</body>
</html></code>```

Title: CSS On hover Ease/ fade triangle in

Body:
I am trying to ease the triangle in on hover, e.g. have the opacity lighter and make it to opacity = 1 after like 4 seconds or something. Is this possible? If so how?

nav a:hover:after {
    content: "";
    display: block;
    border: 8px solid #405580;
    border-bottom-color: #fff;
    position: absolute;
    left:33%;
    margin-top: 23px;

}

I have attached my code pen. Please advise: https://codepen.io/anon/pen/awOZZz

Body:
You can add this code, as written by @Santi.

nav a::after {
  content: "";
  display: block;
  opacity: 0;
  transition: opacity 4s;
}

* {
  margin: 0;
  border: 0;
  padding: 0;
}
body {
  background: #f0f0f0;
  font: 14px/20px Arial, San-Serif;
  color: #555 margin: 0;
}
a {
  color: #FFF;
  text-decoration: none;
  font-weight: bold;
  position: relative;
}
a:hover {
  color: #FFF;
  text-decoration: underline;
}
header {
  background: #405580;
  width: 100%;
  height: 86px;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  opacity: 0.90;
}
nav {
  float: right;
  padding: 35px 20px 0 0;
}
nav ul li {
  display: inline-block;
  float: left;
  padding: 10px;
}
nav a::after {
  content: "";
  display: block;
  opacity: 0;
  transition: opacity 4s;
}
nav a:hover::after {
  content: "";
  display: block;
  border: 8px solid #405580;
  border-bottom-color: #fff;
  position: absolute;
  left: 33%;
  margin-top: 23px;
  opacity: 1;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Adatia.co.uk</title>
  <meta content="width=divice-width, initial-scale=1.0" name="viewport">
  <link href="NewFile.css" rel="stylesheet">
</head>
<body>
  <header>
    <nav>
      <a href="#" id="menu-icon"></a>
      <ul>
        <li>
          <a class="current" href="#">Home</a>
        </li>
        <li>
          <a href="#">Page1</a>
        </li>
        <li>
          <a href="#">Page2</a>
        </li>
        <li>
          <a href="#">Page3</a>
        </li>
        <li>
          <a href="#">Page4</a>
        </li>
        <li>
          <a href="#">Page5</a>
        </li>
      </ul>
    </nav>
  </header>
</body>
</html>


问:
Transform CSS { ul li:hover a } in JQUERY .hover
I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.

CSS:

```<code>ul li:hover a {
    color: #FFF;
}
</code>```

Can anyone Help ?

EDIT:

My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.

JQuery:

```<code>$("ul li").hover(function () {
    $(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
    $(this).stop().animate({ backgroundColor: "black"}, 400);
});
</code>```

To animate background color on hover in menu and submenu.

For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)

```<code>$('ul.submenu li a').hover(function () {
    $(this).css({color:'#FFFFFF'});
}, function () {
    $(this).css({color:'#00FF00'});
});
</code>```

All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.

HTML Structure:

```<code><ul class="menu">

      <li><a href="#">text</a></li>

      <li><a href="#">text</a>

        <ul class="submenu">
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
        </ul>

      </li>

      <li><a href="#">text</a></li>

</ul>
</code>```

答:
Bind a hover function for the li tag. Whenever mouseover/mouseout is on the  tag the event will bubble up to the

```<code>$(function(){
    $("ul li").hover(function(){
        $(this).css("color", "#fff");
    },function(){
        $(this).css("color", "#000000");
    });
});
</code>```

See a working demo

If you can achieve the effect using CSS then why go for javascript solution.

Body:
I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.

CSS:

ul li:hover a {
    color: #FFF;
}

Can anyone Help ?

EDIT:

My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.

JQuery:

$("ul li").hover(function () {
    $(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
    $(this).stop().animate({ backgroundColor: "black"}, 400);
});

To animate background color on hover in menu and submenu.

For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)

$('ul.submenu li a').hover(function () {
    $(this).css({color:'#FFFFFF'});
}, function () {
    $(this).css({color:'#00FF00'});
});

All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.

HTML Structure:

text

text

text

text

text

text

Body:
Bind a hover function for the li tag. Whenever mouseover/mouseout is on the <a> tag the event will bubble up to the <li>

$(function(){
    $("ul li").hover(function(){
        $(this).css("color", "#fff");
    },function(){
        $(this).css("color", "#000000");
    });
});

See a working demo

If you can achieve the effect using CSS then why go for javascript solution.


问:
How to have event only when parent is clicked but not when children (two levels down)
I'm doing a side menu, that hides and reveals a submenu when the parent li element is clicked, and I'm almost done. The problem is that if the li child (two levels down) is clicked it hides the submenu as well.

The parent should be the only one able to trigger the event.

Here you have a simplified version of the Html, CSS and JavaScript (jQuery):

$( document ).ready( function () {
  $( "li.has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}</code>```

      Overview

          Overview

          Account Settings

          Tasks

            Help

      Account Settings

      Tasks

      Help

```

Do you know how to fix this behavior?

答: Make the nav>li>a display block and put the id on that. That way the link takes up the whole width of the li and when you click it, it won't affect the submenu because the submenu isn't in the a element</p>

Body:
I'm doing a side menu, that hides and reveals a submenu when the parent li element is clicked, and I'm almost done. The problem is that if the li child (two levels down) is clicked it hides the submenu as well.

The parent should be the only one able to trigger the event.

Here you have a simplified version of the Html, CSS and JavaScript (jQuery):

$( document ).ready( function () {
  $( "li.has-submenu" ).on( 'click', function (e) {
    if( $("#submenu").hasClass( "hides" ) ){
      $("#submenu").slideDown().toggleClass( "hides" );
    } else {
      $("#submenu").slideUp().toggleClass( "hides" );
    }
  });
});

.hide {
  display: none;
}

#submenu {
  margin-left: 15px;
}

      Overview

          Overview

          Account Settings

          Tasks

            Help

      Account Settings

      Tasks

      Help

Do you know how to fix this behavior?


问:
Compute a confidence interval from sample data assuming unknown distribution
I have sample data for which I would like to compute a confidence interval, assuming a distribution that is not normal and is unknown. Basically, it looks like the distribution is Pareto.  But I don't know for sure.

The answers for the normal distribution:

Compute a confidence interval from sample data

Correct way to obtain confidence interval with scipy

答:
If you don't know the underlying distribution, then my first thought would be to use bootstrapping: https://en.wikipedia.org/wiki/Bootstrapping_(statistics)

In pseudo-code, assuming x is a numpy array containing your data:

```<code>import numpy as np
N = 10000
mean_estimates = []
for _ in range(N):
    re_sample_idx = np.random.randint(0, len(x), x.shape)
    mean_estimates.append(np.mean(x[re_sample_idx]))
</code>```

mean_estimates is now a list of 10000 estimates of the mean of the distribution. Take the 2.5th and 97.5th percentile of these 10000 values, and you have a confidence interval around the mean of your data:

```<code>sorted_estimates = np.sort(np.array(mean_estimates))
conf_interval = [sorted_estimates[int(0.025 * N)], sorted_estimates[int(0.975 * N)]]
</code>```

Body:
If you don't know the underlying distribution, then my first thought would be to use bootstrapping: https://en.wikipedia.org/wiki/Bootstrapping_(statistics)

In pseudo-code, assuming x is a numpy array containing your data:

import numpy as np
N = 10000
mean_estimates = []
for _ in range(N):
    re_sample_idx = np.random.randint(0, len(x), x.shape)
    mean_estimates.append(np.mean(x[re_sample_idx]))

mean_estimates is now a list of 10000 estimates of the mean of the distribution. Take the 2.5th and 97.5th percentile of these 10000 values, and you have a confidence interval around the mean of your data:

sorted_estimates = np.sort(np.array(mean_estimates))
conf_interval = [sorted_estimates[int(0.025 * N)], sorted_estimates[int(0.975 * N)]]