问:
Update belongsTo relationship via native select element
I have been trying to incorporate details of Brenna O'Brien's Ember Conf 2016 talk <select>ing Good Ember Patterns into a project and it is working for simple attributes (in the example below names is an array of strings and model.name is an attr( "string" )):

```<code><select onchange={{action (mut model.name) value="target.value"}}>
  {{#each names as |name|}}
    <option value={{name}} selected={{eq name model.name}}>{{name}}</option>
  {{/each}}
</select>
</code>```

However, when this is applied to a belongsTo relationship and an array of models:

Controller:

```<code>import Ember from 'ember';

export default Ember.Controller.extend({
  titles: null,
  init(){
    this.set( "titles", this.store.peekAll( "title" ) );
  }
});
</code>```

Template:

```<code><select onchange={{action (mut model.title) value="target.value"}}>
  {{#each titles as |title|}}
    <option value={{title}} selected={{eq title.id model.title.id}}>
      {{title.description}}
    </option>
  {{/each}}
</select>
</code>```

This fails; the relationship value is modified but it is not set to a valid title. From some analysis, it appears that the title model is stringified either when it is being handled by HTMLBars or when it is set as the option.value and this is not (cannot?) being converted back when the relationship is set.

I have currently solved it (Ember-Twiddle) by adding an action to the controller:

```<code>actions: {
  title( id ){
    this.set( 'model.title', this.store.peekRecord( "title", id ) );
  }
}
</code>```

and modifying the template to call this:

```<code><select onchange={{action "title" value="target.value"}}>
  {{#each titles as |title|}}
    <option value={{title.id}} selected={{eq title.id model.title.id}}>
      {{title.description}}
    </option>
  {{/each}}
</select>
</code>```

However, I then need to create a function for each relationship I want to update in this way.

Is there a way to directly set a belongsTo relationship from the template without calling an intermediate function or resorting to add-ons? (If not then is there a DRY method of solving this?)

