问:
How to properly add multiple elements event in jQuery custom plugin
I am trying to write my first jquery plugin and I'm having some difficulties trying to implement functions, events and triggers.

Here is the scenario in which I'm working.

I've multiple input box with same class eg. "numberTextBox"

Apply plugin directly to these classes eg. "$(".numberTextBox").inputNumericTextBox();".

I can also give settings in it.

Now plugin should allow only numeric value based on setting either given on default.

what I had in my mind is to properly convert and verify any given value. I want to use both onkeypress and onblur event. For that I wrote simple JavaScript program see here http://jsfiddle.net/wHgH5/29/.

I wanted to create jquery plugin so I can use in future easily with more friendly code.

On "return this each function" you can see I wrote keypress and blur function for that specific reason.

Problems which I am facing:

Firstly the blur event is not working so I can't trigger beforeBlurAction, afterBlurAction, onComplete functions and not to mention all the functionality in triggerBlurAction will not work.

Secondly even on keypress event it's assuming all "numberTextBox" input elements are same and doesn't apply separately. To understand it run the code snippet there are two input box with same classes, now type/press from keyboard "2.1.1" it will only allow "2.1" in that input box but on the second one it won't allow decimal. but if you empty first input box and it will allow writing single decimal on the second input box. I want to do it separately.

Check here https://jsfiddle.net/mzhe2rde/

//JQuery Custom Plugin inputNumericTextBox
(function($) {
  jQuery.fn.inputNumericTextBox = function(options) {

    var defaults = {
      negativeAllow: true,
      decimalAllow: true,
      decimalError: false,
      negativeSignError: false,
      beforeKeypressAction: function() {},
      afterKeypressAction: function() {},
      beforeBlurAction: function() {},
      afterBlurAction: function() {},
      onError: function() {},
      onComplete: function() {},
    };

    var settings = $.extend({}, defaults, options);

    return this.each(function(i, element) {
      $(document).on('keypress', element, function(e) {
        triggerKeypressAction(e, element)
      });
      $(document).on('blur', element, function(e) {
        alert(); //for testing but it's now working
        triggerBlurAction(e, element)
      });
    });

    function triggerKeypressAction(evt, element) {
      settings.beforeKeypressAction.call(element, settings);

      var regex;
      var theEvent = evt || window.event;
      var key = String.fromCharCode(theEvent.keyCode || theEvent.which);
      if (/\./.test(key) && /\./.test($(element).val())) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) {
          theEvent.preventDefault();
        }
        settings.decimalError = true;
        settings.onError.call(element, settings);
        return false;
      }

      /** Any idea on how to allow only one negative sign at the beginning?
         write regex code here **/

      if (settings.decimalAllow) {
        regex = (settings.negativeAllow) ? /[0-9]|\-|\./ : /[0-9]|\./;
      } else {
        regex = (settings.negativeAllow) ? /[0-9]|\-/ : /[0-9]/;
      }
      if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
      }

      settings.afterKeypressAction.call(element, settings);
    }

    function triggerBlurAction(evt, element) {
      settings.beforeBlurAction.call(element, settings);

      var inputValue = $(element).val(),
        parsedValue = (settings.decimalAllow) ? parseFloat(inputValue) : parseInt(inputValue, 10);
      if (isNaN(parsedValue)) {
        $(element).val('');
      } else if (settings.negativeAllow) {
        $(element).val(parsedValue);
      } else {
        $(element).val(Math.abs(parsedValue));
      }

      settings.afterBlurAction.call(element, settings);
      settings.onComplete.call(element, settings);
    }

  };
})(jQuery);

$(".numberTextBox").inputNumericTextBox({
  negativeAllow: true,
  decimalAllow: true,
  beforeKeypressAction: function(e) {
    console.log(this);
    console.log(e);
    console.log('before key');
  },
  afterKeypressAction: function(e) {
    console.log(this);
    console.log(e);
    console.log('after key');
  },
  beforeBlurAction: function(e) {
    console.log(this);
    console.log(e);
    console.log('before blur');
  },
  afterBlurAction: function(e) {
    console.log(this);
    console.log(e);
    console.log('after blur');
  },
  onError: function(e) {
    console.log(this);
    console.log(e);
    console.log('on error');
    if (e.decimalError) {
      alert('More than one decimal number is not allowed');
    } else if (e.negativeSignError) {
      alert('More than one negative sign is not allowed.\n You can only use negative at the start');
    }
  },
  onComplete: function(e) {
    console.log(this);
    console.log(e);
    console.log('on complete');
  },

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <input id="firstbox" type="text" class="numberTextBox" />
  <input id="secondbox" type="text" class="numberTextBox" />
</body></code>```

答:
I thought I should try myself. what I did is put all the content of the plugin to another private function. and call the function in a loop to initialize every element separately. that way I achieved my goal and all events are working properly. and few more to support single negative sign. now it's proper input number textbox.

check it out here https://jsfiddle.net/mzhe2rde/6/

//JQuery Custom Plugin inputNumericTextBox
(function($) {
    "use strict";

    var inputNumericTextBox = function(element, options) {
        var previous_value_set = false;
        var previous_value = '';
        var defaults = {
            negativeAllow: true,
            decimalAllow: true,
            decimalError: false,
            startNegativeSignError: false,
            multipleNegativeSignError: false,
            beforeKeypressAction: function() {},
            afterKeypressAction: function() {},
            beforeKeyupAction: function() {},
            afterKeyupAction: function() {},
            beforeBlurAction: function() {},
            afterBlurAction: function() {},
            onError: function() {},
            onInitializationComplete: function() {},
        };

        var settings = $.extend({}, defaults, options);

        $(element).on('keypress', function(e) {
            //console.log("keypress");
            triggerKeypressAction(e, element);
        });
        $(element).on('keyup', function(e) {
            //console.log("keyup");
            triggerKeyupAction(e, element);
        });
        $(element).on('blur', function(e) {
            //console.log("blur");
            triggerBlurAction(e, element);
        });

        settings.onInitializationComplete.call(element, settings);

        function triggerKeypressAction(evt, element) {
            settings.beforeKeypressAction.call(element, settings);

            var regex;
            var theEvent = evt || window.event;
            var key = String.fromCharCode(theEvent.keyCode || theEvent.which);
            if (/\./.test(key) && /\./.test($(element).val())) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) {
                    theEvent.preventDefault();
                }
                settings.decimalError = true;
                settings.onError.call(element, settings);
                settings.afterKeypressAction.call(element, settings);
                settings.decimalError = false;
                return false;
            }

            if (/-/.test(key) && /-/.test($(element).val())) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) {
                    theEvent.preventDefault();
                }
                settings.multipleNegativeSignError = true;
                settings.onError.call(element, settings);
                settings.afterKeypressAction.call(element, settings);
                settings.multipleNegativeSignError = false;
                return false;
            }

            if (/-/.test(key)) {
                previous_value_set = true;
                previous_value = $(element).val();
            }

            if (settings.decimalAllow) {
                regex = (settings.negativeAllow) ? /[0-9]|-|\./ : /[0-9]|\./;
            } else {
                regex = (settings.negativeAllow) ? /[0-9]|-/ : /[0-9]/;
            }
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();
            }
            settings.afterKeypressAction.call(element, settings);
        }

        function triggerKeyupAction(evt, element) {
            settings.beforeKeyupAction.call(element, settings);

            if (settings.negativeAllow && previous_value_set) {
                if (!(/^-.*/.test($(element).val()))) {
                    $(element).val(previous_value);
                    settings.startNegativeSignError = true;
                    settings.onError.call(element, settings);
                    settings.startNegativeSignError = false;
                }
            }
            previous_value_set = false;
            previous_value = '';

            settings.afterKeyupAction.call(element, settings);
        }

        function triggerBlurAction(evt, element) {
            settings.beforeBlurAction.call(element, settings);

            var inputValue = $(element).val(),
                parsedValue = (settings.decimalAllow) ? parseFloat(inputValue) : parseInt(inputValue, 10);
            if (isNaN(parsedValue)) {
                $(element).val('');
            } else if (settings.negativeAllow) {
                $(element).val(parsedValue);
            } else {
                $(element).val(Math.abs(parsedValue));
            }

            settings.afterBlurAction.call(element, settings);
        }
        return;
    };

    if (!jQuery.fn.inputNumericTextBox) {
        jQuery.fn.inputNumericTextBox = function(options) {
            return this.each(function() {
                inputNumericTextBox(this, options);
                return this;
            });
        };
    }

})(jQuery);

$(".numberTextBox").inputNumericTextBox({
    negativeAllow: true,
    decimalAllow: true,
    beforeKeypressAction: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('before keypress');
    },
    afterKeypressAction: function(e) {
        //console.log(this);
        //onsole.log(e);
        //console.log('after keypress');
    },
    beforeKeyupAction: function(e) {
        //console.log(this);
        //onsole.log(e);
        //console.log('before keyup');
    },
    afterKeyupAction: function(e) {
        //console.log(this);
        //onsole.log(e);
        //console.log('after keyup');
    },
    beforeBlurAction: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('before blur');
    },
    afterBlurAction: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('after blur');
    },
    onError: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('on error');
        if (e.decimalError) {
            alert('More than one decimal number is not allowed');
        } else if (e.multipleNegativeSignError) {
            alert('More than one negative sign is not allowed.');
        } else if (e.startNegativeSignError) {
            alert('You can only use one negative sign at the start');
        }
    },
    onInitializationComplete: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('on complete');
    },

});

/* Last initialization settings will take the precedence but events will trigger on all initialization
 * You shouldn't initialize more than one on a single element because it will create more object and it will take some memory to store it.
 * It's their to support large environment */

/* This is an example of last initialization or initialization more than one */

/*
$(".numberTextBox").inputNumericTextBox();
var n = $(".numberTextBox").inputNumericTextBox({
    negativeAllow: false,
    decimalAllow: true
});
console.log(n);*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
    <input type="text" class="numberTextBox" />
    <input type="text" class="numberTextBox" />
</body></code>```

Body:
I am trying to write my first jquery plugin and I'm having some difficulties trying to implement functions, events and triggers.

Here is the scenario in which I'm working.

I've multiple input box with same class eg. "numberTextBox"

Apply plugin directly to these classes eg. "$(".numberTextBox").inputNumericTextBox();".

I can also give settings in it.

Now plugin should allow only numeric value based on setting either given on default.

what I had in my mind is to properly convert and verify any given value. I want to use both onkeypress and onblur event. For that I wrote simple JavaScript program see here http://jsfiddle.net/wHgH5/29/.

I wanted to create jquery plugin so I can use in future easily with more friendly code.

On "return this each function" you can see I wrote keypress and blur function for that specific reason.

Problems which I am facing:

Firstly the blur event is not working so I can't trigger beforeBlurAction, afterBlurAction, onComplete functions and not to mention all the functionality in triggerBlurAction will not work.

Secondly even on keypress event it's assuming all "numberTextBox" input elements are same and doesn't apply separately. To understand it run the code snippet there are two input box with same classes, now type/press from keyboard "2.1.1" it will only allow "2.1" in that input box but on the second one it won't allow decimal. but if you empty first input box and it will allow writing single decimal on the second input box. I want to do it separately.

Check here https://jsfiddle.net/mzhe2rde/

//JQuery Custom Plugin inputNumericTextBox
(function($) {
  jQuery.fn.inputNumericTextBox = function(options) {

    var defaults = {
      negativeAllow: true,
      decimalAllow: true,
      decimalError: false,
      negativeSignError: false,
      beforeKeypressAction: function() {},
      afterKeypressAction: function() {},
      beforeBlurAction: function() {},
      afterBlurAction: function() {},
      onError: function() {},
      onComplete: function() {},
    };

    var settings = $.extend({}, defaults, options);

    return this.each(function(i, element) {
      $(document).on('keypress', element, function(e) {
        triggerKeypressAction(e, element)
      });
      $(document).on('blur', element, function(e) {
        alert(); //for testing but it's now working
        triggerBlurAction(e, element)
      });
    });

    function triggerKeypressAction(evt, element) {
      settings.beforeKeypressAction.call(element, settings);

      var regex;
      var theEvent = evt || window.event;
      var key = String.fromCharCode(theEvent.keyCode || theEvent.which);
      if (/\./.test(key) && /\./.test($(element).val())) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) {
          theEvent.preventDefault();
        }
        settings.decimalError = true;
        settings.onError.call(element, settings);
        return false;
      }

      /** Any idea on how to allow only one negative sign at the beginning?
         write regex code here **/

      if (settings.decimalAllow) {
        regex = (settings.negativeAllow) ? /[0-9]|\-|\./ : /[0-9]|\./;
      } else {
        regex = (settings.negativeAllow) ? /[0-9]|\-/ : /[0-9]/;
      }
      if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
      }

      settings.afterKeypressAction.call(element, settings);
    }

    function triggerBlurAction(evt, element) {
      settings.beforeBlurAction.call(element, settings);

      var inputValue = $(element).val(),
        parsedValue = (settings.decimalAllow) ? parseFloat(inputValue) : parseInt(inputValue, 10);
      if (isNaN(parsedValue)) {
        $(element).val('');
      } else if (settings.negativeAllow) {
        $(element).val(parsedValue);
      } else {
        $(element).val(Math.abs(parsedValue));
      }

      settings.afterBlurAction.call(element, settings);
      settings.onComplete.call(element, settings);
    }

  };
})(jQuery);

