问:
How to check a SQL CASE with multiple conditions?
I have two tables. Accounts ACC and FinancialTrans FT

The FinancialTrans table is as follows:

```<code>AcctID  TransTypeCode   DateOfTrans
123     TOLL            2016-06-06 00:00:00.000
123     TOLL            2016-06-02 00:00:00.000
123     TOLL            2016-04-28 00:00:00.000
123     PYMT            2016-03-11 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
</code>```

The requirement is:

When any Accounts have NO 'TOLL' or 'PYMT' in the last 2 years print 'Flag'

```<code>SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN
        (SELECT Max(DateOfTrans) FROM FinanceTrans FT
         WHERE ACC.AccountID = FT.AcctID
               AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
               AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
             GROUP BY AcctID, TransTypeCode) IS NULL
        THEN 'Flag'
        ELSE ''
       AND AS NoNo_Flag

FROM Accounts ACC

WHERE Condition 1, Condition 2...
</code>```

答:
So this is how I resolved this issue:

I created a separate column for each, first and then stored those details in a temporary table.

Then I pulled data from the temporary table using conditions to create the flag.

My code is as follows:

```<code>SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,(SELECT Max(DateOfTrans) FROM FinanceTrans FT
        WHERE ACC.AccountID = FT.AcctID
          AND TransTypeCode = 'TOLL'
        GROUP BY AcctID, TransTypeCode) LastTollDate
      ,(SELECT Max(DateOfTrans) FROM FinanceTrans FT
        WHERE ACC.AccountID = FT.AcctID
          AND TransTypeCode = 'PYMT'
        GROUP BY AcctID, TransTypeCode) LastPymtDate

INTO #Temp_Data

FROM Accounts ACC

WHERE Condition 1, Condition 2...

SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN LastTollDate >= DATEADD(year, -2, GETDATE())
        AND LastPymtDate >= DATEADD(year, -2, GETDATE())
        THEN 'Flag'
        ELSE ''
       END AS Flag

FROM #Temp_Data
</code>```

Body:
I have two tables. Accounts ACC and FinancialTrans FT

The FinancialTrans table is as follows:

AcctID  TransTypeCode   DateOfTrans
123     TOLL            2016-06-06 00:00:00.000
123     TOLL            2016-06-02 00:00:00.000
123     TOLL            2016-04-28 00:00:00.000
123     PYMT            2016-03-11 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000

The requirement is:

When any Accounts have NO 'TOLL' or 'PYMT' in the last 2 years print 'Flag'

SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN
        (SELECT Max(DateOfTrans) FROM FinanceTrans FT
         WHERE ACC.AccountID = FT.AcctID
               AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
               AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
             GROUP BY AcctID, TransTypeCode) IS NULL
        THEN 'Flag'
        ELSE ''
       AND AS NoNo_Flag

FROM Accounts ACC

WHERE Condition 1, Condition 2...

Body:
So this is how I resolved this issue:

I created a separate column for each, first and then stored those details in a temporary table.

Then I pulled data from the temporary table using conditions to create the flag.

My code is as follows:

SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,(SELECT Max(DateOfTrans) FROM FinanceTrans FT
        WHERE ACC.AccountID = FT.AcctID
          AND TransTypeCode = 'TOLL'
        GROUP BY AcctID, TransTypeCode) LastTollDate
      ,(SELECT Max(DateOfTrans) FROM FinanceTrans FT
        WHERE ACC.AccountID = FT.AcctID
          AND TransTypeCode = 'PYMT'
        GROUP BY AcctID, TransTypeCode) LastPymtDate

INTO #Temp_Data

FROM Accounts ACC

WHERE Condition 1, Condition 2...

SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN LastTollDate >= DATEADD(year, -2, GETDATE())
        AND LastPymtDate >= DATEADD(year, -2, GETDATE())
        THEN 'Flag'
        ELSE ''
       END AS Flag

FROM #Temp_Data


来源: stackexchange

问:
Keras multiple binary outputs
Can someone help me understand a bit better this problem? I must train a neural network which should output 200 mutually independent categories, each of these categories is a percentage ranging from 0 to 1. This seems to me like a binary_crossentropy problem, but every example I see on the internet uses binary_crossentropy with a single output. Since my output should be 200, if I apply binary_crossentropy, would that be correct?

This is what I have in mind, is that a correct approach or should I change it?

```<code>inputs = Input(shape=(input_shape,))
hidden = Dense(2048, activation='relu')(inputs)
hidden = Dense(2048, activation='relu')(hidden)
output = Dense(200, name='output_cat', activation='sigmoid')(hidden)
model = Model(inputs=inputs, outputs=[output])
loss_map = {'output_cat': 'binary_crossentropy'}
model.compile(loss=loss_map, optimizer="sgd", metrics=['mae', 'accuracy'])
</code>```

答:
To optimize for multiple independent binary classification problems (and not multiple category problem where you can use categorical_crossentropy) using Keras, you could do the following (here I take the example of 2 independent binary outputs, but you can extend that as much as needed):

```<code>    inputs = Input(shape=(input_shape,))
    hidden = Dense(2048, activation='relu')(inputs)
    hidden = Dense(2048, activation='relu')(hidden)
    output = Dense(units = 2, activation='sigmoid')(hidden )
</code>```

here you split your output using Keras's Lambda layer:

```<code>    output_1 = Lambda(lambda x: x[...,:1])(output)
    output_2 = Lambda(lambda x: x[...,1:])(output)

    adad = optimizers.Adadelta()
</code>```

your model output becomes a list of the different independent outputs

```<code>    model = Model(inputs, [output_1, output_2])
</code>```

you compile the model using one loss function for each output, in a list. (In fact, if you give only one kind of loss function, I believe it will apply it to all the outputs independently)

```<code>    model.compile(optimizer=adad, loss=['binary_crossentropy','binary_crossentropy'])
</code>```

ContentLicense: CC BY-SA 4.0

Title: Keras multiple binary outputs

Body:
Can someone help me understand a bit better this problem? I must train a neural network which should output 200 mutually independent categories, each of these categories is a percentage ranging from 0 to 1. This seems to me like a binary_crossentropy problem, but every example I see on the internet uses binary_crossentropy with a single output. Since my output should be 200, if I apply binary_crossentropy, would that be correct?

This is what I have in mind, is that a correct approach or should I change it?

inputs = Input(shape=(input_shape,))
hidden = Dense(2048, activation='relu')(inputs)
hidden = Dense(2048, activation='relu')(hidden)
output = Dense(200, name='output_cat', activation='sigmoid')(hidden)
model = Model(inputs=inputs, outputs=[output])
loss_map = {'output_cat': 'binary_crossentropy'}
model.compile(loss=loss_map, optimizer="sgd", metrics=['mae', 'accuracy'])

Body:
To optimize for multiple independent binary classification problems (and not multiple category problem where you can use categorical_crossentropy) using Keras, you could do the following (here I take the example of 2 independent binary outputs, but you can extend that as much as needed):

    inputs = Input(shape=(input_shape,))
    hidden = Dense(2048, activation='relu')(inputs)
    hidden = Dense(2048, activation='relu')(hidden)
    output = Dense(units = 2, activation='sigmoid')(hidden )

here you split your output using Keras's Lambda layer:

    output_1 = Lambda(lambda x: x[...,:1])(output)
    output_2 = Lambda(lambda x: x[...,1:])(output)

    adad = optimizers.Adadelta()

your model output becomes a list of the different independent outputs

    model = Model(inputs, [output_1, output_2])

you compile the model using one loss function for each output, in a list. (In fact, if you give only one kind of loss function, I believe it will apply it to all the outputs independently)

    model.compile(optimizer=adad, loss=['binary_crossentropy','binary_crossentropy'])

ContentLicense: CC BY-SA 3.0


问:
Powerbuilder - How to create Class Properties
How do I create/define properties for a powerbuilder class?  I'm running PowerBuilder 9 and I've been using public variables like properties , but I want to know how to create/define PowerBuilder properties for a object.

My guess is that in PB 9, variables/properties are very similar in their usage and implementation.

答:
Do you mean properties in the way that e.g. C# or PHP defines them, as wrappers for accessor/mutator methods - something like this (in C#)?

```<code>class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}
</code>```

EDIT: As pointed out by Hugh Brackett, this can be done by using the undocumented INDIRECT keyword.

The classic (documented) way to do this is to write seperate accessor and mutator methods.  For the example above, you would write some Powerbuilder code like this:

(or as source:

```<code>global type uo_timeperiod from nonvisualobject
end type
global uo_timeperiod uo_timeperiod

type variables
private double id_seconds
end variables

forward prototypes
public function double of_get_hours ()
public subroutine of_set_hours (double ad_seconds)
end prototypes

public function double of_get_hours ();
return id_seconds / 3600
end function

public subroutine of_set_hours (double ad_seconds);
id_seconds = ad_seconds * 3600
end subroutine
</code>```

)

ContentLicense: CC BY-SA 2.5

Body:
Do you mean properties in the way that e.g. C# or PHP defines them, as wrappers for accessor/mutator methods - something like this (in C#)?

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

EDIT: As pointed out by Hugh Brackett, this can be done by using the undocumented INDIRECT keyword.

The classic (documented) way to do this is to write seperate accessor and mutator methods.  For the example above, you would write some Powerbuilder code like this:

(or as source:

global type uo_timeperiod from nonvisualobject
end type
global uo_timeperiod uo_timeperiod

type variables
private double id_seconds
end variables

forward prototypes
public function double of_get_hours ()
public subroutine of_set_hours (double ad_seconds)
end prototypes

public function double of_get_hours ();
return id_seconds / 3600
end function

public subroutine of_set_hours (double ad_seconds);
id_seconds = ad_seconds * 3600
end subroutine

)


问:
AngularJS Ng-model-options not able to select object in getter-setter function
I have a problem selecting an object from ng-model with ng-model-options and getter-setter function. I am binding to the ng-model getter-setter function setGetSelectedItem which has to accept an object from ng-options - in my case, item and to assign its properies to the properties of another object specific_data. It does, the object is passed correctly but I am not able to select the option in the select options.

```<code><select name="item" ng-model="setGetSelectedItem"
        ng-options="item as item.title for item in items"
        ng-model-options="{getterSetter: true}">
  <option value="">-- Please select --</option>
</select>
</code>```

And in the controller:

```<code>$scope.items = [{

"description": "Item description",
  "item_type": "OUT",
  "id": 1,
  "title": "Default item"
}];

$scope._objectDataRaw = {
  specific_data: {}
};

$scope.setGetSelectedItem = function(value) {

if (arguments.length) {
  $scope._objectDataRaw.specific_data.property_id = value.id;
  $scope._objectDataRaw.specific_data.property_title = value.title;
  $scope._objectDataRaw.specific_data.property_description =
  value.description;

   return $scope._objectDataRaw.specific_data;
 }
};
</code>```