答:
Unfortunately, until we have routable components, there is no way to do this without sending an action from the component.  Fortunately, we have ember-route-action-helper to help us, and this acts as sort of a shim for routable components.  (https://github.com/DockYard/ember-route-action-helper) - I know you said you wanted to avoid add-ons but this is the only "solution that does not involve defining actions in the component" available at this point in time (as far as I know). Furthermore, it's a very helpful add-on in general.  I'm using it for this use case and others.  Bonus: when the routable components feature lands, you won't really have to do any refactoring.  Anyhow, this is how I solved this problem:

You can specify the action on the route, and use a Mixin for DRY.  (Instead of a Mixin, you could also just extend Route and inherit from that, or you could reopen Route.  I would be opposed to reopening Route, because you are very unlikely to need this action on every single route.  Avoid bloat.)

This Mixin presumes that your model property and the belongsTo model that it references will always have the same name, so only uses one variable: property.  If this is not the case, you'll need to add (and pass) another parameter to setBelongsTo() and specify which parameter is used for set() and peekRecord().

Tested and works on ember-cli: 2.13.2

Option 1: Native Select Method

note: ember-route-action-helper add-on is required

```<code>// mixins/my-mixin.js

import Ember from 'ember';

export default Ember.Mixin.create({
  actions: {
    setBelongsTo(model, property, value) {
      this.get('controller').get(model).set(property, this.store.peekRecord(property, value));
    }
  }
});
</code>```

```<code>// routes/my-route.js

import Ember from 'ember';
import SetBelongsToMixin from 'myApp/mixins/set-belongs-to';

export default Ember.Route.extend(SetBelongsToMixin, {
  model() {
    return this.get('store')find(...);
  }
});
</code>```

// templates/my-route.hbs

<select onchange={{action (route-action 'setBelongsTo' 'model' 'title') value="target.value"}}>
  {{#each titles as |title|}}
    <option value={{title.id}} selected={{eq title.id model.title.id}}>
      {{title.description}}
    </option>
  {{/each}}
</select>
```

<p><strong>Option 2: <code>ember-power-select</code> Method</strong></p>

<p><em>note: <code>ember-route-action-helper</code> add-on is required</em></p>

<p>some slight differences if using <code>ember-power-select</code> (https://github.com/cibernox/ember-power-select)</p>

```// mixins/my-mixin.js

import Ember from 'ember';

export default Ember.Mixin.create({
  actions: {
    setBelongsTo(model, property, value) {
      this.get('controller').get(model).set(property, value);
    }
  }
});
```

```// routes/my-route.js

import Ember from 'ember';
import SetBelongsToMixin from 'myApp/mixins/set-belongs-to';

export default Ember.Route.extend(SetBelongsToMixin, {
  model() {
    return this.get('store')find(...);
  }
});
```

<pre class="lang-hbs prettyprint-override"><code>// templates/my-route.hbs

{{#power-select
  options=titles
  selected=model.title
  onchange=(action (route-action 'setBelongsTo' 'model' 'title'))
  as |title|
}}
  {{title.description}}
{{/power-select}}
</code>```

Edit 1: The OP makes use of ember-truth-helpers add-on to set the selected option.  (Or OP created their own helper for eq.)  The first solution here also uses this add-on.

Body:
I have been trying to incorporate details of Brenna O'Brien's Ember Conf 2016 talk <select>ing Good Ember Patterns into a project and it is working for simple attributes (in the example below names is an array of strings and model.name is an attr( "string" )):

<select onchange={{action (mut model.name) value="target.value"}}>
  {{#each names as |name|}}
    <option value={{name}} selected={{eq name model.name}}>{{name}}</option>
  {{/each}}
</select>

However, when this is applied to a belongsTo relationship and an array of models:

Controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  titles: null,
  init(){
    this.set( "titles", this.store.peekAll( "title" ) );
  }
});

Template:

<select onchange={{action (mut model.title) value="target.value"}}>
  {{#each titles as |title|}}
    <option value={{title}} selected={{eq title.id model.title.id}}>
      {{title.description}}
    </option>
  {{/each}}
</select>

This fails; the relationship value is modified but it is not set to a valid title. From some analysis, it appears that the title model is stringified either when it is being handled by HTMLBars or when it is set as the option.value and this is not (cannot?) being converted back when the relationship is set.

I have currently solved it (Ember-Twiddle) by adding an action to the controller:

actions: {
  title( id ){
    this.set( 'model.title', this.store.peekRecord( "title", id ) );
  }
}

and modifying the template to call this:

<select onchange={{action "title" value="target.value"}}>
  {{#each titles as |title|}}
    <option value={{title.id}} selected={{eq title.id model.title.id}}>
      {{title.description}}
    </option>
  {{/each}}
</select>

However, I then need to create a function for each relationship I want to update in this way.

Is there a way to directly set a belongsTo relationship from the template without calling an intermediate function or resorting to add-ons? (If not then is there a DRY method of solving this?)

Body:
Unfortunately, until we have routable components, there is no way to do this without sending an action from the component.  Fortunately, we have ember-route-action-helper to help us, and this acts as sort of a shim for routable components.  (https://github.com/DockYard/ember-route-action-helper) - I know you said you wanted to avoid add-ons but this is the only "solution that does not involve defining actions in the component" available at this point in time (as far as I know). Furthermore, it's a very helpful add-on in general.  I'm using it for this use case and others.  Bonus: when the routable components feature lands, you won't really have to do any refactoring.  Anyhow, this is how I solved this problem:

You can specify the action on the route, and use a Mixin for DRY.  (Instead of a Mixin, you could also just extend Route and inherit from that, or you could reopen Route.  I would be opposed to reopening Route, because you are very unlikely to need this action on every single route.  Avoid bloat.)

This Mixin presumes that your model property and the belongsTo model that it references will always have the same name, so only uses one variable: property.  If this is not the case, you'll need to add (and pass) another parameter to setBelongsTo() and specify which parameter is used for set() and peekRecord().

Tested and works on ember-cli: 2.13.2

Option 1: Native Select Method

note: ember-route-action-helper add-on is required

// mixins/my-mixin.js

import Ember from 'ember';

export default Ember.Mixin.create({
  actions: {
    setBelongsTo(model, property, value) {
      this.get('controller').get(model).set(property, this.store.peekRecord(property, value));
    }
  }
});

// routes/my-route.js

import Ember from 'ember';
import SetBelongsToMixin from 'myApp/mixins/set-belongs-to';

export default Ember.Route.extend(SetBelongsToMixin, {
  model() {
    return this.get('store')find(...);
  }
});

// templates/my-route.hbs

<select onchange={{action (route-action 'setBelongsTo' 'model' 'title') value="target.value"}}>
  {{#each titles as |title|}}
    <option value={{title.id}} selected={{eq title.id model.title.id}}>
      {{title.description}}
    </option>
  {{/each}}
</select>

Option 2: ember-power-select Method

note: ember-route-action-helper add-on is required

some slight differences if using ember-power-select (https://github.com/cibernox/ember-power-select)

// mixins/my-mixin.js

import Ember from 'ember';

export default Ember.Mixin.create({
  actions: {
    setBelongsTo(model, property, value) {
      this.get('controller').get(model).set(property, value);
    }
  }
});

// routes/my-route.js

import Ember from 'ember';
import SetBelongsToMixin from 'myApp/mixins/set-belongs-to';

export default Ember.Route.extend(SetBelongsToMixin, {
  model() {
    return this.get('store')find(...);
  }
});

// templates/my-route.hbs

{{#power-select
  options=titles
  selected=model.title
  onchange=(action (route-action 'setBelongsTo' 'model' 'title'))
  as |title|
}}
  {{title.description}}
{{/power-select}}

Edit 1: The OP makes use of ember-truth-helpers add-on to set the selected option.  (Or OP created their own helper for eq.)  The first solution here also uses this add-on.


来源: stackexchange

问:
Refactoring fat reducers
I'm working on my project using React-like approach and my problem is that my reducers are quite "flat", but they need to handle many updates in different state tree areas, so they're getting more and more complex.

For example, after dispatching action 'DO_SOMETHING', first I need to update my state within 3 LOC, but then, when the project grows and I need to work on additional features, someone wants to see base result + something extra after executing the same actions. So you can imagine, that after spending many weeks reducers are becoming 'fat' in a way that they are touching many different areas of the same tree, in the same pure way, but it's really hard to structure code inside them properly (one state tree and one store).

In most of the tutorials I can find only given scenario:

dispatch 'ADD_TODO'

update state, add new todo to the array of todos

while in my case it's like:

```<code>case SELECT_FILTER:
    return Object.assign({}, state, {
        oneProperty: ...,
        anotherProperty: null,
        nextProperty: false
        // and the logic is getting bigger and bigger
    })
</code>```

dispatch 'SELECT_FILTER'

update applied filters section (UI summary of applied filters)

update query which will be used to fetch data from server

clear this

copy that

next month this filter should also...

:/

I've tried to create "sets of reducers" - filters reducers, list reducers, and so on, but the problem is that I'm working on the same page and incoming features introduces cross-cutting changes. Simple grouping was ok in smaller app, but now each reducer seems to be interested in too many parts of my state.

So my question is how to structure my reducers properly? Maybe I put too much "local state" into the state tree? Or something else? I'm looking forward to see your solutions related to composing and structuring reducers.

答:
Conveniently, last year I wrote a section for the Redux docs called "Structuring Reducers" :) .  It demonstrates several useful techniques for organizing and composing reducer logic.  In particular, you might be interested in the sections on "Beyond combineReducers" and "Reusing Reducer Logic".

My "Practical Redux" tutorial series also demonstrates some more advanced reducer structures, particularly the post Practical Redux, Part 7: Form Change Handling, Data Editing, and Feature Reducers.

It may also be worth considering dispatching multiple "primitive" actions that could be dispatched in sequence to form larger behaviors.  For example, you might have a thunk that dispatches BASIC_UPDATE, SPECIFIC_EXTRA_UPDATE_1, and SPECIFIC_EXTRA_UPDATE_2 in a row.  There are concerns regarding performance to be aware of with that, but it's a valid approach (and perf concerns can be resolved with various batching strategies).  For more info, see the Redux FAQ entries on dispatching multiple actions and reducing store notification events, my blog post Idiomatic Redux: Thoughts on Thunks, and the Store#Store Change Subscriptions section of my Redux addons catalog.

ContentLicense: CC BY-SA 3.0

Title: Refactoring fat reducers

Body:
I'm working on my project using React-like approach and my problem is that my reducers are quite "flat", but they need to handle many updates in different state tree areas, so they're getting more and more complex.

For example, after dispatching action 'DO_SOMETHING', first I need to update my state within 3 LOC, but then, when the project grows and I need to work on additional features, someone wants to see base result + something extra after executing the same actions. So you can imagine, that after spending many weeks reducers are becoming 'fat' in a way that they are touching many different areas of the same tree, in the same pure way, but it's really hard to structure code inside them properly (one state tree and one store).

In most of the tutorials I can find only given scenario:

dispatch 'ADD_TODO'

update state, add new todo to the array of todos

while in my case it's like:

case SELECT_FILTER:
    return Object.assign({}, state, {
        oneProperty: ...,
        anotherProperty: null,
        nextProperty: false
        // and the logic is getting bigger and bigger
    })

dispatch 'SELECT_FILTER'

update applied filters section (UI summary of applied filters)

update query which will be used to fetch data from server

clear this

copy that

next month this filter should also...

:/

I've tried to create "sets of reducers" - filters reducers, list reducers, and so on, but the problem is that I'm working on the same page and incoming features introduces cross-cutting changes. Simple grouping was ok in smaller app, but now each reducer seems to be interested in too many parts of my state.

So my question is how to structure my reducers properly? Maybe I put too much "local state" into the state tree? Or something else? I'm looking forward to see your solutions related to composing and structuring reducers.


问:
Counting Rows Based on Exist Condition
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

```<code>CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)
</code>```

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

```<code>| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |
</code>```

So here is what I have so far:

```<code>DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId
</code>```

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

答:
Use SUM instead of COUNT:

```<code>DECLARE @userId INT = 1
SELECT pt.ProjectTaskId,
    ISNULL(SUM(CASE WHEN pte.AssignedUserId = @userId THEN 1 END),0) AS AssignedToMe,
    ISNULL(SUM(CASE WHEN pte.AssignedUserId <> @userId THEN 1 END),0) AS AssignedToOthers
FROM ProjectTask pt
INNER JOIN Project p ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY  pt.ProjectTaskId
</code>```

With the data you have provided, it will result:

```<code>ProjectTaskId   AssignedToMe    AssignedToOthers
1               1               3
2               0               0
</code>```

See result in SQL Fiddle.

Title: Counting Rows Based on Exist Condition

Body:
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |

So here is what I have so far:

DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

Body:
Use SUM instead of COUNT:

DECLARE @userId INT = 1
SELECT pt.ProjectTaskId,
    ISNULL(SUM(CASE WHEN pte.AssignedUserId = @userId THEN 1 END),0) AS AssignedToMe,
    ISNULL(SUM(CASE WHEN pte.AssignedUserId <> @userId THEN 1 END),0) AS AssignedToOthers
FROM ProjectTask pt
INNER JOIN Project p ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY  pt.ProjectTaskId

With the data you have provided, it will result:

ProjectTaskId   AssignedToMe    AssignedToOthers
1               1               3
2               0               0

See result in SQL Fiddle.


问:
How to retrieve values in Firebase database and insert them into HTML
Here is my database structure (in red my comments):

The purpose is to show on a simple web page photos of a trip. I am trying to retrieve the value "photourl" in this database for each photo of a trip.

Here is my html code:

```<code>  <div class="main">

      <div class="spot">

        <img id="image" height="400" width="400"/>

      </div>

  </div>

    <p><script>document.write(userid);</script></p>
    <p><script>document.write(tripid);</script></p>
    <p><script>document.write(photourl);</script></p>
</code>```

The last 3 lines are just here to show whether the variables have any value (and when I try my html code, it doesn't show any).

And my javascript code:

```<code>//Get User ID and Trip ID in URL

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam)
    {
        return sParameterName[1];
    }
}
}
   var userid = GetURLParameter('userid');
   var tripid = GetURLParameter('tripid');

//Get image from database

var database = firebase.database();
return firebase.database().ref('/photos/' + userid + 'trips' +
tripid).once('photourl').then(function(insert)
{
document.getElementsById('image').src = photourl;
});
</code>```

My URL will be something like this then: https://travelertest-e316f.firebaseapp.com/?userid=11K47L3qgUOateC4LGSE29Un2W53&tripid=-Kiv3kukHYLMVefSGPqZ

I don't know how to make it work so that it retrieves all "photourl" values no matter how many photos there are in a trip. And I don't know how to display them on a simple html page so that the page shows as many photos as in the trip.

Thanks !

答:
You can iterate over the trip object and get the photourls in an array:</p>

```<code>// add a return statement here if you'll use it as a function
database.ref(`photos/${userId}/trips/${tripId}`).once('value') // will return you all the photo objects inside the `tripId`
.then(photosSnap => {
    const photosObj = photosSnap.val();
    const photosUrl = Object.keys(photosObj).map(key => photosObj[key].photourl);
    // then you can return the array or use it here;
    console.log(photosUrl); // will be an array of all the photourls
}).catch(err => alert(err));
</code>```

Body:
Here is my database structure (in red my comments):

The purpose is to show on a simple web page photos of a trip. I am trying to retrieve the value "photourl" in this database for each photo of a trip.

Here is my html code:

The last 3 lines are just here to show whether the variables have any value (and when I try my html code, it doesn't show any).

And my javascript code:

//Get User ID and Trip ID in URL

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam)
    {
        return sParameterName[1];
    }
}
}
   var userid = GetURLParameter('userid');
   var tripid = GetURLParameter('tripid');

//Get image from database

var database = firebase.database();
return firebase.database().ref('/photos/' + userid + 'trips' +
tripid).once('photourl').then(function(insert)
{
document.getElementsById('image').src = photourl;
});

My URL will be something like this then: https://travelertest-e316f.firebaseapp.com/?userid=11K47L3qgUOateC4LGSE29Un2W53&tripid=-Kiv3kukHYLMVefSGPqZ

I don't know how to make it work so that it retrieves all "photourl" values no matter how many photos there are in a trip. And I don't know how to display them on a simple html page so that the page shows as many photos as in the trip.

Thanks !

Body:
You can iterate over the trip object and get the photourls in an array:

// add a return statement here if you'll use it as a function
database.ref(`photos/${userId}/trips/${tripId}`).once('value') // will return you all the photo objects inside the `tripId`
.then(photosSnap => {
    const photosObj = photosSnap.val();
    const photosUrl = Object.keys(photosObj).map(key => photosObj[key].photourl);
    // then you can return the array or use it here;
    console.log(photosUrl); // will be an array of all the photourls
}).catch(err => alert(err));


问:
My commented code becomes one line in Eclipse
Is there a way to not let code blocks become one line? Example:

```<code>                /*
                 * for (String word : tokens) { if (!StringUtil.hasUppercaseOrNonletter(word)) { filtered.add(word); } }
                 */
</code>```

I don't want to reduce the length of my comment line. For other general comments, I still want to keep the line length.

答:
If the comment is code that you want, then you can just use the eclipse toggle comment which is Ctrl + /

That just makes every line a normal comment so the formatting doesn't get messed up. You can just redo the command if you want to uncomment. That's what I do when commenting code

Body:
Is there a way to not let code blocks become one line? Example:

                /*
                 * for (String word : tokens) { if (!StringUtil.hasUppercaseOrNonletter(word)) { filtered.add(word); } }
                 */

I don't want to reduce the length of my comment line. For other general comments, I still want to keep the line length.


问:
Dividing workload on several threads
I was wondering if anyone knows about a good article which describes dividing workload on to several Threads? Preferebly it would be written for C# but it's really the concept I'm after, so it's not an issue if it's written for a different, similar, language.

I have a problem where I would have to divide a large amount of computing into several threads and then Sum the generated data after one iteration completes (so I would need to know that all threads have finished) and then start a new iteration, supplying all the threads with the data generated in the last iteration (the data would be modified before the end of each iteration).

I hope this makes sense, and is possible. Either way I would appreciate some advice on how to tackle the problem of computing large amounts of data divided on to several threads (so I can use more than one processor's core).

Thank you for your answers!

答:
You should look at Parallel FX (PFX), you can find the blog here and the download link here (Thanks Marc).

Unfortunately I don't know if this will be released for .NET 2.0/3.5 as it is currently slated for .NET 4.0.

If you're looking at implementing it yourself, look into Work Stealing Algorithms.

There is also a library named Power Threading, by Jeffrey Richter from Wintellect which has some rather good classes available for you.

OwnerDisplayName: Rekreativc

ContentLicense: CC BY-SA 2.5

Title: Dividing workload on several threads

OwnerDisplayName: lassevk

LastEditorDisplayName: lassevk


问:
What can I store locally while still being PCI Compliant using Braintree in Rails?
What credit card information am I allowed to store while still being PCI compliant if I am relying on braintree for payment processing?

The reason I am asking is because, as a simple optimization, if a customer has already bought something from my store with a credit card, I can show them the last 4 digits of their credit card, and the card type, without having to make an API call to BrainTree.  I'd have to make the call if they wanted to change the card or make a purchase, but for that one page, I wouldn't.

Question is, am I allowed to store:

the last 4 digits of the credit card

and the card type

and possible the cardholder name

Or where is there a list of PCI compliance "do's and don'ts" I can check out?

答:
Yeah, it's fine to store those things.

Check out the PCI Quick Reference  Guide for a brief overview of what you should and shouldn't do.


问:
Lua - why is string after function call allowed?
I'm trying to implement a simple C++ function, which checks a syntax of Lua script. For that I'm using Lua's compiler function luaL_loadbufferx() and checking its return value afterwards.

Recently, I have ran into a problem, because the code, that I thought should be marked invalid, was not detected and instead the script failed later at a runtime (eg. in lua_pcall()).

Example Lua code (can be tested on official Lua demo):

```<code>function myfunc()
   return "everyone"
end

-- Examples of unexpected behaviour:
-- The following lines pass the compile time check without errors.
print("Hello " .. myfunc() "!") -- Runtime error: attempt to call a string value
print("Hello " .. myfunc() {1,2,3}) -- Runtime error: attempt to call a string value

-- Other examples:
-- The following lines contain examples of invalid syntax, which IS detected by compiler.
print("Hello " myfunc() .. "!") -- Compile error: ')' expected near 'myfunc'
print("Hello " .. myfunc() 5) -- Compile error: ')' expected near '5'
print("Hello " .. myfunc() .. ) -- Compile error: unexpected symbol near ')'
</code>```

The goal is obviously to catch all syntax errors at compile time. So my questions are:

What exactly is meant by calling a string value?

Why is this syntax allowed in the first place? Is it some Lua feature I'm unaware of, or the luaL_loadbufferx() is faulty in this particular example?

Is it possible to detect such errors by any other method without running it? Unfortunately, my function doesn't have access to global variables at compile time, so I can't just just run the code directly via lua_pcall().

Note: I'm using Lua version 5.3.4 (manual here).

Thank you very much for your help.

答:
Both myfunc() "!" and myfunc(){1,2,3} are valid Lua expressions.

Lua allows calls of the form exp string. See functioncall and prefixexp in the Syntax of Lua.

So myfunc() "!" is a valid function call that calls whatever myfunc returns and call it with the string "!".

The same thing happens for a call of the form exp table-literal.

Body:
I'm trying to implement a simple C++ function, which checks a syntax of Lua script. For that I'm using Lua's compiler function luaL_loadbufferx() and checking its return value afterwards.

Recently, I have ran into a problem, because the code, that I thought should be marked invalid, was not detected and instead the script failed later at a runtime (eg. in lua_pcall()).

Example Lua code (can be tested on official Lua demo):

function myfunc()
   return "everyone"
end

-- Examples of unexpected behaviour:
-- The following lines pass the compile time check without errors.
print("Hello " .. myfunc() "!") -- Runtime error: attempt to call a string value
print("Hello " .. myfunc() {1,2,3}) -- Runtime error: attempt to call a string value

-- Other examples:
-- The following lines contain examples of invalid syntax, which IS detected by compiler.
print("Hello " myfunc() .. "!") -- Compile error: ')' expected near 'myfunc'
print("Hello " .. myfunc() 5) -- Compile error: ')' expected near '5'
print("Hello " .. myfunc() .. ) -- Compile error: unexpected symbol near ')'

The goal is obviously to catch all syntax errors at compile time. So my questions are:

What exactly is meant by calling a string value?

Why is this syntax allowed in the first place? Is it some Lua feature I'm unaware of, or the luaL_loadbufferx() is faulty in this particular example?

Is it possible to detect such errors by any other method without running it? Unfortunately, my function doesn't have access to global variables at compile time, so I can't just just run the code directly via lua_pcall().

Note: I'm using Lua version 5.3.4 (manual here).

Thank you very much for your help.


问:
How to take output of function and use as input of another function python?
More specifically my function grabs all the domains in a my database table and returns them. I want to know how to input these domains into another function that will run the Kali Linux tool URLcrazy for each of the domains in that table.

For example my function that outputs these:

google.com

yahoo.com

Here is the function:

```<code>def grab_domains():
    try:
        db = pymysql.connect(host="localhost",
                         user="root", passwd="root",
                         db="typosquat")
except ConnectionAbortedError as e:
    print(e, "\n")

temp = ""
cursor = db.cursor()
cursor.execute('SELECT name From domains')
for rows in cursor.fetchall():
    for entries in rows:
        temp += entries
        domains = entries[0:]
        print(domains)

return temp
</code>```

Here is the output:

google.com

yahoo.com

How do I write another function that will run the script URLcrazy on each of these domains? Assuming all scripts are in same file location.

This is all I have I cant figure out how to run it for each domain, only know how to for a single output.

```<code>def run_urlcrazy():
    np = os.system("urlcrazy " + grab_domains())
    print(np)
    return np
</code>```

How to I get this function to run URLcrazy for each domain?^^

This is my first post ever on stack overflow let me know what I can do to improve it and help me with question if possible! Thanks

答:
You'll need a loop:

```<code>def run_urlcrazy():
    ret_vals = []
    for domain in grab_domains():
        np = os.system("urlcrazy " + domain)
        ret_vals.append(np)
    return ret_vals
</code>```

I recommend a for loop because it can efficiently iterate over whatever your function returns.

You'll need to make a minor modification to your grab_domains() function as well:

```<code>temp = []
cursor = db.cursor()
cursor.execute('SELECT name From domains')
for rows in cursor.fetchall():
    for entries in rows:
        domains = entries[0:]
        temp.extend(domains)

return temp
</code>```

Now, your function returns a list of domains. You can iterate over this.

Body:
More specifically my function grabs all the domains in a my database table and returns them. I want to know how to input these domains into another function that will run the Kali Linux tool URLcrazy for each of the domains in that table.

For example my function that outputs these:

google.com

yahoo.com

Here is the function:

def grab_domains():
    try:
        db = pymysql.connect(host="localhost",
                         user="root", passwd="root",
                         db="typosquat")
except ConnectionAbortedError as e:
    print(e, "\n")

temp = ""
cursor = db.cursor()
cursor.execute('SELECT name From domains')
for rows in cursor.fetchall():
    for entries in rows:
        temp += entries
        domains = entries[0:]
        print(domains)

return temp

Here is the output:

google.com

yahoo.com

How do I write another function that will run the script URLcrazy on each of these domains? Assuming all scripts are in same file location.

This is all I have I cant figure out how to run it for each domain, only know how to for a single output.

def run_urlcrazy():
    np = os.system("urlcrazy " + grab_domains())
    print(np)
    return np

How to I get this function to run URLcrazy for each domain?^^

This is my first post ever on stack overflow let me know what I can do to improve it and help me with question if possible! Thanks

Body:
You'll need a loop:

def run_urlcrazy():
    ret_vals = []
    for domain in grab_domains():
        np = os.system("urlcrazy " + domain)
        ret_vals.append(np)
    return ret_vals

I recommend a for loop because it can efficiently iterate over whatever your function returns.

You'll need to make a minor modification to your grab_domains() function as well:

temp = []
cursor = db.cursor()
cursor.execute('SELECT name From domains')
for rows in cursor.fetchall():
    for entries in rows:
        domains = entries[0:]
        temp.extend(domains)

return temp

Now, your function returns a list of domains. You can iterate over this.


问:
Extract table names from SQLAlchemy exist query
How do i extract the table name from SQLAlchemy exist statement
assume we have the following code

```<code>from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

engine = create_engine('mysql://...')
Session = sessionmaker(bind=engine)

conn = engine.connect()
session = Session(bind=conn)
query_exists = session.query(Person).exists()
</code>```

how can i extract the table name from the query_exists?

答:
```<code>from sqlalchemy.sql.visitors import ClauseVisitor
from sqlalchemy import Table

def extract_tables(sql_stmt):
    tables = []
    visitor = ClauseVisitor()
    cluase_iter = visitor.iterate(elem)
    for e in cluase_iter:
        if isinstance(e, Table):
            tables.append(e)
        if isinstance(e, (ValuesBase, UpdateBase)):
            tables.append(e.table)
    return set(tables)
</code>```

Body:
How do i extract the table name from SQLAlchemy exist statement
assume we have the following code

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

engine = create_engine('mysql://...')
Session = sessionmaker(bind=engine)

conn = engine.connect()
session = Session(bind=conn)
query_exists = session.query(Person).exists()

how can i extract the table name from the query_exists?


问:
How to install R libraries after using homebrew?
for the first time I'm using homebrew and homebrew cask to install programmes and manage packages. After brew install homebrew/science/R and brew cask install rstudioI tried to install some libraries within rstudio but always end up with Warnings and errors with similar syntax:

```<code>installing *source* package ‘Rcpp’ ...
Paket ‘Rcpp’ erfolgreich entpackt und MD5 Summen überprüft
libs
sh: make: command not found
ERROR: compilation failed for package ‘Rcpp’
removing ‘/usr/local/lib/R/3.2/site-library/Rcpp’`

Warning in install.packages :
installation of package ‘Rcpp’ had non-zero exit status`

installing *source* package ‘stringi’ ...
Paket ‘stringi’ erfolgreich entpackt und MD5 Summen überprüft
checking for local ICUDT_DIR... icu55/data
checking for R_HOME...  /usr/local/Cellar/r/3.2.2_1/R.framework/Resources
checking for R... /usr/local/Cellar/r/3.2.2_1/R.framework/Resources/bin/R
checking for R >= 3.1.0... yes
checking for cat... /bin/cat
/usr/local/Cellar/r/3.2.2_1/R.framework/Resources/bin/config: line 150:       make: command not found
/usr/local/Cellar/r/3.2.2_1/R.framework/Resources/bin/config: line 151: make: command not found`
</code>```

and so on...

I installed Xcode 5.1.1on my OSX 10.8.5 (not via Homebrew)
at the beginning of the whole Mac setup process and assumed Command Line Toolsare included.

By the way, brew doctor says Your system is ready to brew

How can I approach that?

答:
As said by hrbrmstr in the comments, in OS X 10.8.5, you also have to install the command line tools:

Install Command Line Tools (CLT)

After Xcode is installed the compiler and command line tools must be installed. This is performed by starting Xcode, opening preferences, click on Download, then Install for Command Line Tools. The CLT are placed in /Applications/Xcode.app/Contents/Developer and various system directories.

Body:
for the first time I'm using homebrew and homebrew cask to install programmes and manage packages. After brew install homebrew/science/R and brew cask install rstudioI tried to install some libraries within rstudio but always end up with Warnings and errors with similar syntax:

installing *source* package ‘Rcpp’ ...
Paket ‘Rcpp’ erfolgreich entpackt und MD5 Summen überprüft
libs
sh: make: command not found
ERROR: compilation failed for package ‘Rcpp’
removing ‘/usr/local/lib/R/3.2/site-library/Rcpp’`

Warning in install.packages :
installation of package ‘Rcpp’ had non-zero exit status`

installing *source* package ‘stringi’ ...
Paket ‘stringi’ erfolgreich entpackt und MD5 Summen überprüft
checking for local ICUDT_DIR... icu55/data
checking for R_HOME...  /usr/local/Cellar/r/3.2.2_1/R.framework/Resources
checking for R... /usr/local/Cellar/r/3.2.2_1/R.framework/Resources/bin/R
checking for R >= 3.1.0... yes
checking for cat... /bin/cat
/usr/local/Cellar/r/3.2.2_1/R.framework/Resources/bin/config: line 150:       make: command not found
/usr/local/Cellar/r/3.2.2_1/R.framework/Resources/bin/config: line 151: make: command not found`

and so on...

I installed Xcode 5.1.1on my OSX 10.8.5 (not via Homebrew)
at the beginning of the whole Mac setup process and assumed Command Line Toolsare included.

By the way, brew doctor says Your system is ready to brew

How can I approach that?


问:
How can I create a role that includes tasks that should not run by default
Most of the tasks in my role should be run anytime the role is included, however, there are a couple tasks that I want to only be run when explicitly called.

For example, in my roles/elastic/tasks/main.yml file I have a lot of tasks which assure directories exist configure logstash and elasticsearch.

Now I want to create new set of tasks which initializes elasticsearch. i.e. It deletes existing data and creates/recreates schema.

I'm aware of tags, but I don't want all tasks to be run by accident if tags are not included when the role is run.

To run the playbook, I'm using ansible-playbook logserver.yml.

logserver.yml looks like this:

```<code>- hosts: localhost
  become: true
  roles:
    - common
    - elastic
</code>```

I have tried adding a new task file, roles/elastic/tasks/init.yml, but I am having a hard time determining how to run that specific task file.

答:
If i'm understanding the question correctly, you could use a conditional on some tasks that relies on a variable set at the command line, with a default value that will fail the conditional check.

in scratch.yml:

```<code>---
- hosts: localhost
  vars:
    my_var: "{{ MY_VAR|default('no') }}"

  tasks:
    - name: test
      debug:
        msg: "my_var: {{ my_var }}"

    - name: test 2
      debug:
        msg: "in conditional"
      when: my_var == 'yes'
</code>```

command line:

```<code>ansible-playbook scratch.yml
</code>```

vs

```<code>ansible-playbook scratch.yml --extra-vars 'MY_VAR=yes'
</code>```

Body:
Most of the tasks in my role should be run anytime the role is included, however, there are a couple tasks that I want to only be run when explicitly called.

For example, in my roles/elastic/tasks/main.yml file I have a lot of tasks which assure directories exist configure logstash and elasticsearch.

Now I want to create new set of tasks which initializes elasticsearch. i.e. It deletes existing data and creates/recreates schema.

I'm aware of tags, but I don't want all tasks to be run by accident if tags are not included when the role is run.

To run the playbook, I'm using ansible-playbook logserver.yml.

logserver.yml looks like this:

- hosts: localhost
  become: true
  roles:
    - common
    - elastic

I have tried adding a new task file, roles/elastic/tasks/init.yml, but I am having a hard time determining how to run that specific task file.

Body:
If i'm understanding the question correctly, you could use a conditional on some tasks that relies on a variable set at the command line, with a default value that will fail the conditional check.

in scratch.yml:

---
- hosts: localhost
  vars:
    my_var: "{{ MY_VAR|default('no') }}"

  tasks:
    - name: test
      debug:
        msg: "my_var: {{ my_var }}"

    - name: test 2
      debug:
        msg: "in conditional"
      when: my_var == 'yes'

command line:

ansible-playbook scratch.yml

vs

ansible-playbook scratch.yml --extra-vars 'MY_VAR=yes'


问:
Exporting Typescript function in Webpack bundle built with gulp, empty object in browser
I'm trying to build a js bundle from typescript with exports that I can call directly from an inline script, but I don't seem to be able to get it to work.

I have a Typescript source file like this:

```<code>export namespace Init {
    export function index() {
        // do some things
    }
}

export function blahblah() { console.log('blahblah') }
</code>```

This sits alongside some other sources in the same folder src/ts/*.ts.  My webpack.config.js looks like this:

```<code>'use strict';

module.exports = {
    context: __dirname,
    output: {
        filename: 'bundle.js',
        library: 'bitthicket',
    },
    devtool: 'sourcemap',
    resolve: {
        extensions: [ '.ts', '.tsx', '.js' ]
    },
    module: {
        rules: [
            { test: /\.tsx?$/, exclude: /node_modules/, loader: 'ts-loader' }
        ]
    }
}
</code>```

And finally, my gulpfile.js looks like this:

```<code>var gulp = require('gulp')
var gutil = require('gulp-util')
var plumber = require('gulp-plumber')
var watch = require('gulp-watch')
var sass = require('gulp-sass')
var ts = require('gulp-typescript')
var clean = require('gulp-clean')
var webpack = require('webpack')
var webpack_config = require('./webpack.config.js')
var webpack_stream = require('webpack-stream')

let _sass = () =>
    gulp.src('src/css/**/*.scss')
        .pipe(plumber())
        .pipe(sass())
        .pipe(gulp.dest('static/css'))
        .on('end', () => gutil.log('_sass: done'))

let _webpack = () =>
    gulp.src('src/ts/**/*.ts')
        .pipe(plumber())
        .pipe(webpack_stream(webpack_config, webpack))
        .pipe(gulp.dest('static/js'))
        .on('end', () => gutil.log('_webpack: done'))

gulp.task('build:sass', _sass)
gulp.task('clean:sass', () => gulp.src('static/css/**/*').pipe(clean()))
gulp.task('watch:sass', () => watch('src/css/**/*.scss', () => _sass()))

gulp.task('build:webpack', _webpack)
gulp.task('clean:ts', () => gulp.src('static/js/**/*').pipe(clean()))
gulp.task('watch:webpack', () => watch('src/ts/**/*.ts', () => _webpack()))

gulp.task('watch', ['watch:sass', 'watch:webpack'])
gulp.task('clean', ['clean:sass', 'clean:ts'])
gulp.task('build', ['build:sass', 'build:webpack'])
gulp.task('default', ['clean', 'build'])
</code>```

In an html file:

```<code><script src="bundle.js" async></script>
<script>window.onload = function() { console.log(bitthicket); }</script>
</code>```

What's happening, as I understand it, is that webpack is getting the piped list of sources as entry files, as though they were placed on the commandline like webpack {src list} bundle.js.  But I've set my library output option, and the bitthicket variable does get set, but it's an empty object.  What happened to Init.index?

Edit: I added the export keyword to the Init namespace, as well as a plain function to init.ts to see what would happen - but the resulting object still doesn't have those functions.

Here's the resulting webpack bootstrapper argument:

```<code>/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

exports.__esModule = true;
var _ = __webpack_require__(2);
var Init;
(function (Init) {
    function index() {
        Nav.attachNavbarScrollWatcher();
        document.addEventListener('scroll', function (event) {
            var articles = document.querySelectorAll('.featured column.summary article');
            var visibleArticle = _.find(articles, function (el) { return Util.isElementInViewport(el); });
            console.log("{0} just became visible", visibleArticle);
        });
    }
    Init.index = index;
})(Init = exports.Init || (exports.Init = {}));
function blahblah() {
    console.log('blahblah');
}
exports.blahblah = blahblah;

/***/ }),
</code>```

As you can see, exports.blahblah and exports.Init.index are assigned in this block - but the object I get back in my browser looks like this:

答:
The real answer to my question is

Do you even module, bro?

I just flat-out misunderstood the relationship between what typescript calls namespaces and modules, and what webpack thinks modules are.

After this exercise in futility, I'm not even sure what the point of Typescript namespaces are anymore, unless you have a multi-stage build process where you use tsc and tsconfig.json to create multiple transpiled bundles that will later be re-bundled by some other loader like Webpack.

Anyway, to the point:

Typescript "namespaces" mean nothing at all to Webpack (more specifically, ts-loader: see TypeStrong/ts-loader#193).  Webpack is not able to walk namespace dependencies, and so you wind up with undefined symbols in the bundle, which means the webpackBootstrap function also had no idea how to load things in the right order.  The entry point in my bundle was kinda like this:

```<code>/* 0 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(1);  // <-- actual entry point, exports are lost
__webpack_require__(2);
exports = __webpack_require__(4); // <-- not entry point, nothing is exported here anyway
/***/ }),
...
</code>```

Webpack (and ts-loader) require a form of modules that it understands in order to make the bootstrapper load things correctly.

I'm still using a Typescript namespace for structure, but I'm exporting it and using import to indicate dependencies on other Typescript modules:

```<code>import * as _ from 'lodash'
import * as Nav from './nav'
import * as Util from './util'

export namespace Init {
    // ...
}
</code>```

The main thing is the expression of the dependencies as es2015-style import/exports.

Body:
I'm trying to build a js bundle from typescript with exports that I can call directly from an inline script, but I don't seem to be able to get it to work.

I have a Typescript source file like this:

export namespace Init {
    export function index() {
        // do some things
    }
}

export function blahblah() { console.log('blahblah') }

This sits alongside some other sources in the same folder src/ts/*.ts.  My webpack.config.js looks like this:

'use strict';

module.exports = {
    context: __dirname,
    output: {
        filename: 'bundle.js',
        library: 'bitthicket',
    },
    devtool: 'sourcemap',
    resolve: {
        extensions: [ '.ts', '.tsx', '.js' ]
    },
    module: {
        rules: [
            { test: /\.tsx?$/, exclude: /node_modules/, loader: 'ts-loader' }
        ]
    }
}

And finally, my gulpfile.js looks like this:

var gulp = require('gulp')
var gutil = require('gulp-util')
var plumber = require('gulp-plumber')
var watch = require('gulp-watch')
var sass = require('gulp-sass')
var ts = require('gulp-typescript')
var clean = require('gulp-clean')
var webpack = require('webpack')
var webpack_config = require('./webpack.config.js')
var webpack_stream = require('webpack-stream')

let _sass = () =>
    gulp.src('src/css/**/*.scss')
        .pipe(plumber())
        .pipe(sass())
        .pipe(gulp.dest('static/css'))
        .on('end', () => gutil.log('_sass: done'))

let _webpack = () =>
    gulp.src('src/ts/**/*.ts')
        .pipe(plumber())
        .pipe(webpack_stream(webpack_config, webpack))
        .pipe(gulp.dest('static/js'))
        .on('end', () => gutil.log('_webpack: done'))

gulp.task('build:sass', _sass)
gulp.task('clean:sass', () => gulp.src('static/css/**/*').pipe(clean()))
gulp.task('watch:sass', () => watch('src/css/**/*.scss', () => _sass()))

gulp.task('build:webpack', _webpack)
gulp.task('clean:ts', () => gulp.src('static/js/**/*').pipe(clean()))
gulp.task('watch:webpack', () => watch('src/ts/**/*.ts', () => _webpack()))

gulp.task('watch', ['watch:sass', 'watch:webpack'])
gulp.task('clean', ['clean:sass', 'clean:ts'])
gulp.task('build', ['build:sass', 'build:webpack'])
gulp.task('default', ['clean', 'build'])

In an html file:

What's happening, as I understand it, is that webpack is getting the piped list of sources as entry files, as though they were placed on the commandline like webpack {src list} bundle.js.  But I've set my library output option, and the bitthicket variable does get set, but it's an empty object.  What happened to Init.index?

Edit: I added the export keyword to the Init namespace, as well as a plain function to init.ts to see what would happen - but the resulting object still doesn't have those functions.

Here's the resulting webpack bootstrapper argument:

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

exports.__esModule = true;
var _ = __webpack_require__(2);
var Init;
(function (Init) {
    function index() {
        Nav.attachNavbarScrollWatcher();
        document.addEventListener('scroll', function (event) {
            var articles = document.querySelectorAll('.featured column.summary article');
            var visibleArticle = _.find(articles, function (el) { return Util.isElementInViewport(el); });
            console.log("{0} just became visible", visibleArticle);
        });
    }
    Init.index = index;
})(Init = exports.Init || (exports.Init = {}));
function blahblah() {
    console.log('blahblah');
}
exports.blahblah = blahblah;

/***/ }),

As you can see, exports.blahblah and exports.Init.index are assigned in this block - but the object I get back in my browser looks like this:

Body:
The real answer to my question is

Do you even module, bro?

I just flat-out misunderstood the relationship between what typescript calls namespaces and modules, and what webpack thinks modules are.

After this exercise in futility, I'm not even sure what the point of Typescript namespaces are anymore, unless you have a multi-stage build process where you use tsc and tsconfig.json to create multiple transpiled bundles that will later be re-bundled by some other loader like Webpack.

Anyway, to the point:

Typescript "namespaces" mean nothing at all to Webpack (more specifically, ts-loader: see TypeStrong/ts-loader#193).  Webpack is not able to walk namespace dependencies, and so you wind up with undefined symbols in the bundle, which means the webpackBootstrap function also had no idea how to load things in the right order.  The entry point in my bundle was kinda like this:

/* 0 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(1);  // <-- actual entry point, exports are lost
__webpack_require__(2);
exports = __webpack_require__(4); // <-- not entry point, nothing is exported here anyway
/***/ }),
...

Webpack (and ts-loader) require a form of modules that it understands in order to make the bootstrapper load things correctly.

I'm still using a Typescript namespace for structure, but I'm exporting it and using import to indicate dependencies on other Typescript modules:

import * as _ from 'lodash'
import * as Nav from './nav'
import * as Util from './util'

export namespace Init {
    // ...
}

The main thing is the expression of the dependencies as es2015-style import/exports.


问:
MCV Core Dropdownlist Stored Procedure
I have a model that looks as follows:

```<code> public partial class RoutePartner
{
    public Guid Id { get; set; }
    [Required]
    public Guid PartnerId { get; set; }
    [Required]
    public string RouteCompany { get; set; }
}
</code>```

The partnerId comes from another TABLE that has an Id and Name. I'm trying to build my CRUD forms to load the list of partners and make them available to the form. That is the best way to do this in MVC Core? I see many .NET examples but none for CORE.

One last point is that partner drop down should be populated by a stored procedure.

Thanks
Dan

答:
Your class doesn't have to be the same as your database. Why not have a class called Partner that has the ParnterID and PartnerName? In your RoutePartner class have a Partner property, instead of just the ID.

```<code>Public class SomeViewModel //Used by your view
{
  public RouteParnter {get; set;}
  public ParnterList List<SelectListItem> {get; set;}

public static List<SelectListItem> PopulateDropdown()
    {
        List<SelectListItem> ls = new List<SelectListItem>();
        DataTable someTable = Database.LoadParnters(); // Database is your data layer
        foreach (var row in someTable.Rows)
        {
            ls.Add(new SelectListItem() { Text = row["PartnerName"].ToString();, Value = row["PartnerID"].ToString(); });
        }
        return ls;
    }
}

 public partial class RoutePartner
{
    public Guid Id { get; set; }
    [Required]
    public Partner SomePartner { get; set; }
    [Required]
    public string RouteCompany { get; set; }

  public RouteParnter(Guid id)
     {
    DataRow returnedRow = Database.LoadRouteParnter(id);
     Id = id;
   // Assuming your DataRow returned has all the info you need.
     RouteCompany = row["RouteCompany"];
     SomePartner = new Partner();
     SomePartner.PartnerId = row["PartnerID"]; // cast to guid, just example
     SomePartner.PartnerName = row["PartnerName"].ToString();

     }
    }

     public class Partner
    {
        public Guid PartnerId { get; set; }
        public string PartnerName { get; set; }

    }
</code>```

I would loosely couple the data layer. You could use ADO.NET or any other way to communicate with the database. I usually do this by creating a parameterized constructor (say taking in an ID to load), to call the data layer. The data layer returns a DataTable, DataRow, DataSet, or a custom object. In the constructor, you populate the values of the RouteParnter object. Likewise you could have a List in the ViewModel.

Title: MCV Core Dropdownlist Stored Procedure

Body:
I have a model that looks as follows:

 public partial class RoutePartner
{
    public Guid Id { get; set; }
    [Required]
    public Guid PartnerId { get; set; }
    [Required]
    public string RouteCompany { get; set; }
}

The partnerId comes from another TABLE that has an Id and Name. I'm trying to build my CRUD forms to load the list of partners and make them available to the form. That is the best way to do this in MVC Core? I see many .NET examples but none for CORE.

One last point is that partner drop down should be populated by a stored procedure.

Thanks
Dan

Body:
Your class doesn't have to be the same as your database. Why not have a class called Partner that has the ParnterID and PartnerName? In your RoutePartner class have a Partner property, instead of just the ID.

Public class SomeViewModel //Used by your view
{
  public RouteParnter {get; set;}
  public ParnterList List<SelectListItem> {get; set;}

public static List<SelectListItem> PopulateDropdown()
    {
        List<SelectListItem> ls = new List<SelectListItem>();
        DataTable someTable = Database.LoadParnters(); // Database is your data layer
        foreach (var row in someTable.Rows)
        {
            ls.Add(new SelectListItem() { Text = row["PartnerName"].ToString();, Value = row["PartnerID"].ToString(); });
        }
        return ls;
    }
}

 public partial class RoutePartner
{
    public Guid Id { get; set; }
    [Required]
    public Partner SomePartner { get; set; }
    [Required]
    public string RouteCompany { get; set; }

  public RouteParnter(Guid id)
     {
    DataRow returnedRow = Database.LoadRouteParnter(id);
     Id = id;
   // Assuming your DataRow returned has all the info you need.
     RouteCompany = row["RouteCompany"];
     SomePartner = new Partner();
     SomePartner.PartnerId = row["PartnerID"]; // cast to guid, just example
     SomePartner.PartnerName = row["PartnerName"].ToString();

     }
    }

     public class Partner
    {
        public Guid PartnerId { get; set; }
        public string PartnerName { get; set; }

    }

I would loosely couple the data layer. You could use ADO.NET or any other way to communicate with the database. I usually do this by creating a parameterized constructor (say taking in an ID to load), to call the data layer. The data layer returns a DataTable, DataRow, DataSet, or a custom object. In the constructor, you populate the values of the RouteParnter object. Likewise you could have a List in the ViewModel.


问:
How to convert a NSString to long double?
I am dealing with a long double value that can have huge values.

At one time I have this number represented as NSString and I need to convert it to long double. I see that the only API I have is

```<code>[myString doubleValue];
</code>```

I don't see a longDoubleValue.

Trying to convert this number using doubleValue...

```<code>long double x = (long double)[@"3765765765E933" doubleValue];
</code>```

gives me inf and the number in question is a legit long double value, as these numbers can go up to 1.18973149535723176502E+4932.

How do I do that?

答:
You can do this using the C library sscanf function. Here is a sample Objective-C wrapper:

```<code>long double stringToLongDouble(NSString *str)
{
   long double result = 0.0L;
   int ret = sscanf(str.UTF8String, "%Lg", &result);
   if (ret != 1)
   {
      // Insert your own error handling here, using NSLog for demo
      NSLog(@"stringToLongDouble: could not parse '%@' as long double", str);
      return 0.0L;
   }
   return result;
}
</code>```

The return from sscanf will be 1 if it succeeds. For possible error returns see the documentation (man 3 scanf in Terminal) and you need to decide how to handle these, the above example just does an NSLog.

Note: The size & precision of long double may vary by platform/OS version. The above has been tested with your value on El Capitan and iOS 10 (simulator only) using Xcode 8.

HTH

Body:
I am dealing with a long double value that can have huge values.

At one time I have this number represented as NSString and I need to convert it to long double. I see that the only API I have is

[myString doubleValue];

I don't see a longDoubleValue.

Trying to convert this number using doubleValue...

long double x = (long double)[@"3765765765E933" doubleValue];

gives me inf and the number in question is a legit long double value, as these numbers can go up to 1.18973149535723176502E+4932.

How do I do that?

Body:
You can do this using the C library sscanf function. Here is a sample Objective-C wrapper:

long double stringToLongDouble(NSString *str)
{
   long double result = 0.0L;
   int ret = sscanf(str.UTF8String, "%Lg", &result);
   if (ret != 1)
   {
      // Insert your own error handling here, using NSLog for demo
      NSLog(@"stringToLongDouble: could not parse '%@' as long double", str);
      return 0.0L;
   }
   return result;
}

The return from sscanf will be 1 if it succeeds. For possible error returns see the documentation (man 3 scanf in Terminal) and you need to decide how to handle these, the above example just does an NSLog.

Note: The size & precision of long double may vary by platform/OS version. The above has been tested with your value on El Capitan and iOS 10 (simulator only) using Xcode 8.

HTH


问:
Finding financial patterns of rows - sql with recursion
Let's consider I have a following table:

```<code>id    date        transaction_type     amount
 1    2017-01-01  deposit              30
 1    2017-01-01  deposit              20
 1    2017-01-02  withdrawal           -20
 1    2017-01-02  deposit              40
 1    2017-01-04  deposit              50
 1    2017-01-05  withdrawal           -100
 1    2017-01-07  withdrawal           -10
 1    2017-01-09  deposit              100
 1    2017-01-11  withdrawal           -50
 1    2017-01-21  deposit              20
 1    2017-01-22  deposit              30
 1    2017-01-31  withdrawal           -60
 2    2017-01-01  deposit              200
 ...  ...         ...                  ...
</code>```

The dates in the table are ordered from the oldest to the newest for each id (timestamp is not visible). I would like to find how many times a specific transaction pattern took place:

deposit -> deposit -> withdrawal, and the time between the first deposit and the withdrawal is 7 days or less.

So for the customer with id = 1, I would have 2 such cases (the third one does not satisfy the time condition).

As a result, I would like to get the following table:

```<code>id   number_of_times
1    2
2    ...
...  ...
</code>```

Is it something that can be done in SQL? Would I require recursion to get to the final table?

UPDATE:
As correctly pointed out, there are no intervening transactions - but what if there were some? Like any number of other transactions between 1st and 2nd deposit etc.

答:
Assuming you have no intervening transactions:</p>

```<code>select id, count(*)
from (select t.*,
             lead(transaction_type) over (partition by id order by date) as next_tt,
             lead(transaction_type, 2) over (partition by id order by date) as next_tt_2,
             lead(date, 2) over (partition by id order by date) as next_date_2
      from t
     ) t
where transaction_type = 'deposit' and next_tt = 'deposit' and
      next_tt_2 = 'withdrawal' and
      next_date_2 < date + interval '7 day'
group by id;
</code>```

Body:
Let's consider I have a following table:

id    date        transaction_type     amount
 1    2017-01-01  deposit              30
 1    2017-01-01  deposit              20
 1    2017-01-02  withdrawal           -20
 1    2017-01-02  deposit              40
 1    2017-01-04  deposit              50
 1    2017-01-05  withdrawal           -100
 1    2017-01-07  withdrawal           -10
 1    2017-01-09  deposit              100
 1    2017-01-11  withdrawal           -50
 1    2017-01-21  deposit              20
 1    2017-01-22  deposit              30
 1    2017-01-31  withdrawal           -60
 2    2017-01-01  deposit              200
 ...  ...         ...                  ...

The dates in the table are ordered from the oldest to the newest for each id (timestamp is not visible). I would like to find how many times a specific transaction pattern took place:

deposit -> deposit -> withdrawal, and the time between the first deposit and the withdrawal is 7 days or less.

So for the customer with id = 1, I would have 2 such cases (the third one does not satisfy the time condition).

As a result, I would like to get the following table:

id   number_of_times
1    2
2    ...
...  ...

Is it something that can be done in SQL? Would I require recursion to get to the final table?

UPDATE:
As correctly pointed out, there are no intervening transactions - but what if there were some? Like any number of other transactions between 1st and 2nd deposit etc.

Body:
Assuming you have no intervening transactions:

select id, count(*)
from (select t.*,
             lead(transaction_type) over (partition by id order by date) as next_tt,
             lead(transaction_type, 2) over (partition by id order by date) as next_tt_2,
             lead(date, 2) over (partition by id order by date) as next_date_2
      from t
     ) t
where transaction_type = 'deposit' and next_tt = 'deposit' and
      next_tt_2 = 'withdrawal' and
      next_date_2 < date + interval '7 day'
group by id;


问:
Java Strategy Pattern - unchecked call as member of type
I had a service that I was doing a lot of if/else statements so I found that using Strategy Pattern could help me a lot.

I am working with Mongo and I need to store two different models in the database in different collections. These models extends a common that have some similar information. I started deciding in runtime what class it would be used, but right now my code is showing a warning: unchecked call to 'save(T)' as a member of type 'Strategy'.

Below is the code I'm trying to do. For now, I just added a @SuppressWarnings("unchecked") and it's working so far, but I'd like to confirm if this might cause problems and what would be a better approach.

Question: How could I fix this?

Code as of now:

```<code>interface Strategy<T extends Person> {
    T save(T model);
    //other methods
}

class StudentStrategy implements Strategy<Student> {
    private StudentRepository studentRepository;

    public Student save(Student student) {
        return studentRepository.save(student);
    }
}
class TeacherStrategy implements Strategy<Teacher> {
    private TeacherRepository teacherRepository;

    public Teacher save(Teacher teacher) {
        return teacherRepository.save(teacher);
    }
}

class PersonService {
    void doSomething(Person person) {
        Strategy strategy = StrategyFactory.getStrategy(person.getType());
        strategy.save(person); //THIS LINE SAYS A unchecked call to 'save(T)' as a member of type 'Strategy'
    }
}

class StrategyFactory {
    public static Strategy getStrategy(PersonType personType) {
        if(personType == STUDENT) return new StudentStrategy();
        if(personType == TEACHER) return new TeacherStrategy();
        return null;
    }
}
</code>```

Old Code:

This is the code I was doing previously. As you can see, there are a lot of if/else. Changing the repository to store Person is not an options as I need the information of each sub class..

```<code>class OldPersonService {
    void doSomething(Person person) {
        if(person.getType == STUDENT) {
            studentRepository.save(person);
        } else {
            teacherRepository.save(person);
        }
        person.setBirthday(new Date());
        person.setName("john");
        if(person.getType == STUDENT) {
            studentRepository.findReferals(person);
        } else {
            teacherRepository.findReferals(person);
        }
    }
}
</code>```

答:
Your factory returns a raw Strategy :

```<code>class StrategyFactory {
    public static Strategy getStrategy(PersonType personType) {
        if(personType == STUDENT) return new StudentStrategy();
        if(personType == TEACHER) return new TeacherStrategy();
        return null;
    }
}
</code>```

So for the client class that uses this factory :

```<code>Strategy strategy = StrategyFactory.getStrategy(person.getType());
strategy.save(person);
</code>```

the compiler emits a warning as save() is a method designed to work with a generic type :

```<code>T save(T model);
</code>```

In your case T should be Student or Teacher but you don't specify it in the factory method.

To ensure type safety for the strategy factory client class, getStrategy() should return a strategy conforms to what the client expect to have.

You could for example define a scoped method type : <T extends Person> that you use to cast the strategy :

```<code> public static <T extends Person>  Strategy<T> getStrategy(PersonType personType) {
        if(personType == STUDENT) return (Strategy<T>) new StudentStrategy();
        if(personType == TEACHER) return (Strategy<T>) new TeacherStrategy();
        return null;
    }
 }
</code>```

You can notice the downcasts in the getStrategy() method.

These are unavoidable if you want to to define a unique method that returns a Strategy instance parameterized with a generic type that changes according to the client request.

Now, it is always better to perform cast in the provider classes than in the client classes where this should be performed multiple times and could be error prone.

In this way, the client could write :

```<code>Strategy<Person> strategy = StrategyFactory.getStrategy(person.getType());
strategy.save(person);
</code>```

Body:
I had a service that I was doing a lot of if/else statements so I found that using Strategy Pattern could help me a lot.

I am working with Mongo and I need to store two different models in the database in different collections. These models extends a common that have some similar information. I started deciding in runtime what class it would be used, but right now my code is showing a warning: unchecked call to 'save(T)' as a member of type 'Strategy'.

Below is the code I'm trying to do. For now, I just added a @SuppressWarnings("unchecked") and it's working so far, but I'd like to confirm if this might cause problems and what would be a better approach.

Question: How could I fix this?

Code as of now:

interface Strategy<T extends Person> {
    T save(T model);
    //other methods
}

class StudentStrategy implements Strategy<Student> {
    private StudentRepository studentRepository;

    public Student save(Student student) {
        return studentRepository.save(student);
    }
}
class TeacherStrategy implements Strategy<Teacher> {
    private TeacherRepository teacherRepository;

    public Teacher save(Teacher teacher) {
        return teacherRepository.save(teacher);
    }
}

class PersonService {
    void doSomething(Person person) {
        Strategy strategy = StrategyFactory.getStrategy(person.getType());
        strategy.save(person); //THIS LINE SAYS A unchecked call to 'save(T)' as a member of type 'Strategy'
    }
}

class StrategyFactory {
    public static Strategy getStrategy(PersonType personType) {
        if(personType == STUDENT) return new StudentStrategy();
        if(personType == TEACHER) return new TeacherStrategy();
        return null;
    }
}

Old Code:

This is the code I was doing previously. As you can see, there are a lot of if/else. Changing the repository to store Person is not an options as I need the information of each sub class..

class OldPersonService {
    void doSomething(Person person) {
        if(person.getType == STUDENT) {
            studentRepository.save(person);
        } else {
            teacherRepository.save(person);
        }
        person.setBirthday(new Date());
        person.setName("john");
        if(person.getType == STUDENT) {
            studentRepository.findReferals(person);
        } else {
            teacherRepository.findReferals(person);
        }
    }
}

Body:
Your factory returns a raw Strategy :

class StrategyFactory {
    public static Strategy getStrategy(PersonType personType) {
        if(personType == STUDENT) return new StudentStrategy();
        if(personType == TEACHER) return new TeacherStrategy();
        return null;
    }
}

So for the client class that uses this factory :

Strategy strategy = StrategyFactory.getStrategy(person.getType());
strategy.save(person);

the compiler emits a warning as save() is a method designed to work with a generic type :

T save(T model);

In your case T should be Student or Teacher but you don't specify it in the factory method.

To ensure type safety for the strategy factory client class, getStrategy() should return a strategy conforms to what the client expect to have.

You could for example define a scoped method type : <T extends Person> that you use to cast the strategy :

 public static <T extends Person>  Strategy<T> getStrategy(PersonType personType) {
        if(personType == STUDENT) return (Strategy<T>) new StudentStrategy();
        if(personType == TEACHER) return (Strategy<T>) new TeacherStrategy();
        return null;
    }
 }

You can notice the downcasts in the getStrategy() method.

These are unavoidable if you want to to define a unique method that returns a Strategy instance parameterized with a generic type that changes according to the client request.

Now, it is always better to perform cast in the provider classes than in the client classes where this should be performed multiple times and could be error prone.

In this way, the client could write :

Strategy<Person> strategy = StrategyFactory.getStrategy(person.getType());
strategy.save(person);


问:
json decode transforms Facebook payload
Facebook POST request from lead ads test tool is getting transformed on my end:

Facebook lead ad testing tool:
https://developers.facebook.com/tools/lead-ads-testing

Code to accept payload:

```<code>$input = json_decode(file_get_contents('php://input'), true);
</code>```

Framework: CakePHP 2.0

Debug:

```<code>2017-07-07 12:12:27 Debug: Array
(
    [entry] => Array
        (
            [0] => Array
                (
                    [changes] => Array
                        (
                            [0] => Array
                                (
                                    [field] => leadgen
                                    [value] => Array
                                        (
                                            [ad_id] => 0
                                            [form_id] => 7.2426956441826E+14
                                            [leadgen_id] => 7.9242177426971E+14
                                            [created_time] => 1499447542
                                            [page_id] => 4.8242822517084E+14
                                            [adgroup_id] => 0
                                        )

                                )

                        )

                    [id] => 482428225170841
                    [time] => 1499447543
                )

        )

    [object] => page
)
</code>```

PHP versions: 5.5.9

The problem:

```<code>[form_id] => 7.2426956441826E+14
[leadgen_id] => 7.9242177426971E+14
</code>```

When it should be:

```<code>[form_id] => 724269564418262
[leadgen_id] => 792421774269707
</code>```

So it seems to be converting those numbers for some reason.

I have a clone of this app on an older version of PHP ( 5.4 ) and dont seems to be having this issue there.

答:
I suspect you may need to set the 'options' of json_decode to use JSON_BIGINT_AS_STRING.
Check out http://php.net/manual/en/function.json-decode.php
And this post led me to the possible solution PHP JSON large integers</p>

Title: json decode transforms Facebook payload

Body:
Facebook POST request from lead ads test tool is getting transformed on my end:

Facebook lead ad testing tool:
https://developers.facebook.com/tools/lead-ads-testing

Code to accept payload:

$input = json_decode(file_get_contents('php://input'), true);

Framework: CakePHP 2.0

Debug:

2017-07-07 12:12:27 Debug: Array
(
    [entry] => Array
        (
            [0] => Array
                (
                    [changes] => Array
                        (
                            [0] => Array
                                (
                                    [field] => leadgen
                                    [value] => Array
                                        (
                                            [ad_id] => 0
                                            [form_id] => 7.2426956441826E+14
                                            [leadgen_id] => 7.9242177426971E+14
                                            [created_time] => 1499447542
                                            [page_id] => 4.8242822517084E+14
                                            [adgroup_id] => 0
                                        )

                                )

                        )

                    [id] => 482428225170841
                    [time] => 1499447543
                )

        )

    [object] => page
)

PHP versions: 5.5.9

The problem:

[form_id] => 7.2426956441826E+14
[leadgen_id] => 7.9242177426971E+14

When it should be:

[form_id] => 724269564418262
[leadgen_id] => 792421774269707

So it seems to be converting those numbers for some reason.

I have a clone of this app on an older version of PHP ( 5.4 ) and dont seems to be having this issue there.


问:
Is there any way "svn unrevert"?
Ack!  I just mistakenly ran "svn revert  somefile"  with the wrong filename pasted in.  Now my nicely modified file is gone!

I'd like a "svn unrevert" command.  AFIK there's no such thing. What is the next best way out of this mess?

答:
If you use Tortoise SVN:

Right click in any directory that's part of an SVN working copy

Select "Settings" from the TortoiseSVN menu.

Click on "Dialogs 1"

Check "Use recycle bin when reverting"

Title: Is there any way "svn unrevert"?


问:
Double slash (//) as XML comment
I was a bit surprised that using double slash as comments seems to be valid XML.

The following parses correctly with Python and xml.etree.ElementTree and under xmllint --format:

```<code><root>
    <child1>text1</child1>
    <child2></child2> //this is a valid comment
    <child3></child3>
</root>
</code>```

I first thought that this could be seen as text node for root element, but trying it on python3 proved me wrong:

```<code>>>> import xml.etree.ElementTree as ET
>>> r=ET.parse("test.xml").getroot()
>>> r.text
'\n    '
>>> child2=r[1]
>>> child2.text
>>> ET.tostring(child2)
b'<child2 /> //this is a valid comment\n    '
</code>```

Can someone point me to the spec where this is allowed ?

答:
This is not a valid comment but rather a text-node of the <root> element.

```<code><child2></child2> //this is a valid comment
</code>```

would be seen as

...element-node("child2"), text-node(" //this is a valid comment\n"), element-node("child3")...

What you want is

```<code><child2></child2> <!-- this is a valid comment -->
</code>```

which would translate to a real XML-comment-node

...element-node("child2"), comment-node(" //this is a valid comment"), element-node("child3")...

(I omitted empty text-nodes for simplicity.)

Title: Double slash (//) as XML comment

Body:
I was a bit surprised that using double slash as comments seems to be valid XML.

The following parses correctly with Python and xml.etree.ElementTree and under xmllint --format:

<root>
    <child1>text1</child1>
    <child2></child2> //this is a valid comment
    <child3></child3>
</root>

I first thought that this could be seen as text node for root element, but trying it on python3 proved me wrong:

>>> import xml.etree.ElementTree as ET
>>> r=ET.parse("test.xml").getroot()
>>> r.text
'\n    '
>>> child2=r[1]
>>> child2.text
>>> ET.tostring(child2)
b'<child2 /> //this is a valid comment\n    '

Can someone point me to the spec where this is allowed ?

Body:
This is not a valid comment but rather a text-node of the <root> element.

<child2></child2> //this is a valid comment

would be seen as

...element-node("child2"), text-node(" //this is a valid comment\n"), element-node("child3")...

What you want is

<child2></child2> <!-- this is a valid comment -->

which would translate to a real XML-comment-node

...element-node("child2"), comment-node(" //this is a valid comment"), element-node("child3")...

(I omitted empty text-nodes for simplicity.)


问:
How can I monitor user activities in my app without touching the main class that extends Activity?
Suppose an app project is already written, all you want to do is to additionally write a somehow standalone script that captures the onClick, onFocusChange or even onAppear in the app. Is that even feasible? How robust is the approach?

All answer I found was to fully add listeners (or global listeners, although less comprehensively functional) for each item or so, which is a boring work for a large project, and not always desired at the end of a production process(where I just cut in).

Another purposed approach was to locate the root of the nodes and scan from there? Correct me if that's a dead end. Other answer mentioned spying app, which is not the case, since it's the original developer who wants to track everything from inside the app.

答:
I am not sure, if this solves your problem but have your extension of views. Eg: MyTextView extends TextView then just override the touchEventHandlers, log what you want and dispatch the event down to the listeners.

So instead of normal TextViews, use  MyTextView.


问:
Redirect back to original page
Given some compojure routes:

```<code>(defroutes app-routes
  (GET "/" [] (display-some-html))
  (GET "/story" [] (display-more-html))
  (GET "/classes" [] (display-other-html))
  (POST "/delete" [id] (do (delete-some-id-from-db id)
                           (magic-redirect-function)))
  (route/resources "/")
  (route/not-found "Not Found"))
</code>```

Suppose I am able to POST to /delete from /, /story, /classes. How would I redirect to the page that the POST request originated from?

答:
The suggestion by deadghost is the best one. Here you can find my solution to getting automatic redirects to your main page using the lib-noir library. I hope this helps someone.</p>

```<code>    (ns hue-web-app.core
    (:require   [ring.middleware.defaults :refer [wrap-defaults api-        defaults site-defaults]]
                [ring.util.response :as response]        ;;from ring
                [compojure.core :refer :all]
                [compojure.route :as route]
                [noir.util.middleware :as middleware]
                [noir.session :as session]]  ;;noir for redirect to work

    (defroutes hue-app-routes
      (GET "/" [] (session/put! :origin "/")
                  (io/file "resources/testsite.html"))
      (GET "/turn-off" [] (turn-group-off 3 user)
                          (response/redirect (session/get! :origin "/")))
      (GET "/turn-on" [] (turn-group-on 3 user)
                         (response/redirect (session/get! :origin "/"))))

    ;;STARTING THE SERVER
    ;;--------------------------------------------------------------        ------------
    (defn siteparams
      []
      (run-jetty (-> #'hue-app-routes
                     wrap-reload
                     wrap-restful-format
                     wrap-params
                     session/wrap-noir-session
                     )
                 {:port 5003
                  :join? false}))
</code>```

Title: Redirect back to original page

Body:
Given some compojure routes:

(defroutes app-routes
  (GET "/" [] (display-some-html))
  (GET "/story" [] (display-more-html))
  (GET "/classes" [] (display-other-html))
  (POST "/delete" [id] (do (delete-some-id-from-db id)
                           (magic-redirect-function)))
  (route/resources "/")
  (route/not-found "Not Found"))

Suppose I am able to POST to /delete from /, /story, /classes. How would I redirect to the page that the POST request originated from?

Body:
The suggestion by deadghost is the best one. Here you can find my solution to getting automatic redirects to your main page using the lib-noir library. I hope this helps someone.

    (ns hue-web-app.core
    (:require   [ring.middleware.defaults :refer [wrap-defaults api-        defaults site-defaults]]
                [ring.util.response :as response]        ;;from ring
                [compojure.core :refer :all]
                [compojure.route :as route]
                [noir.util.middleware :as middleware]
                [noir.session :as session]]  ;;noir for redirect to work

    (defroutes hue-app-routes
      (GET "/" [] (session/put! :origin "/")
                  (io/file "resources/testsite.html"))
      (GET "/turn-off" [] (turn-group-off 3 user)
                          (response/redirect (session/get! :origin "/")))
      (GET "/turn-on" [] (turn-group-on 3 user)
                         (response/redirect (session/get! :origin "/"))))

    ;;STARTING THE SERVER
    ;;--------------------------------------------------------------        ------------
    (defn siteparams
      []
      (run-jetty (-> #'hue-app-routes
                     wrap-reload
                     wrap-restful-format
                     wrap-params
                     session/wrap-noir-session
                     )
                 {:port 5003
                  :join? false}))