$(".numberTextBox").inputNumericTextBox({
  negativeAllow: true,
  decimalAllow: true,
  beforeKeypressAction: function(e) {
    console.log(this);
    console.log(e);
    console.log('before key');
  },
  afterKeypressAction: function(e) {
    console.log(this);
    console.log(e);
    console.log('after key');
  },
  beforeBlurAction: function(e) {
    console.log(this);
    console.log(e);
    console.log('before blur');
  },
  afterBlurAction: function(e) {
    console.log(this);
    console.log(e);
    console.log('after blur');
  },
  onError: function(e) {
    console.log(this);
    console.log(e);
    console.log('on error');
    if (e.decimalError) {
      alert('More than one decimal number is not allowed');
    } else if (e.negativeSignError) {
      alert('More than one negative sign is not allowed.\n You can only use negative at the start');
    }
  },
  onComplete: function(e) {
    console.log(this);
    console.log(e);
    console.log('on complete');
  },

});

  <input id="firstbox" type="text" class="numberTextBox" />
  <input id="secondbox" type="text" class="numberTextBox" />

Body:
I thought I should try myself. what I did is put all the content of the plugin to another private function. and call the function in a loop to initialize every element separately. that way I achieved my goal and all events are working properly. and few more to support single negative sign. now it's proper input number textbox.

check it out here https://jsfiddle.net/mzhe2rde/6/

//JQuery Custom Plugin inputNumericTextBox
(function($) {
    "use strict";

    var inputNumericTextBox = function(element, options) {
        var previous_value_set = false;
        var previous_value = '';
        var defaults = {
            negativeAllow: true,
            decimalAllow: true,
            decimalError: false,
            startNegativeSignError: false,
            multipleNegativeSignError: false,
            beforeKeypressAction: function() {},
            afterKeypressAction: function() {},
            beforeKeyupAction: function() {},
            afterKeyupAction: function() {},
            beforeBlurAction: function() {},
            afterBlurAction: function() {},
            onError: function() {},
            onInitializationComplete: function() {},
        };

        var settings = $.extend({}, defaults, options);

        $(element).on('keypress', function(e) {
            //console.log("keypress");
            triggerKeypressAction(e, element);
        });
        $(element).on('keyup', function(e) {
            //console.log("keyup");
            triggerKeyupAction(e, element);
        });
        $(element).on('blur', function(e) {
            //console.log("blur");
            triggerBlurAction(e, element);
        });

        settings.onInitializationComplete.call(element, settings);

        function triggerKeypressAction(evt, element) {
            settings.beforeKeypressAction.call(element, settings);

            var regex;
            var theEvent = evt || window.event;
            var key = String.fromCharCode(theEvent.keyCode || theEvent.which);
            if (/\./.test(key) && /\./.test($(element).val())) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) {
                    theEvent.preventDefault();
                }
                settings.decimalError = true;
                settings.onError.call(element, settings);
                settings.afterKeypressAction.call(element, settings);
                settings.decimalError = false;
                return false;
            }

            if (/-/.test(key) && /-/.test($(element).val())) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) {
                    theEvent.preventDefault();
                }
                settings.multipleNegativeSignError = true;
                settings.onError.call(element, settings);
                settings.afterKeypressAction.call(element, settings);
                settings.multipleNegativeSignError = false;
                return false;
            }

            if (/-/.test(key)) {
                previous_value_set = true;
                previous_value = $(element).val();
            }

            if (settings.decimalAllow) {
                regex = (settings.negativeAllow) ? /[0-9]|-|\./ : /[0-9]|\./;
            } else {
                regex = (settings.negativeAllow) ? /[0-9]|-/ : /[0-9]/;
            }
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) theEvent.preventDefault();
            }
            settings.afterKeypressAction.call(element, settings);
        }

        function triggerKeyupAction(evt, element) {
            settings.beforeKeyupAction.call(element, settings);

            if (settings.negativeAllow && previous_value_set) {
                if (!(/^-.*/.test($(element).val()))) {
                    $(element).val(previous_value);
                    settings.startNegativeSignError = true;
                    settings.onError.call(element, settings);
                    settings.startNegativeSignError = false;
                }
            }
            previous_value_set = false;
            previous_value = '';

            settings.afterKeyupAction.call(element, settings);
        }

        function triggerBlurAction(evt, element) {
            settings.beforeBlurAction.call(element, settings);

            var inputValue = $(element).val(),
                parsedValue = (settings.decimalAllow) ? parseFloat(inputValue) : parseInt(inputValue, 10);
            if (isNaN(parsedValue)) {
                $(element).val('');
            } else if (settings.negativeAllow) {
                $(element).val(parsedValue);
            } else {
                $(element).val(Math.abs(parsedValue));
            }

            settings.afterBlurAction.call(element, settings);
        }
        return;
    };

    if (!jQuery.fn.inputNumericTextBox) {
        jQuery.fn.inputNumericTextBox = function(options) {
            return this.each(function() {
                inputNumericTextBox(this, options);
                return this;
            });
        };
    }

})(jQuery);

$(".numberTextBox").inputNumericTextBox({
    negativeAllow: true,
    decimalAllow: true,
    beforeKeypressAction: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('before keypress');
    },
    afterKeypressAction: function(e) {
        //console.log(this);
        //onsole.log(e);
        //console.log('after keypress');
    },
    beforeKeyupAction: function(e) {
        //console.log(this);
        //onsole.log(e);
        //console.log('before keyup');
    },
    afterKeyupAction: function(e) {
        //console.log(this);
        //onsole.log(e);
        //console.log('after keyup');
    },
    beforeBlurAction: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('before blur');
    },
    afterBlurAction: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('after blur');
    },
    onError: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('on error');
        if (e.decimalError) {
            alert('More than one decimal number is not allowed');
        } else if (e.multipleNegativeSignError) {
            alert('More than one negative sign is not allowed.');
        } else if (e.startNegativeSignError) {
            alert('You can only use one negative sign at the start');
        }
    },
    onInitializationComplete: function(e) {
        //console.log(this);
        //console.log(e);
        //console.log('on complete');
    },

});

/* Last initialization settings will take the precedence but events will trigger on all initialization
 * You shouldn't initialize more than one on a single element because it will create more object and it will take some memory to store it.
 * It's their to support large environment */

/* This is an example of last initialization or initialization more than one */

/*
$(".numberTextBox").inputNumericTextBox();
var n = $(".numberTextBox").inputNumericTextBox({
    negativeAllow: false,
    decimalAllow: true
});
console.log(n);*/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
    <input type="text" class="numberTextBox" />
    <input type="text" class="numberTextBox" />
</body>


来源: stackexchange

问:
Using type families and Generics to find an Id value
This question is related to this one, where I wanted to avoid the boilerplate of extracting an Id value from a data structure, but in a type-safe manner.

I'll repeat the relevant details of the problem here: suppose you have a type Id:

```<code>newtype Id = Id { _id :: Int }
</code>```

And you want to define a function getId that extracts this Id from any structure that contains at least one Id value:

```<code>class Identifiable e where
    getId :: e -> Id
</code>```