Here is a jsfiddle with the problem:
Can not select the object

And I need it to pass it as an object, and not as object.property.
Any help would be greatly appreciated.

答:
Instead of using the getterSetter option, use the ng-change directive to set the specific_data object:

```<code><select name="item" ng-model="selectedItem"
        ng-options="item as item.title for item in items"
        ̶n̶g̶-̶m̶o̶d̶e̶l̶-̶o̶p̶t̶i̶o̶n̶s̶=̶"̶{̶g̶e̶t̶t̶e̶r̶S̶e̶t̶t̶e̶r̶:̶ ̶t̶r̶u̶e̶}̶"̶
        ng-change="setSelectedItem(selectedItem)" >
  <option value="">-- Please select --</option>
</select>
</code>```

The DEMO

angular.module("app",[])
.controller("ctrl", function($scope) {
    $scope.items = [{

      "description": "Item description",
      "item_type": "OUT",
      "id": 1,
      "title": "Default item"
    }];

    $scope._objectDataRaw = {
      specific_data: {}
    };

    $scope.setSelectedItem = function(value) {
      $scope._objectDataRaw.specific_data.property_id = value.id;
      $scope._objectDataRaw.specific_data.property_title = value.title;
      $scope._objectDataRaw.specific_data.property_description =
      value.description;
    };
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl">
    <select name="item" ng-model="selectedItem"
        ng-options="item as item.title for item in items"
        ng-change="setSelectedItem(selectedItem)" >
      <option value="">-- Please select --</option>
    </select>
    <hr>
    _objectDataRaw={{_objectDataRaw}}
  </body></code>```

Body:
I have a problem selecting an object from ng-model with ng-model-options and getter-setter function. I am binding to the ng-model getter-setter function setGetSelectedItem which has to accept an object from ng-options - in my case, item and to assign its properies to the properties of another object specific_data. It does, the object is passed correctly but I am not able to select the option in the select options.

<select name="item" ng-model="setGetSelectedItem"
        ng-options="item as item.title for item in items"
        ng-model-options="{getterSetter: true}">
  <option value="">-- Please select --</option>
</select>

And in the controller:

$scope.items = [{

"description": "Item description",
  "item_type": "OUT",
  "id": 1,
  "title": "Default item"
}];

$scope._objectDataRaw = {
  specific_data: {}
};

$scope.setGetSelectedItem = function(value) {

if (arguments.length) {
  $scope._objectDataRaw.specific_data.property_id = value.id;
  $scope._objectDataRaw.specific_data.property_title = value.title;
  $scope._objectDataRaw.specific_data.property_description =
  value.description;

   return $scope._objectDataRaw.specific_data;
 }
};

Here is a jsfiddle with the problem:
Can not select the object

And I need it to pass it as an object, and not as object.property.
Any help would be greatly appreciated.

Body:
Instead of using the getterSetter option, use the ng-change directive to set the specific_data object:

<select name="item" ng-model="selectedItem"
        ng-options="item as item.title for item in items"
        ̶n̶g̶-̶m̶o̶d̶e̶l̶-̶o̶p̶t̶i̶o̶n̶s̶=̶"̶{̶g̶e̶t̶t̶e̶r̶S̶e̶t̶t̶e̶r̶:̶ ̶t̶r̶u̶e̶}̶"̶
        ng-change="setSelectedItem(selectedItem)" >
  <option value="">-- Please select --</option>
</select>

The DEMO

angular.module("app",[])
.controller("ctrl", function($scope) {
    $scope.items = [{

      "description": "Item description",
      "item_type": "OUT",
      "id": 1,
      "title": "Default item"
    }];

    $scope._objectDataRaw = {
      specific_data: {}
    };

    $scope.setSelectedItem = function(value) {
      $scope._objectDataRaw.specific_data.property_id = value.id;
      $scope._objectDataRaw.specific_data.property_title = value.title;
      $scope._objectDataRaw.specific_data.property_description =
      value.description;
    };
})

<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl">
    <select name="item" ng-model="selectedItem"
        ng-options="item as item.title for item in items"
        ng-change="setSelectedItem(selectedItem)" >
      <option value="">-- Please select --</option>
    </select>
    <hr>
    _objectDataRaw={{_objectDataRaw}}
  </body>


问:
HTML-based event listener for webcomponents/custom events (JS)
TL;DR; Is it possible to define an event listener in HTML (not JS) for a custom events?

Basing on this codepen, I'm trying to do the following:

```<code><my-checkreport
  onclick="myFunction()"
  oncheck="myFunction1)"
  check="myFunction()"
></my-checkreport>
</code>```

where myFunction does some console.log stuff that I can see in the browser console. Native onlick works, of course, but neither oncheck nor check work, for the custom event defined below (source taken from above linked codepen):

```<code>customElements.define('my-checkbox', class extends HTMLElement {
  constructor() {
    super();
    const shadowRoot = this.attachShadow({mode: 'open'});
    this.checkEvent = new CustomEvent("check", {
      bubbles: true,
      cancelable: false,
    });
    shadowRoot.innerHTML = `
      <label>
        <input type="checkbox" id="my-checkbox"></input>
        Dummy Enabled
      </label>`;
    shadowRoot.querySelector('#my-checkbox').addEventListener('click', (e) => {
      console.log('checked', e.target.checked);
      this.dispatchEvent(this.checkEvent);
    });
  }
});
</code>```

Is it possible to attach event listeners for custom events in HTML?

答:
This is the closest I can come to emulating the DOM declaration of an event handler. This code does everything, from what I can tell, that the DOM does for built in event handlers.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>On-Event Test</title>
    <script>
    function onCheckHandler(event) {
      console.log('onCheckHandler: %O', event);
      event.stopPropagation();
      event.stopImmediatePropagation();
      //event.preventDefault();
    }

    function eventListener(event) {
      console.log('eventListener: %O', event);
    }
    (function() {
      var template = `<div>Click to Check</div>`;
      class MyEl extends HTMLElement {
        constructor() {
          super();

          var rootEl = this.attachShadow({mode: 'open'});
          rootEl.innerHTML = template;
          rootEl.firstChild.addEventListener('click', () => {
            var checkEvent = new CustomEvent("check", {bubbles:true,cancelable:true});
            if (this.dispatchEvent(checkEvent)) {
              // Do default operation here
              console.log('Performing default operation');
            }
          });
          this._onCheckFn = null;
        }

        static get observedAttributes() {
          return ['oncheck'];
        }

        attributeChangedCallback(attrName, oldVal, newVal) {
          if (attrName === 'oncheck' && oldVal !== newVal) {
            if (newVal === null) {
              this.oncheck = null;
            }
            else {
              this.oncheck = Function(`return function oncheck(event) {\n\t${newVal};\n};`)();
            }
          }
        }

        get oncheck() {
          return this._onCheckFn;
        }
        set oncheck(handler) {
          if (this._onCheckFn) {
            this.removeEventListener('check', this._onCheckFn);
            this._onCheckFn = null;
          }

          if (typeof handler === 'function') {
            this._onCheckFn = handler;
            this.addEventListener('check', this._onCheckFn);
          }
        }
      }

      // Define our web component
      customElements.define('my-el', MyEl);
    })();
    </script>
  </head>
  <body>
    <my-el oncheck="onCheckHandler(event)"></my-el>
  </body>
</html>
</code>```

To get this to work you need two steps:

Step One:

The component code must support an attribute change.

When the attribute is set to a string (The function to call) then the code creates a temporary function that attempts to call the function provided as the attribute value. That function is then passed on to step two.

When the attribute is set to anything else or the attribute is removed then the code passes a null on to step two.

Step Two:

The component code must support the oncheck property.

Whenever this property is changed it needs to remove any previously defined event handler for this property by calling removeEventListener.

If the new value of the property is a function then is calls addEventListener with that function as the handler.

This was fun to figure out. At first I thought that the DOM based oncheck handler would always be first. But by testing onclick and addEventHandler('click') I discovered that the event handlers are added in the order received. If onclick is provided in the DOM than that event listener is added first. If you then call removeAttribute('onclick') and then setAttribute('onclick', 'handler(event)') then that event handler is moved to the end of the list.

So this code replicates exactly what I same with the click event.

Body:
TL;DR; Is it possible to define an event listener in HTML (not JS) for a custom events?

Basing on this codepen, I'm trying to do the following:

<my-checkreport
  onclick="myFunction()"
  oncheck="myFunction1)"
  check="myFunction()"
></my-checkreport>

where myFunction does some console.log stuff that I can see in the browser console. Native onlick works, of course, but neither oncheck nor check work, for the custom event defined below (source taken from above linked codepen):

customElements.define('my-checkbox', class extends HTMLElement {
  constructor() {
    super();
    const shadowRoot = this.attachShadow({mode: 'open'});
    this.checkEvent = new CustomEvent("check", {
      bubbles: true,
      cancelable: false,
    });
    shadowRoot.innerHTML = `

        <input type="checkbox" id="my-checkbox"></input>
        Dummy Enabled
      `;
    shadowRoot.querySelector('#my-checkbox').addEventListener('click', (e) => {
      console.log('checked', e.target.checked);
      this.dispatchEvent(this.checkEvent);
    });
  }
});

Is it possible to attach event listeners for custom events in HTML?

Body:
This is the closest I can come to emulating the DOM declaration of an event handler. This code does everything, from what I can tell, that the DOM does for built in event handlers.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>On-Event Test</title>
    <script>
    function onCheckHandler(event) {
      console.log('onCheckHandler: %O', event);
      event.stopPropagation();
      event.stopImmediatePropagation();
      //event.preventDefault();
    }

    function eventListener(event) {
      console.log('eventListener: %O', event);
    }
    (function() {
      var template = `<div>Click to Check</div>`;
      class MyEl extends HTMLElement {
        constructor() {
          super();

          var rootEl = this.attachShadow({mode: 'open'});
          rootEl.innerHTML = template;
          rootEl.firstChild.addEventListener('click', () => {
            var checkEvent = new CustomEvent("check", {bubbles:true,cancelable:true});
            if (this.dispatchEvent(checkEvent)) {
              // Do default operation here
              console.log('Performing default operation');
            }
          });
          this._onCheckFn = null;
        }

        static get observedAttributes() {
          return ['oncheck'];
        }

        attributeChangedCallback(attrName, oldVal, newVal) {
          if (attrName === 'oncheck' && oldVal !== newVal) {
            if (newVal === null) {
              this.oncheck = null;
            }
            else {
              this.oncheck = Function(`return function oncheck(event) {\n\t${newVal};\n};`)();
            }
          }
        }

        get oncheck() {
          return this._onCheckFn;
        }
        set oncheck(handler) {
          if (this._onCheckFn) {
            this.removeEventListener('check', this._onCheckFn);
            this._onCheckFn = null;
          }

          if (typeof handler === 'function') {
            this._onCheckFn = handler;
            this.addEventListener('check', this._onCheckFn);
          }
        }
      }

      // Define our web component
      customElements.define('my-el', MyEl);
    })();
    </script>
  </head>
  <body>
    <my-el oncheck="onCheckHandler(event)"></my-el>
  </body>
</html>

To get this to work you need two steps:

Step One:

The component code must support an attribute change.

When the attribute is set to a string (The function to call) then the code creates a temporary function that attempts to call the function provided as the attribute value. That function is then passed on to step two.

When the attribute is set to anything else or the attribute is removed then the code passes a null on to step two.

Step Two:

The component code must support the oncheck property.

Whenever this property is changed it needs to remove any previously defined event handler for this property by calling removeEventListener.

If the new value of the property is a function then is calls addEventListener with that function as the handler.

This was fun to figure out. At first I thought that the DOM based oncheck handler would always be first. But by testing onclick and addEventHandler('click') I discovered that the event handlers are added in the order received. If onclick is provided in the DOM than that event listener is added first. If you then call removeAttribute('onclick') and then setAttribute('onclick', 'handler(event)') then that event handler is moved to the end of the list.

So this code replicates exactly what I same with the click event.


问:
Normalize a row of data in a query - Turn one row into many
Is there a better way of doing this , I am using SQL Server 2012.

I have a table built by as vendor that looks like the below:

```<code>Customer, Date, Desc1, Qty1, Price1, Desc2, Qty2, Price2, Desc3, Qty3, Price3
</code>```

I want a result set that returns this;

```<code>Customer, Date, Desc, Qty, Price
</code>```

I am doing it today by the following solution , anyone have something better or more efficient?

```<code>Select Customer, Date, Desc1, Qty1, Price1
UNION ALL
Select Customer, Date, Desc2, Qty2, Price2
UNION ALL
Select Customer, Date, Desc3, Qty3, Price3
</code>```

答:
The UNION ALL method works just fine.  However, you may have different performance or readability with CROSS APPLY:

```<code>SELECT t1.Customer,
    t1.[Date],
    x.[Desc],
    x.Qty,
    x.Price
FROM UnnamedTable t1
CROSS APPLY (
    VALUES (Desc1, Qty1, Price1),
        (Desc2, Qty2, Price2),
        (Desc3, Qty3, Price3)
    ) x ([Desc], Qty, Price);
</code>```

That's assuming that each repeating group is really the same data type.  That is, Qty1, Qty2, and Qty3 are all int (or similar), and so on.

Alternately, you could use an UNPIVOT expression, but, honestly, I find UNPIVOT's syntax to be extremely arcane.

Body:
Is there a better way of doing this , I am using SQL Server 2012.

I have a table built by as vendor that looks like the below:

Customer, Date, Desc1, Qty1, Price1, Desc2, Qty2, Price2, Desc3, Qty3, Price3

I want a result set that returns this;

Customer, Date, Desc, Qty, Price

I am doing it today by the following solution , anyone have something better or more efficient?

Select Customer, Date, Desc1, Qty1, Price1
UNION ALL
Select Customer, Date, Desc2, Qty2, Price2
UNION ALL
Select Customer, Date, Desc3, Qty3, Price3

Body:
The UNION ALL method works just fine.  However, you may have different performance or readability with CROSS APPLY:

SELECT t1.Customer,
    t1.[Date],
    x.[Desc],
    x.Qty,
    x.Price
FROM UnnamedTable t1
CROSS APPLY (
    VALUES (Desc1, Qty1, Price1),
        (Desc2, Qty2, Price2),
        (Desc3, Qty3, Price3)
    ) x ([Desc], Qty, Price);

That's assuming that each repeating group is really the same data type.  That is, Qty1, Qty2, and Qty3 are all int (or similar), and so on.

Alternately, you could use an UNPIVOT expression, but, honestly, I find UNPIVOT's syntax to be extremely arcane.


答:
Here is an alternative for SQL Server; it uses cross apply and values and it is an efficient and very flexible substitute for the unpivot command and is really useful for "normalizing" data.

```<code>select Customer, Date, ca.description, ca.qty, ca.price
from YourTable
cross apply (
   values
      (Desc1, Qty1, Price1)
    , (Desc2, Qty2, Price2)
    , (Desc3, Qty3, Price3)
    , (Desc4, Qty4, Price4)
    ) ca (description, qty, price)
</code>```

NB: Each row within the values area forms a new row of output, so when laid out as you see above it is visually similar to the final layout.

For more details on this see: Spotlight on UNPIVOT, Part 1 (Brad Schultz)

Title: Normalize a row of data in a query - Turn one row into many

Body:
Here is an alternative for SQL Server; it uses cross apply and values and it is an efficient and very flexible substitute for the unpivot command and is really useful for "normalizing" data.

select Customer, Date, ca.description, ca.qty, ca.price
from YourTable
cross apply (
   values
      (Desc1, Qty1, Price1)
    , (Desc2, Qty2, Price2)
    , (Desc3, Qty3, Price3)
    , (Desc4, Qty4, Price4)
    ) ca (description, qty, price)

NB: Each row within the values area forms a new row of output, so when laid out as you see above it is visually similar to the final layout.

For more details on this see: Spotlight on UNPIVOT, Part 1 (Brad Schultz)


问:
Remove a property in an object immutably
I am using Redux. In my reducer I'm trying to remove a property from an object like this:

```<code>const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}
</code>```

And I want to have something like this without having to mutate the original state:

```<code>const newState = {
    a: '1',
    b: '2',
    c: {
       x: '42',
    },
}
</code>```

I tried:

```<code>let newState = Object.assign({}, state);
delete newState.c.y
</code>```

but for some reasons, it deletes the property from both states.

Could help me to do that?

答:
I normally use

```<code>Object.assign({}, existingState, {propToRemove: undefined})
</code>```

I realise this isn't actually removing the property but for almost all purposes 1 its functionally equivalent. The syntax for this is much simpler than the alternatives which I feel is a pretty good tradeoff.

1 If you are using hasOwnProperty(), you will need to use the more complicated solution.

Body:
I am using Redux. In my reducer I'm trying to remove a property from an object like this:

const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}

And I want to have something like this without having to mutate the original state:

const newState = {
    a: '1',
    b: '2',
    c: {
       x: '42',
    },
}

I tried:

let newState = Object.assign({}, state);
delete newState.c.y

but for some reasons, it deletes the property from both states.

Could help me to do that?

Body:
I normally use

Object.assign({}, existingState, {propToRemove: undefined})

I realise this isn't actually removing the property but for almost all purposes 1 its functionally equivalent. The syntax for this is much simpler than the alternatives which I feel is a pretty good tradeoff.

1 If you are using hasOwnProperty(), you will need to use the more complicated solution.


问:
*ngFor and filter pipe
What you see:

list of the palette components that you can select

the selected palette above the list

the palette selected is not in the list anymore !WRONG!

each time you pick a palette only the one you had selected before is being drawn which causes the list to expand with duplicates

What I did:

```<code><ng-container
          *ngFor="let palette of palettes | exclude: currentPalette.name">
    <div class="span-6">
      <app-palette
              (click)="choosePalette(palette)"
              [palette]="palette"
              [name]="palette.name"
              [icon]="palette.icon.name">
      </app-palette>
    </div>
  </ng-container>
</code>```

What actually worked:

```<code><ng-container
          *ngFor="let palette of palettes">
    <div class="span-6" *ngIf="palette.name !== currentPalette.name">
      <!-- TODO pipe this to not show already selected -->
      <app-palette
              (click)="choosePalette(palette)"
              [palette]="palette"
              [name]="palette.name"
              [icon]="palette.icon.name">
      </app-palette>
    </div>
  </ng-container>
</code>```

The 'exclude' pipe is just a filter (array.filter(p => p.name !== name));

When i debug the entire thing, it shows to me that everything is being processed just fine but only the component that should show up is being redrawn, but the rest stays along with the item that should disappear. This causes items it duplicate and floods the list.

How can I do it with a pipe? Or where was I mistaken?

答:
Ok I solved it. It wasn't a problem with a pipe it was a problem with rendering DOM elements.

app-palette has [ngStyle] directive that references object like this:

```<code>[ngStyle]=palette.foregound
</code>```

just change every reference to:

```<code>[ngStyle]=palette?.foreground
</code>```

Voila!

Title: *ngFor and filter pipe

Body:
What you see:

list of the palette components that you can select

the selected palette above the list

the palette selected is not in the list anymore !WRONG!

each time you pick a palette only the one you had selected before is being drawn which causes the list to expand with duplicates

What I did:

<ng-container
          *ngFor="let palette of palettes | exclude: currentPalette.name">

      <app-palette
              (click)="choosePalette(palette)"
              [palette]="palette"
              [name]="palette.name"
              [icon]="palette.icon.name">
      </app-palette>

  </ng-container>

What actually worked:

<ng-container
          *ngFor="let palette of palettes">

      <app-palette
              (click)="choosePalette(palette)"
              [palette]="palette"
              [name]="palette.name"
              [icon]="palette.icon.name">
      </app-palette>

  </ng-container>

The 'exclude' pipe is just a filter (array.filter(p => p.name !== name));

When i debug the entire thing, it shows to me that everything is being processed just fine but only the component that should show up is being redrawn, but the rest stays along with the item that should disappear. This causes items it duplicate and floods the list.

How can I do it with a pipe? Or where was I mistaken?

Body:
Ok I solved it. It wasn't a problem with a pipe it was a problem with rendering DOM elements.

app-palette has [ngStyle] directive that references object like this:

[ngStyle]=palette.foregound

just change every reference to:

[ngStyle]=palette?.foreground

Voila!


问:
Merge data frames and replace NONE with values in R
I have two data.frames:

```<code>data.frame1:
CustID  FirstName   LastName    Address         DOB         City    Phone
132    Mary         K               999 Drive   1/1/2011    Chicago 888-0000
133    Mona         J               222 Road    1/4/2002    NY      999-8888
188    Jack         S               122 Street  9/2/2009    Washin  777-9999
None    Helen       L               111 Rd      1/4/2010
None    John        M               888 Lane    4/2/2002
None    Sally       K               222 Street  2/3/2002

data.frame2
CustID FirstName LastName Address   DOB         City
132    Mary      K        999 Drive 1/1/2011    Chicago
133    Mona      J         222 Road 1/4/2002    NY
188    Jack      S      122 Street  9/2/2009    Washington
3338    Helen   L         111 Rd    1/4/2010
882     John    M       888 Lane    4/2/2002
976    Sally    K     222 Street    2/3/2002
</code>```

Data.frame1 contains None in CustID column. I need to replace these Nones with a CustID from data.frame2 and make sure that columns FirstName, LastName, Address, DOB match from both data sets, because some names can match from both data sets but have different address and DOB - these are not the same people.
I have converted these columns into character from factor (not sure if it matters), and applied match() function but received 0 matches (which i know is wrong)
this is my code:

```<code>data.frame1$ID[match(c(data.framr2$'FirstName',
                     data.frame2$'LastName',
                     data.frame2$'DOB',
                     data.frame2$'Address'),
                     c(data.frame1$'FirstName',
                     data.frame1$'LastName',
                     data.frame1$'DOB',
                     data.frame1$'Address'))]
</code>```

答:
This code should illustrate how you have to proceed:

merge the data.frames by "fname" and "lname" (consider only the rows where id is missing)

select the "id" column of the merged data.frame and copy it to df1

Example

```<code>df1 <- data.frame(id=c(NA, 12, NA, 13),
    fname=c("A","B","Z","D"),
    lname=c("1","2","3","4"))

df2 <- data.frame(id=c(1, 21, 33, 44),
    fname=c("Z","A","A","Z")  ,
    lname=c("1","3","1","3"))

df1[!complete.cases(df1),1] <- merge(
    x=df1[!complete.cases(df1[,"id"]),],
    y=df2,
    by=c("fname", "lname"))[,"id.y"]
</code>```

Body:
I have two data.frames:

data.frame1:
CustID  FirstName   LastName    Address         DOB         City    Phone
132    Mary         K               999 Drive   1/1/2011    Chicago 888-0000
133    Mona         J               222 Road    1/4/2002    NY      999-8888
188    Jack         S               122 Street  9/2/2009    Washin  777-9999
None    Helen       L               111 Rd      1/4/2010
None    John        M               888 Lane    4/2/2002
None    Sally       K               222 Street  2/3/2002

data.frame2
CustID FirstName LastName Address   DOB         City
132    Mary      K        999 Drive 1/1/2011    Chicago
133    Mona      J         222 Road 1/4/2002    NY
188    Jack      S      122 Street  9/2/2009    Washington
3338    Helen   L         111 Rd    1/4/2010
882     John    M       888 Lane    4/2/2002
976    Sally    K     222 Street    2/3/2002

Data.frame1 contains None in CustID column. I need to replace these Nones with a CustID from data.frame2 and make sure that columns FirstName, LastName, Address, DOB match from both data sets, because some names can match from both data sets but have different address and DOB - these are not the same people.
I have converted these columns into character from factor (not sure if it matters), and applied match() function but received 0 matches (which i know is wrong)
this is my code:

data.frame1$ID[match(c(data.framr2$'FirstName',
                     data.frame2$'LastName',
                     data.frame2$'DOB',
                     data.frame2$'Address'),
                     c(data.frame1$'FirstName',
                     data.frame1$'LastName',
                     data.frame1$'DOB',
                     data.frame1$'Address'))]

Body:
This code should illustrate how you have to proceed:

merge the data.frames by "fname" and "lname" (consider only the rows where id is missing)

select the "id" column of the merged data.frame and copy it to df1

Example

df1 <- data.frame(id=c(NA, 12, NA, 13),
    fname=c("A","B","Z","D"),
    lname=c("1","2","3","4"))

df2 <- data.frame(id=c(1, 21, 33, 44),
    fname=c("Z","A","A","Z")  ,
    lname=c("1","3","1","3"))

df1[!complete.cases(df1),1] <- merge(
    x=df1[!complete.cases(df1[,"id"]),],
    y=df2,
    by=c("fname", "lname"))[,"id.y"]


问:
RMAN error during auxillary backup
I am getting ORA error while doing Auxillary cloning for database from two different server using RMAN backup while using below command:-

```<code>duplicate database to "HFSDBRED" backup location '/orabackup/RMAN/HFSDBRED_BKP' nofilenamecheck set DB_FILE_NAME_CONVERT=('/oradata/HFSDBPRD/datafile','/oradata/HFSDBRED/datafile') set LOG_FILE_NAME_CONVERT=('/oradata/HFSDBPRD/onlinelog','/oradata/HFSDBRED/onlinelog','/optware/oracle/HFSDBPRD/onlinelog','/optware/oracle/HFSDBRED/onlinelog');
</code>```

Error:-

```<code>RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-00558: error encountered while parsing input commands
RMAN-01009: syntax error: found "identifier": expecting one of: "backup, db_file_name_convert, device, dorecover, force, from, high, logfile, nofilenamecheck, noredo, noresume, open, password, pfile, skip readonly, skip, spfile, tablespace, to restore point, undo, until restore point, until, ;"
RMAN-01008: the bad identifier was: LOG_FILE_NAME_CONVERT
RMAN-01007: at line 3 column 1 file: standard input
</code>```

答:
you should use DB & LOG_FILE_NAME_CONVERT values without paranthesis, as follows :

```<code>set DB_FILE_NAME_CONVERT='/oradata/HFSDBPRD/datafile','/oradata/HFSDBRED/datafile'
set LOG_FILE_NAME_CONVERT='/oradata/HFSDBPRD/onlinelog','/oradata/HFSDBRED/onlinelog','/optware/oracle/HFSDBPRD/onlinelog','/optware/oracle/HFSDBRED/onlinelog'
</code>```

Title: RMAN error during auxillary backup

Body:
I am getting ORA error while doing Auxillary cloning for database from two different server using RMAN backup while using below command:-

duplicate database to "HFSDBRED" backup location '/orabackup/RMAN/HFSDBRED_BKP' nofilenamecheck set DB_FILE_NAME_CONVERT=('/oradata/HFSDBPRD/datafile','/oradata/HFSDBRED/datafile') set LOG_FILE_NAME_CONVERT=('/oradata/HFSDBPRD/onlinelog','/oradata/HFSDBRED/onlinelog','/optware/oracle/HFSDBPRD/onlinelog','/optware/oracle/HFSDBRED/onlinelog');

Error:-

RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-00558: error encountered while parsing input commands
RMAN-01009: syntax error: found "identifier": expecting one of: "backup, db_file_name_convert, device, dorecover, force, from, high, logfile, nofilenamecheck, noredo, noresume, open, password, pfile, skip readonly, skip, spfile, tablespace, to restore point, undo, until restore point, until, ;"
RMAN-01008: the bad identifier was: LOG_FILE_NAME_CONVERT
RMAN-01007: at line 3 column 1 file: standard input

Body:
you should use DB & LOG_FILE_NAME_CONVERT values without paranthesis, as follows :

set DB_FILE_NAME_CONVERT='/oradata/HFSDBPRD/datafile','/oradata/HFSDBRED/datafile'
set LOG_FILE_NAME_CONVERT='/oradata/HFSDBPRD/onlinelog','/oradata/HFSDBRED/onlinelog','/optware/oracle/HFSDBPRD/onlinelog','/optware/oracle/HFSDBRED/onlinelog'


问:
Ploting a Buffer Around a Point on a Map - R SF
I've been trying to plot a buffer around a point on a map but when I do the buffer doesn't appear in the right place like this.

Faulty R Map

The correct location is in California.

Here's my code:

```<code>library(tigris)
library(sf)
library(tidyverse)

projection <- 102003

options(tigris_use_cache =  TRUE)
county_polys <- counties(class = 'sf') %>%
  filter(STATEFP %in% c('06','41','53','04','16','32','49')) %>%
  st_transform(projection)

  centroids <- county_polys %>%
  as_tibble %>% select(INTPTLON,INTPTLAT) %>%
  mutate(
    INTPTLON = as.double(INTPTLON),
    INTPTLAT = as.double(INTPTLAT)) %>%
  st_as_sf(coords = c('INTPTLON','INTPTLAT'), crs = projection)

 pt <- centroids[2,]
 pt_buffer <- st_buffer(pt,150000)

 ggplot() + geom_sf(data = county_polys) + geom_sf(data = pt_buffer,color = 'red')
</code>```

答:
We can use the st_centroid function to get the centroid to avoid errors. There is no need to convert the sf object to other classes.

```<code># This is the only thing I changed from your original code
# Get the centroid by st_centroid
centroids <- county_polys %>% st_centroid()

pt <- centroids[2,]
pt_buffer <- st_buffer(pt,150000)

ggplot() + geom_sf(data = county_polys) + geom_sf(data = pt_buffer,color = 'red')
</code>```

Body:
I've been trying to plot a buffer around a point on a map but when I do the buffer doesn't appear in the right place like this.

Faulty R Map

The correct location is in California.

Here's my code:

library(tigris)
library(sf)
library(tidyverse)

projection <- 102003

options(tigris_use_cache =  TRUE)
county_polys <- counties(class = 'sf') %>%
  filter(STATEFP %in% c('06','41','53','04','16','32','49')) %>%
  st_transform(projection)

  centroids <- county_polys %>%
  as_tibble %>% select(INTPTLON,INTPTLAT) %>%
  mutate(
    INTPTLON = as.double(INTPTLON),
    INTPTLAT = as.double(INTPTLAT)) %>%
  st_as_sf(coords = c('INTPTLON','INTPTLAT'), crs = projection)

 pt <- centroids[2,]
 pt_buffer <- st_buffer(pt,150000)

 ggplot() + geom_sf(data = county_polys) + geom_sf(data = pt_buffer,color = 'red')

Body:
We can use the st_centroid function to get the centroid to avoid errors. There is no need to convert the sf object to other classes.

# This is the only thing I changed from your original code
# Get the centroid by st_centroid
centroids <- county_polys %>% st_centroid()

pt <- centroids[2,]
pt_buffer <- st_buffer(pt,150000)

ggplot() + geom_sf(data = county_polys) + geom_sf(data = pt_buffer,color = 'red')


问:
How can I change div content with JavaScript?
I have simple HTML code with some JavaScript. It looks like:

  <input type="radio" name="radiobutton" value="A" onClick="changeDivContent()">
  <input type="radio" name="radiobutton" value="B" onClick="changeDivContent()">

```

I just wanted to be able to change the div's content (it's inner html) with selecting one of "A" or "B" radio buttons, but div#content does not have javascript attribute "value", so I am asking how it can be done.

答:
```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="radio" name="radiobutton" value="A" onclick = "populateData(event)">
  <input type="radio" name="radiobutton" value="B" onclick = "populateData(event)">

    <div id="content"></div>
</body>
</html>
</code>```

-----------------JS- code------------

```<code>var targetDiv = document.getElementById('content');
    var htmlContent = '';

    function populateData(event){
      switch(event.target.value){
        case 'A':{
         htmlContent = 'Content for A';
          break;
        }
        case 'B':{
          htmlContent = "content for B";
break;
        }
      }
      targetDiv.innerHTML = htmlContent;
    }
</code>```

```<code>Step1: on click of the radio button it calls function populate data, with event (an object that has event details such as name of the element, value etc..);

Step2: I extracted the value through event.target.value and then simple switch will give me freedom to add custom text.
</code>```

Live Code

https://jsbin.com/poreway/edit?html,js,output

Body:
I have simple HTML code with some JavaScript. It looks like:

  <input type="radio" name="radiobutton" value="A" onClick="changeDivContent()">
  <input type="radio" name="radiobutton" value="B" onClick="changeDivContent()">

I just wanted to be able to change the div's content (it's inner html) with selecting one of "A" or "B" radio buttons, but div#content does not have javascript attribute "value", so I am asking how it can be done.

Body:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="radio" name="radiobutton" value="A" onclick = "populateData(event)">
  <input type="radio" name="radiobutton" value="B" onclick = "populateData(event)">

    <div id="content"></div>
</body>
</html>

-----------------JS- code------------

var targetDiv = document.getElementById('content');
    var htmlContent = '';

    function populateData(event){
      switch(event.target.value){
        case 'A':{
         htmlContent = 'Content for A';
          break;
        }
        case 'B':{
          htmlContent = "content for B";
break;
        }
      }
      targetDiv.innerHTML = htmlContent;
    }

Step1: on click of the radio button it calls function populate data, with event (an object that has event details such as name of the element, value etc..);

Step2: I extracted the value through event.target.value and then simple switch will give me freedom to add custom text.

Live Code

https://jsbin.com/poreway/edit?html,js,output


问:
How to debug a stackoverflowexception in .NET
Scenario:

I've just been on a roll and implemented a bunch of code, but when I execute it I get thrown a StackOverflowException? The StackOverflowException doesn't have a stacktrace so I'm stuck. I know why a stack overflow might occur, but to fix it I need to know where it's root is.

All I'm getting is: An unhandled exception of type 'System.StackOverflowException' occurred in tag-you're-it.dll

Options:

Scan through all the changes and try to pin point the problem. (could be slow)

Use a debugger and step through till you find the problem. (probably better than 1.)

Use a profile and look for the most called methods.

?

PS:

This is a hypothetical situation (although not too uncommon) and therefore no code is available.

答:
At the method that is the "entry point" to the operation that fails, put a breakpoint. Step through the code and watch for occurrences of the same sequence of method calls happening over and over in an identical pattern so the call stack gets deeper and deeper.

As soon as you notice that, put a breakpoint at the current location, wherever that is. Continue execution (F5 in Visual Studio) - if you're on the right track then the debugger will stop very quickly at the same location, and the call stack will be even deeper.

Now you have a "live" stack frame you can examine, in order to figure out how to ensure that this recursion will properly terminate.


问:
Magento2 Custom Widget Not Appearing
I created a module with a Custom Widget. When logging into the admin, going to content->widgets, creating an instance, and setting that instance to appear on the homepage, the widget appears as expected.

I have removed this instance and am now trying to create the widget by going to content->pages, editing the homepage -> content section, and selecting insert widget. I created a new instance of the widget and added some additional text into the homepage -> content section.

When I load the homepage the widget does not appear, though the rest of the text does appear.

The block for the widget is being called ( I tested this with a var_dump and exit).

The template is not being rendered however.

Here is my Block:

```<code><?php

namespace MyNamespace\Slider\Block\Widget;

use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Block\Product\Context;

class Slider extends Template
{
    protected $_template = "Yamazaki_Slider::widget/slider.phtml";

    /**
     * @var CollectionFactory
     */
    protected $_productCollectionFactory;

    /**
     * @var CollectionFactory
     */
    protected $_imageHelper;

    /**
     * @param Context $context
     * @param CollectionFactory $productCollectionFactory
     */
    public function __construct(Context $context, CollectionFactory $productCollectionFactory)
    {
        $this->_imageHelper = $context->getImageHelper();
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context);
    }

    /**
     * Retrieve featured products collection
     */
    public function getProducts()
    {
        $collection = $this->_productCollectionFactory->create();
        return $collection->addAttributeToSelect('*')->addAttributeToFilter('is_featured','1');
    }
}
</code>```

and my Template:

```<code><?php $imageBlock = $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct'); ?>

