问:
Mixins for ES6 classes, transpiled with babel
According to various sources (2ality, esdiscuss) one should be able to add mixins to classes:

EDIT discovered that class methods are not enumerable so that cannot work. Edited the code below, but still no joy

```<code>class CartoonCharacter {
  constructor(author) {
    this.author = author;
  }

  drawnBy() {
    console.log("drawn by", this.author);
  }
}

// THIS CANNOT WORK
// class methods are not enumerable
// class Human {
//  haveFun() {
//    console.log("drinking beer");
//  }
// }

let Human = Object.create({}, {
  haveFun:   {
    enumerable: true,
    value: function () {
      console.log("drinking beer");
    }
  }
});

class Simpson extends Object.assign(CartoonCharacter, Human) {
  constructor(author) {
    super(author);
  }
}

let homer = new Simpson("Matt Groening");
homer.drawnBy();  // expected: drawn by Matt Groening
homer.haveFun();  // expected: drinking beer
</code>```

I get the "drawn by Matt Groening" but instead of the "drinking beer" I get an error

```<code>-> Uncaught TypeError: E.haveFun is not a function
</code>```

答:
As it has been discussed before by @mfeineis, @aadit-m-shah and @gotofritz as well as shown with the latest post from @ftor, one always needs to think carefully of witch class going to cripple into a "mixin" and than how to (re)assemble them into a hierarchy that still could be considered a good design. Such examples just show, that JavaScript might be in need for something that comes closer to traits than what we already (forced to) use instead. Something like ...

Applicable Objects/Types

that do not intermingle theirs syntax with that of classes,

because they are supposed to work exclusively at object/instance level, thus also from within (class) constructors and from within the (function) bodies of other applicable types, ...

therefore just being containers of both Trait and Object Composition Rules which exclusively will be executed at such a trait's/ApplicableType's apply time.

In order to prove such a concept in practice I did refactor all of the above examples into composition of trait from trait and into object composition from traits inside class constructors.

I would like discussing such an approach, its advantages and its shortcomings in comparison with all of the already accepted techniques that are in use today.

// - stateful applicable object/type proxy that does
//   link `this` context and injected local state.
//
const withExposeInternalStateProxy = Trait.create(function (use, applicator) {

  applicator(function (stateValue) {

    this.valueOf = function valueOf () {
      return Object.assign({}, stateValue);
    };
    this.toString = function toString () {
      return JSON.stringify(stateValue);
    };
  });
});

// - applicable object/type that just implements plain behavior.
// - also known as: function based mixin ... kind of "FLight Mixin reloaded".
//
const withHumanBehavior = Trait.create(function (use, applicator) {

  function allowWeekness() {
    return "allow weekness";
  }
  function showStrength() {
    return "show strength";
  }
  function thinkFirst() {
    return "think first";
  }
  function drinkingBeer() {
    return "drinking beer";
  }
  applicator(function () {

    this.allowWeekness = allowWeekness;
    this.showStrength = showStrength;
    this.thinkFirst = thinkFirst;
    this.drinkingBeer = drinkingBeer;
  });
});

// - composite trait that uses its trait composition language ... trait from trait(s).
//
const withStrongBeerDrinkingHabit = Trait.create(function (use, applicator) {

  use(withHumanBehavior)
    .apply(withHumanBehavior, "drinkingBeer").as("haveFun");

  //.apply.all.without("thinkFirst");
  //.apply(withHumanBehavior).without("thinkFirst");
});

// - trait that defines a specialized use case of another behavior.
//
const withDoAcceptAlreadyExistingDrinkingHabit = Trait.create(function (use, applicator) {
  applicator(function () {
    var
      type = this;

    if (typeof type.haveFun !== "function") {
      withStrongBeerDrinkingHabit.call(type);
    }
  });
});

class CartoonCharacter {

  constructor(stateValue) {

    // linking `this` context and injected local state.
    withExposeInternalStateProxy.call(this, stateValue);
  }
  drawnBy() {
    return ("drawn by " + this.valueOf().author);
  }
}

class MaleSimpsonsType extends CartoonCharacter {

  constructor(stateValue) {
    super(stateValue);

    // object/type composition
    //
    withDoAcceptAlreadyExistingDrinkingHabit.call(super.constructor.prototype);

    // withStrongBeerDrinkingHabit.call(super.constructor.prototype); // do not always apply.
    //
    // withStrongBeerDrinkingHabit.call(this); // nope ...prototype is the far better choice.
  }
  sayHey() {
    return ("Hey, I am " + this.valueOf().name);
  }
}

const homer = new MaleSimpsonsType({ name: "Homer Simpson", author: "Matt Groening" });

console.log("\n");
console.log('(homer + "") : ', (homer + ""));
console.log('homer.valueOf() : ', homer.valueOf());

console.log("\n");
console.log('homer.drawnBy() : ', homer.drawnBy());
console.log('homer.haveFun() : ', homer.haveFun());
console.log('homer.sayHey() : ', homer.sayHey());

console.log("\n");
console.log('Object.keys(homer) : ', Object.keys(homer));
console.log('homer.constructor : ', homer.constructor);
console.log('Object.keys(homer.constructor.prototype) : ', Object.keys(homer.constructor.prototype));
console.log('homer.constructor.prototype : ', homer.constructor.prototype);
console.log('(homer instanceof MaleSimpsonsType) : ', (homer instanceof MaleSimpsonsType));
console.log('(homer instanceof CartoonCharacter) : ', (homer instanceof CartoonCharacter));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100%!important; top: 0; }</code>```

```

For backing up the above example, there is another thread - Refactoring legacy mixin-based class hierarchies - where I also took the chance of refactoring the OP's given example. This one does feature after and around modification of plain object based behavior. The same approach/toolset that was used here, did meet there all of the OP's requirements. One now is able of working with classes, gets encapsulated state/data for free and also has stateful support for any kind of method modification.

Body:
According to various sources (2ality, esdiscuss) one should be able to add mixins to classes:

EDIT discovered that class methods are not enumerable so that cannot work. Edited the code below, but still no joy

class CartoonCharacter {
  constructor(author) {
    this.author = author;
  }

  drawnBy() {
    console.log("drawn by", this.author);
  }
}

// THIS CANNOT WORK
// class methods are not enumerable
// class Human {
//  haveFun() {
//    console.log("drinking beer");
//  }
// }

let Human = Object.create({}, {
  haveFun:   {
    enumerable: true,
    value: function () {
      console.log("drinking beer");
    }
  }
});

class Simpson extends Object.assign(CartoonCharacter, Human) {
  constructor(author) {
    super(author);
  }
}

let homer = new Simpson("Matt Groening");
homer.drawnBy();  // expected: drawn by Matt Groening
homer.haveFun();  // expected: drinking beer

I get the "drawn by Matt Groening" but instead of the "drinking beer" I get an error

-> Uncaught TypeError: E.haveFun is not a function

Body:
As it has been discussed before by @mfeineis, @aadit-m-shah and @gotofritz as well as shown with the latest post from @ftor, one always needs to think carefully of witch class going to cripple into a "mixin" and than how to (re)assemble them into a hierarchy that still could be considered a good design. Such examples just show, that JavaScript might be in need for something that comes closer to traits than what we already (forced to) use instead. Something like ...

Applicable Objects/Types

that do not intermingle theirs syntax with that of classes,

because they are supposed to work exclusively at object/instance level, thus also from within (class) constructors and from within the (function) bodies of other applicable types, ...

therefore just being containers of both Trait and Object Composition Rules which exclusively will be executed at such a trait's/ApplicableType's apply time.

In order to prove such a concept in practice I did refactor all of the above examples into composition of trait from trait and into object composition from traits inside class constructors.

I would like discussing such an approach, its advantages and its shortcomings in comparison with all of the already accepted techniques that are in use today.

// - stateful applicable object/type proxy that does
//   link `this` context and injected local state.
//
const withExposeInternalStateProxy = Trait.create(function (use, applicator) {

  applicator(function (stateValue) {

    this.valueOf = function valueOf () {
      return Object.assign({}, stateValue);
    };
    this.toString = function toString () {
      return JSON.stringify(stateValue);
    };
  });
});

// - applicable object/type that just implements plain behavior.
// - also known as: function based mixin ... kind of "FLight Mixin reloaded".
//
const withHumanBehavior = Trait.create(function (use, applicator) {

  function allowWeekness() {
    return "allow weekness";
  }
  function showStrength() {
    return "show strength";
  }
  function thinkFirst() {
    return "think first";
  }
  function drinkingBeer() {
    return "drinking beer";
  }
  applicator(function () {

    this.allowWeekness = allowWeekness;
    this.showStrength = showStrength;
    this.thinkFirst = thinkFirst;
    this.drinkingBeer = drinkingBeer;
  });
});

// - composite trait that uses its trait composition language ... trait from trait(s).
//
const withStrongBeerDrinkingHabit = Trait.create(function (use, applicator) {

  use(withHumanBehavior)
    .apply(withHumanBehavior, "drinkingBeer").as("haveFun");

  //.apply.all.without("thinkFirst");
  //.apply(withHumanBehavior).without("thinkFirst");
});

// - trait that defines a specialized use case of another behavior.
//
const withDoAcceptAlreadyExistingDrinkingHabit = Trait.create(function (use, applicator) {
  applicator(function () {
    var
      type = this;

    if (typeof type.haveFun !== "function") {
      withStrongBeerDrinkingHabit.call(type);
    }
  });
});

class CartoonCharacter {

  constructor(stateValue) {

    // linking `this` context and injected local state.
    withExposeInternalStateProxy.call(this, stateValue);
  }
  drawnBy() {
    return ("drawn by " + this.valueOf().author);
  }
}

class MaleSimpsonsType extends CartoonCharacter {

  constructor(stateValue) {
    super(stateValue);

    // object/type composition
    //
    withDoAcceptAlreadyExistingDrinkingHabit.call(super.constructor.prototype);

    // withStrongBeerDrinkingHabit.call(super.constructor.prototype); // do not always apply.
    //
    // withStrongBeerDrinkingHabit.call(this); // nope ...prototype is the far better choice.
  }
  sayHey() {
    return ("Hey, I am " + this.valueOf().name);
  }
}

const homer = new MaleSimpsonsType({ name: "Homer Simpson", author: "Matt Groening" });

console.log("\n");
console.log('(homer + "") : ', (homer + ""));
console.log('homer.valueOf() : ', homer.valueOf());

console.log("\n");
console.log('homer.drawnBy() : ', homer.drawnBy());
console.log('homer.haveFun() : ', homer.haveFun());
console.log('homer.sayHey() : ', homer.sayHey());