Now the problem is how to define such a class in a type-safe manner, while at the same time avoiding the boilerplate using Generics.

In my previous question I was pointed to type families, and in particular to the ideas described in this blog post. As far as I understand the idea is to define a type-class MkIdentifiable such that:

```<code>class MakeIdentifiable (res :: Res) e where
    mkGetId :: Proxy res -> e -> Id
</code>```

Where a value is of type Res only if there is at least one Id value that is nested inside of it:

```<code>data Crumbs = Here | L Crumbs | R Crumbs
data Res = Found Crumbs | NotFound
</code>```

Then, it seems, one could define:

```<code>instance MakeIdentifiable (Found e) e => Identifiable e where
    getId = mkGetId (Proxy :: Proxy (Found e))
</code>```

Now the question is how to define a type family for Res that is associated to the types of GHC.Generics (U1, K1, :*:, :+:).

I've tried the following:

```<code>type family HasId e :: Res where
    HasId Id = Found Here
    HasId ((l :+: r) p) = Choose (HasId (l p)) (HasId (r p))
</code>```

Where Choose would be something like what is defined in the aforementioned blog post:

```<code>type family Choose e f :: Res where
    Choose (Found a) b = Found (L1 a)
    Choose a (Found b) = Found (R1 b)
    Choose a b = NotFound
</code>```

But this won't compile as HasId (l p) has kind Res and a type is expected instead.

答:
You're pretty close to making Choose typecheck. L1 and R1 are constructors of (:+:), not Crumbs. There's also a type GHC.Generics.R :: * which hides the R constructor from Crumbs at the type level, but you can use 'R to disambiguate (singly-quoted names are constructors, doubly-quoted are type constructors).

It's also good practice to annotate kinds of types, much like we annotate types of toplevel functions.

```<code>type family Choose (e :: Res) (f :: Res) :: Res where
  Choose (Found a) b = Found ('L a)
  Choose a (Found b) = Found ('R b)
  Choose NotFound NotFound = NotFound  -- I'm not a fan of overlapping families
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This question is related to this one, where I wanted to avoid the boilerplate of extracting an Id value from a data structure, but in a type-safe manner.

I'll repeat the relevant details of the problem here: suppose you have a type Id:

newtype Id = Id { _id :: Int }

And you want to define a function getId that extracts this Id from any structure that contains at least one Id value:

class Identifiable e where
    getId :: e -> Id

Now the problem is how to define such a class in a type-safe manner, while at the same time avoiding the boilerplate using Generics.

In my previous question I was pointed to type families, and in particular to the ideas described in this blog post. As far as I understand the idea is to define a type-class MkIdentifiable such that:

class MakeIdentifiable (res :: Res) e where
    mkGetId :: Proxy res -> e -> Id

Where a value is of type Res only if there is at least one Id value that is nested inside of it:

data Crumbs = Here | L Crumbs | R Crumbs
data Res = Found Crumbs | NotFound

Then, it seems, one could define:

instance MakeIdentifiable (Found e) e => Identifiable e where
    getId = mkGetId (Proxy :: Proxy (Found e))

Now the question is how to define a type family for Res that is associated to the types of GHC.Generics (U1, K1, :*:, :+:).

I've tried the following:

type family HasId e :: Res where
    HasId Id = Found Here
    HasId ((l :+: r) p) = Choose (HasId (l p)) (HasId (r p))

Where Choose would be something like what is defined in the aforementioned blog post:

type family Choose e f :: Res where
    Choose (Found a) b = Found (L1 a)
    Choose a (Found b) = Found (R1 b)
    Choose a b = NotFound

But this won't compile as HasId (l p) has kind Res and a type is expected instead.

Body:
You're pretty close to making Choose typecheck. L1 and R1 are constructors of (:+:), not Crumbs. There's also a type GHC.Generics.R :: * which hides the R constructor from Crumbs at the type level, but you can use 'R to disambiguate (singly-quoted names are constructors, doubly-quoted are type constructors).

It's also good practice to annotate kinds of types, much like we annotate types of toplevel functions.

type family Choose (e :: Res) (f :: Res) :: Res where
  Choose (Found a) b = Found ('L a)
  Choose a (Found b) = Found ('R b)
  Choose NotFound NotFound = NotFound  -- I'm not a fan of overlapping families


问:
how to improve the performance of in sql expression
I am now execution a sql similar to below：

```<code>select * from table_name where num in (123,124....,210) and type='a'
</code>```

the records of the table_name is around 1500000, so the execution time is very long, is there any idea that I could improve the efficiency?

Thanks.

答: Yes, you should add index on type and num column

Body:
I am now execution a sql similar to below：

select * from table_name where num in (123,124....,210) and type='a'

the records of the table_name is around 1500000, so the execution time is very long, is there any idea that I could improve the efficiency?

Thanks.


问:
Getting wider output in PyCharm's built-in console
I'm relatively new to using the PyCharm IDE, and have been unable to find a way to better shape the output when in a built-in console session. I'm typically working with pretty wide dataframes, that would fit easily across my monitor, but the display is cutting and wrapping them much sooner than needed.

Does anyone know of a setting to change this behavior to take advantage of the full width of my screen?

I would like to prevent it from wrapping after only a few columns (for example, the column 'ReadmitRate' should be immediately to the right of 'SNFDaysPerSNFCase')

答:
The answer by @mattvivier works nicely when printing Pandas dataframes (thanks!).

However, if you are printing NumPy arrays, you need to set np.set_printoptions as well:

```<code>import pandas as pd
import numpy as np
desired_width = 320
pd.set_option('display.width', desired_width)
np.set_printoptions(linewidth=desired_width)
</code>```

See docs on NumPy and set_printoptions.

ContentLicense: CC BY-SA 4.0

Body:
The answer by @mattvivier works nicely when printing Pandas dataframes (thanks!).

However, if you are printing NumPy arrays, you need to set np.set_printoptions as well:

import pandas as pd
import numpy as np
desired_width = 320
pd.set_option('display.width', desired_width)
np.set_printoptions(linewidth=desired_width)

See docs on NumPy and set_printoptions.


问:
Why two collection views in two table view cells won't work in Swift 4?
I read similar questions such as how to have multiple collection view in multiple table view cells and I connected my collection views cells and use identifier names for them but I don't know why I receive this Error:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier extera_infoCollectionViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
  * First throw call stack:

**Remember that I read Similar questions and the first table view cell with collection view working well and the problem is for second one **
here is my code for main view controller that has a table view and the table view has two cells

```<code>func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if collectionView == fieldOfActivityCell().fieldofActivitiesCollectionView {
        let fullfields : String = self.adv.resultValue[0].work_field!
        let fullfieldsArr : [String] = fullfields.components(separatedBy: ",")
        print(fullfieldsArr)
        return fullfieldsArr.count

    } else {

        let extera_infofields : String = self.adv.resultValue[0].extera_info!
        let extera_infofieldsArr : [String] = extera_infofields.components(separatedBy: ",")
        print(extera_infofieldsArr)
        return extera_infofieldsArr.count
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == fieldOfActivityCell().fieldofActivitiesCollectionView {

        let fieldsCells = collectionView.dequeueReusableCell(withReuseIdentifier: "fieldOfActivityCollectionViewCell", for: indexPath) as! fieldOfActivityCollectionViewCell

        let fullfields : String = self.adv.resultValue[0].work_field!
        let fullfieldsArr : [String] = fullfields.components(separatedBy: ",")

        fieldsCells.title.text = fullfieldsArr[indexPath.row]

        return fieldsCells
    }
    else {
        let extera_infoCells = collectionView.dequeueReusableCell(withReuseIdentifier: "extera_infoCollectionViewCell", for: indexPath) as! extera_infoCollectionViewCell

        let extera_info : String = self.adv.resultValue[0].extera_info!
        let extera_infoArr : [String] = extera_info.components(separatedBy: ",")

        extera_infoCells.infoText.text = extera_infoArr[indexPath.row]

        return extera_infoCells
    }
}
</code>```

and here is the table view codes in same view controller:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0{

        let fieldCell = self.showAdvTableView.dequeueReusableCell(withIdentifier: "fieldOfActivityCell", for: indexPath) as! fieldOfActivityCell

        return fieldCell

    } else {

        let fieldCell = self.showAdvTableView.dequeueReusableCell(withIdentifier: "extera_infoCell", for: indexPath) as! extera_infoCell

        return fieldCell
   }
</code>```

here is table view first cell class:

```<code>class fieldOfActivityCell: UITableViewCell {

    @IBOutlet weak var fieldofActivitiesCollectionView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        if let flowLayout = fieldofActivitiesCollectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSize.init(width: 1.0, height: 1.0) }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

extension fieldOfActivityCell {

    func setCollectionViewDataSourceDelegate
            <D: UICollectionViewDelegate & UICollectionViewDataSource>
    (_ dataSourceDelegate:D , forRow row : Int )

    {
        fieldofActivitiesCollectionView.delegate = dataSourceDelegate
        fieldofActivitiesCollectionView.dataSource = dataSourceDelegate
        fieldofActivitiesCollectionView.reloadData()
    }
}
</code>```

and here is the second tableview cell class:

```<code>@IBOutlet weak var extra_infoCollectionView: UICollectionView!

override func awakeFromNib() {
    super.awakeFromNib()

    if let flowLayout = extra_infoCollectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSize.init(width: 1.0, height: 1.0) }
}
}

 extension extera_infoCell {

    func setCollectionViewDataSourceDelegate
    <D: UICollectionViewDelegate & UICollectionViewDataSource>
    (_ dataSourceDelegate:D , forRow row : Int )

    {
        extra_infoCollectionView.delegate = dataSourceDelegate
        extra_infoCollectionView.dataSource = dataSourceDelegate
        extra_infoCollectionView.reloadData()
    }
}
</code>```

答:
First step: using Tags - you just need to use tag for them and use if else to choose which collection view has selected with tag so the answer is this :

```<code>if collectionView.tag == 1 {
do some thing//////
}else {
do some thing else}
</code>```

and you should use this in both cellForRowAtIndexPath and numberOfRows methods you can use this for table view too

Second step: you have to change the name of 'collection view' that you are dequeueing inside the cellForRowAt method in CollectionView data source:

```<code>if collectionView.tag == 1 {
    let cell = yourFirstCollectionView.dequeueReusableCell(...) as yourCell
    ....
    return cell
} else {
    let cell = yourSecondCollectionView.dequeueReusableCell(...) as yourCell
    ....
    return cell
}
</code>```

Body:
I read similar questions such as how to have multiple collection view in multiple table view cells and I connected my collection views cells and use identifier names for them but I don't know why I receive this Error:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier extera_infoCollectionViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
  * First throw call stack:

**Remember that I read Similar questions and the first table view cell with collection view working well and the problem is for second one **
here is my code for main view controller that has a table view and the table view has two cells

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if collectionView == fieldOfActivityCell().fieldofActivitiesCollectionView {
        let fullfields : String = self.adv.resultValue[0].work_field!
        let fullfieldsArr : [String] = fullfields.components(separatedBy: ",")
        print(fullfieldsArr)
        return fullfieldsArr.count

    } else {

        let extera_infofields : String = self.adv.resultValue[0].extera_info!
        let extera_infofieldsArr : [String] = extera_infofields.components(separatedBy: ",")
        print(extera_infofieldsArr)
        return extera_infofieldsArr.count
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == fieldOfActivityCell().fieldofActivitiesCollectionView {

        let fieldsCells = collectionView.dequeueReusableCell(withReuseIdentifier: "fieldOfActivityCollectionViewCell", for: indexPath) as! fieldOfActivityCollectionViewCell

        let fullfields : String = self.adv.resultValue[0].work_field!
        let fullfieldsArr : [String] = fullfields.components(separatedBy: ",")

        fieldsCells.title.text = fullfieldsArr[indexPath.row]

        return fieldsCells
    }
    else {
        let extera_infoCells = collectionView.dequeueReusableCell(withReuseIdentifier: "extera_infoCollectionViewCell", for: indexPath) as! extera_infoCollectionViewCell

        let extera_info : String = self.adv.resultValue[0].extera_info!
        let extera_infoArr : [String] = extera_info.components(separatedBy: ",")

        extera_infoCells.infoText.text = extera_infoArr[indexPath.row]

        return extera_infoCells
    }
}

and here is the table view codes in same view controller:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0{

        let fieldCell = self.showAdvTableView.dequeueReusableCell(withIdentifier: "fieldOfActivityCell", for: indexPath) as! fieldOfActivityCell

        return fieldCell

    } else {

        let fieldCell = self.showAdvTableView.dequeueReusableCell(withIdentifier: "extera_infoCell", for: indexPath) as! extera_infoCell

        return fieldCell
   }

here is table view first cell class:

class fieldOfActivityCell: UITableViewCell {

    @IBOutlet weak var fieldofActivitiesCollectionView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        if let flowLayout = fieldofActivitiesCollectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSize.init(width: 1.0, height: 1.0) }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

extension fieldOfActivityCell {

    func setCollectionViewDataSourceDelegate
            <D: UICollectionViewDelegate & UICollectionViewDataSource>
    (_ dataSourceDelegate:D , forRow row : Int )

    {
        fieldofActivitiesCollectionView.delegate = dataSourceDelegate
        fieldofActivitiesCollectionView.dataSource = dataSourceDelegate
        fieldofActivitiesCollectionView.reloadData()
    }
}

and here is the second tableview cell class:

@IBOutlet weak var extra_infoCollectionView: UICollectionView!

override func awakeFromNib() {
    super.awakeFromNib()

    if let flowLayout = extra_infoCollectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSize.init(width: 1.0, height: 1.0) }
}
}

 extension extera_infoCell {

    func setCollectionViewDataSourceDelegate
    <D: UICollectionViewDelegate & UICollectionViewDataSource>
    (_ dataSourceDelegate:D , forRow row : Int )

    {
        extra_infoCollectionView.delegate = dataSourceDelegate
        extra_infoCollectionView.dataSource = dataSourceDelegate
        extra_infoCollectionView.reloadData()
    }
}

Body:
First step: using Tags - you just need to use tag for them and use if else to choose which collection view has selected with tag so the answer is this :

if collectionView.tag == 1 {
do some thing//////
}else {
do some thing else}

and you should use this in both cellForRowAtIndexPath and numberOfRows methods you can use this for table view too

Second step: you have to change the name of 'collection view' that you are dequeueing inside the cellForRowAt method in CollectionView data source:

if collectionView.tag == 1 {
    let cell = yourFirstCollectionView.dequeueReusableCell(...) as yourCell
    ....
    return cell
} else {
    let cell = yourSecondCollectionView.dequeueReusableCell(...) as yourCell
    ....
    return cell
}


问:
Vertical Wrapping in HTML
I'm looking for a good way to do a vertical wrap.  My goal is to fit a list of checkboxes into a div.  I have the checkboxes sorted alphabetically, and I want the list to flow from the top of the div to the bottom and then begin again in a new column when they reach the bottom.  Right now, I can do this by breaking the list into chunks of a predefined size on the server-side before feeding it into my html template.  But things get messy when the list gets so long that you have to scroll.  I'm hoping to force it to scroll horizontally only.  This is not so easy, since I'm holding each chunk in a floating div, so white-space:nowrap doesn't seem to cut it. Currently, I'm using javascript count the number of list chunks and extend the width of an intermediary container (inside the div that serves as the viewport but containing the divs that contain the data).  I want something that looks roughly like this:

```<code> __________________________
| []..... []..... [].....  |
| []..... []..... [].....  |
| []..... [].....          |
| []..... [].....          |
|__________________________|
|<|_____________|___||___|>|
</code>```

So I guess I have two questions:

Is there a good way to vertically wrap a list?

Is there a good way to force horizontal scrolling when the data gets too large for the viewport?

答:
To manage the scroll of your viewport, you can set the CSS overflow property:</p>

```<code>div#viewport{
  overflow: scroll;
  overflow-x: scroll; /* not sure if it's standard */
  height: 150px;
}
</code>```

OwnerDisplayName: David Berger

ContentLicense: CC BY-SA 2.5

Title: Vertical Wrapping in HTML

Body:
I'm looking for a good way to do a vertical wrap.  My goal is to fit a list of checkboxes into a div.  I have the checkboxes sorted alphabetically, and I want the list to flow from the top of the div to the bottom and then begin again in a new column when they reach the bottom.  Right now, I can do this by breaking the list into chunks of a predefined size on the server-side before feeding it into my html template.  But things get messy when the list gets so long that you have to scroll.  I'm hoping to force it to scroll horizontally only.  This is not so easy, since I'm holding each chunk in a floating div, so white-space:nowrap doesn't seem to cut it. Currently, I'm using javascript count the number of list chunks and extend the width of an intermediary container (inside the div that serves as the viewport but containing the divs that contain the data).  I want something that looks roughly like this:

 __________________________
| []..... []..... [].....  |
| []..... []..... [].....  |
| []..... [].....          |
| []..... [].....          |
|__________________________|
|<|_____________|___||___|>|

So I guess I have two questions:

Is there a good way to vertically wrap a list?

Is there a good way to force horizontal scrolling when the data gets too large for the viewport?

Body:
To manage the scroll of your viewport, you can set the CSS overflow property:

div#viewport{
  overflow: scroll;
  overflow-x: scroll; /* not sure if it's standard */
  height: 150px;
}

OwnerDisplayName: GiDo


问:
Memory leak in C++ seems to get worse after adding delete statements
Edit: Can someone explain why adding the delete operators do not change the Valgrind output? Please do not ask me to read C++ books, I have browsed through a couple and have not found the answers there.

I am new to C++, having come from the java world, I seem to have trouble understanding how to use new and delete operators.

I have a method (myMethod()) which initiates a class, MyClass. In MyClass there are a few arrays and few other objects being created using the new and new[] operators. Initially I did not have a destructor written for this class (I assumed that when the control returns to main from my method, these the MyClass object and everything related to it would be automatically "freed").

When I ran my program with Valgrind, this is the leak summary I got:

```<code>==9446== LEAK SUMMARY:
==9446==    definitely lost: 1,957,019 bytes in 38 blocks.
==9446==    indirectly lost: 4,171,184 bytes in 3,040 blocks.
==9446==      possibly lost: 0 bytes in 0 blocks.
==9446==    still reachable: 91,984 bytes in 991 blocks.
==9446==         suppressed: 0 bytes in 0 blocks.
==9446== Reachable blocks (those to which a pointer was found) are not shown.
==9446== To see them, rerun with: --show-reachable=yes
</code>```

So I added a destructor which deletes all the arrays and sets the objects to null. I do not explicitly call delete on the MyClass object. Now when I run my program using Valgrind, this is the leak summary I get.

```<code>LEAK SUMMARY:
==9223==    definitely lost: 1,957,019 bytes in 38 blocks.
==9223==    indirectly lost: 4,171,184 bytes in 3,040 blocks.
==9223==      possibly lost: 0 bytes in 0 blocks.
==9223==    still reachable: 91,984 bytes in 991 blocks.
==9223==         suppressed: 0 bytes in 0 blocks.
==9223== Reachable blocks (those to which a pointer was found) are not shown.
==9223== To see them, rerun with: --show-reachable=yes
</code>```

When I explicitly delete the MyClass object, the nubmer of bytes lost is more!

```<code>==9268== LEAK SUMMARY:
==9268==    definitely lost: 3,353,187 bytes in 1,253 blocks.
==9268==    indirectly lost: 28,376 bytes in 343 blocks.
==9268==      possibly lost: 0 bytes in 0 blocks.
==9268==    still reachable: 91,984 bytes in 991 blocks.
==9268==         suppressed: 0 bytes in 0 blocks.
==9268== Reachable blocks (those to which a pointer was found) are not shown.
==9268== To see them, rerun with: --show-reachable=yes
</code>```

I tried renaming the destructor to a method freeMemory() and then called freeMemory() before exitting from myMethod() and this is the leak summary. This is higher than either of them.

```<code>== LEAK SUMMARY:
==8998==    definitely lost: 5,271,299 bytes in 1,205 blocks.
==8998==    indirectly lost: 67,264 bytes in 410 blocks.
==8998==      possibly lost: 0 bytes in 0 blocks.
==8998==    still reachable: 91,984 bytes in 991 blocks.
==8998==         suppressed: 0 bytes in 0 blocks.
==8998== Reachable blocks (those to which a pointer was found) are not shown.
==8998== To see them, rerun with: --show-reachable=yes
</code>```