<?php foreach($this->getProducts() as $product): ?>
    <?php $productImage = $imageBlock->getImage($product, 'product_page_image_large'); ?>
    <?php echo $productImage->toHtml(); ?>
<?php endforeach ?>
</code>```

The other files in my module are:

etc/widget.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
<widget id="yamazaki_slider" class="MyNamespace\Slider\Block\Widget\Slider">
    <label translate="true">My Image Slider</label>
    <description>My Image Slider</description>
</widget>
</widgets>
</code>```

module.xml and registration.php.

I do not have a etc/layout.xml file as I have noticed some widget/modules contain. Do I need this, or any other files?

Also, If I "Hide the Editor" inside content->pages->edit->content I see:

```<code><p>{{widget type="MyNamespace\Slider\Block\Widget\Slider"}}</p>`
</code>```

If I replace this with

```<code>{{block class="MyNamespace\Slider\Block\Widget\Slider" template="widget/slider.phtml"}}
</code>```

The Content appears as expected

答:
I managed to get the Block to Render

I had to add implements \Magento\Widget\Block\BlockInterface to  MyNamespace\Slider\Block\Widget\Slider.

I'm not sure why this rendered, prior to adding the implements, using the first approach and not the second.

Magento is seriously lacking documentation!

Title: Magento2 Custom Widget Not Appearing

Body:
I created a module with a Custom Widget. When logging into the admin, going to content->widgets, creating an instance, and setting that instance to appear on the homepage, the widget appears as expected.

I have removed this instance and am now trying to create the widget by going to content->pages, editing the homepage -> content section, and selecting insert widget. I created a new instance of the widget and added some additional text into the homepage -> content section.

When I load the homepage the widget does not appear, though the rest of the text does appear.

The block for the widget is being called ( I tested this with a var_dump and exit).

The template is not being rendered however.

Here is my Block:

<?php

namespace MyNamespace\Slider\Block\Widget;

use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Block\Product\Context;

class Slider extends Template
{
    protected $_template = "Yamazaki_Slider::widget/slider.phtml";

    /**
     * @var CollectionFactory
     */
    protected $_productCollectionFactory;

    /**
     * @var CollectionFactory
     */
    protected $_imageHelper;

    /**
     * @param Context $context
     * @param CollectionFactory $productCollectionFactory
     */
    public function __construct(Context $context, CollectionFactory $productCollectionFactory)
    {
        $this->_imageHelper = $context->getImageHelper();
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context);
    }

    /**
     * Retrieve featured products collection
     */
    public function getProducts()
    {
        $collection = $this->_productCollectionFactory->create();
        return $collection->addAttributeToSelect('*')->addAttributeToFilter('is_featured','1');
    }
}

and my Template:

<?php $imageBlock = $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct'); ?>

<?php foreach($this->getProducts() as $product): ?>
    <?php $productImage = $imageBlock->getImage($product, 'product_page_image_large'); ?>
    <?php echo $productImage->toHtml(); ?>
<?php endforeach ?>

The other files in my module are:

etc/widget.xml:

<?xml version="1.0" encoding="UTF-8"?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
<widget id="yamazaki_slider" class="MyNamespace\Slider\Block\Widget\Slider">
    My Image Slider
    <description>My Image Slider</description>
</widget>
</widgets>

module.xml and registration.php.

I do not have a etc/layout.xml file as I have noticed some widget/modules contain. Do I need this, or any other files?

Also, If I "Hide the Editor" inside content->pages->edit->content I see:

{{widget type="MyNamespace\Slider\Block\Widget\Slider"}}
`