console.log("\n");
console.log('Object.keys(homer) : ', Object.keys(homer));
console.log('homer.constructor : ', homer.constructor);
console.log('Object.keys(homer.constructor.prototype) : ', Object.keys(homer.constructor.prototype));
console.log('homer.constructor.prototype : ', homer.constructor.prototype);
console.log('(homer instanceof MaleSimpsonsType) : ', (homer instanceof MaleSimpsonsType));
console.log('(homer instanceof CartoonCharacter) : ', (homer instanceof CartoonCharacter));

.as-console-wrapper { max-height: 100%!important; top: 0; }

<script>(function(r){function g(a){var c="none",b;Y(a)&&(ta(a)?c=ua:(b=Z(a),t("^class\\s+"+a.name+"\\s+\\{").test(b)?c=va:t("\\([^)]*\\)\\s+=>\\s+\\(").test(b)?c=wa:z(a)&&(c=xa(a)?ya:za(a)||Aa(a)||Ba(a)?Ca:aa)));return c===aa}function C(a){return["^\\[object\\s+",a,"\\]$"].join("")}function v(a,c){var b=Da[c];return!!b&&0<=b.indexOf(a)}function M(a,c,b){return function(){var d=arguments;c.apply(b,d);return a.apply(b,d)}}function N(a,c,b){return function(){var d=arguments,e=a.apply(b,d);c.apply(b,d);return e}}function Ea(a,c,b,d){return function(){var e=arguments;c.call(b,e,d);return a.apply(b,e)}}function Fa(a,c,b,d){return function(){var e=arguments,f=a.apply(b,e);c.call(b,e,d);return f}}function Ga(a,c,b,d){return function(){var e=arguments,f=a.apply(b,e);c.call(b,f,e,d);return f}}function Ha(a,c,b,d){return function(){var e=arguments,f;try{f=a.apply(b,e)}catch(l){c.call(b,l,e,d)}return f}}function Ia(a,c,b,d){return function(){var e=arguments,f,g;try{f=a.apply(b,e)}catch(m){g=m}c.call(b,g||f,e,d);return f}}function Ja(a,c,b,d){return function(){return c.call(b,a,c,arguments,d)}}function Ka(a,c){return function(){var b=this[a];g(b)||(b=u);this[a]=M(b,c,this)}}function La(a,c){return function(){var b=this[a];g(b)||(b=u);this[a]=N(b,c,this)}}function Ma(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ea(d,c,this,b)}}function Na(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Fa(d,c,this,b)}}function Oa(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ga(d,c,this,b)}}function Pa(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ha(d,c,this,b)}}function Qa(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ia(d,c,this,b)}}function Ra(a,c){return function(b){var d=this[a];g(d)||(d=u);this[a]=Ja(d,c,this,b)}}function ba(a,c,b){a.useTraits.rules.push(new A({type:"without",traitList:c,methodNameList:b}))}function ca(a,c,b,d){a.useTraits.rules.push(new A({type:"as",trait:c,methodName:b,methodAlias:d}))}function da(a){return ea(p(a)).reduce(function(a,b){q(b)&&a.push(F(b));return a},[])}function fa(){var a,c,b,d,e;if(O(this))if(d=this.valueOf(),e=d.parentLink,w(e))if(b=e.getSetup(),a=b.chainData,c=a.recentCalleeName,v(c,"without"))if(c=da(arguments),1<=c.length)a.recentCalleeName="without",ba(b,d.traitList,c);else throw new h("Not even a single <String> type was passed to 'without' as to be excluded method name.");else{a=["\u2026 invalid chaining of '",c,"().without()'"].join("");if("applyBehavior"==c)throw new n([a," in case of excluding one or more certain behaviors."].join(""));throw new n(a);}else throw new k("Please do not spoof the context of 'use'.");else throw new k("Please do not spoof the context of 'apply'.");return e}function P(a,c){var b=a.getSetup();if(Sa(c,a.valueOf().traitList))b.chainData.recentCalleeName="applyTraits",b=new Q({traitList:c,parentLink:a}),a.putChild(b);else throw new h("Any trait that got passed to 'apply' needs to be registered before via 'use'.");return b}function Sa(a,c){return a.every(function(a){return 0<=c.indexOf(a)})}function Ta(){var a;a=this.getSetup();var c=this.valueOf().traitList;I(this,a,a.chainData.recentCalleeName);a=P(this,c);return fa.apply(a,arguments)}function Ua(){var a=this.getSetup(),c=this.valueOf().traitList;I(this,a,a.chainData.recentCalleeName);return P(this,c)}function ga(){var a,c,b;b=p(arguments);if(w(this))if(a=this.getSetup(),c=a.chainData,c=c.recentCalleeName,I(this,a,c),a=["\u2026 invalid chaining of '",c,"().apply()'"].join(""),v(c,"apply"))if(x(b[0]))if(q(b[1]))if(v(c,"applyBehavior")){c=b[0];b=F(b[1]);a=this.getSetup();var d;if(0<=this.valueOf().traitList.indexOf(c))if(d={},c.call(d),g(d[b]))a.chainData.recentCalleeName="applyBehavior",b=new R({trait:c,methodName:b,parentLink:this}),this.putChild(b);else throw new k(["The requested '",b,"' method has not been implemented by the trait that got passed to 'apply'."].join(""));else throw new h("Any trait that got passed to 'apply' needs to be registered before via 'use'.");}else throw new n([a," in case of applying just a certain behavior."].join(""));else if(p(b).every(x))if(v(c,"applyTraits"))b=P(this,b);else throw new n([a," in case of applying from one or more traits."].join(""));else throw new h("'apply(\u2026)' excepts either, as its 2nd delimiting argument, just a 'String' type or exclusively one or more 'Trait' and 'Function' types.");else throw new h("'apply(<Trait|Function>, \u2026)' excepts as its 1st argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(a);else throw new k("'use(\u2026).apply(\u2026)' only works within a validly chained context, please do not try spoofing the latter.");return b}function ha(){var a;a=this;if(O(a)||G(a))a=a.valueOf(),a=a.parentLink,a=ga.apply(a,arguments);else throw new k("Please do not spoof the context of 'apply'.");return a}function I(a,c,b){var d,e;a&&!c.chainData.isTerminated&&(d=a.getChild())&&(e=d.valueOf())&&("applyTraits"==b&&O(d)?ba(c,e.traitList,[]):"applyBehavior"==b&&G(d)&&(a=e.methodName,ca(c,e.trait,a,a)));c.chainData.recentCalleeName="apply"}function R(a){this.valueOf=function(){return{trait:a.trait,methodName:a.methodName,parentLink:a.parentLink}};this.toString=function(){return["ApplyLink::singleBehavior :: ",S.stringify(a)].join("")};return this}function G(a){var c;return null!=a&&(a instanceof R||g(a.as)&&g(a.after)&&g(a.before)&&g(a.valueOf)&&(c=a.valueOf())&&x(c.trait)&&q(c.methodName)&&w(c.parentLink))}function Q(a){this.valueOf=function(){return{traitList:a.traitList,parentLink:a.parentLink}};this.toString=function(){return["ApplyLink::fromTraits :: ",S.stringify(a)].join("")};return this}function O(a){var c;return null!=a&&(a instanceof Q||g(a.without)&&g(a.valueOf)&&(c=a.valueOf())&&T(c.traitList)&&w(c.parentLink))}function U(a,c){var b=null;this.getSetup=function(){return c};this.deleteChild=function(){b=null};this.putChild=function(a){b=a};this.getChild=function(){return b};this.valueOf=function(){return{traitList:p(a.traitList)}};this.toString=function(){return["UseRoot :: ",S.stringify(a)].join("")};this.apply=ga.bind(this);this.apply.all=Ua.bind(this);this.apply.all.without=Ta.bind(this);return this}function w(a){var c;return null!=a&&(a instanceof U||g(a.apply)&&g(a.valueOf)&&g(a.getSetup)&&(c=a.valueOf())&&T(c.traitList)&&(c=a.getSetup())&&ia(c))}function Va(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Ka(a,c));else throw new h("'before(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'before(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function Wa(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Ma(a,c));else throw new h("'before.stateful(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'before.stateful(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function Xa(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(La(a,c));else throw new h("'after(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'after(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function Ya(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Na(a,c));else throw new h("'after.stateful(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'after.stateful(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function Za(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Oa(a,c));else throw new h("'afterReturning(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'afterReturning(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function $a(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Pa(a,c));else throw new h("'afterThrowing(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'afterThrowing(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function ab(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Qa(a,c));else throw new h("'afterFinally(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'afterFinally(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function bb(a,c){var b=this.applicator,d=b.root,e=b.modifiers;b.canRequire=!1;if(q(a))if(g(c))e.push(Ra(a,c));else throw new h("'around(\u2026, <Function>)' excepts as its 2nd argument just a 'Function' type.");else throw new h("'around(<String>, \u2026)' excepts as its 1st argument just a 'String' type.");return d}function cb(){var a=this.applicator,c=a.root,b=a.didRequire;if(a.canRequire)if(a.canRequire=!1,a.didRequire=!0,b=da(arguments),1<=b.length)a.requires=b;else throw new h("Not even a single <String> type was passed to 'requires' as method name that a trait, at its apply time, expects to be present at least.");else{if(b)throw new n("'requires' can be invoked exactly once, right after having executed a trait's 'applicator' method.");throw new n("'requires' can not bee invoked after a modifier method, but has to be the direct follower of a trait's 'applicator' method.");}return c}function db(a){I(this.useTraits.root,this,this.chainData.recentCalleeName);this.chainData.isTerminated=!0;var c=this.applicator,b=this.useTraits.rules,d=0>=b.length;if(!d&&!ja(b))throw new k("The trait composition language's rule set does not result in applicable behavior. This happens e.g. if all behavior has been deleted via 'without'.");if(null!=a)if(g(a=F(a)))c.body=a,a.call(c.proxy);else throw new h("The applicator should either stay empty or receive a sole applicable type like a 'Trait' or a 'Function' type.");else d&&0>=c.modifiers.length&&D.warn("The trait descriptor till now did neither receive an applicable function via the 'applicator' method nor any composition rule via 'use(\u2026).apply(\u2026)' nor any method modifier.");return c.root}function eb(){var a;a=ea(p(arguments)).filter(function(a){return x(a)});if(1<=a.length)a=new U({traitList:a},this);else throw new h("Not even a single valid 'Trait' or 'Function' type has been provided to 'use(<Trait|Function>[, \u2026])'.");return this.useTraits.root=a}function y(a,c){return a.findIndex(function(a){return a.trait===c})}function ka(a){return{type:a.type,trait:a.trait,methodName:a.methodName}}function la(a){return{type:a.type,trait:a.trait,fromTrait:a.fromTrait,methodName:a.methodName}}function A(a){this.valueOf=function(){return fb[a.type](a)}}function ja(a){var c=!0;if(1<=a.length){var b={},c=ma(a),d=na(c);d.forEach(function(a){a.trait.call(a.proxy)});a.forEach(function(a){a.execute(b,d)});c=1<=J(b).length}return c}function gb(a,c,b){var d;if(b[0]!==oa&&(d=c.reduce(function(b,c){g(a[c])||b.push(c);return b},[]),1<=d.length))throw new h("The type misses following required method(s) \u2026 '"+d.join("', '")+"'.");return d}function hb(a,c,b){a.forEach(function(a){a.call(c,b)})}function ib(a){this.call=function(){var c=p(arguments),b;b=c.shift();b=null!=b&&b||null;a.apply(b,c);return b};this.apply=function(c,b){null==b&&(b=[]);c=null!=c&&c||null;a.apply(c,b);return c};return this}function jb(a){this.requires=function(){return p(a)};return this}function kb(a){var c=[],b={};a.call(b,oa);c=J(b).sort(function(a,b){return a<b&&-1||a>b&&1||0});b=null;this.keys=function(){return p(c)};return this}function pa(a,c){this.toString=function(){return"[object Trait]"};this.valueOf=function(){return a};ib.call(this,a);jb.call(this,c);kb.call(this,a);return this}function qa(a){var c;if(c=!!a)(c=a instanceof pa)||(c="object"==typeof a&&g(a.call)&&g(a.apply)&&g(a.valueOf)&&g(a.valueOf()));return c}function x(a){return qa(a)||g(a)}function ma(a){return a.reduce(function(a,b){var c=b.valueOf(),e=c.trait,f=c.fromTrait;e&&0>a.indexOf(e)&&a.push(e);f&&0>a.indexOf(f)&&a.push(f);(c.traitList||[]).forEach(function(b){0>a.indexOf(b)&&a.push(b)});return a},[])}function na(a){return a.map(function(a){return{trait:a,proxy:{}}})}function lb(a,c,b,d){var e=[],f={};if(!(0>=c.length||ja(c)))throw new k("The trait composition language's rule set does not result in applicable behavior. This happens e.g. if all behavior has been deleted via 'without'.");g(b)&&(b.call(f),e=J(f));return[a,c,e,d].some(function(a){return 1<=a.length})}function mb(a){var c,b=a.useTraits.rules,d=a.applicator;a=d.body;var e=d.requires,d=d.modifiers,f=ma(b);lb(f,b,a,d)&&(d=function(a,b,c,d,e){return function(){var f=this,h=p(arguments),l=na(a);l.forEach(function(a){a.trait.apply(a.proxy,h)});b.forEach(function(a){a.execute(f,l)});gb(f,c,h);g(d)&&d.apply(f,h);hb(e,f,h);return f}}(f,b,e,a,d),c=new pa(d,e));return c}var V=r.Function,H=r.Object,B=r.Array,t=r.RegExp,S=r.JSON,h=r.TypeError,k=r.ReferenceError,n=r.SyntaxError,nb=V.prototype,K=H.prototype,ra=U.prototype,sa=Q.prototype,L=R.prototype,oa={},aa="applicable-function",ya="buildin-constructor",va="class-constructor",wa="arrow-function",ua="generator-function",Ca="interface-type",Da={without:["apply","applyTraits"],as:["apply","applyBehavior"],after:["apply","applyBehavior","after","before"],before:["apply","applyBehavior","after","before"],apply:"apply applyBehavior applyTraits without as after before use".split(" "),applyTraits:"apply applyBehavior applyTraits without as after before use".split(" "),applyBehavior:"apply applyBehavior applyTraits without as after before use".split(" ")},fb={beforeWrap:ka,afterWrap:ka,beforeApply:la,afterApply:la,without:function(a){return{type:a.type,traitList:p(a.traitList),methodNameList:p(a.methodNameList)}},as:function(a){return{type:a.type,trait:a.trait,methodName:a.methodName,methodAlias:a.methodAlias}}},ob={beforeWrap:function(a,c,b){var d=y(b,a.trait);b=b[d];a=a.methodName;c[a]=M((b&&b.proxy||{})[a],c[a],c)},afterWrap:function(a,c,b){var d=y(b,a.trait);b=b[d];a=a.methodName;c[a]=N((b&&b.proxy||{})[a],c[a],c)},beforeApply:function(a,c,b){var d=y(b,a.trait),e=y(b,a.fromTrait),d=b[d],e=b[e];b=d&&d.proxy||{};e=e&&e.proxy||{};a=a.methodName;a in c&&delete c.methodName;c[a]=M(b[a],e[a],c)},afterApply:function(a,c,b){var d=y(b,a.trait),e=y(b,a.fromTrait),d=b[d],e=b[e];b=d&&d.proxy||{};e=e&&e.proxy||{};a=a.methodName;a in c&&delete c.methodName;c[a]=N(b[a],e[a],c)},without:function(a,c,b){var d=a.traitList,e=a.methodNameList.reduce(function(a,b){a[b]=null;return a},{});d.forEach(function(a){a=y(b,a);var d=(a=b[a])&&a.proxy||{};J(d).forEach(function(a){a in e||(a in c&&delete c.methodName,c[a]=function(a,b){return function(){return a.apply(b,arguments)}}(d[a],c))})});a=b=d=e=null},as:function(a,c,b){var d=y(b,a.trait);b=(b=b[d])&&b.proxy||{};d=a.methodAlias;a=a.methodName;d in c&&delete c.methodAlias;c[d]=function(a,b){return function(){return a.apply(b,arguments)}}(b[a],c);a=b=d=b=b=d=a=null}},F=function(a,c){return function(b){return b==c?b:a.call(b).valueOf()}}(K.valueOf,null),E=function(a){return function(c){return a.call(c)}}(K.toString),Z=function(a){return function(c){return a.call(c)}}(nb.toString),pb=function(a){try{a.call(null,"length"),a=function(a,b){return function(c,e){return c!=b&&a.call(c,e)}}(a,null)}catch(c){a=function(a,c){return function(b,d){var e=b!=c;if(e)try{e=a.call(b,d)}catch(m){e=!0}return e}}(a,null)}return a}(K.propertyIsEnumerable),Y=function(a){return function(c){return typeof c==a}}(typeof V),z=function(a){return function(c){return Y(c)&&typeof c.call==a&&typeof c.apply==a}}(typeof V),qb=function(a){return function(c){return t(a).test(E(c))}}(C("Function")),ia=function(a){return function(c){return t(a).test(E(c))}}(C("Object")),rb=z(H.getPrototypeOf)&&H.getPrototypeOf||function(a){var c=a&&a.__proto__;return c||null===c?c:qb(a.constructor)?a.constructor.prototype:a instanceof H?K:null},W=function(a){return function(c){return(c=t(a).exec(Z(c)))&&c[1]}}("^function\\s+([^(]+)\\("),xa=function(a){return function(c){return t(a).test(W(c))}}("^(?:Array|ArrayBuffer|AsyncFunction|Atomics|Boolean|DataView|Date|Error|EvalError|Float32Array|Float64Array|Function|Generator|GeneratorFunction|Int16Array|Int32Array|Int8Array|InternalError|Collator|DateTimeFormat|NumberFormat|Iterator|Map|Number|Object|Promise|Proxy|RangeError|ReferenceError|RegExp|Bool16x8|Bool32x4|Bool64x2|Bool8x16|Float32x4|Float64x2|Int16x8|Int32x4|Int8x16|Uint16x8|Uint32x4|Uint8x16|Set|SharedArrayBuffer|StopIteration|String|Symbol|SyntaxError|TypeError|TypedArray|URIError|Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|WeakMap|WeakSet)$"),X=function(a,c){var b=t(c);return b.test(W(a))||b.test(W(rb(a)))},za=function(a){return function(c){return X(c,a)}}("^(?:Node|CharacterData|Event|DOMError|DOMException|DOMImplementation|DOMStringList|DOMTokenList|EventTarget|HTMLCollection|MutationObserver|MutationRecord|NodeFilter|NodeIterator|NodeList|Range|TreeWalker|URL|Document)$"),Aa=function(a){return function(c){return X(c,a)}}("^(?:HTMLElement|HTMLMediaElement|Element)$"),Ba=function(a){return function(c){return X(c,a)}}("^(?:CanvasRenderingContext2D|CanvasGradient|CanvasPattern|TextMetrics|ImageData|DOMStringMap|MediaError|HTMLCollection|NodeList)$"),ta=function(a){return function(c){return t(a).test(E(c))}}(C("GeneratorFunction")),q=function(a){return function(c){return t(a).test(E(c))}}(C("String")),T=z(B.isArray)&&B.isArray||function(a){return function(c){return t(a).test(E(c))}}(C("Array")),sb=z(B.isArguments)&&B.isArguments||function(a,c){var b=function(b){return t(a).test(E(b))};b(arguments)||(b=function(a){return ia(a)&&"number"==typeof a.length&&c(a.length)&&!pb(a,"length")});return b}(C("Arguments"),r.Number.isFinite),p=z(B.from)&&B.from||function(a){return function(c){return a.call(c)}}(B.prototype.slice),ea=function c(b){b=sb(b)&&p(b)||b;T(b)&&(b=b.reduce(function(b,e){return b.concat(c(e))},[]));return b},J=H.keys,u=function(){},D;D=(D=r.console)&&z(D.warn)&&z(D.log)&&D||{warn:u,log:u};L.as=function(c){var b,d,e,f,g;if(G(this))if(f=this.valueOf(),g=f.parentLink,w(g))if(e=g.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"as"))if(q(c=F(c)))if(b=f.trait,f=f.methodName,f!==c)d.recentCalleeName="as",ca(e,b,f,c);else throw new h("Using identical method names in case of aliasing is considered to be a rule violating contradiction.");else throw new h("'as(<String>)' excepts as its sole argument just a 'String' type.");else{c=["\u2026 invalid chaining of '",b,"().as()'"].join("");if("applyTraits"==b)throw new n([c," in case of aliasing just a certain behavior."].join(""));throw new n(c);}else throw new k("Please do not spoof the context of 'use'.");else throw new k("Please do not spoof the context of 'apply'.");return g};L.after=function(c){var b,d,e,f,l,m;if(G(this))if(f=this.valueOf(),m=f.parentLink,w(m))if(e=m.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"after"))if(x(c))if(b=m.valueOf(),b=b.traitList,0<=b.indexOf(c))if(b=f.trait,b!==c)if(l=f.methodName,f={},c.call(f),g(f[l]))d.recentCalleeName="after",e.useTraits.rules.push(new A({type:"afterApply",trait:c,fromTrait:b,methodName:l}));else throw new k(["Please consider applying '",l,"' directly. This expected behavior has not been implemented by the trait that got passed to 'after'."].join(""));else throw new k("Passing identical trait references to both 'apply' and 'after' is a contradiction that violates the composition rules.");else throw new h("Any trait passed to 'after' has to be registered before via 'use'.");else throw new h("'after(<Trait|Function>)' excepts as its sole argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(["\u2026 invalid chaining of '",b,"().after()'"].join(""));else throw new k("Please do not spoof the context of 'use'.");else throw new k("Please do not spoof the context of 'apply'.");return m};L.before=function(c){var b,d,e,f,l,m;if(G(this))if(f=this.valueOf(),m=f.parentLink,w(m))if(e=m.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"before"))if(x(c))if(b=m.valueOf(),b=b.traitList,0<=b.indexOf(c))if(b=f.trait,b!==c)if(l=f.methodName,f={},c.call(f),g(f[l]))d.recentCalleeName="before",e.useTraits.rules.push(new A({type:"beforeApply",trait:c,fromTrait:b,methodName:l}));else throw new k(["Please consider applying '",l,"' directly. This expected behavior has not been implemented by the trait that got passed to 'before'."].join(""));else throw new k("Passing identical trait references to both 'apply' and 'before' is a contradiction that violates the composition rules.");else throw new h("Any trait passed to 'before' has to be registered before via 'use'.");else throw new h("'before(<Trait|Function>)' excepts as its sole argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(["\u2026 invalid chaining of '",b,"().before()'"].join(""));else throw new k("Please do not spoof the context of 'use'.");else throw new k("Please do not spoof the context of 'apply'.");return m};L.apply=ha;sa.without=fa;sa.apply=ha;ra.after=function(c){var b,d,e,f;if(w(this))if(e=this.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"after"))if(x(c))if(b=this.valueOf(),b=b.traitList,0<=b.indexOf(c))if(b=this.getChild(),f=b.valueOf(),b=f.trait,b!==c)if(f=f.methodName,b={},c.call(b),g(b[f]))d.recentCalleeName="after",e.useTraits.rules.push(new A({type:"afterWrap",trait:c,methodName:f}));else throw new k(["Please consider applying '",f,"' directly. This expected behavior has not been implemented by the trait that got passed to 'after'."].join(""));else throw new k("Passing identical trait references to both 'apply' and 'after' is a contradiction that violates the composition rules.");else throw new h("Any trait passed to 'after' has to be registered before via 'use'.");else throw new h("'after(<Trait|Function>)' excepts as its sole argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(["\u2026 invalid chaining of '",b,"().after()'"].join(""));else throw new k("Please do not spoof the context of 'use'.");return this};ra.before=function(c){var b,d,e,f;if(w(this))if(e=this.getSetup(),d=e.chainData,b=d.recentCalleeName,v(b,"before"))if(x(c))if(b=this.valueOf(),b=b.traitList,0<=b.indexOf(c))if(b=this.getChild(),f=b.valueOf(),b=f.trait,b!==c)if(f=f.methodName,b={},c.call(b),g(b[f]))d.recentCalleeName="before",e.useTraits.rules.push(new A({type:"beforeWrap",trait:c,methodName:f}));else throw new k(["Please consider applying '",f,"' directly. This expected behavior has not been implemented by the trait that got passed to 'before'."].join(""));else throw new k("Passing identical trait references to both 'apply' and 'before' is a contradiction that violates the composition rules.");else throw new h("Any trait passed to 'before' has to be registered before via 'use'.");else throw new h("'before(<Trait|Function>)' excepts as its sole argument explicitly either a 'Trait' or a 'Function' type.");else throw new n(["\u2026 invalid chaining of '",b,"().before()'"].join(""));else throw new k("Please do not spoof the context of 'use'.");return this};A.prototype.execute=function(c,b){var d=this.valueOf();ob[d.type](d,c,b)};return r.Trait={create:function(c){var b,d,e;g(c=F(c))&&(e={chainData:{isTerminated:!1,recentCalleeName:"use"},useTraits:{root:null,rules:[]},applicator:{body:null,proxy:{},root:{},modifiers:[],requires:[],canRequire:!0,didRequire:!1}},b=e.applicator.root,b.requires=cb.bind(e),b.before=Va.bind(e),b.after=Xa.bind(e),b.before.stateful=Wa.bind(e),b.after.stateful=Ya.bind(e),b.afterReturning=Za.bind(e),b.afterThrowing=$a.bind(e),b.afterFinally=ab.bind(e),b.around=bb.bind(e),b=eb.bind(e),d=db.bind(e),c(b,d),e=mb(e));return e},isTrait:qa,isApplicable:x}})(Function("return this")());</script>

For backing up the above example, there is another thread - Refactoring legacy mixin-based class hierarchies - where I also took the chance of refactoring the OP's given example. This one does feature after and around modification of plain object based behavior. The same approach/toolset that was used here, did meet there all of the OP's requirements. One now is able of working with classes, gets encapsulated state/data for free and also has stateful support for any kind of method modification.


来源: stackexchange

问:
Detecting cycles in a graph
I want it to return true if there is a cycle and false if there is not. It works if there is only one edge per node...

eg:

```<code>walkways_info = """\
U 3
0 1
1 2
2 0
"""'

print(interesting_path_feasible(walkways_info))
</code>```

But it doesn't work when there are multiple edges per node as the dictionary doesn't hold multiple values.

eg:

```<code>walkways_info = """\
U 7
1 2
1 5
1 6
2 3
2 5
3 4
4 5
"""
</code>```

How would I fix this?
Thanks in advance :)

```<code>def interesting_path_feasible(walkways_info_str):
    """Determines if a cycle exists"""
    graph_dict = dict(e.split(' ') for e in walkways_info_str.splitlines())
    visited = set()
    path = [object()]
    path_set = set(path)
    stack = [iter(graph_dict)]
    while stack:
        for node in stack[-1]:
            if node in path_set:
                return True
            elif node not in visited:
                visited.add(node)
                path.append(node)
                path_set.add(node)
                stack.append(iter(graph_dict.get(node, ())))
                break
        else:
            path_set.remove(path.pop())
            stack.pop()
    return False
</code>```

答:
Make the value a list, e.g.

```<code>a["abc"] = [1, 2, "bob"]
</code>```

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

```<code>key = "somekey"
a.setdefault(key, [])
a[key].append(1)
</code>```

Results:

```<code>a {'somekey': [1]}
</code>```

Next, try:

```<code>key = "somekey"
a.setdefault(key, [])
a[key].append(2)
</code>```

Results:

```<code>a {'somekey': [1, 2]}
</code>```

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

```<code>a.setdefault("somekey",[]).append("bob")
</code>```

Results:

```<code>a {'somekey': [1, 2, 'bob']}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Detecting cycles in a graph

Body:
I want it to return true if there is a cycle and false if there is not. It works if there is only one edge per node...

eg:

walkways_info = """\
U 3
0 1
1 2
2 0
"""'

print(interesting_path_feasible(walkways_info))

But it doesn't work when there are multiple edges per node as the dictionary doesn't hold multiple values.

eg:

walkways_info = """\
U 7
1 2
1 5
1 6
2 3
2 5
3 4
4 5
"""

How would I fix this?
Thanks in advance :)

def interesting_path_feasible(walkways_info_str):
    """Determines if a cycle exists"""
    graph_dict = dict(e.split(' ') for e in walkways_info_str.splitlines())
    visited = set()
    path = [object()]
    path_set = set(path)
    stack = [iter(graph_dict)]
    while stack:
        for node in stack[-1]:
            if node in path_set:
                return True
            elif node not in visited:
                visited.add(node)
                path.append(node)
                path_set.add(node)
                stack.append(iter(graph_dict.get(node, ())))
                break
        else:
            path_set.remove(path.pop())
            stack.pop()
    return False

Body:
Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

a {'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

a {'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

a {'somekey': [1, 2, 'bob']}


问:
string.empty and string.isnullorempty
I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox.

```<code>      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }
</code>```

but when I tried to use string,isnullorempty then I am not getting the seterror icon..
Can you guys plz tell me what is the proper way of using string.isnullorempty in this case..

答:
Can it be this is not realted to he string test?

ErrorProvider errorProvider = new
  ErrorProvider();

Hmpf. Seriously. The ErrorProvider should exist on the form. You are just creating one on teh fly (which turns invalid at the end of hthe method) and are not even hooking those up properly in the form.

The ErrorProvider should be put onto the form.

ContentLicense: CC BY-SA 2.5

Title: string.empty and string.isnullorempty

Body:
I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox.

      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }

but when I tried to use string,isnullorempty then I am not getting the seterror icon..
Can you guys plz tell me what is the proper way of using string.isnullorempty in this case..


问:
GC overhead limit exceeded while reading huge txt files
I have a 20GB folder which consist of 358 txt files and there are 733,019,372 lines total and all txt files format is below

```<code>77 clueweb12-0211wb-83-00000
88 clueweb12-0211wb-83-00001
82 clueweb12-0211wb-83-00002
82 clueweb12-0211wb-83-00003
64 clueweb12-0211wb-83-00004
80 clueweb12-0211wb-83-00005
83 clueweb12-0211wb-83-00006
75 clueweb12-0211wb-83-00007
</code>```

My purpose is while program is traversing all the txt file recursively reading files line by line,seperate into two parts each line(e.g 88 and clueweb12-0211wb-83-0003) and put these parts into a LinkedHashMap<String, List<String>>. Afther that, take docIds(clueweb12-0211wb-83-00006) from user as an argument and put the score belongs to this docIds(83).If a non-existing docID is encountered, -1 should be returned as a score.For example:

```<code>clueweb12-0003wb-22-11553,foo,clueweb12-0109wb-78-15059,bar,clueweb12-0302wb-50-22339
</code>```

should print out : 84,-1,19,-1,79

And i take the path to file from user as an argument.

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

import static java.nio.file.FileVisitResult.CONTINUE;

public class App extends SimpleFileVisitor<Path>{

    public LinkedHashMap<String, List<String>> list = new LinkedHashMap<>(); // Put there scores and docIds

    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes attr) throws IOException {

     File file =  new File(path.toString());
     BufferedReader br = new BufferedReader(new FileReader(file));
     String line;

    while((line = br.readLine()) != null){

        if(list.containsKey(line.split(" ")[0])){
            list.get(line.split(" ")[0]).add(line.split(" ")[1]);
        }
        else{
            list.put(line.split(" ")[0],new ArrayList(Arrays.asList(line.split(" ")[1])));
        }

    }
        return CONTINUE;
    }

    public static void main(String args[]) throws IOException {

        if (args.length < 2) {
            System.err.println("Usage: java App spamDir docIDs ...");
            return;
        }
        Path spamDir = Paths.get(args[0]);
        String[] docIDs = args[1].split(",");

        App ap = new App();
        Files.walkFileTree(spamDir, ap);
        ArrayList scores = new ArrayList(); // keep scores in that list

        //Search the Lists in LinkedHashMap
        for(int j=0; j<docIDs.length; j++){
            Set set = ap.list.entrySet();
            Iterator i = set.iterator();
            int counter = 0;
            while(i.hasNext()){

                // if LinkedHashMap has the docID add it to scores List
                Map.Entry me = (Map.Entry) i.next();
                ArrayList searchList = (ArrayList) me.getValue();
                if(searchList.contains(docIDs[j])){
                    scores.add(me.getKey());
                    counter++;
                    break;

                }
                else {

                    continue;
                }

            }
            // if LinkedHashMap has not the docId add -1 to scores List
            if(counter == 0){
                scores.add("-1");
            }

        }

        String joined = String.join("," , scores);
        System.out.println(joined);

    }
}
</code>```

But I encountered that problem :

```<code>Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at ceng.bim208.App.visitFile(App.java:35)
    at ceng.bim208.App.visitFile(App.java:18)
    at java.nio.file.Files.walkFileTree(Files.java:2670)
    at java.nio.file.Files.walkFileTree(Files.java:2742)
    at ceng.bim208.App.main(App.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

I tried to use XmX2048M to increase heap size but it doesn't solve my problem. What should i do?

In addition, if i run the program on a different path(include 2 txt file same format) it works correctly.

答:
The following does it the new way and corrects some faults.

```<code>public Map<String, List<String>> map = new HashMap<>();

@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attr)
        throws IOException {

    Files.lines(path).forEach(line -> {
        String[] keyValue = line.split(" ", 2);
        map.compute(keyValue[0],
             (key, oldList) -> {
                  List<String> list = oldList == null
                      ? new ArrayList<>()
                      : oldList;
                  list.add(keyValue[1]);
                  return list;
             });
    });
    return CONTINUE;
}
</code>```

A LinkedHashMap maintains the order of adding, which is needlessly costing memory.

The splitting should be done once.

The file should be closed. I use Files.lines which allows terse coding.

(Tip) The Charset (encoding) is not given, hence platform default. One might consider adding it as parameter.

The Map.compute comes in handy to decide on the old value (a List) whether to create a new one.

One might save on memory by not storing a List<String> but something like List<byte[]> with the bytes something like:

```<code>byte[] bytes = keyValue[1].getBytes(Charset.defaultCharset());
String s = new String(bytes, Charset.defaultCharset());
</code>```

Compared to a String for plain ASCII you'll save half the bytes (a char is two bytes).

Probably a database, like an embedded java Derby or H2 will do better.

Body:
I have a 20GB folder which consist of 358 txt files and there are 733,019,372 lines total and all txt files format is below

77 clueweb12-0211wb-83-00000
88 clueweb12-0211wb-83-00001
82 clueweb12-0211wb-83-00002
82 clueweb12-0211wb-83-00003
64 clueweb12-0211wb-83-00004
80 clueweb12-0211wb-83-00005
83 clueweb12-0211wb-83-00006
75 clueweb12-0211wb-83-00007

My purpose is while program is traversing all the txt file recursively reading files line by line,seperate into two parts each line(e.g 88 and clueweb12-0211wb-83-0003) and put these parts into a LinkedHashMap<String, List<String>>. Afther that, take docIds(clueweb12-0211wb-83-00006) from user as an argument and put the score belongs to this docIds(83).If a non-existing docID is encountered, -1 should be returned as a score.For example:

clueweb12-0003wb-22-11553,foo,clueweb12-0109wb-78-15059,bar,clueweb12-0302wb-50-22339

should print out : 84,-1,19,-1,79

And i take the path to file from user as an argument.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

import static java.nio.file.FileVisitResult.CONTINUE;

public class App extends SimpleFileVisitor<Path>{

    public LinkedHashMap<String, List<String>> list = new LinkedHashMap<>(); // Put there scores and docIds

    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes attr) throws IOException {

     File file =  new File(path.toString());
     BufferedReader br = new BufferedReader(new FileReader(file));
     String line;

    while((line = br.readLine()) != null){

        if(list.containsKey(line.split(" ")[0])){
            list.get(line.split(" ")[0]).add(line.split(" ")[1]);
        }
        else{
            list.put(line.split(" ")[0],new ArrayList(Arrays.asList(line.split(" ")[1])));
        }

    }
        return CONTINUE;
    }

    public static void main(String args[]) throws IOException {

        if (args.length < 2) {
            System.err.println("Usage: java App spamDir docIDs ...");
            return;
        }
        Path spamDir = Paths.get(args[0]);
        String[] docIDs = args[1].split(",");

        App ap = new App();
        Files.walkFileTree(spamDir, ap);
        ArrayList scores = new ArrayList(); // keep scores in that list

        //Search the Lists in LinkedHashMap
        for(int j=0; j<docIDs.length; j++){
            Set set = ap.list.entrySet();
            Iterator i = set.iterator();
            int counter = 0;
            while(i.hasNext()){

                // if LinkedHashMap has the docID add it to scores List
                Map.Entry me = (Map.Entry) i.next();
                ArrayList searchList = (ArrayList) me.getValue();
                if(searchList.contains(docIDs[j])){
                    scores.add(me.getKey());
                    counter++;
                    break;

                }
                else {

                    continue;
                }

            }
            // if LinkedHashMap has not the docId add -1 to scores List
            if(counter == 0){
                scores.add("-1");
            }

        }

        String joined = String.join("," , scores);
        System.out.println(joined);

    }
}

But I encountered that problem :

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at ceng.bim208.App.visitFile(App.java:35)
    at ceng.bim208.App.visitFile(App.java:18)
    at java.nio.file.Files.walkFileTree(Files.java:2670)
    at java.nio.file.Files.walkFileTree(Files.java:2742)
    at ceng.bim208.App.main(App.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

I tried to use XmX2048M to increase heap size but it doesn't solve my problem. What should i do?

In addition, if i run the program on a different path(include 2 txt file same format) it works correctly.

Body:
The following does it the new way and corrects some faults.

public Map<String, List<String>> map = new HashMap<>();

@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attr)
        throws IOException {

    Files.lines(path).forEach(line -> {
        String[] keyValue = line.split(" ", 2);
        map.compute(keyValue[0],
             (key, oldList) -> {
                  List<String> list = oldList == null
                      ? new ArrayList<>()
                      : oldList;
                  list.add(keyValue[1]);
                  return list;
             });
    });
    return CONTINUE;
}

A LinkedHashMap maintains the order of adding, which is needlessly costing memory.

The splitting should be done once.

The file should be closed. I use Files.lines which allows terse coding.

(Tip) The Charset (encoding) is not given, hence platform default. One might consider adding it as parameter.

The Map.compute comes in handy to decide on the old value (a List) whether to create a new one.

One might save on memory by not storing a List<String> but something like List<byte[]> with the bytes something like:

byte[] bytes = keyValue[1].getBytes(Charset.defaultCharset());
String s = new String(bytes, Charset.defaultCharset());

Compared to a String for plain ASCII you'll save half the bytes (a char is two bytes).

Probably a database, like an embedded java Derby or H2 will do better.


问:
Kibana - Create line Chart on Bar Chart in Same graph
I am a newbie in Elastic Stack and i am trying the following and i am struck.

I want to render a line chart on the bar chart on same graph. I have been browsing for long time now but could not find any link for this.

In Kibana 5.2, is it possible to create a line chart on bar chart on same graph ? Can someone who has done it in the past confirm if it is feasible ?

if yes, can you share any pointers.

答:
If you want to mix bars and lines it's possible via the Timelion plugin (which is included in Kibana since version 5). Put something like this in the Timelion tab:

```<code>.es(*).bars(),.es(*).lines()
</code>```

And you should be able to see something like:

Now it's just a matter of doing the query you want to plot.

For understanding it in detail, on Timelion tab, on top right corner, you will see a tab - Docs. Once you click on Docs, you will get a link - Go to Tutorial.

Try the link and it walks you through the steps.

Body:
If you want to mix bars and lines it's possible via the Timelion plugin (which is included in Kibana since version 5). Put something like this in the Timelion tab:

.es(*).bars(),.es(*).lines()

And you should be able to see something like:

Now it's just a matter of doing the query you want to plot.

For understanding it in detail, on Timelion tab, on top right corner, you will see a tab - Docs. Once you click on Docs, you will get a link - Go to Tutorial.

Try the link and it walks you through the steps.


问:
Get m4v to autoplay while hidden in iOS
```<code><video muted controls="true" loop id="v" width="100%" height="100%" src="pattern.m4v">
</code>```

The video plays when I hit it direct on iOS (localhost/patter.m4v) yet it absolutely will NOT play when I hit my index.html. In fact, I can't even get the video to play by tapping on it directly even when visible.

答:
This took way too long to solve for how simple of a problem it is AND how simple the solution was.

Out of all the articles I read, this article on html5 video in webkit helped the most. If my solution does not work for you, I highly encourage you to consult that link as the solution to your problem is likely in there.

Problems

For whatever reason, my <canvas> element was over my <video> element, even if not visually. If this is your problem, there are tricks like position: absolute and/or z-index:999

I needed playinline for my video or it would only play full screen. Note that autoplay and videoElement.play() only work with playinline.

Cliff notes:

Apple relaxed rules on html video in iOS 10

autoplay works in iOS10 (a)

playsinlineworks in iOS10 (a)

Code

```<code><video playsinline muted controls loop autoplay id="v" width="400" height="400" src="pattern.m4v">
</code>```

a: As long as it abides by the rules listed in the link above (second paragraph)

Title: Get m4v to autoplay while hidden in iOS

Body:
<video muted controls="true" loop id="v" width="100%" height="100%" src="pattern.m4v">

The video plays when I hit it direct on iOS (localhost/patter.m4v) yet it absolutely will NOT play when I hit my index.html. In fact, I can't even get the video to play by tapping on it directly even when visible.

Body:
This took way too long to solve for how simple of a problem it is AND how simple the solution was.

Out of all the articles I read, this article on html5 video in webkit helped the most. If my solution does not work for you, I highly encourage you to consult that link as the solution to your problem is likely in there.

Problems

For whatever reason, my <canvas> element was over my <video> element, even if not visually. If this is your problem, there are tricks like position: absolute and/or z-index:999

I needed playinline for my video or it would only play full screen. Note that autoplay and videoElement.play() only work with playinline.

Cliff notes:

Apple relaxed rules on html video in iOS 10

autoplay works in iOS10 (a)

playsinlineworks in iOS10 (a)

Code

<video playsinline muted controls loop autoplay id="v" width="400" height="400" src="pattern.m4v">

a: As long as it abides by the rules listed in the link above (second paragraph)


问:
How to customize group label in Angular UI-Select
In Angular ui-select (GitHub Link), how can I customize group label?

As shown in the image, the list is grouped by country, how can I customize the group label so to make it larger then the selection items?

Plunker Example

```<code><ui-select ng-model="person.selected" theme="bootstrap" ng-disabled="disabled" style="min-width: 300px;" title="Choose a person">
<ui-select-match placeholder="Select a person in the list or search his name/age...">{{$select.selected.name}}</ui-select-match>
<ui-select-choices group-by="'country'" repeat="person in people | propsFilter: {name: $select.search, age: $select.search}">
  <div ng-bind-html="person.name | highlight: $select.search"></div>
  <small>
    email: {{person.email}}
    age: <span ng-bind-html="''+person.age | highlight: $select.search"></span>
  </small>
</ui-select-choices>
</ui-select>
</code>```

The example is modified from the official example link.

Thanks in advance.

答:
We had similar need, but we did not want to change this style for all groups.

So here is the solution we found:

Add class biggerGroup to your ui-select-choices like in this example:

```<code><ui-select-choices class="biggerGroup" group-by="'country'" repeat="person in people | propsFilter: {name: $select.search, age: $select.search}">
</code>```

Add this in your .css file:

```<code>.biggerGroup > .ui-select-choices-group > .ui-select-choices-group-label {
    font-size: 20px;
}
</code>```

Now, if you need to change group styling in your selection, just add this biggerGroup class and voila.

I hope it may help someone.

Body:
In Angular ui-select (GitHub Link), how can I customize group label?

As shown in the image, the list is grouped by country, how can I customize the group label so to make it larger then the selection items?

Plunker Example

<ui-select ng-model="person.selected" theme="bootstrap" ng-disabled="disabled" style="min-width: 300px;" title="Choose a person">
<ui-select-match placeholder="Select a person in the list or search his name/age...">{{$select.selected.name}}</ui-select-match>
<ui-select-choices group-by="'country'" repeat="person in people | propsFilter: {name: $select.search, age: $select.search}">

    email: {{person.email}}
    age:

</ui-select-choices>
</ui-select>

The example is modified from the official example link.

Thanks in advance.

Body:
We had similar need, but we did not want to change this style for all groups.

So here is the solution we found:

Add class biggerGroup to your ui-select-choices like in this example:

<ui-select-choices class="biggerGroup" group-by="'country'" repeat="person in people | propsFilter: {name: $select.search, age: $select.search}">

Add this in your .css file:

.biggerGroup > .ui-select-choices-group > .ui-select-choices-group-label {
    font-size: 20px;
}

Now, if you need to change group styling in your selection, just add this biggerGroup class and voila.

I hope it may help someone.


问:
Detect HTML5 Geolocation Support Using PHP
I need to detect HTML5 Geolocation support using PHP so that I can load a backup JavaScript that supports Geolocation using IP Address.

How to do this with or without PHP.

答:
Well the only way to detect Geolocation is with the navigator, and used like so:

```<code>if(navigator.geolocation)
{
     //Geo in Browser
}
</code>```

So what I would personally do is create an Ajax request to server and do a redirect like so:

```<code>if(navigator.geolocation)
{
    navigator.geolocation.getCurrentPosition(function(position){
        /*
            * Send Position to server where you can store it in Session
         */
        document.location = '/'; //Redirect and use the session data from above
    }, function(message){
        /*
            * Send false to the server, and then refresh to remove the js geo check.
         */
    });
}
</code>```

on server side you would do something like so:

```<code><?php /* session/geolocation.php */

//Require system files
include '../MasterBootloader.php';

/*
    * Session is already started in the above inclustion
*/

if(!isset($_SESSION['geo']['checked']) && is_agax_request())
{
    $_SESSION['geo'] = array();
    if(isset($_GET['postition']))
    {
        $_SESSION['geo']['supported'] = true;
        $_SESSION['geo']['location'] = json_decode($_REQUEST['geo_position']);
    }
    $_SESSION['geo']['checked'] = true;
}
?>
</code>```

now when the javascript redirects you, in your index you can check to see if the exists before outputting your html, then you will know server side if GEO is supported!

Body:
Well the only way to detect Geolocation is with the navigator, and used like so:

if(navigator.geolocation)
{
     //Geo in Browser
}

So what I would personally do is create an Ajax request to server and do a redirect like so:

if(navigator.geolocation)
{
    navigator.geolocation.getCurrentPosition(function(position){
        /*
            * Send Position to server where you can store it in Session
         */
        document.location = '/'; //Redirect and use the session data from above
    }, function(message){
        /*
            * Send false to the server, and then refresh to remove the js geo check.
         */
    });
}

on server side you would do something like so:

<?php /* session/geolocation.php */

//Require system files
include '../MasterBootloader.php';

/*
    * Session is already started in the above inclustion
*/

if(!isset($_SESSION['geo']['checked']) && is_agax_request())
{
    $_SESSION['geo'] = array();
    if(isset($_GET['postition']))
    {
        $_SESSION['geo']['supported'] = true;
        $_SESSION['geo']['location'] = json_decode($_REQUEST['geo_position']);
    }
    $_SESSION['geo']['checked'] = true;
}
?>

now when the javascript redirects you, in your index you can check to see if the exists before outputting your html, then you will know server side if GEO is supported!


问:
How does this float square root approximation work?
I found a rather strange but working square root approximation for floats; I really don't get it. Can someone explain me why this code works?

```<code>float sqrt(float f)
{
    const int result = 0x1fbb4000 + (*(int*)&f >> 1);
    return *(float*)&result;
}
</code>```

I've test it a bit and it outputs values off of std::sqrt() by about 1 to 3%. I know of the Quake III's fast inverse square root and I guess it's something similar here (without the newton iteration) but I'd really appreciate an explanation of how it works.

(nota: I've tagged it both c and c++ since it's both valid-ish (see comments) C and C++ code)

答:
See Oliver Charlesworth’s explanation of why this almost works.  I’m addressing an issue raised in the comments.

Since several people have pointed out the non-portability of this, here are some ways you can make it more portable, or at least make the compiler tell you if it won’t work.

First, C++ allows you to check std::numeric_limits<float>::is_iec559 at compile time, such as in a static_assert.  You can also check that sizeof(int) == sizeof(float), which will not be true if int is 64-bits, but what you really want to do is use uint32_t, which if it exists will always be exactly 32 bits wide, will have well-defined behavior with shifts and overflow, and will cause a compilation error if your weird architecture has no such integral type.  Either way, you should also static_assert() that the types have the same size.  Static assertions have no run-time cost and you should always check your preconditions this way if possible.

Unfortunately, the test of whether converting the bits in a float to a uint32_t and shifting is big-endian, little-endian or neither cannot be computed as a compile-time constant expression.  Here, I put the run-time check in the part of the code that depends on it, but you might want to put it in the initialization and do it once.  In practice, both gcc and clang can optimize this test away at compile time.

You do not want to use the unsafe pointer cast, and there are some systems I’ve worked on in the real world where that could crash the program with a bus error.  The maximally-portable way to convert object representations is with memcpy().  In my example below, I type-pun with a union, which works on any actually-existing implementation.  (Language lawyers object to it, but no successful compiler will ever break that much legacy code silently.)  If you must do a pointer conversion (see below) there is alignas().  But however you do it, the result will be implementation-defined, which is why we check the result of converting and shifting a test value.

Anyway, not that you’re likely to use it on a modern CPU, here’s a gussied-up C++14 version that checks those non-portable assumptions:

```<code>#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
#include <vector>

using std::cout;
using std::endl;
using std::size_t;
using std::sqrt;
using std::uint32_t;

template <typename T, typename U>
  inline T reinterpret(const U x)
/* Reinterprets the bits of x as a T.  Cannot be constexpr
 * in C++14 because it reads an inactive union member.
 */
{
  static_assert( sizeof(T)==sizeof(U), "" );
  union tu_pun {
    U u = U();
    T t;
  };

  const tu_pun pun{x};
  return pun.t;
}

constexpr float source = -0.1F;
constexpr uint32_t target = 0x5ee66666UL;

const uint32_t after_rshift = reinterpret<uint32_t,float>(source) >> 1U;
const bool is_little_endian = after_rshift == target;

float est_sqrt(const float x)
/* A fast approximation of sqrt(x) that works less well for subnormal numbers.
 */
{
  static_assert( std::numeric_limits<float>::is_iec559, "" );
  assert(is_little_endian); // Could provide alternative big-endian code.

 /* The algorithm relies on the bit representation of normal IEEE floats, so
  * a subnormal number as input might be considered a domain error as well?
  */
  if ( std::isless(x, 0.0F) || !std::isfinite(x) )
    return std::numeric_limits<float>::signaling_NaN();

  constexpr uint32_t magic_number = 0x1fbb4000UL;
  const uint32_t raw_bits = reinterpret<uint32_t,float>(x);
  const uint32_t rejiggered_bits = (raw_bits >> 1U) + magic_number;
  return reinterpret<float,uint32_t>(rejiggered_bits);
}

int main(void)
{
  static const std::vector<float> test_values{
    4.0F, 0.01F, 0.0F, 5e20F, 5e-20F, 1.262738e-38F };

  for ( const float& x : test_values ) {
    const double gold_standard = sqrt((double)x);
    const double estimate = est_sqrt(x);
    const double error = estimate - gold_standard;

    cout << "The error for (" << estimate << " - " << gold_standard << ") is "
         << error;

    if ( gold_standard != 0.0 && std::isfinite(gold_standard) ) {
      const double error_pct = error/gold_standard * 100.0;
      cout << " (" << error_pct << "%).";
    } else
      cout << '.';

    cout << endl;
  }

  return EXIT_SUCCESS;
}
</code>```

Update

Here is an alternative definition of reinterpret<T,U>() that avoids type-punning.  You could also implement the type-pun in modern C, where it’s allowed by standard, and call the function as extern "C".  I think type-punning is more elegant, type-safe and consistent with the quasi-functional style of this program than memcpy().  I also don’t think you gain much, because you still could have undefined behavior from a hypothetical trap representation. Also, clang++ 3.9.1 -O -S is able to statically analyze the type-punning version, optimize the variable is_little_endian to the constant 0x1, and eliminate the run-time test, but it can only optimize this version down to a single-instruction stub.

But more importantly, this code isn’t guaranteed to work portably on every compiler.  For example, some old computers can’t even address exactly 32 bits of memory.  But in those cases, it should fail to compile and tell you why.  No compiler is just suddenly going to break a huge amount of legacy code for no reason.  Although the standard technically gives permission to do that and still say it conforms to C++14, it will only happen on an architecture very different from we expect.  And if our assumptions are so invalid that some compiler is going to turn a type-pun between a float and a 32-bit unsigned integer into a dangerous bug, I really doubt the logic behind this code will hold up if we just use memcpy() instead.  We want that code to fail at compile time, and to tell us why.

```<code>#include <cassert>
#include <cstdint>
#include <cstring>

using std::memcpy;
using std::uint32_t;

template <typename T, typename U> inline T reinterpret(const U &x)
/* Reinterprets the bits of x as a T.  Cannot be constexpr
 * in C++14 because it modifies a variable.
 */
{
  static_assert( sizeof(T)==sizeof(U), "" );
  T temp;

  memcpy( &temp, &x, sizeof(T) );
  return temp;
}

constexpr float source = -0.1F;
constexpr uint32_t target = 0x5ee66666UL;

const uint32_t after_rshift = reinterpret<uint32_t,float>(source) >> 1U;
extern const bool is_little_endian = after_rshift == target;
</code>```

However, Stroustrup et al., in the C++ Core Guidelines, recommend a reinterpret_cast instead:

```<code>#include <cassert>

template <typename T, typename U> inline T reinterpret(const U x)
/* Reinterprets the bits of x as a T.  Cannot be constexpr
 * in C++14 because it uses reinterpret_cast.
 */
{
  static_assert( sizeof(T)==sizeof(U), "" );
  const U temp alignas(T) alignas(U) = x;
  return *reinterpret_cast<const T*>(&temp);
}
</code>```

The compilers I tested can also optimize this away to a folded constant.  Stroustrup’s reasoning is [sic]:

Accessing the result of an reinterpret_cast to a different type from the objects declared type is still undefined behavior, but at least we can see that something tricky is going on.

Update

From the comments: C++20 introduces std::bit_cast, which converts an object representation to a different type with unspecified, not undefined, behavior.  This doesn’t guarantee that your implementation will use the same format of float and int that this code expects, but it doesn’t give the compiler carte blanche to break your program arbitrarily because there’s technically undefined behavior in one line of it.  It can also give you a constexpr conversion.

Body:
I found a rather strange but working square root approximation for floats; I really don't get it. Can someone explain me why this code works?

float sqrt(float f)
{
    const int result = 0x1fbb4000 + (*(int*)&f >> 1);
    return *(float*)&result;
}

I've test it a bit and it outputs values off of std::sqrt() by about 1 to 3%. I know of the Quake III's fast inverse square root and I guess it's something similar here (without the newton iteration) but I'd really appreciate an explanation of how it works.

(nota: I've tagged it both c and c++ since it's both valid-ish (see comments) C and C++ code)

Body:
See Oliver Charlesworth’s explanation of why this almost works.  I’m addressing an issue raised in the comments.

Since several people have pointed out the non-portability of this, here are some ways you can make it more portable, or at least make the compiler tell you if it won’t work.

First, C++ allows you to check std::numeric_limits<float>::is_iec559 at compile time, such as in a static_assert.  You can also check that sizeof(int) == sizeof(float), which will not be true if int is 64-bits, but what you really want to do is use uint32_t, which if it exists will always be exactly 32 bits wide, will have well-defined behavior with shifts and overflow, and will cause a compilation error if your weird architecture has no such integral type.  Either way, you should also static_assert() that the types have the same size.  Static assertions have no run-time cost and you should always check your preconditions this way if possible.

Unfortunately, the test of whether converting the bits in a float to a uint32_t and shifting is big-endian, little-endian or neither cannot be computed as a compile-time constant expression.  Here, I put the run-time check in the part of the code that depends on it, but you might want to put it in the initialization and do it once.  In practice, both gcc and clang can optimize this test away at compile time.

You do not want to use the unsafe pointer cast, and there are some systems I’ve worked on in the real world where that could crash the program with a bus error.  The maximally-portable way to convert object representations is with memcpy().  In my example below, I type-pun with a union, which works on any actually-existing implementation.  (Language lawyers object to it, but no successful compiler will ever break that much legacy code silently.)  If you must do a pointer conversion (see below) there is alignas().  But however you do it, the result will be implementation-defined, which is why we check the result of converting and shifting a test value.

Anyway, not that you’re likely to use it on a modern CPU, here’s a gussied-up C++14 version that checks those non-portable assumptions:

#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
#include <vector>

using std::cout;
using std::endl;
using std::size_t;
using std::sqrt;
using std::uint32_t;

template <typename T, typename U>
  inline T reinterpret(const U x)
/* Reinterprets the bits of x as a T.  Cannot be constexpr
 * in C++14 because it reads an inactive union member.
 */
{
  static_assert( sizeof(T)==sizeof(U), "" );
  union tu_pun {
    U u = U();
    T t;
  };

  const tu_pun pun{x};
  return pun.t;
}

constexpr float source = -0.1F;
constexpr uint32_t target = 0x5ee66666UL;

const uint32_t after_rshift = reinterpret<uint32_t,float>(source) >> 1U;
const bool is_little_endian = after_rshift == target;

float est_sqrt(const float x)
/* A fast approximation of sqrt(x) that works less well for subnormal numbers.
 */
{
  static_assert( std::numeric_limits<float>::is_iec559, "" );
  assert(is_little_endian); // Could provide alternative big-endian code.

 /* The algorithm relies on the bit representation of normal IEEE floats, so
  * a subnormal number as input might be considered a domain error as well?
  */
  if ( std::isless(x, 0.0F) || !std::isfinite(x) )
    return std::numeric_limits<float>::signaling_NaN();

  constexpr uint32_t magic_number = 0x1fbb4000UL;
  const uint32_t raw_bits = reinterpret<uint32_t,float>(x);
  const uint32_t rejiggered_bits = (raw_bits >> 1U) + magic_number;
  return reinterpret<float,uint32_t>(rejiggered_bits);
}

int main(void)
{
  static const std::vector<float> test_values{
    4.0F, 0.01F, 0.0F, 5e20F, 5e-20F, 1.262738e-38F };

  for ( const float& x : test_values ) {
    const double gold_standard = sqrt((double)x);
    const double estimate = est_sqrt(x);
    const double error = estimate - gold_standard;

    cout << "The error for (" << estimate << " - " << gold_standard << ") is "
         << error;

    if ( gold_standard != 0.0 && std::isfinite(gold_standard) ) {
      const double error_pct = error/gold_standard * 100.0;
      cout << " (" << error_pct << "%).";
    } else
      cout << '.';

    cout << endl;
  }

  return EXIT_SUCCESS;
}

Update

Here is an alternative definition of reinterpret<T,U>() that avoids type-punning.  You could also implement the type-pun in modern C, where it’s allowed by standard, and call the function as extern "C".  I think type-punning is more elegant, type-safe and consistent with the quasi-functional style of this program than memcpy().  I also don’t think you gain much, because you still could have undefined behavior from a hypothetical trap representation. Also, clang++ 3.9.1 -O -S is able to statically analyze the type-punning version, optimize the variable is_little_endian to the constant 0x1, and eliminate the run-time test, but it can only optimize this version down to a single-instruction stub.

But more importantly, this code isn’t guaranteed to work portably on every compiler.  For example, some old computers can’t even address exactly 32 bits of memory.  But in those cases, it should fail to compile and tell you why.  No compiler is just suddenly going to break a huge amount of legacy code for no reason.  Although the standard technically gives permission to do that and still say it conforms to C++14, it will only happen on an architecture very different from we expect.  And if our assumptions are so invalid that some compiler is going to turn a type-pun between a float and a 32-bit unsigned integer into a dangerous bug, I really doubt the logic behind this code will hold up if we just use memcpy() instead.  We want that code to fail at compile time, and to tell us why.

#include <cassert>
#include <cstdint>
#include <cstring>

using std::memcpy;
using std::uint32_t;

template <typename T, typename U> inline T reinterpret(const U &x)
/* Reinterprets the bits of x as a T.  Cannot be constexpr
 * in C++14 because it modifies a variable.
 */
{
  static_assert( sizeof(T)==sizeof(U), "" );
  T temp;

  memcpy( &temp, &x, sizeof(T) );
  return temp;
}

constexpr float source = -0.1F;
constexpr uint32_t target = 0x5ee66666UL;

const uint32_t after_rshift = reinterpret<uint32_t,float>(source) >> 1U;
extern const bool is_little_endian = after_rshift == target;

However, Stroustrup et al., in the C++ Core Guidelines, recommend a reinterpret_cast instead:

#include <cassert>

template <typename T, typename U> inline T reinterpret(const U x)
/* Reinterprets the bits of x as a T.  Cannot be constexpr
 * in C++14 because it uses reinterpret_cast.
 */
{
  static_assert( sizeof(T)==sizeof(U), "" );
  const U temp alignas(T) alignas(U) = x;
  return *reinterpret_cast<const T*>(&temp);
}

The compilers I tested can also optimize this away to a folded constant.  Stroustrup’s reasoning is [sic]:

Accessing the result of an reinterpret_cast to a different type from the objects declared type is still undefined behavior, but at least we can see that something tricky is going on.

Update

From the comments: C++20 introduces std::bit_cast, which converts an object representation to a different type with unspecified, not undefined, behavior.  This doesn’t guarantee that your implementation will use the same format of float and int that this code expects, but it doesn’t give the compiler carte blanche to break your program arbitrarily because there’s technically undefined behavior in one line of it.  It can also give you a constexpr conversion.

ContentLicense: CC BY-SA 4.0


问:
Optimize a algorithm that find a specific Fibonacci number

Given an number A, I want to find the Ath Fibonacci number
  that is multiple of 3 or if the number representation has at least a 3
  on it.

Example:

Fibonacci > 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...

Input: 1, Output: 3;

3 is the first Fibonacci number that is multiple of 3 or has an 3 on
  it.

Input: 3, Output: 21;

21 is the third Fibonacci number that is multiple of 3 or has an 3 on
  it.

Edit: Variable type changed to unsigned long long int and ajust on Fibonacci generator. Thanks @rcgldr and @Jarod42 for the help!

My code:

```<code>#include<bits/stdc++.h>

using namespace std;

int tem(unsigned long long int i){

    while(i != 0){
        if(i%10 == 3){
            return true;
        }
        i = i/10;
    }
    return false;
}

int main(){

    int a, count = 0;
    unsigned long long int f1 = 1, f2 = 1;

    while(scanf("%d", &a) != EOF){
        for(unsigned long long int i = 2; i > 0; i++){
            i = f1 + f2;
            f1 = f2;
            f2 = i;
                if((i%3 == 0) || tem(i)){
                    count++;
                    if(count == a){
                        cout << i << endl;
                        break;
                    }
                }

        }
    }
}
</code>```

When A > 20, it starts to slow down. Makes sense because it tends to be exponecial. My code is not very efficient, but I didn't find an better logic to use.

I looked into these links, but didn't find an conclusion:

1 - Recursive Fibonacci

2 - Fibonacci Optimization

Any ideas? Thanks for the help!

答:
Just pointing out some obvious coding errors

```<code>for(unsigned long long int i = 2; i > 0; i++)
</code>```

is redundant.

```<code>for(;;){
  unsigned long long i = f1+f2;
</code>```

should suffice. Secondly

```<code>return 0;
</code>```

is meaningless because it breaks out of the while loop. A break would be better.

Body:
Given an number A, I want to find the Ath Fibonacci number
  that is multiple of 3 or if the number representation has at least a 3
  on it.

Example:

Fibonacci > 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...

Input: 1, Output: 3;

3 is the first Fibonacci number that is multiple of 3 or has an 3 on
  it.

Input: 3, Output: 21;

21 is the third Fibonacci number that is multiple of 3 or has an 3 on
  it.

Edit: Variable type changed to unsigned long long int and ajust on Fibonacci generator. Thanks @rcgldr and @Jarod42 for the help!

My code:

#include<bits/stdc++.h>

using namespace std;

int tem(unsigned long long int i){

    while(i != 0){
        if(i%10 == 3){
            return true;
        }
        i = i/10;
    }
    return false;
}

int main(){

    int a, count = 0;
    unsigned long long int f1 = 1, f2 = 1;

    while(scanf("%d", &a) != EOF){
        for(unsigned long long int i = 2; i > 0; i++){
            i = f1 + f2;
            f1 = f2;
            f2 = i;
                if((i%3 == 0) || tem(i)){
                    count++;
                    if(count == a){
                        cout << i << endl;
                        break;
                    }
                }

        }
    }
}

When A > 20, it starts to slow down. Makes sense because it tends to be exponecial. My code is not very efficient, but I didn't find an better logic to use.

I looked into these links, but didn't find an conclusion:

1 - Recursive Fibonacci

2 - Fibonacci Optimization

Any ideas? Thanks for the help!

Body:
Just pointing out some obvious coding errors

for(unsigned long long int i = 2; i > 0; i++)

is redundant.

for(;;){
  unsigned long long i = f1+f2;

should suffice. Secondly

return 0;

is meaningless because it breaks out of the while loop. A break would be better.


问:
instantiating unique elements of std::vector without a copy constructor
Say I have a std::vector, and I have a class. I want to initialize all of the elements of this vector, but for each of these elements, the constructor of the class will take unique arguments.

Do I need to give the class a copy constructor, or is there some weird syntax where I can instantiate elements of the std::vector without using an equal sign?

答:
You can create new elements in the vector directly using emplacement operations.

For example:

```<code>struct X { X(int, char); X(std::string, double, bool); };

std::vector<X> v;

v.emplace_back(1, 'x');              // direct-initializes element X(1, 'x')
v.emplace_back("foo", 1.5, false);   // ditto with element X("foo", 1.5, false)
</code>```

Basically, emplace_back is like push_back, but directly creates the object (even using explicit constructors). Note that your X still needs to be copyable or movable, since pushing back new elements requires reallocation, which requires copying or moving. (Insertion in the middle moreover requires assignability.) Elements that are unmovable (e.g. std::mutex) can only go into node-based containers (e.g. std::list), also with emplacement. Once inserted, a node never moves.

Body:
You can create new elements in the vector directly using emplacement operations.

For example:

struct X { X(int, char); X(std::string, double, bool); };

std::vector<X> v;

v.emplace_back(1, 'x');              // direct-initializes element X(1, 'x')
v.emplace_back("foo", 1.5, false);   // ditto with element X("foo", 1.5, false)

Basically, emplace_back is like push_back, but directly creates the object (even using explicit constructors). Note that your X still needs to be copyable or movable, since pushing back new elements requires reallocation, which requires copying or moving. (Insertion in the middle moreover requires assignability.) Elements that are unmovable (e.g. std::mutex) can only go into node-based containers (e.g. std::list), also with emplacement. Once inserted, a node never moves.


问:
mongoid $in: statement how do I ignore a field if the value is a blank array?
So, I have a database of projects and im writing a search query. I want the user to be able to choose what fields they use or do not use, they are not required to fill them all in. Any fields the user ignores I dont want the query to be limited by what was not selected.

if a user skips proposal_status: in the html form I dont want the query to limit the search by a blank array. How would I alter my query to ignore the proposal_status line if params[:status] is a blank array?

```<code>Project.where(
  job_number: /#{params[:job_number]}/i,
  project_name: /#{params[:project_name]}/i,
  proposal_status: {:$in => params[:status] } # params[:status] == []
)
</code>```

答:
These two queries are equivalent:

```<code>Project.where(
  job_number: /#{params[:job_number]}/i,
  project_name: /#{params[:project_name]}/i,
  proposal_status: {:$in => params[:status] }
)

Project.where(job_number: /#{params[:job_number]}/i)
       .where(project_name: /#{params[:project_name]}/i)
       .where(proposal_status: {:$in => params[:status] })
</code>```

If you build the query piece by piece then leaving out one piece is easy:

```<code>q = Project.where(job_number: /#{params[:job_number]}/i)
q = q.where(project_name: /#{params[:project_name]}/i)
q = q.where(proposal_status: {:$in => params[:status] }) if(params[:status].present?)
</code>```

Also, Mongoid patches (or at least used to) some methods into Symbol so you could say:

```<code>where(:proposal_status.in => params[:status])
# --------------------^^^
</code>```

to simplify things (unless they don't do this anymore of course).

Body:
So, I have a database of projects and im writing a search query. I want the user to be able to choose what fields they use or do not use, they are not required to fill them all in. Any fields the user ignores I dont want the query to be limited by what was not selected.

if a user skips proposal_status: in the html form I dont want the query to limit the search by a blank array. How would I alter my query to ignore the proposal_status line if params[:status] is a blank array?

Project.where(
  job_number: /#{params[:job_number]}/i,
  project_name: /#{params[:project_name]}/i,
  proposal_status: {:$in => params[:status] } # params[:status] == []
)

Body:
These two queries are equivalent:

Project.where(
  job_number: /#{params[:job_number]}/i,
  project_name: /#{params[:project_name]}/i,
  proposal_status: {:$in => params[:status] }
)

Project.where(job_number: /#{params[:job_number]}/i)
       .where(project_name: /#{params[:project_name]}/i)
       .where(proposal_status: {:$in => params[:status] })

If you build the query piece by piece then leaving out one piece is easy:

q = Project.where(job_number: /#{params[:job_number]}/i)
q = q.where(project_name: /#{params[:project_name]}/i)
q = q.where(proposal_status: {:$in => params[:status] }) if(params[:status].present?)

Also, Mongoid patches (or at least used to) some methods into Symbol so you could say:

where(:proposal_status.in => params[:status])
# --------------------^^^

to simplify things (unless they don't do this anymore of course).


问:
How do I get a distinct, ordered list of names from a DataTable using LINQ?
I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause.

```<code>var names =
    (from DataRow dr in dataTable.Rows
    orderby (string)dr["Name"]
    select (string)dr["Name"]).Distinct();
</code>```

Why does the orderby not get enforced?

答:
Try the following

```<code>var names = (from dr in dataTable.Rows
             select (string)dr["Name"]).Distinct().OrderBy(name => name);
</code>```

this should work for what you need.

Body:
I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause.

var names =
    (from DataRow dr in dataTable.Rows
    orderby (string)dr["Name"]
    select (string)dr["Name"]).Distinct();

Why does the orderby not get enforced?

LastEditorDisplayName: Keith

Body:
Try the following

var names = (from dr in dataTable.Rows
             select (string)dr["Name"]).Distinct().OrderBy(name => name);

this should work for what you need.


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答: T is already a type parameter, you don't need to call typeof on it. TypeOf takes a type and returns its type parameter.</p>

OwnerDisplayName: Sara Chipps

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

OwnerDisplayName: Jonathan Holland

LastEditorDisplayName: Jonathan Holland


问:
Strategy Pattern the right thing?
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

```<code>switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}
</code>```

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

```<code>abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}
</code>```

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

答:
Because version is only known at runtime it will definitely boil down to some conditional (if or switch or using a map between strings and a prototype etc).

Hence the worthy goal is to reduce the number of conditionals/isolate the change points.

Title: Strategy Pattern the right thing?

Body:
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static


问:
Handler in subdirectory of AWS Lambda function not running
I'm getting an awfully unfortunate error on Lambda:

```<code>Unable to import module 'lib/index': Error
at require (internal/module.js:20:19)
</code>```

Which is strange because there is definitely a function called handler getting exported from lib/index...not sure if the whole subdirectory thing has been an issue for others so I wanted to ask.

sam-template.yaml

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Does something crazy
Resources:
  SomeFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lib/index.handler
      Role: arn:aws:iam::...:role/lambda-role
      Runtime: nodejs6.10
      Timeout: 10
      Events:
        Timer:
          Type: Schedule
          Properties:
            Schedule: rate(1 minute)
</code>```

Module structure

```<code>|-- lib
|     `-- index.js
`-- src
      `-- index.js
</code>```

I have nested it here because I'm transpiling ES6 during my build process using the following, excerpt from package.json:
"build": "babel src -d lib"

buildspec.yaml

```<code>version: 0.1
phases:
    install:
        commands:
            - npm install
            - aws cloudformation package --template-file sam-template.yaml --s3-bucket some-bucket --output-template-file compiled-sam-template.yaml
    build:
        commands:
            - npm run build
    post_build:
        commands:
            - npm prune --production
artifacts:
    files:
        - 'node_modules/**/*'
        - 'lib/**/*'
        - 'compiled-template.yaml'
</code>```

答:
The aws cloudformation package command is shipping the built assets, which is run in the install phase of the shown code. Moving it to the post_build will ensure it captures everything needed, including the lib/index in question:

```<code>post_build:
  commands:
    - npm prune --production
    - aws cloudformation package ...
</code>```

Body:
I'm getting an awfully unfortunate error on Lambda:

Unable to import module 'lib/index': Error
at require (internal/module.js:20:19)

Which is strange because there is definitely a function called handler getting exported from lib/index...not sure if the whole subdirectory thing has been an issue for others so I wanted to ask.

sam-template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Does something crazy
Resources:
  SomeFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lib/index.handler
      Role: arn:aws:iam::...:role/lambda-role
      Runtime: nodejs6.10
      Timeout: 10
      Events:
        Timer:
          Type: Schedule
          Properties:
            Schedule: rate(1 minute)

Module structure

|-- lib
|     `-- index.js
`-- src
      `-- index.js

I have nested it here because I'm transpiling ES6 during my build process using the following, excerpt from package.json:
"build": "babel src -d lib"

buildspec.yaml

version: 0.1
phases:
    install:
        commands:
            - npm install
            - aws cloudformation package --template-file sam-template.yaml --s3-bucket some-bucket --output-template-file compiled-sam-template.yaml
    build:
        commands:
            - npm run build
    post_build:
        commands:
            - npm prune --production
artifacts:
    files:
        - 'node_modules/**/*'
        - 'lib/**/*'
        - 'compiled-template.yaml'

Body:
The aws cloudformation package command is shipping the built assets, which is run in the install phase of the shown code. Moving it to the post_build will ensure it captures everything needed, including the lib/index in question:

post_build:
  commands:
    - npm prune --production
    - aws cloudformation package ...