I guess my question is what is going on? Valgrind seems to indicate that the leak is in the constructor for MyClass and in a method in MyClass. Can someone explain to me how the new and delete operators work? I am not able to find a clear resource online, so if anyone can point me to such resource, that would be great too!

答:
Since you're coming from Java, I should mention first that most often you do not need to use new in C++.

If you need a variable of type T, then just declare a variable of type T. That's it.

For your array, instead of using a pointer and new, use a std::vector, like

```<code>#include <vector>

int main()
{
    std::vector<int>  v( 10 );    // 10 elements
    v.resize( 42 );               // now 42 elements
}
</code>```

It manages the memory automatically and correctly.

As to the error you are encountering, it is probably due to failure to consider all ways that your object can be copied. There is a rule of 3 (for C++98) that says that if you need any of custom destructor, custom copy constructor, or custom copy assignment operator, then you probably need all three. But again, instead of fiddling with that, which is difficult to get right, just use std::vector, or some other container.

And where you do need to manage lifetimes more directly, use smart pointers such as std::auto_ptr (from the standard library) and boost::shared_ptr (from the Boost library). That centralizes the tricky lifetime management code. Out of sight, Just Working™.

Cheers & hth.

Body:
Edit: Can someone explain why adding the delete operators do not change the Valgrind output? Please do not ask me to read C++ books, I have browsed through a couple and have not found the answers there.

I am new to C++, having come from the java world, I seem to have trouble understanding how to use new and delete operators.

I have a method (myMethod()) which initiates a class, MyClass. In MyClass there are a few arrays and few other objects being created using the new and new[] operators. Initially I did not have a destructor written for this class (I assumed that when the control returns to main from my method, these the MyClass object and everything related to it would be automatically "freed").

When I ran my program with Valgrind, this is the leak summary I got:

==9446== LEAK SUMMARY:
==9446==    definitely lost: 1,957,019 bytes in 38 blocks.
==9446==    indirectly lost: 4,171,184 bytes in 3,040 blocks.
==9446==      possibly lost: 0 bytes in 0 blocks.
==9446==    still reachable: 91,984 bytes in 991 blocks.
==9446==         suppressed: 0 bytes in 0 blocks.
==9446== Reachable blocks (those to which a pointer was found) are not shown.
==9446== To see them, rerun with: --show-reachable=yes

So I added a destructor which deletes all the arrays and sets the objects to null. I do not explicitly call delete on the MyClass object. Now when I run my program using Valgrind, this is the leak summary I get.

LEAK SUMMARY:
==9223==    definitely lost: 1,957,019 bytes in 38 blocks.
==9223==    indirectly lost: 4,171,184 bytes in 3,040 blocks.
==9223==      possibly lost: 0 bytes in 0 blocks.
==9223==    still reachable: 91,984 bytes in 991 blocks.
==9223==         suppressed: 0 bytes in 0 blocks.
==9223== Reachable blocks (those to which a pointer was found) are not shown.
==9223== To see them, rerun with: --show-reachable=yes

When I explicitly delete the MyClass object, the nubmer of bytes lost is more!

==9268== LEAK SUMMARY:
==9268==    definitely lost: 3,353,187 bytes in 1,253 blocks.
==9268==    indirectly lost: 28,376 bytes in 343 blocks.
==9268==      possibly lost: 0 bytes in 0 blocks.
==9268==    still reachable: 91,984 bytes in 991 blocks.
==9268==         suppressed: 0 bytes in 0 blocks.
==9268== Reachable blocks (those to which a pointer was found) are not shown.
==9268== To see them, rerun with: --show-reachable=yes

I tried renaming the destructor to a method freeMemory() and then called freeMemory() before exitting from myMethod() and this is the leak summary. This is higher than either of them.

== LEAK SUMMARY:
==8998==    definitely lost: 5,271,299 bytes in 1,205 blocks.
==8998==    indirectly lost: 67,264 bytes in 410 blocks.
==8998==      possibly lost: 0 bytes in 0 blocks.
==8998==    still reachable: 91,984 bytes in 991 blocks.
==8998==         suppressed: 0 bytes in 0 blocks.
==8998== Reachable blocks (those to which a pointer was found) are not shown.
==8998== To see them, rerun with: --show-reachable=yes

I guess my question is what is going on? Valgrind seems to indicate that the leak is in the constructor for MyClass and in a method in MyClass. Can someone explain to me how the new and delete operators work? I am not able to find a clear resource online, so if anyone can point me to such resource, that would be great too!

Body:
Since you're coming from Java, I should mention first that most often you do not need to use new in C++.

If you need a variable of type T, then just declare a variable of type T. That's it.

For your array, instead of using a pointer and new, use a std::vector, like

#include <vector>

int main()
{
    std::vector<int>  v( 10 );    // 10 elements
    v.resize( 42 );               // now 42 elements
}

It manages the memory automatically and correctly.

As to the error you are encountering, it is probably due to failure to consider all ways that your object can be copied. There is a rule of 3 (for C++98) that says that if you need any of custom destructor, custom copy constructor, or custom copy assignment operator, then you probably need all three. But again, instead of fiddling with that, which is difficult to get right, just use std::vector, or some other container.

And where you do need to manage lifetimes more directly, use smart pointers such as std::auto_ptr (from the standard library) and boost::shared_ptr (from the Boost library). That centralizes the tricky lifetime management code. Out of sight, Just Working™.

Cheers & hth.


问:
Apply all IEntityTypeConfiguration derived classes in EF Core
Does anyone know of a way or have an implementation to apply ALL classes that derive from IEntityTypeConfiguration<> to the DbContext at runtime?

There doesn't seem to be anything built in and loading each one manually via:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new Table1Config())
    modelBuilder.ApplyConfiguration(new Table2Config())
    ...
    modelBuilder.ApplyConfiguration(new TableNConfig())
}
</code>```

is going to prove rather tedious for a database with many tables.

答:
```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    var implementedConfigTypes = Assembly.GetExecutingAssembly()
        .GetTypes()
        .Where(t => !t.IsAbstract
            && !t.IsGenericTypeDefinition
            && t.GetTypeInfo().ImplementedInterfaces.Any(i =>
                i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)));

    foreach (var configType in implementedConfigTypes)
    {
        dynamic config = Activator.CreateInstance(configType);
        modelBuilder.ApplyConfiguration(config);
    }
}
</code>```

Body:
Does anyone know of a way or have an implementation to apply ALL classes that derive from IEntityTypeConfiguration<> to the DbContext at runtime?

There doesn't seem to be anything built in and loading each one manually via:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new Table1Config())
    modelBuilder.ApplyConfiguration(new Table2Config())
    ...
    modelBuilder.ApplyConfiguration(new TableNConfig())
}

is going to prove rather tedious for a database with many tables.


问:
Extracting attachments from Lotus Notes Email with Java
In my project I am attempting to read lotus notes email in the Inbox. Right now I have two emails in my inbox, each email has an attachment, and I am trying to open each email and download the attachment from that email.

The issue I am having now is that my program is only reading the first email.

```<code>try
    {
        NotesThread.sinitThread();

        Session session = NotesFactory.createSession();
        Database database = session.getDatabase("servername", "mailbox link");
        View view = database.getView("$Inbox");
        Document document = view.getFirstDocument();

        while(document != null)
        {

            RichTextItem Body = (RichTextItem)document.getFirstItem("Body");
            Vector vector = Body.getEmbeddedObjects();
            Enumeration iterator = vector.elements();

            while (iterator.hasMoreElements())
            {
              EmbeddedObject eo = (EmbeddedObject)iterator.nextElement();
              if(eo.getType()==EmbeddedObject.EMBED_ATTACHMENT)
                {
                    attachment = eo.getName();
                    eo.extractFile("destination" + eo.getName());
                    eo.remove();
                }

            }//end of inner while

            logger.info("Received email and downloaded attachment");
            document = view.getNextDocument(document);

        } //end of outer while

    }
    catch(NotesException nex)
    {
       logger.severe("Exception in INotes connection");
    }
    finally
    {
        NotesThread.stermThread();

    }