If I replace this with

{{block class="MyNamespace\Slider\Block\Widget\Slider" template="widget/slider.phtml"}}

The Content appears as expected


答:
You can also see the answer to this question about transposing lists of lists, and do something like:

```<code>at = list(map(list, zip(*a)))
b = at[0][1:3]
</code>```

Though as someone has mentioned in the comments, if you're going to be doing a lot of matrix manipulation, you'd be better off using NumPy.

Title: selecting specific part of array

Body:
Lets say I have an array

a = [[[1, 2], [3, 4]],
     [[5, 6], [7, 8]],
     [[9, 10], [11, 12]],
     [[13, 14], [15, 16]],
     [[17, 18], [19, 20]]]

At the end I would like an array

b = [[[5, 6]],[[9, 10]]]

I thought that

b = a[1:3][0:1]

would work. But from that i get

b=[[[5, 6], [7, 8]]]

Body:
You can also see the answer to this question about transposing lists of lists, and do something like:

at = list(map(list, zip(*a)))
b = at[0][1:3]

Though as someone has mentioned in the comments, if you're going to be doing a lot of matrix manipulation, you'd be better off using NumPy.


问:
How do you find out the caller function in JavaScript?
```<code>function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is 'main'?
}
</code>```

Is there a way to find out the call stack?

答:
I would do this:</p>

```<code>function Hello() {
  console.trace();
}
</code>```

OwnerDisplayName: CodeMeIt

Body:
function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is 'main'?
}

Is there a way to find out the call stack?

LastEditorDisplayName: Tomalak

Body:
I would do this:

function Hello() {
  console.trace();
}


问:
While loop with two variables (using the "or" section in python)
I have written a program that serves the starting basis for a login menu. It should only allow two inputs; "1" or "2". If they enter 1, they continue as an existing user, but if they enter 2 they continue as a new user. I have a while loop to prevent the user from inputting anything besides these two values.

Why does the code only allow the user to input a "1" to continue the code, but not the "2". I've looked online, but I haven't seen the way people would code or in a while loop. Could anyone make the necessary adjustments to the or so that it works? Thanks.

Edit: Best response by "bastelflp".

```<code>#Program menu
YESorNo = input("""
[---------------------------------]

      Welcome to the program!

[---------------------------------]

     Are you an existing user?

 1. [YES]
 2. [NO]

-----------------------------------
Type [1] for "YES" or [2] for "NO".

""")

while YESorNo.strip() != ("1" or "2"):
    YESorNo = input("""
[---------------------------------]

     Welcome to the program!

[---------------------------------]

     Are you an existing user?

 1. [YES]
 2. [NO]

-----------------------------------
Type [1] for "YES" or [2] for "NO".

""")

if YESorNo == "1":
        print("Welcome back!")

elif YESorNo == "2":
        print("Welcome!")
</code>```

答:
```<code>YESorNo.strip() != ("1" or "2")
</code>```

Since or is an operator, "1" or "2" is evaluated before the comparison. The string "1" is truthy, so the result of "1" or "2" is "1". So the original expression simplifies to YESorNO.strip() != "1". For more details, I suggest you read about truthiness in Python. Also you should learn more about the order of evaluation of operators.

To fix the problem you can do this instead:

```<code>YESorNo.strip() != "1" and YESorNo.strip() != "2"
</code>```

or this:

```<code>not (YESorNo.strip() == "1" or YESorNo.strip() == "2")
</code>```

or this:

```<code>YESorNo.strip() not in ["1", "2"]
</code>```

The first two take advantage of the correct order of operation evaluation to do what you want. The last alternative uses a list of options to compare against, which is closer to your original code.

Body:
I have written a program that serves the starting basis for a login menu. It should only allow two inputs; "1" or "2". If they enter 1, they continue as an existing user, but if they enter 2 they continue as a new user. I have a while loop to prevent the user from inputting anything besides these two values.

Why does the code only allow the user to input a "1" to continue the code, but not the "2". I've looked online, but I haven't seen the way people would code or in a while loop. Could anyone make the necessary adjustments to the or so that it works? Thanks.

Edit: Best response by "bastelflp".

#Program menu
YESorNo = input("""
[---------------------------------]

      Welcome to the program!

[---------------------------------]

     Are you an existing user?

 1. [YES]
 2. [NO]

-----------------------------------
Type [1] for "YES" or [2] for "NO".

""")

while YESorNo.strip() != ("1" or "2"):
    YESorNo = input("""
[---------------------------------]

     Welcome to the program!

[---------------------------------]

     Are you an existing user?

 1. [YES]
 2. [NO]

-----------------------------------
Type [1] for "YES" or [2] for "NO".

""")

if YESorNo == "1":
        print("Welcome back!")

elif YESorNo == "2":
        print("Welcome!")

Body:
YESorNo.strip() != ("1" or "2")

Since or is an operator, "1" or "2" is evaluated before the comparison. The string "1" is truthy, so the result of "1" or "2" is "1". So the original expression simplifies to YESorNO.strip() != "1". For more details, I suggest you read about truthiness in Python. Also you should learn more about the order of evaluation of operators.

To fix the problem you can do this instead:

YESorNo.strip() != "1" and YESorNo.strip() != "2"

or this:

not (YESorNo.strip() == "1" or YESorNo.strip() == "2")

or this:

YESorNo.strip() not in ["1", "2"]

The first two take advantage of the correct order of operation evaluation to do what you want. The last alternative uses a list of options to compare against, which is closer to your original code.


问:
jQuery table sort change the color of sorted by column:
I have a following html table and jQuery function to sort the table by table header columns:

//sort summary table
$('th').click(function() {
  var table = $(this).parents('table').eq(0)
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
  this.asc = !this.asc;
  if (!this.asc) {
    rows = rows.reverse();
  }

  for (var i = 0; i < rows.length; i++) {
    table.append(rows[i]);
  }
});

function comparer(index) {
  return function(a, b) {
 var valA = getCellValue(a, index),
        valB = getCellValue(b, index)
    return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
  }
}