</code>```

I thought the line --
      document = view.getNextDocument(document)

would open the  next email in the Inbox. But I am only getting the first email as the result.

Appreciate any pointers.

答:
You can use view.getFirstDocument, get the first mail, and use the view.getNextDocument (Document document) to read the next message.
Or use view.getNthDocument (int index) to read mail.

Body:
In my project I am attempting to read lotus notes email in the Inbox. Right now I have two emails in my inbox, each email has an attachment, and I am trying to open each email and download the attachment from that email.

The issue I am having now is that my program is only reading the first email.

try
    {
        NotesThread.sinitThread();

        Session session = NotesFactory.createSession();
        Database database = session.getDatabase("servername", "mailbox link");
        View view = database.getView("$Inbox");
        Document document = view.getFirstDocument();

        while(document != null)
        {

            RichTextItem Body = (RichTextItem)document.getFirstItem("Body");
            Vector vector = Body.getEmbeddedObjects();
            Enumeration iterator = vector.elements();

            while (iterator.hasMoreElements())
            {
              EmbeddedObject eo = (EmbeddedObject)iterator.nextElement();
              if(eo.getType()==EmbeddedObject.EMBED_ATTACHMENT)
                {
                    attachment = eo.getName();
                    eo.extractFile("destination" + eo.getName());
                    eo.remove();
                }

            }//end of inner while

            logger.info("Received email and downloaded attachment");
            document = view.getNextDocument(document);

        } //end of outer while

    }
    catch(NotesException nex)
    {
       logger.severe("Exception in INotes connection");
    }
    finally
    {
        NotesThread.stermThread();

    }

I thought the line --
      document = view.getNextDocument(document)

would open the  next email in the Inbox. But I am only getting the first email as the result.

Appreciate any pointers.


问:
Recaptcha - Does not show validation image
I click on "I am not Robot" Checkbox. The Validation is successful,it simply accepts me as a human, without prompting validation image.  Couple of days back when i was testing recaptcha everything was working fine. i.e it was prompting validation image. I tried disabling plugins on chrome but no luck. Any idea why no image shows up ? Thanks!</p>

答:
It is not mandatory that Google  Recaptcha will always prompt you to select images for verifying.This version 2 of Recaptcha is made to solve the purpose of not selecting images or not giving too much input from the user. Most of the time it validates by clicking the I Am not robot check box , if in case it fails it prompt image validation..
I hope it will clear your doubt.</p>


问:
UITableView internal inconsistency: _visibleRows and _visibleCells must be of same length
I'm currently trying to make a self sizing tableview (where the cells autosize to fit their inner view's autolayout).

One of the cells has a tableview in it. The idea is that the cell should be the size of the contentSize.height of the tableview.

I subclassed UITableView to accomplish this, and when the tableview loads, it looks great. However, this error gets spit out:

[Assert] UITableView internal inconsistency: _visibleRows and _visibleCells must be of same length. _visibleRows: {0, 4}; _visibleCells.count: 8, _visibleCells:

Additionally, when I try to scroll the tableview after this error there is very strange behavior and the tableview starts an infinite loop of layoutsubviews.

Any idea what this error means? I haven't been able to find anything substantial referencing this error on the internet. Thanks in advance!

答:
in my case it was due to editing tableview on background queue
use your updating method like this
DispatchQueue.main.async { [weak self] in
      self?.updateUI()
 }


问:
SQL Server Get only Date form column with Date and Time
I have been trying to get only date from a column with date and time.

Here is a sample:

```<code>Select BDATE
from PersonData
</code>```

Current output:

```<code>1977-12-05 15:40:54.000
</code>```

Desired output:

```<code>1977-12-05
</code>```

How can I use the CONVERT date from datetime?

Thanks in advance

答:
You can use FORMAT like this:</p>

```<code>SELECT FORMAT([BDATE],'yyy-MM-dd') AS 'BDATE' FROM PersonData;
</code>```

Body:
I have been trying to get only date from a column with date and time.

Here is a sample:

Select BDATE
from PersonData

Current output:

1977-12-05 15:40:54.000

Desired output:

1977-12-05

How can I use the CONVERT date from datetime?

Thanks in advance

Body:
You can use FORMAT like this:

SELECT FORMAT([BDATE],'yyy-MM-dd') AS 'BDATE' FROM PersonData;


问:
Multi-threading in Android
I'm new to Android and Java. I'm trying to download 1000 plus images. I don't want to do that serially in a UI thread as that will be slow. Hence, I implemented multi-threading using thread and runnable in the below manner.

The for-loop will be called 1000 plus times. So is it an efficient way of achieving it? Will the OS manage the thread pool by its own?

```<code>private void syncS3Data() {
    tStart = System.currentTimeMillis();
    try {
        for (final AWSSyncFile f : awsSyncData.getFiles()) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    beginDownload(f);
                }

            }).start();
        }
    } catch (Exception ex) {
        progressDialog.dismiss();
        showMessage("Error:" + ex.getStackTrace().toString());
    }
}
</code>```

答:
Instead of creating threads for each download, create one thread and use that for downloading all images.

You can use AsyncTask Refer: https://developer.android.com/reference/android/os/AsyncTask.html

```<code>private class DownloadFilesTask extends AsyncTask<SomeObject, Integer, Long> {
    protected Long doInBackground(SomeObject... objs) {

        for (final AWSSyncFile f : obj.getFiles()) {
           beginDownload(f);
        }
    }

    protected void onPostExecute(Long result) {
       //Task Completed
    }

new DownloadFilesTask().execute(someObj);
</code>```

Title: Multi-threading in Android

Body:
I'm new to Android and Java. I'm trying to download 1000 plus images. I don't want to do that serially in a UI thread as that will be slow. Hence, I implemented multi-threading using thread and runnable in the below manner.

The for-loop will be called 1000 plus times. So is it an efficient way of achieving it? Will the OS manage the thread pool by its own?

private void syncS3Data() {
    tStart = System.currentTimeMillis();
    try {
        for (final AWSSyncFile f : awsSyncData.getFiles()) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    beginDownload(f);
                }

            }).start();
        }
    } catch (Exception ex) {
        progressDialog.dismiss();
        showMessage("Error:" + ex.getStackTrace().toString());
    }
}

Body:
Instead of creating threads for each download, create one thread and use that for downloading all images.

You can use AsyncTask Refer: https://developer.android.com/reference/android/os/AsyncTask.html

private class DownloadFilesTask extends AsyncTask<SomeObject, Integer, Long> {
    protected Long doInBackground(SomeObject... objs) {

        for (final AWSSyncFile f : obj.getFiles()) {
           beginDownload(f);
        }
    }

    protected void onPostExecute(Long result) {
       //Task Completed
    }

new DownloadFilesTask().execute(someObj);


问:
Apache installation; libpcre error
When installing Apache on Ubuntu 11.10, I get the following error:

configure: error: APR not found. Please read the documentation.

I followed the instructions here, then, I get the error below:

configure: error: pcre-config for libpcre not found. PCRE is required and available from http://pcre.org/

What am I doing wrong and how can I resolve it?

答:
This worked for me </p>

<p>./configure --prefix /u01/apache  --with-included-apr --with-pcre=/usr/local/pcre/bin/pcre2-config</p>

Title: Apache installation; libpcre error

Body:
This worked for me

./configure --prefix /u01/apache  --with-included-apr --with-pcre=/usr/local/pcre/bin/pcre2-config


答:
Here is the syntax for the convert() function.

CONVERT(data_type(length), expression, style)

The datatype to convert expression to. Can be one of the following: bigint, int, smallint, tinyint, bit, decimal, numeric, money, smallmoney, float, real, datetime, smalldatetime, char, varchar, text, nchar, nvarchar, ntext, binary, varbinary, or image. Required filed.

The length of the resulting data type (for char, varchar, nchar, nvarchar, binary and varbinary).Its and Optional.

The Expression value to convert to another data type. Required filed.

The Style format used to convert between data types, such as a date or string format.Its an Optional.

refer the below query to your answer,

```<code>   select CONVERT(date,BDATE) from PersonData
</code>```

Refer the below link to various type of Convert Formation.

https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

Title: SQL Server Get only Date form column with Date and Time

Body:
Here is the syntax for the convert() function.

CONVERT(data_type(length), expression, style)

The datatype to convert expression to. Can be one of the following: bigint, int, smallint, tinyint, bit, decimal, numeric, money, smallmoney, float, real, datetime, smalldatetime, char, varchar, text, nchar, nvarchar, ntext, binary, varbinary, or image. Required filed.

The length of the resulting data type (for char, varchar, nchar, nvarchar, binary and varbinary).Its and Optional.

The Expression value to convert to another data type. Required filed.

The Style format used to convert between data types, such as a date or string format.Its an Optional.

refer the below query to your answer,

   select CONVERT(date,BDATE) from PersonData

Refer the below link to various type of Convert Formation.

https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql


问:
Batch Reading a Result Set from a SQL Server Sproc with a very large amount of data?
I'm attempting to perform a data export using .NET code from SQL Server. I have the bulk of the export logic inside of a stored procedure that's returning a resultset with FOR JSON AUTO to export data. The Stored Proc builds the JSON result exactly as I need it and my .NET code essentially just needs to consume that Stored Proc and put the results to an FTP location. This works great for most of my exports.

The problem is that some exports have a large amount of data with the resulting JSON file being hundreds of megabytes (and it will be gigabytes). I'm running into issues where I start to get OutOfMemeoryExceptions being thrown because of how I handle this data (i.e. storing it all in memory within .NET both inside of a DataTable that I fill and then later into a StringBuilder). While I have temporarily thrown more money/memory at the problem, this isn't a scalable solution.

So I clearly need to change strategies, which is fine since my current process is not terribly well-optimized. The most obvious counter-strategy is then to use a SqlDataReader and call while (reader.Read()) and push it to a temp file on disk (to later stream to an FTP). And technically, this approach works since I don't really need to "intelligently process" the recordset - just store it and ship it. But reader.Read() will just get 1 record at a time (which, with FOR JSON AUTO this is more than 1 record but is still quite tiny compared to hundreds of megabytes). The problem with this approach is that the tiny size of the data payloads here are really way too small and this makes way too many round-trips to the database which results in this export simply being too slow. I normally optimize with chunky over chatty and this option is simply too chatty but the way I'm doing it today is too chunky.

Is there something in between those two options? I'd LOVE if I could do the SqlDataReader but tell it to batch it into 1000 records per round-trip to the database since these network round-trips are what are killing me with this counter-strategy. Alternatively, if there was some way I could control the size of the records when from the FOR JSON AUTO recordset to be much larger than they currently are (8k? I forget), that might be an option as well.

I have Entity Framework in my solution although I'm dropping down to ADO.NET for my current code. I would be willing to include another frameworks if that's necessary. But a simple ADO.NET solution would be ideal.

答:
While it may not be a perfect solution, this is the implementation I went with:

```<code>    /// <summary>
    ///     Calls a stored procedure that returns data as "FOR JSON AUTO" and stores the results into a temporary file.
    /// </summary>
    /// <param name="connection">SQLConnection to execute the stored procedure on.</param>
    /// <param name="commandTextForJsonQuery">CommandText for the execution.</param>
    /// <param name="parameters">All input and output parameters.</param>
    /// <param name="optionalFilePathAndName">
    ///     Optional file name and path to write to. If not specified, a Temp file will be created.
    ///     If specified but the file does not exist, the file will be created. If it exists, it will first be deleted and all
    ///     contents will be lost.
    /// </param>
    /// <param name="commandTimeoutInSeconds">CommandTimeout to use with execution.</param>
    /// <returns>Returns the filename and path with the data in it.</returns>
    private static async Task<string> CallJsonQueryAndSaveToFile(SqlConnection connection, string commandTextForJsonQuery, SqlParameter[] parameters, string optionalFilePathAndName, int commandTimeoutInSeconds)
    {
        var needsToCloseConnection = false;
        optionalFilePathAndName = string.IsNullOrWhiteSpace(optionalFilePathAndName)
                                      ? Path.GetTempFileName()
                                      : optionalFilePathAndName;

        if (File.Exists(optionalFilePathAndName))
        {
            File.Delete(optionalFilePathAndName);
        }

        using (var file = File.AppendText(optionalFilePathAndName))
        {
            using (var command = new SqlCommand(commandTextForJsonQuery, connection)
                                 {
                                     CommandTimeout = commandTimeoutInSeconds,
                                     CommandType = CommandType.Text
                                 })
            {
                command.Parameters.AddRange(parameters);

                try
                {
                    if (connection.State != ConnectionState.Open)
                    {
                        needsToCloseConnection = true;
                        connection.Open();
                    }

                    using (var reader = command.ExecuteReader())
                    {
                        while (await reader.ReadAsync())
                        {
                            await file.WriteAsync(reader.GetString(0));
                        }
                    }
                }
                finally
                {
                    if (needsToCloseConnection)
                    {
                        connection.Close();
                    }
                }
            }
        }

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

An example of the commandTextForJsonQuery in my case:

```<code>var cmdText = "EXEC @procResult = [dbo].[spFoo] @Param1, @Param2, @Param3"
</code>```

This implementation seems to run much faster than I had expected. While I haven't heavily tested it when hosted in Azure, while testing it locally I'm able to saturate my 200mbps ISP connection, which is good enough for me. I don't need this to be perfectly optimized, just "optimized enough" so it doesn't take forever to execute.

Body:
While it may not be a perfect solution, this is the implementation I went with:

    /// <summary>
    ///     Calls a stored procedure that returns data as "FOR JSON AUTO" and stores the results into a temporary file.
    /// </summary>
    /// <param name="connection">SQLConnection to execute the stored procedure on.</param>
    /// <param name="commandTextForJsonQuery">CommandText for the execution.</param>
    /// <param name="parameters">All input and output parameters.</param>
    /// <param name="optionalFilePathAndName">
    ///     Optional file name and path to write to. If not specified, a Temp file will be created.
    ///     If specified but the file does not exist, the file will be created. If it exists, it will first be deleted and all
    ///     contents will be lost.
    /// </param>
    /// <param name="commandTimeoutInSeconds">CommandTimeout to use with execution.</param>
    /// <returns>Returns the filename and path with the data in it.</returns>
    private static async Task<string> CallJsonQueryAndSaveToFile(SqlConnection connection, string commandTextForJsonQuery, SqlParameter[] parameters, string optionalFilePathAndName, int commandTimeoutInSeconds)
    {
        var needsToCloseConnection = false;
        optionalFilePathAndName = string.IsNullOrWhiteSpace(optionalFilePathAndName)
                                      ? Path.GetTempFileName()
                                      : optionalFilePathAndName;

        if (File.Exists(optionalFilePathAndName))
        {
            File.Delete(optionalFilePathAndName);
        }

        using (var file = File.AppendText(optionalFilePathAndName))
        {
            using (var command = new SqlCommand(commandTextForJsonQuery, connection)
                                 {
                                     CommandTimeout = commandTimeoutInSeconds,
                                     CommandType = CommandType.Text
                                 })
            {
                command.Parameters.AddRange(parameters);

                try
                {
                    if (connection.State != ConnectionState.Open)
                    {
                        needsToCloseConnection = true;
                        connection.Open();
                    }

                    using (var reader = command.ExecuteReader())
                    {
                        while (await reader.ReadAsync())
                        {
                            await file.WriteAsync(reader.GetString(0));
                        }
                    }
                }
                finally
                {
                    if (needsToCloseConnection)
                    {
                        connection.Close();
                    }
                }
            }
        }

        return optionalFilePathAndName;
    }
}

An example of the commandTextForJsonQuery in my case:

var cmdText = "EXEC @procResult = [dbo].[spFoo] @Param1, @Param2, @Param3"

This implementation seems to run much faster than I had expected. While I haven't heavily tested it when hosted in Azure, while testing it locally I'm able to saturate my 200mbps ISP connection, which is good enough for me. I don't need this to be perfectly optimized, just "optimized enough" so it doesn't take forever to execute.


问:
Renaming files from a list using a shell script
I would like to rename files from a list. This is the file format:

Original name

New name

```<code>000000000000402a.ogg
Dth_BrkNck_FOD_MALE_MALE_001
000000000000402c.ogg
Dth_BrkNck_FOD_MALE_MALE_002
000000000000402e.ogg
Dth_BrkNck_FOD_MALE_MALE_003
0000000000004030.ogg
Dth_BrkNck_FOD_MALE_MALE_004
</code>```

I'm kinda new to shell scripts, so any help will be appreciated. Thank you.

答:
Seems like there is not direct connection b/w Original file name and New file name, To rename a file,

mv OriginalName NewName

one way is to repeat the step for multiple files, ( we can create all commands in a notepad and paste it altogether)
or we can put it in a shell script , say renamer.sh as below and execute it,

```<code>cat renamer.sh
mv 000000000000402a.ogg Dth_BrkNck_FOD_MALE_MALE_001
mv 000000000000402c.ogg Dth_BrkNck_FOD_MALE_MALE_002
mv 000000000000402e.ogg Dth_BrkNck_FOD_MALE_MALE_003
mv 0000000000004030.ogg Dth_BrkNck_FOD_MALE_MALE_004
</code>```

to execute :- sh renamer.sh

Body:
I would like to rename files from a list. This is the file format:

Original name

New name

000000000000402a.ogg
Dth_BrkNck_FOD_MALE_MALE_001
000000000000402c.ogg
Dth_BrkNck_FOD_MALE_MALE_002
000000000000402e.ogg
Dth_BrkNck_FOD_MALE_MALE_003
0000000000004030.ogg
Dth_BrkNck_FOD_MALE_MALE_004

I'm kinda new to shell scripts, so any help will be appreciated. Thank you.

Body:
Seems like there is not direct connection b/w Original file name and New file name, To rename a file,

mv OriginalName NewName

one way is to repeat the step for multiple files, ( we can create all commands in a notepad and paste it altogether)
or we can put it in a shell script , say renamer.sh as below and execute it,

cat renamer.sh
mv 000000000000402a.ogg Dth_BrkNck_FOD_MALE_MALE_001
mv 000000000000402c.ogg Dth_BrkNck_FOD_MALE_MALE_002
mv 000000000000402e.ogg Dth_BrkNck_FOD_MALE_MALE_003
mv 0000000000004030.ogg Dth_BrkNck_FOD_MALE_MALE_004

to execute :- sh renamer.sh


问:
How to get the load time of a web page using chrome console window and console commands?
How can I get the load time of a web page in Chrome's JavaScript console?

I openede google.com and tried the following commands: console.time, console.loadTime. Is there a specific command which I can use to obtain the full load time of a given page?

答: Go to the Performance tab in the developer tools and click on the refresh icon in the performance tab.</p>


问:
Android: saving application state when going to the "background"
I have a complex Android app with a decent amount of application state that needs to be persisted (in a specific format). Writing out the data is not an instantaneous operation and so it would be ideal to minimize persisting it unnecessarily.

Because of the persistence overhead it is not practical to persist the state every time it is changed. Ideally, persisting state would be triggered when the app is "backgrounded" by the user tapping the 'home' button or tapping the 'back' button on the app's root Activity (or by an incoming call, etc.). This minimizes persistence overhead while maintaining state consistency from the user's perspective. The question is how can you detect if the app is being "backgrounded"?

The Activity lifecycle calls (onStart, onResume, onPause and friends) don't help as the app has many different activities, any one of which could be active when the user taps 'home'. Furthermore, the calls get called when Activities get pushed, popped (and bottom killed) on the Activity stack and so they don't reflect if the app is going away or not.

So how does an app detect when it is going to the background?

答:
The Activity lifecycle calls (onStart, onResume, onPause and friends) don't help as the app has many different activities

Your activities should be independent enough that you shouldn't need to know when your entire application is in the background. It sounds like you have other design issues that we can't help you with without more specifics.


问:
Changing visibility of java 8 default method
I have a class (Say FOO) and it has a method with default visibility,
like below :

```<code>void sayHi() {}
</code>```

Now, If a override this method in extending class I cannot decrease it's visibility. So I can only use default or public.

```<code>public class MyClassTest extends FOO {
    @Override
    // Or I can use public void sayHi()
    void sayHi() {
        System.out.println("Overriden sayHi");
    }
}
</code>```

Now if I write an Interface in Java 8 with a default method like below :

```<code>public interface InterfaceX {

    // Java-8 defalu method
    default String printName() {
        System.out.println("Interface1 default metod");
        return "Interface1 default metod";
    }
}
</code>```

Now, if I override this method in a class It should compile if a keep overridden method's visibility default.

```<code>public class Java8InterfaceTest implements InterfaceX{
    @Override
     void printHello() {
        System.out.println("Printing..!");
        Interface1.super.printName();
    }
 }
</code>```

It says

Cannot reduce the visibility of the inherited method from InterfaceX

I already know that every method in interface in public by default, but in the above example we are using default which I think is one of the access modifier in java.

I have following questions:

Is default in interface different from default visibility which is provide when no access modifier applied?

If it's different then how it's different?

答:
I think that if you write your interface as :

```<code>interface Test {
    default public void go() {

    }
}
</code>```

it would make sense. default methods are still public; nothing to do with "default" visibility.

Body:
I have a class (Say FOO) and it has a method with default visibility,
like below :

void sayHi() {}

Now, If a override this method in extending class I cannot decrease it's visibility. So I can only use default or public.

public class MyClassTest extends FOO {
    @Override
    // Or I can use public void sayHi()
    void sayHi() {
        System.out.println("Overriden sayHi");
    }
}

Now if I write an Interface in Java 8 with a default method like below :

public interface InterfaceX {

    // Java-8 defalu method
    default String printName() {
        System.out.println("Interface1 default metod");
        return "Interface1 default metod";
    }
}

Now, if I override this method in a class It should compile if a keep overridden method's visibility default.

public class Java8InterfaceTest implements InterfaceX{
    @Override
     void printHello() {
        System.out.println("Printing..!");
        Interface1.super.printName();
    }
 }

It says

Cannot reduce the visibility of the inherited method from InterfaceX

I already know that every method in interface in public by default, but in the above example we are using default which I think is one of the access modifier in java.

I have following questions:

Is default in interface different from default visibility which is provide when no access modifier applied?

If it's different then how it's different?

Body:
I think that if you write your interface as :

interface Test {
    default public void go() {

    }
}

it would make sense. default methods are still public; nothing to do with "default" visibility.


问:
Python/Flask Login form throws 500 error on IIS
Due to my restrictions at work, I have to rely on hosting my webapp on IIS 7.5.
I configured IIS to serve the application via wfastcgi.py.

The issue is, that a login form, throws an HTTP 500 error on IIS, when clicking on the login button. The site gets loaded without issue. Also, code works perfectly fine, when I am running it on the flask development server.

I have an extended version of the code, with access to a sqlite DB.
I was able to narrow down the issue to the login session creation part.
I am not sure, whether the issue is about the way how IIS handles POST and GET requests with wfastcgi.py, or something else.

Here's the simplified version of the code, which throws the same error:
UPDATE: Changed the view functions to the proper return redirect.

```<code>import wiw_ad_controller as parser
import sys
from flask import Flask, flash, render_template, redirect, url_for, request, session, abort
import os

app = Flask(__name__)

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():
    if not session.get('logged_in'):

        return render_template('login.html')
    else:
        return render_template('index.html')

@app.route('/login', methods=['POST'])
def login():
    if request.form['username'] == 'admin' and request.form['password'] == 'admin':
        session['logged_in'] = True
        flash("Login was successfull")
    else:
        flash("Wrong password!")
    return redirect(url_for('index'))

@app.route('/search', methods=['GET','POST'])
def lookup_data():
    if (session.get('logged_in')==True):
        if request.method == 'POST' or request.method == 'GET':

            if (request.form['gpn'] and request.form['gpn'].isdigit()):

                #code removed - not needed
                return render_template('fetched_data.html', user_wiw=user_wiw, user_ad=user_ad)
            else:
                flash('Wrong ID')
            return index()
    return redirect(url_for('index'))

@app.route("/logout")
def logout():
    session['logged_in'] = False
    return redirect(url_for('index'))

@app.errorhandler(500)
def internal_error(exception):
    app.logger.exception(exception)
    return render_template('500.html'), 500

@app.errorhandler(404)
def internal_error(exception):
    app.logger.exception(exception)
    return render_template('404.html'), 404

if __name__ == '__main__':
    app.secret_key=os.urandom(12)
    app.run(debug=True)
</code>```

答:
I had this same error but my app already had a secret key.

Alas! after two days of searching I used your function to display the traceback and I narrowed down to my problem.

The process executing the app did not have access to the database. This problem is related to configuration of iis. The identity of the application pool has to have access to the DB. U can change this identity as instructed here

For other problems anyone faces in iis using Flask I would recommend googling them with using the name asp.net not python  or flask eg:
Use: "IIS internal server error asp.net"
Instead of: "IIS internal server error flask"

Body:
Due to my restrictions at work, I have to rely on hosting my webapp on IIS 7.5.
I configured IIS to serve the application via wfastcgi.py.

The issue is, that a login form, throws an HTTP 500 error on IIS, when clicking on the login button. The site gets loaded without issue. Also, code works perfectly fine, when I am running it on the flask development server.

I have an extended version of the code, with access to a sqlite DB.
I was able to narrow down the issue to the login session creation part.
I am not sure, whether the issue is about the way how IIS handles POST and GET requests with wfastcgi.py, or something else.

Here's the simplified version of the code, which throws the same error:
UPDATE: Changed the view functions to the proper return redirect.

import wiw_ad_controller as parser
import sys
from flask import Flask, flash, render_template, redirect, url_for, request, session, abort
import os

app = Flask(__name__)

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():
    if not session.get('logged_in'):

        return render_template('login.html')
    else:
        return render_template('index.html')

@app.route('/login', methods=['POST'])
def login():
    if request.form['username'] == 'admin' and request.form['password'] == 'admin':
        session['logged_in'] = True
        flash("Login was successfull")
    else:
        flash("Wrong password!")
    return redirect(url_for('index'))

@app.route('/search', methods=['GET','POST'])
def lookup_data():
    if (session.get('logged_in')==True):
        if request.method == 'POST' or request.method == 'GET':

            if (request.form['gpn'] and request.form['gpn'].isdigit()):

                #code removed - not needed
                return render_template('fetched_data.html', user_wiw=user_wiw, user_ad=user_ad)
            else:
                flash('Wrong ID')
            return index()
    return redirect(url_for('index'))

@app.route("/logout")
def logout():
    session['logged_in'] = False
    return redirect(url_for('index'))

@app.errorhandler(500)
def internal_error(exception):
    app.logger.exception(exception)
    return render_template('500.html'), 500

@app.errorhandler(404)
def internal_error(exception):
    app.logger.exception(exception)
    return render_template('404.html'), 404

if __name__ == '__main__':
    app.secret_key=os.urandom(12)
    app.run(debug=True)


问:
Excel - Search for string in list
So let's say we have a list of sentences in the cells of column A that may or may not contain names.

```<code>A1: "The sea was blue"
A2: "together with Mary"
A3: "onward and upward" and so on...
</code>```

I want to be able to check if a certain name exist within the entire list with True / False. For example, if I checked Mary it would return True. Joe would return False.

I've tried a few things, but they only seem to work if the name is the only thing in the cell. I want it to be able to search sentences in the list of cells, I'm just not sure how to proceed.

Much appreciated!

答:
If cell B1 holds value being searched i.e. Mary or Joe and A1:A3 holds list then following formula will give desired results.

=IF(ISNA(LOOKUP(2^15,SEARCH(" "&B1&" "," "&A1:A3&" ",1))),FALSE,TRUE)

Or even following shall work if any substring match is fine:

=COUNTIF(A1:A3,"*"&B1&"*")>0

Title: Excel - Search for string in list

Body:
So let's say we have a list of sentences in the cells of column A that may or may not contain names.

A1: "The sea was blue"
A2: "together with Mary"
A3: "onward and upward" and so on...

I want to be able to check if a certain name exist within the entire list with True / False. For example, if I checked Mary it would return True. Joe would return False.

I've tried a few things, but they only seem to work if the name is the only thing in the cell. I want it to be able to search sentences in the list of cells, I'm just not sure how to proceed.

Much appreciated!


问:
Spark executor is throwing error "java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver"
I am trying to import a table from my oracle database using spark and here I am using Scala to import the table.
My jdbc driver is ojdbc7.jar and it's added in both the parameter spark.driver.extraClassPath and spark.executor.extraClassPath in configuration file

spark.driver.extraClassPath      :/usr/lib/hadoop-lzo/lib/*:/usr/lib/hadoop/hadoop-aws.jar:/usr/share/aws/aws-java-sdk/*:/usr/share/aws/emr/emrfs/conf:/usr/s
hare/aws/emr/emrfs/lib/*:/usr/share/aws/emr/emrfs/auxlib/*:/usr/share/aws/emr/security/conf:/usr/share/aws/emr/security/lib/*:/home/hadoop/ojdbc7.jar
spark.driver.extraLibraryPath    /usr/lib/hadoop/lib/native:/usr/lib/hadoop-lzo/lib/native
spark.executor.extraClassPath    :/usr/lib/hadoop-lzo/lib/*:/usr/lib/hadoop/hadoop-aws.jar:/usr/share/aws/aws-java-sdk/*:/usr/share/aws/emr/emrfs/conf:/usr/s
hare/aws/emr/emrfs/lib/*:/usr/share/aws/emr/emrfs/auxlib/*:/usr/share/aws/emr/security/conf:/usr/share/aws/emr/security/lib/*:/home/hadoop/ojdbc7.jar
spark.executor.extraLibraryPath  /usr/lib/hadoop/lib/native:/usr/lib/hadoop-lzo/lib/native

I can successfully import the table. I can print the schema of the table. But while performing any operations like Count,show() it throws below error

`

Caused by: java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver
  at java.lang.ClassLoader.findClass(ClassLoader.java:530)   at
  org.apache.spark.util.ParentClassLoader.findClass(ParentClassLoader.scala:26)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)   at
  org.apache.spark.util.ParentClassLoader.loadClass(ParentClassLoader.scala:34)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)   at
  org.apache.spark.util.ParentClassLoader.loadClass(ParentClassLoader.scala:30)
  at
  org.apache.spark.repl.ExecutorClassLoader.findClass(ExecutorClassLoader.scala:77)
  ... 21 more

`

答: This error was because Spark was not able to locate the ojdbc7.jar from every core node. So placing this jar in a shared location like /usr/lib/spark/jars will resolve this issue. </p>


问:
Are there memset function implementations that fill the buffer in reverse order?
I know that there are implementations of memcpy, which copied memory in reverse order to optimize for some processors. At one time, a bug "Strange sound on mp3 flash website" was connected with that. Well, it was an interesting story, but my question is about another function.

I am wondering, there is a memset function in the world, which fills the buffer, starting from the end. It is clear that in theory nothing prevents doing such an implementation of a function. But I am interested exactly in the fact that this function was done in practice by someone somewhere. I would be especially grateful on the link on the library with such a function.

P.S. I understand that in terms of applications programming it has completely no difference whether the buffer is filled in the ascending or descending order. However, it is important for me to find out whether there was any "reverse" function implementation. I need it for writing an article.

答:
The Linux kernel's memset for the SuperH architecture has this property:

https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/sh/lib/memset.S?id=v4.14

Presumably it's done this way because the mov instruction exists in predecrement form (mov.l Rm,@-Rn) but not postincrement form. See:

http://shared-ptr.com/sh_insns.html

If you want something that's not technically kernel internals on a freestanding implementation, but an actual hosted C implementation that application code could get linked to, musl libc also has an example:

https://git.musl-libc.org/cgit/musl/tree/src/string/memset.c?id=v1.1.18

Here, the C version of memset (used on many but not all target archs) does not actually fill the whole buffer backwards, but rather starts from both the beginning and end in a manner that reduces the number of conditional branches and makes them all predictable for very small memsets. See the commit message where it was added for details:

https://git.musl-libc.org/cgit/musl/commit/src/string/memset.c?id=a543369e3b06a51eacd392c738fc10c5267a195f

Some of the arch-specific asm versions of memset also have this property:

https://git.musl-libc.org/cgit/musl/tree/src/string/x86_64/memset.s?id=v1.1.18