function getCellValue(row, index) {
  return $(row).children('td').eq(index).text();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
 <tr>
   <th>S.No.</th>
   <th>School</th>
   <th>Campus City / State</th>
   <th>Campaign Name</th>
   <th>Work Order</th>
 </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>EL PASO UNIVERSITY</td>
      <td> EL PASO/TX</td>
      <td>Full Campaign</td>
      <td>#10055</td>
    </tr>
    <tr>
      <td>2</td>
      <td>DALLAS UNIVERSITY</td>
      <td> DALLAS/TX</td>
      <td>Mini Campaign</td>
      <td>#10056</td>
    </tr>
    <tr>
    <td>3</td>
          <td>MINNESOTA UNIVERSITY</td>
      <td> MINNEAPOLIS/MN</td>
      <td>Full Campaign</td>
      <td>#10059</td>
    </tr>
  </tbody>
</table></code>```

All the functionality for sorting table is working fine. But couldn't figure out how to let user know current ordering of
table is sorted by which column. I just want to add simple css color to separate the currently clicked column. Any idea?

答:
Adding the css colors to all headers except the clicked one will do the trick. This can be achieved by something like:

```<code>$('th').css({'background-color' : '#808080'});
$('th').css({'color' : '#FFFFFF'});
$(this).css('background-color', '#6f3d3d'); //change the background color
$(this).css({'color' : '#0000FF'});    //change the font color
</code>```

Just add the above code to your function:

//sort summary table
$('th').click(function(){
  //add your css trick
  $('th').css({'background-color' : '#808080'});
  $('th').css({'color' : '#FFFFFF'});
  $(this).css('background-color', '#6f3d3d');
  $(this).css({'color' : '#0000FF'});

  var table = $(this).parents('table').eq(0)
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
  this.asc = !this.asc
  if (!this.asc) {
    rows = rows.reverse();
  }
  for (var i = 0; i < rows.length; i++) {
    table.append(rows[i]);
  }
});

function comparer(index) {
  return function(a, b) {
    var valA = getCellValue(a, index),
        valB = getCellValue(b, index)
      return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
  }
}

function getCellValue(row, index) {
  return $(row).children('td').eq(index).text();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>S.No.</th>
      <th>School</th>
      <th>Campus City / State</th>
      <th>Campaign Name</th>
      <th>Work Order</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>EL PASO UNIVERSITY</td>
      <td> EL PASO/TX</td>
      <td>Full Campaign</td>
      <td>#10055</td>
    </tr>
    <tr>
      <td>2</td>
      <td>DALLAS UNIVERSITY</td>
      <td> DALLAS/TX</td>
      <td>Mini Campaign</td>
      <td>#10056</td>
    </tr>
    <tr>
      <td>3</td>
      <td>MINNESOTA UNIVERSITY</td>
      <td> MINNEAPOLIS/MN</td>
      <td>Full Campaign</td>
      <td>#10059</td>
    </tr>
  </tbody>
</table></code>```

Body:
I have a following html table and jQuery function to sort the table by table header columns:

//sort summary table
$('th').click(function() {
  var table = $(this).parents('table').eq(0)
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
  this.asc = !this.asc;
  if (!this.asc) {
    rows = rows.reverse();
  }

  for (var i = 0; i < rows.length; i++) {
    table.append(rows[i]);
  }
});

function comparer(index) {
  return function(a, b) {
 var valA = getCellValue(a, index),
        valB = getCellValue(b, index)
    return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
  }
}

function getCellValue(row, index) {
  return $(row).children('td').eq(index).text();
}

   S.No.
   School
   Campus City / State
   Campaign Name
   Work Order

      1
      EL PASO UNIVERSITY
       EL PASO/TX
      Full Campaign
      #10055

      2
      DALLAS UNIVERSITY
       DALLAS/TX
      Mini Campaign
      #10056

    3
          MINNESOTA UNIVERSITY
       MINNEAPOLIS/MN
      Full Campaign
      #10059

All the functionality for sorting table is working fine. But couldn't figure out how to let user know current ordering of
table is sorted by which column. I just want to add simple css color to separate the currently clicked column. Any idea?

Body:
Adding the css colors to all headers except the clicked one will do the trick. This can be achieved by something like:

$('th').css({'background-color' : '#808080'});
$('th').css({'color' : '#FFFFFF'});
$(this).css('background-color', '#6f3d3d'); //change the background color
$(this).css({'color' : '#0000FF'});    //change the font color

Just add the above code to your function:

//sort summary table
$('th').click(function(){
  //add your css trick
  $('th').css({'background-color' : '#808080'});
  $('th').css({'color' : '#FFFFFF'});
  $(this).css('background-color', '#6f3d3d');
  $(this).css({'color' : '#0000FF'});

  var table = $(this).parents('table').eq(0)
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
  this.asc = !this.asc
  if (!this.asc) {
    rows = rows.reverse();
  }
  for (var i = 0; i < rows.length; i++) {
    table.append(rows[i]);
  }
});

function comparer(index) {
  return function(a, b) {
    var valA = getCellValue(a, index),
        valB = getCellValue(b, index)
      return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
  }
}

function getCellValue(row, index) {
  return $(row).children('td').eq(index).text();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>S.No.</th>
      <th>School</th>
      <th>Campus City / State</th>
      <th>Campaign Name</th>
      <th>Work Order</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>EL PASO UNIVERSITY</td>
      <td> EL PASO/TX</td>
      <td>Full Campaign</td>
      <td>#10055</td>
    </tr>
    <tr>
      <td>2</td>
      <td>DALLAS UNIVERSITY</td>
      <td> DALLAS/TX</td>
      <td>Mini Campaign</td>
      <td>#10056</td>
    </tr>
    <tr>
      <td>3</td>
      <td>MINNESOTA UNIVERSITY</td>
      <td> MINNEAPOLIS/MN</td>
      <td>Full Campaign</td>
      <td>#10059</td>
    </tr>
  </tbody>
</table>


问:
Alarm Even Application Closed in iPhone
I am working on iPhone application in which there is an option for Alarm. Is it possible to araise alarm even my application close.</p>

答: Use local notification available in 4.0. for a tutorial see this link</p>

Title: Alarm Even Application Closed in iPhone


问:
How to avoid content inside

 being cut off while printing in html
I have a lot of content inside a ``` tag that I am printing. I am using media queries for the print style. Everything is fine except that the last line on the first page is cut. Half of it remains on the first page and the other half is displayed on the next page. I don't know how to shift the overflow to the next page.

答:
I figured it out. I had to add the following to the style sheet.</p>

```<code>pre
{
display:inline;
}
</code>```

Body:
I have a lot of content inside a
 tag that I am printing. I am using media queries for the print style. Everything is fine except that the last line on the first page is cut. Half of it remains on the first page and the other half is displayed on the next page. I don't know how to shift the overflow to the next page.

Body:
I figured it out. I had to add the following to the style sheet.

pre
{
display:inline;
}


答:
```<code>YESorNo.strip() != ("1" or "2")
</code>```

This will get evaluated in the following order;

Brackets first

```<code>YESorNo.strip() != "1"
</code>```

Then equality.

You need to do either this;

```<code>YESorNo.strip() not in ("1", "2")
</code>```

or

```<code>not (YESorNo.strip() != "1" and YESorNo.strip() != "2")
</code>```

Title: While loop with two variables (using the "or" section in python)

Body:
YESorNo.strip() != ("1" or "2")

This will get evaluated in the following order;

Brackets first

YESorNo.strip() != "1"

Then equality.

You need to do either this;

YESorNo.strip() not in ("1", "2")

or

not (YESorNo.strip() != "1" and YESorNo.strip() != "2")


问:
PreparedStatement setNull in SELECT query
I am using Postgresql together with HikariCP and my query is something like

SELECT * FROM my_table WHERE int_val = ? ...

Now, I would like to set NULL value to my variables - I have tried

```<code>ps.setNull(1, Types.INTEGER); // ps is instance of PreparedStatement
try (ResultSet rs = ps.executeQuery()) {
... // get result from resultset
}
</code>```

Although I have rows matching the conditions ( NULL in column 'int_val'), I have not received any records..

The problem is (I think) in query produced by the Statement, looks like:

```<code>System.out.println(ps.toString());
// --> SELECT * FROM my_table WHERE int_val = NULL ...
</code>```

But the query should look like:

"SELECT * FROM my_table WHERE int_val IS NULL ..." - this query works

I need to use dynamically create PreparedStatements which will contain NULL values, so I cannot somehow easily bypass this.

I have tried creating connection without the HikariCP with the same result, so I thing the problem is in the postgresql driver? Or am I doing something wrong?

UPDATE:

Based on answer from @Vao Tsun I have set transform_null_equals = on in postgresql.conf , which started changing val = null --> val is null in 'simple' Statements, but NOT in PreparedStatements..

To summarize:

```<code>try (ResultSet rs = st.executeQuery(SELECT * FROM my_table WHERE int_val = NULL)){
  // query is replaced to '.. int_val IS NULL ..' and gets correct result
}

ps.setNull(1, Types.INTEGER);
try (ResultSet rs = ps.executeQuery()) {
  // Does not get replaced and does not get any result
}
</code>```

I am using JVM version 1.8.0_121, the latest postgres driver (42.1.4), but I have also tried older driver (9.4.1212). Database version -- PostgreSQL 9.6.2, compiled by Visual C++ build 1800, 64-bit.

答:
It is meant behaviour that comparison x = null is equal to null (no matter what x is equal to). Basically for SQL NULL is unknown, not the actual value... To bypass it you can set transform_null_equals to on or true. Please checkout docs:

https://www.postgresql.org/docs/current/static/functions-comparison.html

Some applications might expect that expression = NULL returns true if
  expression evaluates to the null value. It is highly recommended that
  these applications be modified to comply with the SQL standard.
  However, if that cannot be done the transform_null_equals
  configuration variable is available. If it is enabled, PostgreSQL will
  convert x = NULL clauses to x IS NULL.

Body:
I am using Postgresql together with HikariCP and my query is something like

SELECT * FROM my_table WHERE int_val = ? ...

Now, I would like to set NULL value to my variables - I have tried

ps.setNull(1, Types.INTEGER); // ps is instance of PreparedStatement
try (ResultSet rs = ps.executeQuery()) {
... // get result from resultset
}

Although I have rows matching the conditions ( NULL in column 'int_val'), I have not received any records..

The problem is (I think) in query produced by the Statement, looks like:

System.out.println(ps.toString());
// --> SELECT * FROM my_table WHERE int_val = NULL ...

But the query should look like:

"SELECT * FROM my_table WHERE int_val IS NULL ..." - this query works

I need to use dynamically create PreparedStatements which will contain NULL values, so I cannot somehow easily bypass this.

I have tried creating connection without the HikariCP with the same result, so I thing the problem is in the postgresql driver? Or am I doing something wrong?

UPDATE:

Based on answer from @Vao Tsun I have set transform_null_equals = on in postgresql.conf , which started changing val = null --> val is null in 'simple' Statements, but NOT in PreparedStatements..

To summarize:

try (ResultSet rs = st.executeQuery(SELECT * FROM my_table WHERE int_val = NULL)){
  // query is replaced to '.. int_val IS NULL ..' and gets correct result
}

ps.setNull(1, Types.INTEGER);
try (ResultSet rs = ps.executeQuery()) {
  // Does not get replaced and does not get any result
}

I am using JVM version 1.8.0_121, the latest postgres driver (42.1.4), but I have also tried older driver (9.4.1212). Database version -- PostgreSQL 9.6.2, compiled by Visual C++ build 1800, 64-bit.


答:
You just need to add a condition to your JS that will check if this column is currently the sorted-by column,

```<code>$('th').click(function() {
  if (!$(this).hasClass('sort-by')) {
    $('th').removeClass('sort-by');
    $(this).addClass('sort-by');
    // logic for sorting by this column
  }
});
</code>```

and add a simple rule to your CSS

```<code>.sort-by {
  background-color: blue; // or whatever
}
</code>```

Title: jQuery table sort change the color of sorted by column:

Body:
You just need to add a condition to your JS that will check if this column is currently the sorted-by column,

$('th').click(function() {
  if (!$(this).hasClass('sort-by')) {
    $('th').removeClass('sort-by');
    $(this).addClass('sort-by');
    // logic for sorting by this column
  }
});

and add a simple rule to your CSS

.sort-by {
  background-color: blue; // or whatever
}


问:
Javascript: Remove class from siblings and children of click target
I am trying to build something akin to the OS X Finder. Select an element from a top level list and add class to it for styling and to show child list, then select an element of child list. I have this working. The problem is removing the "active" class from the top level item when a sibling is clicked. Also, removing "active" from any child list item when a top level item is clicked.

In essence: how do I select all siblings of the click even target, and how do I select all children of the click event target.

I know this would be easy with jquery, but I am not able to use jquery on this project.

Here is what I have so far:

var allThings = document.querySelectorAll('.thing'); //all tabs on page

function clickHandler(e) {
 e.preventDefault();
 //var siblings = getSiblings(e.target);
  //console.log("siblings = " + siblings);
  //for (var i = 0; i < siblings.length; i++) {
    //siblings[i].classList.remove("active");
  //}
  //e.target.nextSibling.classList.remove("active");
  //e.target.previousSibling.classList.remove("active");
 e.target.classList.toggle("active");
};

function getSiblings(el, filter) {
  var siblings = [];
  el = el.parentNode.firstChild;
  do { if (!filter || filter(el)) siblings.push(el); }       while (el = el.nextSibling);
  return siblings;
}

for (var i = 0; i < allThings.length; i++) {
    allThings[i].onclick = clickHandler;
    //allThings[i].children.classList.remove("active");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  display: inline-block;
  vertical-align: top;
}

.thing {
  position: relative;
  background: white;
}

.thing ul {
  display: none;
}

.thing.active {
  background: #ddd;
}

.thing.active > ul {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 100%;
}</code>```

First 001

Second 001

Third 001

Third 002

First 002

Second 002

Third 011

Third 012

First 003

Second 031

Third 031

Third 032

```

https://jsfiddle.net/samhadr/ym2Lx7sn/6/

答:
A click event should do two things:

Remove class active from all sibling and descendant elements.

Add class active to the clicked element.

A querySelectorAll can help with part 1, while part 2 is quite direct:

```<code>function clickHandler( e ) {

    e.preventDefault();

    e.target.parentElement.querySelectorAll( ".active" ).forEach( e =>
        e.classList.remove( "active" ) );

    e.target.classList.add( "active" );

};
</code>```

Body:
I am trying to build something akin to the OS X Finder. Select an element from a top level list and add class to it for styling and to show child list, then select an element of child list. I have this working. The problem is removing the "active" class from the top level item when a sibling is clicked. Also, removing "active" from any child list item when a top level item is clicked.

In essence: how do I select all siblings of the click even target, and how do I select all children of the click event target.

I know this would be easy with jquery, but I am not able to use jquery on this project.

Here is what I have so far:

var allThings = document.querySelectorAll('.thing'); //all tabs on page

function clickHandler(e) {
 e.preventDefault();
 //var siblings = getSiblings(e.target);
  //console.log("siblings = " + siblings);
  //for (var i = 0; i < siblings.length; i++) {
    //siblings[i].classList.remove("active");
  //}
  //e.target.nextSibling.classList.remove("active");
  //e.target.previousSibling.classList.remove("active");
 e.target.classList.toggle("active");
};

function getSiblings(el, filter) {
  var siblings = [];
  el = el.parentNode.firstChild;
  do { if (!filter || filter(el)) siblings.push(el); }       while (el = el.nextSibling);
  return siblings;
}

for (var i = 0; i < allThings.length; i++) {
    allThings[i].onclick = clickHandler;
    //allThings[i].children.classList.remove("active");
}

ul {
  display: inline-block;
  vertical-align: top;
}

.thing {
  position: relative;
  background: white;
}

.thing ul {
  display: none;
}

.thing.active {
  background: #ddd;
}

.thing.active > ul {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 100%;
}

First 001

Second 001

Third 001

Third 002

First 002

Second 002

Third 011

Third 012

First 003

Second 031

Third 031

Third 032

https://jsfiddle.net/samhadr/ym2Lx7sn/6/

Body:
A click event should do two things:

Remove class active from all sibling and descendant elements.

Add class active to the clicked element.

A querySelectorAll can help with part 1, while part 2 is quite direct:

function clickHandler( e ) {

    e.preventDefault();

    e.target.parentElement.querySelectorAll( ".active" ).forEach( e =>
        e.classList.remove( "active" ) );

    e.target.classList.add( "active" );

};


问:
Mocking Globals to test browser modules in node
I have some JavaScript modules which consume and declare globals. I'm aware that this is an anti-pattern, but it's a stopgap solution: until our dependencies come around to publishing their own ES module versions, we destructure them from globals. Here's what we do with Redux, as an example.

```<code>// Example: instead of
import createStore from '../path/to/redux.js';
// we do
const {createStore} = Redux;
</code>```

This works a treat in the browser, and when the dependencies update it will be simple to refactor, however, testing in node with mocha is a different story:

```<code>// myReducer.test.mjs

import reducer from '../../src/redux-modules/myReducer';
import initialState from '../../src/redux-modules/myReducer';

export default function videosReducerTests() {
  assert('reducer', function() {
    it('should return initial state by default', function() {
      reducer({}, {}).should.equal(initialState);
    });
  });
}
</code>```

I've installed @std/esm to help node work with es modules, and set up my package.json with the following:

```<code>"devDependencies": {
  "@std/esm": "^0.14.0",
},
"@std/esm":"js",
"scripts": {
  "redux-test": "node -r @std/esm test/redux/index.mjs",
}
</code>```

The result of running yarn redux-test is

```<code>ReferenceError: Redux is not defined
</code>```

I've tried mocking the namespaces I need with global.Redux = {createStore: Function} etc. at the top of my test files, but those are all ignored, since imports are 'hoisted'.

Any tips on how to get around this block?

答: You might just stick with importing the full redux. It's small enough and may simplify browser/node things.

Body:
I have some JavaScript modules which consume and declare globals. I'm aware that this is an anti-pattern, but it's a stopgap solution: until our dependencies come around to publishing their own ES module versions, we destructure them from globals. Here's what we do with Redux, as an example.

// Example: instead of
import createStore from '../path/to/redux.js';
// we do
const {createStore} = Redux;

This works a treat in the browser, and when the dependencies update it will be simple to refactor, however, testing in node with mocha is a different story:

// myReducer.test.mjs

import reducer from '../../src/redux-modules/myReducer';
import initialState from '../../src/redux-modules/myReducer';

export default function videosReducerTests() {
  assert('reducer', function() {
    it('should return initial state by default', function() {
      reducer({}, {}).should.equal(initialState);
    });
  });
}

I've installed @std/esm to help node work with es modules, and set up my package.json with the following:

"devDependencies": {
  "@std/esm": "^0.14.0",
},
"@std/esm":"js",
"scripts": {
  "redux-test": "node -r @std/esm test/redux/index.mjs",
}

The result of running yarn redux-test is

ReferenceError: Redux is not defined

I've tried mocking the namespaces I need with global.Redux = {createStore: Function} etc. at the top of my test files, but those are all ignored, since imports are 'hoisted'.

Any tips on how to get around this block?


问:
Consolidating multiple list entries into one email (where a row associates content with email address)
My google sheets system reads through live list and sends automated emails to the person responsible for the content in a given row.

This list includes variables such as date, description, and the assignee's email. The list runs row-by-row, so due to the code that I am using, one person may receive several emails for each row to which they are assigned.

I would like to change the code so that it compiles like-email addresses on the list and sends the content of each row in a single email (ideally formatted as a table). How can I achieve this?

The script I am currently using is below:

```<code>function AssignmentEmail() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Assignments");
  var range = sheet.getRange("A3:G950");
  var info = range.getValues();
  for (i in info) {
    var col = info[i];
    var date = Utilities.formatDate(col[0], "PST", "YYYY-MMM-dd");
    var observation = col[1];
    var lab = col[2];
    var contact = col[3];
    var action = col[4];
    var email = col[6];
    if (email="distribution list address") {
      MailApp.sendEmail(email, "*Text and variables for group*");
    }
    else if (email!="") {
      MailApp.sendEmail(email,"*Text and variables for individual*");
    }
  }
}
</code>```

Thanks for your help!

答:
You could push each row to an array in a dictionary using the email address as the key.  You'd use JavaScript object to do this. The dictionary will store your data in in key:value pairs, with the email address as the key & an array of values storing the data you want to send to that address. What you'll end up with is dictionary looking a bit like this:

```<code>{"email.address@domain.tld": [['data row 1', 1, 'foo'],
                              ['data row 2', 2, 'bar']
                             ],
 "another.email@domain.tld": [['only one data row', 0, 'baz']],
 "group.email@domain.tld":   [['1st of many', 10, 'lorem'],
                              ['2nd row', 20, 'ipsum'],
                              ['3rd row', 30, 'dolor'],
                              ['Nth row', 100, 'si amet']
                             ]
}
</code>```

So, you extract the email address from your data row & look for that email in the keys of your dictionary:

if the email is present, push the new row of data to the array that
at that key;

if not, create a new array with the email address as
they key & the row of data as the first element.

Once the dictionary is populated you can then iterate over the keys using the for(var key in dictionary){} construction.  You access the values under each key in the form dictionary.key or dictionary[key].  It's just an array with names instead of numbers for the indices! (Actually not, but the analogy suffices.) So you can access the first element of the array under a given key in the form dictionary[key][0] (or dictionary.key[0]). And you can still use the value in key (in your case, the email address), so you could write Logger.log("key = %s, values = %s", key, dictionary[key]).

The code would look something like this:

```<code>/*...connect to your data source as above...*/
var info = range.getValues();
/* Create an empty JS Object to provide our dictionary.
 *+ we'll add each email address as a dict key as we see it.
 *+ each key will point to an array which will be the data
 *+ to be entered into each email to the recipient address (the key) */
var email_data_store = {};
for (i in info) {
  var col = info[i];
/*...variable assignments as above...*/
  var email = col[6];
  if(email != ""){
    if(!(email in email_data_store)){ // Does a key matching this email already exist?
      // if not, create it:
      email_data_store[email] = [];
      // so now we have an empty array under the key `email`
    }
    email_data_store[email].push(/* an array of your values */);
  }
}

// now iterate over the dict to format the emails & send
for(var email in email_data_store){
  /* in here, iterate over the 2D arrays in email_data_store[email]
   *+ You can use array notation to address all items,
   *+ so that you don't have the potential confusion of
   *+ mixing array & object notation */
  for(var i = 0, lim = email_data_store[email].length; i < lim; ++i){
    /* format your data here */
  }
  MailApp.sendEmail(email, /* your formatted email body */);
}
/* whatever cleanup you want to do before ending your function */
</code>```

More documentation: MDN on JS Objects

Body:
My google sheets system reads through live list and sends automated emails to the person responsible for the content in a given row.

This list includes variables such as date, description, and the assignee's email. The list runs row-by-row, so due to the code that I am using, one person may receive several emails for each row to which they are assigned.

I would like to change the code so that it compiles like-email addresses on the list and sends the content of each row in a single email (ideally formatted as a table). How can I achieve this?

The script I am currently using is below:

function AssignmentEmail() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Assignments");
  var range = sheet.getRange("A3:G950");
  var info = range.getValues();
  for (i in info) {
    var col = info[i];
    var date = Utilities.formatDate(col[0], "PST", "YYYY-MMM-dd");
    var observation = col[1];
    var lab = col[2];
    var contact = col[3];
    var action = col[4];
    var email = col[6];
    if (email="distribution list address") {
      MailApp.sendEmail(email, "*Text and variables for group*");
    }
    else if (email!="") {
      MailApp.sendEmail(email,"*Text and variables for individual*");
    }
  }
}

Thanks for your help!

Body:
You could push each row to an array in a dictionary using the email address as the key.  You'd use JavaScript object to do this. The dictionary will store your data in in key:value pairs, with the email address as the key & an array of values storing the data you want to send to that address. What you'll end up with is dictionary looking a bit like this:

{"email.address@domain.tld": [['data row 1', 1, 'foo'],
                              ['data row 2', 2, 'bar']
                             ],
 "another.email@domain.tld": [['only one data row', 0, 'baz']],
 "group.email@domain.tld":   [['1st of many', 10, 'lorem'],
                              ['2nd row', 20, 'ipsum'],
                              ['3rd row', 30, 'dolor'],
                              ['Nth row', 100, 'si amet']
                             ]
}

So, you extract the email address from your data row & look for that email in the keys of your dictionary:

if the email is present, push the new row of data to the array that
at that key;

if not, create a new array with the email address as
they key & the row of data as the first element.

Once the dictionary is populated you can then iterate over the keys using the for(var key in dictionary){} construction.  You access the values under each key in the form dictionary.key or dictionary[key].  It's just an array with names instead of numbers for the indices! (Actually not, but the analogy suffices.) So you can access the first element of the array under a given key in the form dictionary[key][0] (or dictionary.key[0]). And you can still use the value in key (in your case, the email address), so you could write Logger.log("key = %s, values = %s", key, dictionary[key]).

The code would look something like this:

/*...connect to your data source as above...*/
var info = range.getValues();
/* Create an empty JS Object to provide our dictionary.
 *+ we'll add each email address as a dict key as we see it.
 *+ each key will point to an array which will be the data
 *+ to be entered into each email to the recipient address (the key) */
var email_data_store = {};
for (i in info) {
  var col = info[i];
/*...variable assignments as above...*/
  var email = col[6];
  if(email != ""){
    if(!(email in email_data_store)){ // Does a key matching this email already exist?
      // if not, create it:
      email_data_store[email] = [];
      // so now we have an empty array under the key `email`
    }
    email_data_store[email].push(/* an array of your values */);
  }
}

// now iterate over the dict to format the emails & send
for(var email in email_data_store){
  /* in here, iterate over the 2D arrays in email_data_store[email]
   *+ You can use array notation to address all items,
   *+ so that you don't have the potential confusion of
   *+ mixing array & object notation */
  for(var i = 0, lim = email_data_store[email].length; i < lim; ++i){
    /* format your data here */
  }
  MailApp.sendEmail(email, /* your formatted email body */);
}
/* whatever cleanup you want to do before ending your function */

More documentation: MDN on JS Objects


问:
Auto width and height for SVG image
I am new to SVG, so sorry if this is a bit of a noob question. I am trying to figure out how to get an image to display with the full width and height of the referenced image. I am using D3.js to build a graph and I want a logo to appear in the corner. The problem is that the image href will be set using javascript, so the image being referenced is never a fixed width or height. What I am wanting is the image to display in it's full width and height, not scaled up or down. What I was hoping for is the ability to automatically set the width and height of the image based on it's content, such as setting the width and height attributes to auto. This however just results in the image not being shown.

```<code>d3.select("body")
  .append("svg")
  .attr('id','mySVG')
  .attr({
      "width": "100%",
      "height": "100%"
  })
  .attr("viewBox", "0 0 " + width + " " + height )
  .attr("preserveAspectRatio", "none");

d3.select('#mySVG')
  .append('image')
  .attr('image-rendering','optimizeQuality')
  .attr('height','auto')     <--- This does not work
  .attr('width','auto')      <--- This does not work
  .attr('xlink:href', logoUrl)
  .attr('x','0')
  .attr('y','0');
</code>```

How would I go about specifying that the SVG image width and height must be dynamically determined based on the referenced image size?

答: It's a couple years since this has been asked but I'm currently trying to determine some things about the use of auto as a value for width or height myself and thought I would share what I've found. According to Amelia Bellamy-Royds' 2015 article  on scaling SVGs and the codepen example she provides, if you put auto in as either the width or the height value of your <svg>, along with a value for the viewBox, you should be able to see the content scaling proportionately. Unfortunately, she also points out that at the time this only worked in "Blink/Firefox" browsers. Blink is a fork of part of WebKit, so it's possible that by now Chrome will support this as well. I am seeing behavior in Chrome which would seem to support this possibility, but I'm also getting an error so YMMV.

Title: Auto width and height for SVG image

Body:
I am new to SVG, so sorry if this is a bit of a noob question. I am trying to figure out how to get an image to display with the full width and height of the referenced image. I am using D3.js to build a graph and I want a logo to appear in the corner. The problem is that the image href will be set using javascript, so the image being referenced is never a fixed width or height. What I am wanting is the image to display in it's full width and height, not scaled up or down. What I was hoping for is the ability to automatically set the width and height of the image based on it's content, such as setting the width and height attributes to auto. This however just results in the image not being shown.

d3.select("body")
  .append("svg")
  .attr('id','mySVG')
  .attr({
      "width": "100%",
      "height": "100%"
  })
  .attr("viewBox", "0 0 " + width + " " + height )
  .attr("preserveAspectRatio", "none");

d3.select('#mySVG')
  .append('image')
  .attr('image-rendering','optimizeQuality')
  .attr('height','auto')     <--- This does not work
  .attr('width','auto')      <--- This does not work
  .attr('xlink:href', logoUrl)
  .attr('x','0')
  .attr('y','0');

How would I go about specifying that the SVG image width and height must be dynamically determined based on the referenced image size?