问:
Using jquery $.ajax causes browser lock-up with arbor.js but 'native' JSON doesn't?
I'm making a Force Directed Graph of semanticproxy.com data using this arbor fork.  I have a main Explorer object which controls the nodes (following is abbreviated):

```<code>function Explorer(canvas) {
  // set up particle system
  this.ps = arbor.ParticleSystem(1000, 600, 0.5);
  this.ps.renderer = Renderer(canvas);
  this.canvas = $(canvas).get(0);

  var self = this;

  $('body').bind('subjectFound', function(event, sourceNode, targetName, targetRelevance) {
    self.addEdge(sourceNode, targetName, targetRelevance);
  });
}

Explorer.prototype.addEdge = function(source, target, relevance) {
  var target = this.ps.addNode(target);
  if (source != target) this.ps.addEdge(source, target, {relevance:relevance});
}

// start the explorer up on a new subject
Explorer.prototype.start = function(name) {
  var node = this.ps.addNode(name);
  node.populate(this.ps);
};

var xplor = new Explorer("#viewport");
xplor.start("Andreas Michl");
</code>```

You'll notice that the start() method adds a node to the particle system (works great), and then populates that node. Here's the code for the node, in part (please note that I'm augmenting the arbor.js Node prototype):

```<code>// fills this node with data from SemanticProxy
Node.prototype.populate = function() {
  var self = this;

  // get the semantic data for this subject
  // setup the handler function
  var functionName = "subjectHandler" + new Date().getTime();
  window[functionName] = function(data) {
    // invoke function with saved context and parameter
    self._fillFromSP.call(self, data);
  }
  var url = "http://service.semanticproxy.com/processurl/"+SP_KEY+"/jsonp:"+functionName+"/http://en.wikipedia.org/wiki/"+this.name;
  $.ajax({url: url, dataType: "script", type: "GET", cache: false, callback: null, data: null});
};

// fills this subject with data from SemanticProxy
Node.prototype._fillFromSP = function(data) {
  var self = this;
  $.each(data, function(key, val) {
    if (key != "doc") {
      if (val.name && val.relevance) {
        $('body').triggerHandler('subjectFound', [self, val.name, val.relevance]);
      }
    }
  });
}
</code>```

So once the semanticproxy data is returned it should trigger the 'subjectFound' handler in the Explorer object and add a node, just like it did before with the first node. But it chokes every time - the diagram locks up and the usage on one of my cpu cores hits 100% (Firefox and Chrome).

However, if I change the populate method to the following, it works fine:

```<code>Node.prototype.populate = function() {
  var self = this;

  // get the semantic data for this subject
  // setup the handler function
  var functionName = "subjectHandler" + new Date().getTime();
  window[functionName] = function(data) {
    // invoke function with saved context and parameter
    self._fillFromSP.call(self, data);
  }
  window[functionName](json);
};

var json = {"doc":{"info"  ...  "length":48}]}};
</code>```

where the json variable holds the data from the very same semanticproxy URL as before.  All the relevant nodes appear and render beautifully.  So it's only when I use the $.ajax call, and it's only when the data actually get's back to my browser that it locks up. I can step through the code and it calls the $('body').triggerHandler with the correct parameters the correct number of times. It successfully triggers everything to the Explorer.addEdge() call where the arbor particle system is told to add some nodes - and that's when it doesn't work. But only when using the AJAX call!

Any ideas?  Thanks in advance.

Update:
I just set up a little Rails controller to use as a proxy. No luck either. Instead of the $.ajax call and the weird window handler, in the populate method I just did a straight:

```<code>var url = "http://localhost:3000/?url=http://service.semanticproxy.com/processurl/8bv73k5hgj9prkhee9rrr9s4/json/http://en.wikipedia.org/wiki/Andreas_Michl";
$.getJSON(url, function(data) {
  self._fillFromSP(data);
});
</code>```

But that had the same behaviour - lock-up.  Maybe a race condition or something else in the arbor code?

Solution

The populate method now reads:

```<code>// fills this node with data from Wikipedia and SemanticProxy
Node.prototype.populate = function() {
  var self = this;

  // get the semantic data for this subject
  var ajaxWorker = new Worker('javascripts/worker_ajax.js');
  ajaxWorker.onmessage = function(event) {
    self._fillFromSP(event.data);
  };
  ajaxWorker.postMessage({name: this.name});
};
</code>```

and worker_ajax.js is:

```<code>onmessage = function(event) {
  var SP_KEY = "xxxx";
  var url = "http://service.semanticproxy.com/processurl/"+SP_KEY+"/jsonp:handle/http://en.wikipedia.org/wiki/"+event.data.name;
  importScripts(url);
}

var handle = function(json) {
  postMessage(json);
}
</code>```

答:
WebWorkers and JSONP don't go together, because WebWorkers have no DOM to attach elements to, in other words you cannot attach your script tag to anywhere.

Read this article for a possible work-around: http://cggallant.blogspot.com/2010/10/jsonp-overview-and-jsonp-in-html-5-web.html

As for using JQuery in Webworkers, take a look at this topic: HTML Web Worker and Jquery Ajax call

Body:
I'm making a Force Directed Graph of semanticproxy.com data using this arbor fork.  I have a main Explorer object which controls the nodes (following is abbreviated):

function Explorer(canvas) {
  // set up particle system
  this.ps = arbor.ParticleSystem(1000, 600, 0.5);
  this.ps.renderer = Renderer(canvas);
  this.canvas = $(canvas).get(0);

  var self = this;

  $('body').bind('subjectFound', function(event, sourceNode, targetName, targetRelevance) {
    self.addEdge(sourceNode, targetName, targetRelevance);
  });
}

Explorer.prototype.addEdge = function(source, target, relevance) {
  var target = this.ps.addNode(target);
  if (source != target) this.ps.addEdge(source, target, {relevance:relevance});
}

// start the explorer up on a new subject
Explorer.prototype.start = function(name) {
  var node = this.ps.addNode(name);
  node.populate(this.ps);
};

var xplor = new Explorer("#viewport");
xplor.start("Andreas Michl");

You'll notice that the start() method adds a node to the particle system (works great), and then populates that node. Here's the code for the node, in part (please note that I'm augmenting the arbor.js Node prototype):

// fills this node with data from SemanticProxy
Node.prototype.populate = function() {
  var self = this;

  // get the semantic data for this subject
  // setup the handler function
  var functionName = "subjectHandler" + new Date().getTime();
  window[functionName] = function(data) {
    // invoke function with saved context and parameter
    self._fillFromSP.call(self, data);
  }
  var url = "http://service.semanticproxy.com/processurl/"+SP_KEY+"/jsonp:"+functionName+"/http://en.wikipedia.org/wiki/"+this.name;
  $.ajax({url: url, dataType: "script", type: "GET", cache: false, callback: null, data: null});
};

// fills this subject with data from SemanticProxy
Node.prototype._fillFromSP = function(data) {
  var self = this;
  $.each(data, function(key, val) {
    if (key != "doc") {
      if (val.name && val.relevance) {
        $('body').triggerHandler('subjectFound', [self, val.name, val.relevance]);
      }
    }
  });
}

So once the semanticproxy data is returned it should trigger the 'subjectFound' handler in the Explorer object and add a node, just like it did before with the first node. But it chokes every time - the diagram locks up and the usage on one of my cpu cores hits 100% (Firefox and Chrome).

However, if I change the populate method to the following, it works fine:

Node.prototype.populate = function() {
  var self = this;

  // get the semantic data for this subject
  // setup the handler function
  var functionName = "subjectHandler" + new Date().getTime();
  window[functionName] = function(data) {
    // invoke function with saved context and parameter
    self._fillFromSP.call(self, data);
  }
  window[functionName](json);
};

var json = {"doc":{"info"  ...  "length":48}]}};

where the json variable holds the data from the very same semanticproxy URL as before.  All the relevant nodes appear and render beautifully.  So it's only when I use the $.ajax call, and it's only when the data actually get's back to my browser that it locks up. I can step through the code and it calls the $('body').triggerHandler with the correct parameters the correct number of times. It successfully triggers everything to the Explorer.addEdge() call where the arbor particle system is told to add some nodes - and that's when it doesn't work. But only when using the AJAX call!

Any ideas?  Thanks in advance.

Update:
I just set up a little Rails controller to use as a proxy. No luck either. Instead of the $.ajax call and the weird window handler, in the populate method I just did a straight:

var url = "http://localhost:3000/?url=http://service.semanticproxy.com/processurl/8bv73k5hgj9prkhee9rrr9s4/json/http://en.wikipedia.org/wiki/Andreas_Michl";
$.getJSON(url, function(data) {
  self._fillFromSP(data);
});

But that had the same behaviour - lock-up.  Maybe a race condition or something else in the arbor code?

Solution

The populate method now reads:

// fills this node with data from Wikipedia and SemanticProxy
Node.prototype.populate = function() {
  var self = this;

  // get the semantic data for this subject
  var ajaxWorker = new Worker('javascripts/worker_ajax.js');
  ajaxWorker.onmessage = function(event) {
    self._fillFromSP(event.data);
  };
  ajaxWorker.postMessage({name: this.name});
};

and worker_ajax.js is:

onmessage = function(event) {
  var SP_KEY = "xxxx";
  var url = "http://service.semanticproxy.com/processurl/"+SP_KEY+"/jsonp:handle/http://en.wikipedia.org/wiki/"+event.data.name;
  importScripts(url);
}

var handle = function(json) {
  postMessage(json);
}


来源: stackexchange

问:
How can I shorten the use of this function? Alexa/NodeJs
I have this function that I am using to return a slot value. If the slot is a synonym, it will revise the synonym to the canonical slot value. Here is the code I have now:

```<code>var slotHelper = function() { };

slotHelper.prototype.slotValue = (slot, useId) => {
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
};

//Example
//let category = slotValue(handlerInput.requestEnvelope.request.intent.slots.category, true);

module.exports = new slotHelper();
</code>```

I am trying to shorten the //example to where I can just type this:

```<code>let category = slotHelper.slotValue(category);
</code>```

And return the canonical slot value.

I have tried some different approaches and they all result in: "Error handled: category is not defined"

Here are the different approaches I tried:

```<code>var slotHelper = function() { };

slotHelper.prototype.slotValue = (slotName, useId) => {
    let slot = handlerInput.requestEnvelope.request.intent.slots[slotName];
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
}

module.exports = new slotHelper();
</code>```

AND

```<code>var slotHelper = function() { };

slotHelper.prototype.slotValue = (slotName, useId) => {
    let slot = handlerInput.requestEnvelope.request.intent.slots.slotName;
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
}

module.exports = new slotHelper();
</code>```

Of course, with the second one slotName is greyed out because that's not the right approach. Does anyone have any idea how I can revise this to where I can use:

```<code>let category = slotHelper.slotValue(category);
</code>```

I am trying to generalize this function so that I can use it for all my slots in the future. This would make it easier to work with in my code... instead of always having to put:

```<code>let category = slotHelper.slotValue(handlerInput.requestEnvelope.request.intent.slots.category);
</code>```

答: Use this function as it's the helper you're looking for</p>

ContentLicense: CC BY-SA 4.0

Body:
I have this function that I am using to return a slot value. If the slot is a synonym, it will revise the synonym to the canonical slot value. Here is the code I have now:

var slotHelper = function() { };

slotHelper.prototype.slotValue = (slot, useId) => {
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
};

//Example
//let category = slotValue(handlerInput.requestEnvelope.request.intent.slots.category, true);

module.exports = new slotHelper();

I am trying to shorten the //example to where I can just type this:

let category = slotHelper.slotValue(category);

And return the canonical slot value.

I have tried some different approaches and they all result in: "Error handled: category is not defined"

Here are the different approaches I tried:

var slotHelper = function() { };

slotHelper.prototype.slotValue = (slotName, useId) => {
    let slot = handlerInput.requestEnvelope.request.intent.slots[slotName];
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
}

module.exports = new slotHelper();

AND

var slotHelper = function() { };

slotHelper.prototype.slotValue = (slotName, useId) => {
    let slot = handlerInput.requestEnvelope.request.intent.slots.slotName;
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
}

module.exports = new slotHelper();

Of course, with the second one slotName is greyed out because that's not the right approach. Does anyone have any idea how I can revise this to where I can use:

let category = slotHelper.slotValue(category);

I am trying to generalize this function so that I can use it for all my slots in the future. This would make it easier to work with in my code... instead of always having to put:

let category = slotHelper.slotValue(handlerInput.requestEnvelope.request.intent.slots.category);


问:
How to get environment variable in Jenkins Groovy script console?
In Jenkins configuration (http://JenkinsURL/configure) within "Global properties" I defined some "Environment variables".

How can I access them in the Groovy Script console (http://JenkinsURL/script)?

I've tried to find appropriate solution (for example the solutions mentioned in: Access to build environment variables from a groovy script in a Jenkins build step (Windows))
but it seems that none of them work for me.

I've tried for example:

```<code>System.getenv("myVar")
</code>```

and

```<code>manager.build.getEnvironment(listener).get('myVar') //no manager error
</code>```

and

```<code>import jenkins.model.Jenkins
Jenkins.instance.getProperty('myVar') //No signature of method: hudson.model.Hudson.getProperty() is applicable for argument types: (java.lang.String)
</code>```

and

```<code>import jenkins.model.Jenkins
Jenkins.instance.ParameterValue("DEV_local")
</code>```

答:
You can use System to get environment variables.

```<code>def env = System.getenv()
println(env['JENKINS_HOME'])
</code>```

(See also http://@myJenkHostname@/env-vars.html (where @myJenkHostname@ is your Jenkins hostname) for a list of built-in environment variables.)

ContentLicense: CC BY-SA 3.0

Body:
In Jenkins configuration (http://JenkinsURL/configure) within "Global properties" I defined some "Environment variables".

How can I access them in the Groovy Script console (http://JenkinsURL/script)?

I've tried to find appropriate solution (for example the solutions mentioned in: Access to build environment variables from a groovy script in a Jenkins build step (Windows))
but it seems that none of them work for me.

I've tried for example:

System.getenv("myVar")

and

manager.build.getEnvironment(listener).get('myVar') //no manager error

and

import jenkins.model.Jenkins
Jenkins.instance.getProperty('myVar') //No signature of method: hudson.model.Hudson.getProperty() is applicable for argument types: (java.lang.String)

and

import jenkins.model.Jenkins
Jenkins.instance.ParameterValue("DEV_local")

Body:
You can use System to get environment variables.

def env = System.getenv()
println(env['JENKINS_HOME'])

(See also http://@myJenkHostname@/env-vars.html (where @myJenkHostname@ is your Jenkins hostname) for a list of built-in environment variables.)


问:
How can I change the color of a textbox based on the cell value in a loop?
On my userform, I have a "next" button which loops through a worksheet.  If cell in column CL = "yes", then change color of textbox10 to Yellow, otherwise leave it white.  Problem is, it will only change to yellow if I don't have an "Else" statement, and  then it won't turn back to white.

I've tried changing Private Sub TextBox10_Change() to Private Sub TextBox10_Enter() and then also added a ...Textbox10_Exit() but still the same results.

```<code>Private Sub TextBox10_change()

Dim i As Integer

Dim Lastrow As Integer

Lastrow = Cells(rows.Count, 1).End(xlUp).Row

For i = 2 To Lastrow

If ActiveSheet.Range("CL" & i) = "yes" Then
    Me.TextBox10.BackColor = vbYellow
Else
    Me.TextBox10.BackColor = vbWhite
End If

Next i

End Sub
</code>```

Basically, nothing happens unless I remove:

```<code>Else

  Me.Textbox10.BackColor = vbWhite
</code>```

and even then it turns yellow but never turns back to white.

答: The way it is written, it will only display a color change for the textbox, based on the value of CL in the last row, Did you want for it to cycle through one row at a time?</p>

Body:
On my userform, I have a "next" button which loops through a worksheet.  If cell in column CL = "yes", then change color of textbox10 to Yellow, otherwise leave it white.  Problem is, it will only change to yellow if I don't have an "Else" statement, and  then it won't turn back to white.

I've tried changing Private Sub TextBox10_Change() to Private Sub TextBox10_Enter() and then also added a ...Textbox10_Exit() but still the same results.

Private Sub TextBox10_change()

Dim i As Integer

Dim Lastrow As Integer

Lastrow = Cells(rows.Count, 1).End(xlUp).Row

For i = 2 To Lastrow

If ActiveSheet.Range("CL" & i) = "yes" Then
    Me.TextBox10.BackColor = vbYellow
Else
    Me.TextBox10.BackColor = vbWhite
End If

Next i

End Sub

Basically, nothing happens unless I remove:

Else

  Me.Textbox10.BackColor = vbWhite

and even then it turns yellow but never turns back to white.


问:
Need to add 0 to match the length
I have unique identifiers for each row. For example 19Jan187938 or 19Jan206414 but there are some which are like 19Jan17333. I need to add a 0 before the number if it's 5 digits, so it becomes 19Jan017333.

I tried,

```<code>=TEXT(CONCATENATE(19,AB2,C2),"000000")
</code>```

even with 11 0's, since the total length is 11. Nothing changes.

答:
Try the following:

```<code>=CONCATENATE(LEFT(AB2,5),TEXT(RIGHT(AB2,LEN(AB2)-5),"000000"))
</code>```

It will basically, take the first 5 characters and concatenate that with the remaining characters formatted as a six digit number with leading zeroes

Title: Need to add 0 to match the length

Body:
I have unique identifiers for each row. For example 19Jan187938 or 19Jan206414 but there are some which are like 19Jan17333. I need to add a 0 before the number if it's 5 digits, so it becomes 19Jan017333.

I tried,

=TEXT(CONCATENATE(19,AB2,C2),"000000")

even with 11 0's, since the total length is 11. Nothing changes.

Body:
Try the following:

=CONCATENATE(LEFT(AB2,5),TEXT(RIGHT(AB2,LEN(AB2)-5),"000000"))

It will basically, take the first 5 characters and concatenate that with the remaining characters formatted as a six digit number with leading zeroes


问:
Exported Blender Model "faces" the wrong way When Importing to SceneKit
I've bought a 3D model form TurboSquid, and I need to scale it down to an exact size. I'm a complete newbie when it comes to 3D modelling and Blender but I've managed to find enough tutorials to do this and export the file.

The problem is that I can only get it to export a view from the corner of the object, which I problematic as I want to line-up several of the objects together as part of my ARKit app.

I'm exporting as a Collada .dae file, selecting "Selection Only" as I only need the model, no lights or camera (is this right?).

Is there any specific way it needs to point in Blender? Would aligning it with the camera help (even though I'm exporting the object only)? Can I select a side to be the "front"?

I can angle it somewhat correctly in the SceneKit Editor but I'd prefer to do it in Blender.

答:
I can't remember where I got this or I would happily give credit, but it's how I got my Turbo Squid models to work.  I needed to flip mine around and fix the Y-Up axis, but you might be able to fix your rotation with this.

Make sure everything is selected and press R (for rotate). Just like with scaling, you’ll find that mouse movement rotates the selected objects. But we want to do a particular rotation: 180 degrees around Blender’s Z-axis. To do that quickly, assuming you already pressed R, press Z, then type 180, and press Enter. From my experience, doing this rotation will correct the orientation of your model.
Just as with scale, to apply rotation permanently, press Ctrl+A. In the menu that pops up, click “Rotation”.

Set Y-Up for Scenekit if you need it.

/Applications/Xcode.app/Contents/Developer/usr/bin/scntool --convert fighter0.dae --format c3d --output out.dae --force-y-up --force-interleaved --look-for-pvrtc-image


问:
Reducer error always undefined when passing wrong URL in NgRx in Ionic 3
Could someone help me to see what's wrong here that every time I try to cause an error I get:
core.js:12632 ERROR TypeError: Cannot read property 'error' of undefined

My Effect:

```<code>  @Effect() loadByEmail = this.actions
    .pipe(
      ofType(ProfileActions.ActionTypes.Begin),
      map((action: ProfileActions.LoadProfileBegin) => action),
      switchMap(action => this.service.loadByEmail(action.email, true)),
      map(response => ({
        type: ProfileActions.ActionTypes.Success,
        payload: response,
        error: null
      })),
      catchError((error) => of ({
        type: ProfileActions.ActionTypes.Failure,
        error: error
      }))
    );
</code>```

The reducer:

```<code>export interface ProfileState {
  payload: any;
  loading: boolean;
  error: any;
}

const initialState: ProfileState = {
  loading: false,
  error: null,
  payload: null
};

export function profileReducer(state = initialState, action: profileActions.ActionsUnion): ProfileState {
  switch (action.type) {

    case profileActions.ActionTypes.Begin: {
      return {
        ...state,
        loading: true,
        error: null
      };
    }

    case profileActions.ActionTypes.Success: {
      return {
        ...state,
        loading: false,
        payload: action.payload.data
      };
    }

    case profileActions.ActionTypes.Failure: {
      return {
        ...state,
        loading: false,
        error: action.payload.error /* this is the line 49*/
      };
    }

    default: {
      return state;
    }
  }
}

export const getProfile = (state: ProfileState) => state.payload;
</code>```

I think I might be doing some big mistake here that causes this problem, I need to capture the error when subscribing.

Here are the actions, actually it's a very basic stuff, it's just a flow to load a profile from the web service by an email address.

Here are the three actions:

```<code>export enum ActionTypes {
  Begin = "[Profile] Load data begin",
    Success = "[Profile] Load data success",
    Failure = "[Profile] Load data failure"
}

export class LoadProfileBegin implements Action {
  readonly type = ActionTypes.Begin;
  constructor(public email: string) {}
}

/**
 * The main thing to note here is that our LoadDataSuccess and
 * LoadDataFailure actions will include a payload - we will either
 * pass the loaded data along with LoadDataSuccess or we will
 * pass the error to LoadDataFailure.
 */
export class LoadProfileSuccess implements Action {
  readonly type = ActionTypes.Success;

  constructor(public payload: {
    data: any
  }) { }
}

export class LoadProfileFailure implements Action {
  readonly type = ActionTypes.Failure;

  constructor(public payload: {
    error: any
  }) { }
}

export type ActionsUnion = LoadProfileBegin | LoadProfileSuccess | LoadProfileFailure;
</code>```

Then I have a service to call a rest service which will return an Observable to the Effect:

```<code>  public loadByEmail(email: string, showLoading ? : boolean): Observable < any > {
    const data: any = {
      'email': email
    };
    return <Observable < any >> this.restService.sendPost('profiles__/find-by-email', data);
  }
</code>```

Then I have two methods: one to dispatch the action and the other to return the state:

```<code>  loadProfileState(email: string) {
    this.store.dispatch(new ProfileActions.LoadProfileBegin(email));
  }

  getProfileState(): Store < ProfileState > {
    return this.store.select(getProfileState);
  }
</code>```

And then in some component I subscribe trying to catch the error:

```<code>this.profileService.getProfileState().subscribe(state => {
  if (state.payload) {
    const profile = state.payload.json;
    this.setProfileData(profile, true);
  }

  if (state.error){
    // This one here never reaches
  }
});
</code>```

As you can see on the image below the error happens but never capture and passed using the action:

I know it's a lot but if someone could notice anything and point it to me I would appreciate very much.

答:
I doubt that your reducer is being called when your effect "catchError" operator returns of(....). In fact, you must return an action like - </p>

```<code>@Effect() loadByEmail = this.actions
    .pipe(
      ofType(ProfileActions.ActionTypes.Begin),
      map((action: ProfileActions.LoadProfileBegin) => action),
      switchMap(action => this.service.loadByEmail(action.email, true)),
      map(response => ({
        type: ProfileActions.ActionTypes.Success,
        payload: response,
        error: null
      })),
      catchError((error) => [new ProfileActions.LoadProfileFailure({error})])
    );
</code>```

Body:
Could someone help me to see what's wrong here that every time I try to cause an error I get:
core.js:12632 ERROR TypeError: Cannot read property 'error' of undefined

My Effect:

  @Effect() loadByEmail = this.actions
    .pipe(
      ofType(ProfileActions.ActionTypes.Begin),
      map((action: ProfileActions.LoadProfileBegin) => action),
      switchMap(action => this.service.loadByEmail(action.email, true)),
      map(response => ({
        type: ProfileActions.ActionTypes.Success,
        payload: response,
        error: null
      })),
      catchError((error) => of ({
        type: ProfileActions.ActionTypes.Failure,
        error: error
      }))
    );

The reducer:

export interface ProfileState {
  payload: any;
  loading: boolean;
  error: any;
}

const initialState: ProfileState = {
  loading: false,
  error: null,
  payload: null
};

export function profileReducer(state = initialState, action: profileActions.ActionsUnion): ProfileState {
  switch (action.type) {

    case profileActions.ActionTypes.Begin: {
      return {
        ...state,
        loading: true,
        error: null
      };
    }

    case profileActions.ActionTypes.Success: {
      return {
        ...state,
        loading: false,
        payload: action.payload.data
      };
    }

    case profileActions.ActionTypes.Failure: {
      return {
        ...state,
        loading: false,
        error: action.payload.error /* this is the line 49*/
      };
    }

    default: {
      return state;
    }
  }
}

export const getProfile = (state: ProfileState) => state.payload;

I think I might be doing some big mistake here that causes this problem, I need to capture the error when subscribing.

Here are the actions, actually it's a very basic stuff, it's just a flow to load a profile from the web service by an email address.

Here are the three actions:

export enum ActionTypes {
  Begin = "[Profile] Load data begin",
    Success = "[Profile] Load data success",
    Failure = "[Profile] Load data failure"
}

export class LoadProfileBegin implements Action {
  readonly type = ActionTypes.Begin;
  constructor(public email: string) {}
}

/**
 * The main thing to note here is that our LoadDataSuccess and
 * LoadDataFailure actions will include a payload - we will either
 * pass the loaded data along with LoadDataSuccess or we will
 * pass the error to LoadDataFailure.
 */
export class LoadProfileSuccess implements Action {
  readonly type = ActionTypes.Success;

  constructor(public payload: {
    data: any
  }) { }
}

export class LoadProfileFailure implements Action {
  readonly type = ActionTypes.Failure;

  constructor(public payload: {
    error: any
  }) { }
}

export type ActionsUnion = LoadProfileBegin | LoadProfileSuccess | LoadProfileFailure;

Then I have a service to call a rest service which will return an Observable to the Effect:

  public loadByEmail(email: string, showLoading ? : boolean): Observable < any > {
    const data: any = {
      'email': email
    };
    return <Observable < any >> this.restService.sendPost('profiles__/find-by-email', data);
  }

Then I have two methods: one to dispatch the action and the other to return the state:

  loadProfileState(email: string) {
    this.store.dispatch(new ProfileActions.LoadProfileBegin(email));
  }

  getProfileState(): Store < ProfileState > {
    return this.store.select(getProfileState);
  }

And then in some component I subscribe trying to catch the error:

this.profileService.getProfileState().subscribe(state => {
  if (state.payload) {
    const profile = state.payload.json;
    this.setProfileData(profile, true);
  }

  if (state.error){
    // This one here never reaches
  }
});

As you can see on the image below the error happens but never capture and passed using the action:

I know it's a lot but if someone could notice anything and point it to me I would appreciate very much.

Body:
I doubt that your reducer is being called when your effect "catchError" operator returns of(....). In fact, you must return an action like -

@Effect() loadByEmail = this.actions
    .pipe(
      ofType(ProfileActions.ActionTypes.Begin),
      map((action: ProfileActions.LoadProfileBegin) => action),
      switchMap(action => this.service.loadByEmail(action.email, true)),
      map(response => ({
        type: ProfileActions.ActionTypes.Success,
        payload: response,
        error: null
      })),
      catchError((error) => [new ProfileActions.LoadProfileFailure({error})])
    );


问:
How to dynamically add css to ckeditor without a css file
I have a situation where I am storing dynamic css data about a text object in a database as json. I need to map that same css data into styles in CKEditor. I am successfully able to load the classes into the CKEDITOR styles dropdown by parsing the json into the style set by running:

```<code>CKEDITOR.stylesSet.add('myStyles',styleObj);
</code>```

Unfortunately this does not fully work with the onscreen text because the css does not exists as a file.

I've also successfully generate the css into the head of the dom by appending the dynamically generated css to a style tag. Unfortunately this still does not connect the actual css generated to the CKEDITOR because it is in a separate context.

Does anyone know how I can either connect document level css to the CKEDITOR instance or generate the CSS in a way that CKEDITOR understands? I'd prefer not to write a temporary CSS file to disk for every single user who needs to view the text object.

答:
Just for posterity.  I've seen answers that say this will work

```<code>    CKEDITOR.on('instanceCreated', function (event) {
        event.editor.addCss(styles);
    });
</code>```

but it does not, you have to use

```<code>    CKEDITOR.on('instanceCreated', function (event) {
        CKEDITOR.addCss(styles);
    });
</code>```

also if your styles variable changes you have to destroy and recreate your ckeditor instance with the new styles.

Body:
I have a situation where I am storing dynamic css data about a text object in a database as json. I need to map that same css data into styles in CKEditor. I am successfully able to load the classes into the CKEDITOR styles dropdown by parsing the json into the style set by running:

CKEDITOR.stylesSet.add('myStyles',styleObj);

Unfortunately this does not fully work with the onscreen text because the css does not exists as a file.

I've also successfully generate the css into the head of the dom by appending the dynamically generated css to a style tag. Unfortunately this still does not connect the actual css generated to the CKEDITOR because it is in a separate context.

Does anyone know how I can either connect document level css to the CKEDITOR instance or generate the CSS in a way that CKEDITOR understands? I'd prefer not to write a temporary CSS file to disk for every single user who needs to view the text object.

Body:
Just for posterity.  I've seen answers that say this will work

    CKEDITOR.on('instanceCreated', function (event) {
        event.editor.addCss(styles);
    });

but it does not, you have to use

    CKEDITOR.on('instanceCreated', function (event) {
        CKEDITOR.addCss(styles);
    });

also if your styles variable changes you have to destroy and recreate your ckeditor instance with the new styles.


问:
Should this code fail to compile in C++17?
I was updating a project to use C++17 and found a few instances where code that followed this pattern was causing a compile error on recent versions of clang:

```<code>#include <boost/variant.hpp>

struct vis : public boost::static_visitor<void>
{
    void operator()(int) const { }
};

int main()
{
    boost::variant<int> v = 0;
    boost::apply_visitor(vis{}, v);
}
</code>```

Using clang v8.0 in C++17 mode, this fails with the following error:

```<code><source>:11:30: error: temporary of type 'boost::static_visitor<void>' has protected destructor
    boost::apply_visitor(vis{}, v);
                             ^
/opt/compiler-explorer/libs/boost_1_64_0/boost/variant/static_visitor.hpp:53:5: note: declared protected here
    ~static_visitor() = default;
</code>```

However, it compiles cleanly in C++14 mode. I found that if I change the brace initialization vis{} to parentheses vis(), then it compiles correctly in both modes. Every version of gcc that I've tried allows both variants in C++17 mode.

Is this a correct change in behavior from C++14 to C++17, or is this a clang bug? If it is correct, why is it now invalid in C++17 (or maybe it always was, but clang just allows it in earlier standard revisions)?

答:
clang is correct here. Here's a reduced example:

```<code>struct B {
protected:
    B() { }
};

struct D : B { };

auto d = D{};
</code>```

In C++14, D is not an aggregate because it has a base class, so D{} is "normal" (non-aggregate) initialization which invokes D's default constructor, which in turn invokes B's default constructor. This is fine, because D has access to B's default constructor.

In C++17, the definition of aggregate was widened - base classes are now allowed (as long as they're non-virtual). D is now an aggregate, which means that D{} is aggregate initialization. And in aggregate-initialization, this means that we (the caller) are initializing all the subobjects - including the base class subobject. But we do not have access to B's constructor (it is protected), so we cannot invoke it, so it is ill-formed.

Fear not, the fix is easy. Use parentheses:

```<code>auto d = D();
</code>```

This goes back to invoking D's default constructor as before.

Body:
I was updating a project to use C++17 and found a few instances where code that followed this pattern was causing a compile error on recent versions of clang:

#include <boost/variant.hpp>

struct vis : public boost::static_visitor<void>
{
    void operator()(int) const { }
};

int main()
{
    boost::variant<int> v = 0;
    boost::apply_visitor(vis{}, v);
}

Using clang v8.0 in C++17 mode, this fails with the following error:

<source>:11:30: error: temporary of type 'boost::static_visitor<void>' has protected destructor
    boost::apply_visitor(vis{}, v);
                             ^
/opt/compiler-explorer/libs/boost_1_64_0/boost/variant/static_visitor.hpp:53:5: note: declared protected here
    ~static_visitor() = default;

However, it compiles cleanly in C++14 mode. I found that if I change the brace initialization vis{} to parentheses vis(), then it compiles correctly in both modes. Every version of gcc that I've tried allows both variants in C++17 mode.

Is this a correct change in behavior from C++14 to C++17, or is this a clang bug? If it is correct, why is it now invalid in C++17 (or maybe it always was, but clang just allows it in earlier standard revisions)?

Body:
clang is correct here. Here's a reduced example:

struct B {
protected:
    B() { }
};

struct D : B { };

auto d = D{};

In C++14, D is not an aggregate because it has a base class, so D{} is "normal" (non-aggregate) initialization which invokes D's default constructor, which in turn invokes B's default constructor. This is fine, because D has access to B's default constructor.

In C++17, the definition of aggregate was widened - base classes are now allowed (as long as they're non-virtual). D is now an aggregate, which means that D{} is aggregate initialization. And in aggregate-initialization, this means that we (the caller) are initializing all the subobjects - including the base class subobject. But we do not have access to B's constructor (it is protected), so we cannot invoke it, so it is ill-formed.

Fear not, the fix is easy. Use parentheses:

auto d = D();

This goes back to invoking D's default constructor as before.


问:
User photo disappears when I change the password
I have a form where the user's photo appears. Every time I change the user password, the photo disappears from the form. I already tried to take the image of the form but it did not solve. The password change is done through onSubmit.

HTML:

```<code><form (ngSubmit)="onSubmit($event)">
  <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">Configuração do Usuário: <b> {{userId?.name}} </b></h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
    <div class="example-container" style="width: 100%; margin: auto; margin-top: 2%">
      <img class="img-modal" style="border-radius: 50%; width: 60px; height: 60px;" src={{userId?.photo}}>
      <div class="example-container password-width">
        <mat-form-field>
          <input matInput placeholder="Alterar a Senha" [type]="hide ? 'text' : 'password'" [(ngModel)]="senha" name="senha">
          <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 'visibility_off'}}</mat-icon>
        </mat-form-field>
      </div>
      <app-panel-config-user></app-panel-config-user>
    </div>
  </div>
  <div class="modal-footerButtonConfig">
    <button type="button" class="btn btn-danger btn-sm buttonConfig" *ngIf="userId?.status == 1">Desativar
      Usuário</button>
    <button type="button" class="btn btn-success btn-sm buttonConfig" *ngIf="userId?.status == 0">Ativar
      Usuário</button>
    <button type="button" class="btn btn-sm buttonConfig buttonColor" style="background-color: #6239BD; color: white" *ngIf="userId?.is_admin == 0">Tornar Administrador</button>
    <button type="button" class="btn btn-sm buttonConfig buttonColor" style="background-color: #6239BD; color: white" *ngIf="userId?.is_admin == 1">Remover Administrador</button>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Fechar</button>
    <button type="submit" class="btn btn-sm buttonColor" style="background-color: #6239BD; color: white">Salvar</button>
  </div>
</form>
</code>```

Code change password:

```<code>onSubmit(
    userPass: UserPass,
    messageSucess: string = 'Senha alterada com Sucesso!',
    messageError: string = 'Falha ao alterar a senha.',
    action: string = '') {
    userPass.password = this.senha;
    return this.userService.putPass(this.idUser, userPass).subscribe(response => {
      if (!response) {
        console.log(Error);
      } else {
        this.userId = response;

        if (this.userId['success'] === true) {
          this.senha = '';
          this.snackBar.open(messageSucess, action, {
            duration: 4000,
            panelClass: ['success-class']
          });
        } else {
          this.snackBar.open(messageError, action, {
            duration: 4000,
            panelClass: ['error-class']
          });
        }
      }
    });
  }
</code>```

答:
Your problem is the line

```<code>this.userId = response;
</code>```

You are setting the userId to the response ({success: true}) - but the response isn't a userId!

Remove this line, and it should work again.

Body:
I have a form where the user's photo appears. Every time I change the user password, the photo disappears from the form. I already tried to take the image of the form but it did not solve. The password change is done through onSubmit.

HTML:

<form (ngSubmit)="onSubmit($event)">

Configuração do Usuário:  {{userId?.name}}

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      ×
    </button>

        <mat-form-field>
          <input matInput placeholder="Alterar a Senha" [type]="hide ? 'text' : 'password'" [(ngModel)]="senha" name="senha">
          <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 'visibility_off'}}</mat-icon>
        </mat-form-field>

      <app-panel-config-user></app-panel-config-user>

    <button type="button" class="btn btn-danger btn-sm buttonConfig" *ngIf="userId?.status == 1">Desativar
      Usuário</button>
    <button type="button" class="btn btn-success btn-sm buttonConfig" *ngIf="userId?.status == 0">Ativar
      Usuário</button>
    <button type="button" class="btn btn-sm buttonConfig buttonColor" style="background-color: #6239BD; color: white" *ngIf="userId?.is_admin == 0">Tornar Administrador</button>
    <button type="button" class="btn btn-sm buttonConfig buttonColor" style="background-color: #6239BD; color: white" *ngIf="userId?.is_admin == 1">Remover Administrador</button>

    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Fechar</button>
    <button type="submit" class="btn btn-sm buttonColor" style="background-color: #6239BD; color: white">Salvar</button>

</form>

Code change password:

onSubmit(
    userPass: UserPass,
    messageSucess: string = 'Senha alterada com Sucesso!',
    messageError: string = 'Falha ao alterar a senha.',
    action: string = '') {
    userPass.password = this.senha;
    return this.userService.putPass(this.idUser, userPass).subscribe(response => {
      if (!response) {
        console.log(Error);
      } else {
        this.userId = response;

        if (this.userId['success'] === true) {
          this.senha = '';
          this.snackBar.open(messageSucess, action, {
            duration: 4000,
            panelClass: ['success-class']
          });
        } else {
          this.snackBar.open(messageError, action, {
            duration: 4000,
            panelClass: ['error-class']
          });
        }
      }
    });
  }

Body:
Your problem is the line

this.userId = response;

You are setting the userId to the response ({success: true}) - but the response isn't a userId!

Remove this line, and it should work again.


问:
Mobile responsive top menu
I m using Clarity Design System with angular and the top menu is not mobile response

```<code> <header class="header-2">
  <div class="branding">
      <a class="nav-link">
          <clr-icon shape="home"  size="24"></clr-icon>
          <span class="title">title</span>
      </a>
     </div>
    <div class="header-nav">
      <a class="nav-link nav-text" routerLink="/home">Home</a>
      <a class="active nav-link nav-text"
    routerLink="/login">Login</a>
   </div>
  </header>
</code>```

I m expecting the top menu to turn into few lines (button) when the width is reduce

Or should I use different tags ?

答:
Yes it is working perfect now, it solved the behavior

So now is:

```<code><clr-main-container>
<clr-header class="header-2">
<div class="branding">
      <a class="nav-link">
      <clr-icon shape="home"  size="24"></clr-icon>
      <span class="title">{{title}}</span>
      </a>
  </div>
  <div class="header-nav" [clr-nav-level]="1">
  <div class="header-nav">
      <a class="nav-link nav-text" routerLink="/home">Home</a>
      <a class="active nav-link nav-text" routerLink="/login">Login</a>

  </div>
</div>
  </clr-header>
</code>```

Thank you very much

Title: Mobile responsive top menu

Body:
I m using Clarity Design System with angular and the top menu is not mobile response

          <clr-icon shape="home"  size="24"></clr-icon>
          title

      Home
      Login

I m expecting the top menu to turn into few lines (button) when the width is reduce

Or should I use different tags ?

Body:
Yes it is working perfect now, it solved the behavior

So now is:

<clr-main-container>
<clr-header class="header-2">
<div class="branding">
      <a class="nav-link">
      <clr-icon shape="home"  size="24"></clr-icon>
      <span class="title">{{title}}</span>
      </a>
  </div>
  <div class="header-nav" [clr-nav-level]="1">
  <div class="header-nav">
      <a class="nav-link nav-text" routerLink="/home">Home</a>
      <a class="active nav-link nav-text" routerLink="/login">Login</a>

  </div>
</div>
  </clr-header>

Thank you very much


问:
extracting specific values in R
I am a beginner in R coding and I have the sample data here. I am trying to extract all the entries which have 2 "d7" and one "d1" for identical Idvalue number.

```<code>
Sample   name         Idvalue_number
a       d1                 1
f       d7                 1
b       d7                 1
s       d1                 5
g       d7                 5
r       d7                 5
z       d1                 7
y       d7                 7
d       d1                 7

Expected output
a   d1  1
f   d7  1
b   d7  1
s   d1  5
g   d7  5
r   d7  5

</code>```

Some code I have tried which is not giving me the desired output is here:

```<code>d1d7 <- data_ %>%
  group_by(dvalue_number) %>%
  filter(n() >= 3 & any(name == first(name)))
</code>```

Could someone help me here? Thanks in advance.

答:
One way that you can do it is shown below.]</p>

```<code>library(tidyverse)

#create a dataframe for example
df = data.frame(Sample = c("a", "f", "b", "s", "g", "r", "z", "y", "d"),
                name = c("d1", "d7", "d7", "d1",  "d7", "d7", "d7", "d7","d7"),
                Idvalue_number = c(1, 1, 1, 5, 5, 5, 7, 7, 7))

df %>% group_by(Idvalue_number, name) %>%
  summarise(total = n()) %>%
  filter(name == "d1" & total == 1 | name == "d7" & total == 2)

  Idvalue_number name  total
           <dbl> <fct> <int>
1              1 d1        1
2              1 d7        2
3              5 d1        1
4              5 d7        2
</code>```

Title: extracting specific values in R

Body:
I am a beginner in R coding and I have the sample data here. I am trying to extract all the entries which have 2 "d7" and one "d1" for identical Idvalue number.

Sample   name         Idvalue_number
a       d1                 1
f       d7                 1
b       d7                 1
s       d1                 5
g       d7                 5
r       d7                 5
z       d1                 7
y       d7                 7
d       d1                 7

Expected output
a   d1  1
f   d7  1
b   d7  1
s   d1  5
g   d7  5
r   d7  5

Some code I have tried which is not giving me the desired output is here:

d1d7 <- data_ %>%
  group_by(dvalue_number) %>%
  filter(n() >= 3 & any(name == first(name)))

Could someone help me here? Thanks in advance.

Body:
One way that you can do it is shown below.]

library(tidyverse)

#create a dataframe for example
df = data.frame(Sample = c("a", "f", "b", "s", "g", "r", "z", "y", "d"),
                name = c("d1", "d7", "d7", "d1",  "d7", "d7", "d7", "d7","d7"),
                Idvalue_number = c(1, 1, 1, 5, 5, 5, 7, 7, 7))

df %>% group_by(Idvalue_number, name) %>%
  summarise(total = n()) %>%
  filter(name == "d1" & total == 1 | name == "d7" & total == 2)

  Idvalue_number name  total
           <dbl> <fct> <int>
1              1 d1        1
2              1 d7        2
3              5 d1        1
4              5 d7        2


问:
How can I select elements having specific siblings?
How can I prevent anchor () tag from doing nothing if li has ul according to the following code:

```<code><aside class="sidebar">
 <div id="leftside-navigation" class="nano">
  <ul class="nano-content">
   <li>
    <a href="index.html">
      <span>Home</span>
    </a>
   </li>
   <li class="sub-menu">
     <a href="javascript:void(0);">
       <span>Categories</span>
       <i class="arrow fa fa-angle-right pull-right"></i>
     </a>
     <ul>
       <li>
         <a href="index.html">
           <span>Home</span>
         </a>
       </li>
       <li>
         <a href="index.html">
           <span>Lifestyles</span>
         </a>
       </li>
       <li>
         <a href="index.html">
           <span>Technology</span>
         </a>
        </li>
      </ul>
    </li>
  </ul>
</div>
</code>```

I've tried to put javascript:void(0) - it works but I wanted to make it with if else statement or any other way.

I wanted to do that is:

if li.submenu has ul li.has-submenu a prevent default

答:
You can write a selector for a that's a child of an li that has a submenu.

```<code>$("li:has(ul) > a").click(function(e) {
    e.preventDefault();
});
</code>```

Body:
How can I prevent anchor () tag from doing nothing if li has ul according to the following code:

      Home

       Categories

           Home

           Lifestyles

           Technology

I've tried to put javascript:void(0) - it works but I wanted to make it with if else statement or any other way.

I wanted to do that is:

if li.submenu has ul li.has-submenu a prevent default

Body:
You can write a selector for a that's a child of an li that has a submenu.

$("li:has(ul) > a").click(function(e) {
    e.preventDefault();
});


问:
"Object reference not set to an instance of an object" when creating a new Web API controller with EF Scaffolding in Visual Studio 2012
I have an MVC4/Web API project, with an Entity Framework, Code First data model. When I try to create a new API Controller with read/write methods using a data context & model, I get an alert saying "Object reference not set to an instance of an object".

I've done a bit of searching and found that some causes are incorrect project type Guids in the .csproj file, incomplete installation of the MvcScaffolding nuget package and one suggestion of installing Powershell 3.

I have made sure all my project type guids are correct, made sure the MvcScaffolding package is installed correctly, and I've even installed Powershell 3.

None of this has solved the problem for me. All I can think is there is a problem with my data context/model although it created the tables/relationships fine. Code below:

Context:

```<code>public class PropertySearchContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Property>().HasRequired(p => p.Office).WithMany(o => o.Properties).HasForeignKey(p => p.OfficeId);
    }

    public DbSet<Office> Offices { get; set; }
    public DbSet<Property> Properties { get; set; }
}
</code>```

Model:

```<code>[Serializable]
public class Property
{
    public int PropertyId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Postcode { get; set; }

    public int Bedrooms { get; set; }
    public int Bathrooms { get; set; }

    public string UmbracoNodeId { get; set; }
    public string MainImageUrl { get; set; }
    public string ListingImageUrl { get; set; }
    public int TotalImageCount { get; set; }
    public PropertyType PropertyType { get; set; }
    public PropertyStatus PropertyStatus { get; set; }
    public long Price { get; set; }
    public string ListingUrl { get; set; }

    //Navigation Properties
    public int OfficeId { get; set; }
    public virtual Office Office { get; set; }

    //Meta properties
    public DateTime CreatedAt { get; set; }
    public string CreatedBy { get; set; }
    public DateTime UpdatedAt { get; set; }
    public string UpdatedBy { get; set; }
}
</code>```

Connection String:

```<code><add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />
</code>```

Any help with this would be greatly appreciated as I've tried every suggestion and I still can't create a controller with scaffolding. Driving me mad!

Thanks!

答: If you have more than one project in your solution try to rebuild all.</p>

Body:
I have an MVC4/Web API project, with an Entity Framework, Code First data model. When I try to create a new API Controller with read/write methods using a data context & model, I get an alert saying "Object reference not set to an instance of an object".

I've done a bit of searching and found that some causes are incorrect project type Guids in the .csproj file, incomplete installation of the MvcScaffolding nuget package and one suggestion of installing Powershell 3.

I have made sure all my project type guids are correct, made sure the MvcScaffolding package is installed correctly, and I've even installed Powershell 3.

None of this has solved the problem for me. All I can think is there is a problem with my data context/model although it created the tables/relationships fine. Code below:

Context:

public class PropertySearchContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Property>().HasRequired(p => p.Office).WithMany(o => o.Properties).HasForeignKey(p => p.OfficeId);
    }

    public DbSet<Office> Offices { get; set; }
    public DbSet<Property> Properties { get; set; }
}

Model:

[Serializable]
public class Property
{
    public int PropertyId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Postcode { get; set; }

    public int Bedrooms { get; set; }
    public int Bathrooms { get; set; }

    public string UmbracoNodeId { get; set; }
    public string MainImageUrl { get; set; }
    public string ListingImageUrl { get; set; }
    public int TotalImageCount { get; set; }
    public PropertyType PropertyType { get; set; }
    public PropertyStatus PropertyStatus { get; set; }
    public long Price { get; set; }
    public string ListingUrl { get; set; }

    //Navigation Properties
    public int OfficeId { get; set; }
    public virtual Office Office { get; set; }

    //Meta properties
    public DateTime CreatedAt { get; set; }
    public string CreatedBy { get; set; }
    public DateTime UpdatedAt { get; set; }
    public string UpdatedBy { get; set; }
}

Connection String:

<add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />

Any help with this would be greatly appreciated as I've tried every suggestion and I still can't create a controller with scaffolding. Driving me mad!

Thanks!


问:
Stagger Repeated Dates in Google Sheets?
I am trying to make an attendance and time sheet for my team at work. However, we only work on MWF. How can I autofill dates in a row but skip weekends?

Have been looking at the WORKDAY function.

I successfully have GSheets repeat every other day, but I need to skip dates that fall on Sunday.

Current:
(01/07, 01/09, 01/11, 01/13, 01/15)

Expected:
(01/07, 01/09, 01/11, 01/15)

答:
With a Monday date in A1, in A2 and dragged across to suit:

```<code>=A1+if(weekday(A1)<>6,2,4)
</code>```

should create a series of successive Monday, Wednesday and Friday dates.

Body:
With a Monday date in A1, in A2 and dragged across to suit:

=A1+if(weekday(A1)<>6,2,4)

should create a series of successive Monday, Wednesday and Friday dates.


问:
"Unable to read TLD META-INF/jsf_core.tld from jsf-impl-2.0.jar" error when integrating JSF
We have a Struts+Spring+Hibernate Application and we are trying to integrate JSF. For that we have done some configuration in web.xml and struts-config.xml. I have added some
JAR files to WEB-INF/lib.

The jar files containing in my WEB-INF/lib are listed here:

antlr-2.7.6rc1.jar,asm.jar,asm-attrs.jar,bsh-2.0b2.jar,c3p0-0.9.1.2-jdk1.3.jar,cglib-2.1.3.jar,commons-beanutils-1.7.jar,commons-betwixt-0.8.jar,commons-cli-1.0.jar,commons-codec-1.3.jar,commons-collections-3.jar,commons-dbcp-1.2.1.jar,commons-digester-1.7.jar,commons-discovery-0.2.jar,commons-fileupload.jar,commons-httpclient-3.1.jar,commons-io-1.3.1.jar,commons-lang-2.3.jar,commons-logging-1.1.jar,commons-pool-1.2.jar,commons-validator.jar,connector-1_5.jar,dom4j-1.6.1.jar,ehcache-1.1.jar,el-api-6.0.20.jar,el-impl-2.2.0-SNAPSHOT.jar,hibernate-3.1.3.jar,jetty-util-6.0.0,.jar,servlet-api-2.3.jar,spring-2.5.6.jar,standard.jar,struts.jar,xercesImpl-2.6.2.jar,xmlParserAPIs-2.6.2.jar,xstream-1.3.1

The below jar file are the ones newly added for integrating JSF:

jsf-api-2.0.jar,jsf-impl-2.0.jar,myfaces-jsf-api-1.0.9.jar.jar.jar,struts-faces-1.3.10.jar

My web.xml is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>SSHIntgr</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/config/applicationContext.xml</param-value>
    </context-param>

     <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>
            org.apache.struts.action.ActionServlet
        </servlet-class>

        <init-param>
            <param-name>config</param-name>
            <param-value>/config/struts-config.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>3</param-value>
        </init-param>
        <init-param>
            <param-name>detail</param-name>
            <param-value>3</param-value>
        </init-param>
        <init-param>
            <param-name>locale</param-name>
            <param-value>true</param-value>
        </init-param>

        <load-on-startup>2</load-on-startup>
    </servlet>
    <!-- struts-faces configuration start -->
     <servlet>
      <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- struts-faces configuration start -->
<listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
 <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

My struts-config.xml is

```<code><struts-config>

    <form-beans>
        <form-bean name="usrForm" type="com.sshi.web.form.UsrForm" />
    </form-beans>

    <global-exceptions />

    <global-forwards />

    <action-mappings>

        <action path="/login" type="com.sshi.web.action.LoginAction"
            name="usrForm" scope="request">
            <forward name="allowUser" path="/pages/Welcome.jsp"/>
            <forward name="denyUser" path="/index.jsp"/>
        </action>

    </action-mappings>

  <controller>
<set-property property="processorClass"
value="org.apache.struts.faces.
application.FacesRequestProcessor"/>
</controller>
 <message-resources key="MessageResources" parameter="MessageResources"  null="false" />
     <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property property="pathnames"
            value="/config/validator-rules.xml,/config/validation.xml" />
        <set-property property="stopOnFirstError" value="true" />
    </plug-in>
</struts-config>
</code>```

I am using Spring source toll suite, Tomcat 5.5 and JDK 1.5.
My Tomcat 5.5\common\lib contains JAR files

commons-el.jar,jasper-compiler.jar,jasper-compiler-jdt.jar,jasper-runtime.jar,jsp-api.jar,naming-factory.jar,naming-factory-dbcp.jar,
    naming-resources.jar,servlet-api.jar

My Server is starting properly but not able to load JSP page, I am getting the  exception as

```<code>org.apache.jasper.JasperException: Unable to read TLD "META-INF/jsf_core.tld" from JAR file "file:/SSHIntgr/WEB-INF/lib/jsf-impl-2.0.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagLibraryValidator class: com.sun.faces.taglib.jsf_core.CoreValidator
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:50)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:179)
at org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:181)
at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:418)
at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:483)
</code>```

How can I solve this?

答:
You're using tomcat 5.5 which is a Servlet 2.4 container, but JSF 2.0 requires Servlet 2.5 or newer.

So you have 2 options:

Upgrade your servletcontainer to a Servlet 2.5 comparible one (e.g. Tomcat 6.0).

Downgrade JSF to 1.2 which is compatible with Servlet 2.4.

Unrelated to the concrete problem: the file servlet-api-2.3.jar does not belong in WEB-INF/lib. Get rid of it. It's supposed to be already provided by the servletcontainer (in this case, the one in Tomcat's /lib). Keeping this file will only lead to missing class def or abstract method errors during runtime.

Body:
We have a Struts+Spring+Hibernate Application and we are trying to integrate JSF. For that we have done some configuration in web.xml and struts-config.xml. I have added some
JAR files to WEB-INF/lib.

The jar files containing in my WEB-INF/lib are listed here:

antlr-2.7.6rc1.jar,asm.jar,asm-attrs.jar,bsh-2.0b2.jar,c3p0-0.9.1.2-jdk1.3.jar,cglib-2.1.3.jar,commons-beanutils-1.7.jar,commons-betwixt-0.8.jar,commons-cli-1.0.jar,commons-codec-1.3.jar,commons-collections-3.jar,commons-dbcp-1.2.1.jar,commons-digester-1.7.jar,commons-discovery-0.2.jar,commons-fileupload.jar,commons-httpclient-3.1.jar,commons-io-1.3.1.jar,commons-lang-2.3.jar,commons-logging-1.1.jar,commons-pool-1.2.jar,commons-validator.jar,connector-1_5.jar,dom4j-1.6.1.jar,ehcache-1.1.jar,el-api-6.0.20.jar,el-impl-2.2.0-SNAPSHOT.jar,hibernate-3.1.3.jar,jetty-util-6.0.0,.jar,servlet-api-2.3.jar,spring-2.5.6.jar,standard.jar,struts.jar,xercesImpl-2.6.2.jar,xmlParserAPIs-2.6.2.jar,xstream-1.3.1

The below jar file are the ones newly added for integrating JSF:

jsf-api-2.0.jar,jsf-impl-2.0.jar,myfaces-jsf-api-1.0.9.jar.jar.jar,struts-faces-1.3.10.jar

My web.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>SSHIntgr</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/config/applicationContext.xml</param-value>
    </context-param>

     <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>
            org.apache.struts.action.ActionServlet
        </servlet-class>

        <init-param>
            <param-name>config</param-name>
            <param-value>/config/struts-config.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>3</param-value>
        </init-param>
        <init-param>
            <param-name>detail</param-name>
            <param-value>3</param-value>
        </init-param>
        <init-param>
            <param-name>locale</param-name>
            <param-value>true</param-value>
        </init-param>

        <load-on-startup>2</load-on-startup>
    </servlet>

     <servlet>
      <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
 <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

My struts-config.xml is

<struts-config>

    <form-beans>
        <form-bean name="usrForm" type="com.sshi.web.form.UsrForm" />
    </form-beans>

    <global-exceptions />

    <global-forwards />

    <action-mappings>

        <action path="/login" type="com.sshi.web.action.LoginAction"
            name="usrForm" scope="request">
            <forward name="allowUser" path="/pages/Welcome.jsp"/>
            <forward name="denyUser" path="/index.jsp"/>
        </action>

    </action-mappings>

  <controller>
<set-property property="processorClass"
value="org.apache.struts.faces.
application.FacesRequestProcessor"/>
</controller>
 <message-resources key="MessageResources" parameter="MessageResources"  null="false" />
     <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property property="pathnames"
            value="/config/validator-rules.xml,/config/validation.xml" />
        <set-property property="stopOnFirstError" value="true" />
    </plug-in>
</struts-config>

I am using Spring source toll suite, Tomcat 5.5 and JDK 1.5.
My Tomcat 5.5\common\lib contains JAR files

commons-el.jar,jasper-compiler.jar,jasper-compiler-jdt.jar,jasper-runtime.jar,jsp-api.jar,naming-factory.jar,naming-factory-dbcp.jar,
    naming-resources.jar,servlet-api.jar

My Server is starting properly but not able to load JSP page, I am getting the  exception as

org.apache.jasper.JasperException: Unable to read TLD "META-INF/jsf_core.tld" from JAR file "file:/SSHIntgr/WEB-INF/lib/jsf-impl-2.0.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagLibraryValidator class: com.sun.faces.taglib.jsf_core.CoreValidator
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:50)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:179)
at org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:181)
at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:418)
at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:483)

How can I solve this?


问:
How to configure lamda timeout via Skill project
Is there easy way to configure aws-lambda timeout in Alexa Node.js Skill project configuration file?

I know how to set/reset aws-lambda timeout using console. However for auto deployment via CLI I would like to know how to set/reset this time via Alexa Node.Js Skill project

答: It's not possible to do this via skill config files, sorry</p>


问:
Document extraction fails in publish log after uploading using BIM 360 API
I am trying to upload the files using document management API. The file gets uploaded but fails with "We couldn't process the following document. Extraction failed"  error message.

I tried uploading image,PDF etc. But the same file gets extracted and published successfully when done manually through UI

答: Just tested with this sample (source code here) and worked fine.


问:
Translating from SQL to R (concat and inner joins)
```<code>SELECT CONCAT(a.name,' ', a.surname) as "Deluxe drivers", m.producer, m.model
from employer a
INNER JOIN Driver s on s.iddriver=a.idemployer
INNER JOIN Taxi t ON t.idtaxi=s.idtaxi
INNER JOIN Model m ON m.idmodelcar=t.idmodelcar
WHERE m.producer IN ('Audi','Skoda','Honda','Hyundai') AND m.year>2010
GROUP BY a.name, a.surname, m.producer, m.model
ORDER BY 2,3
</code>```

So this is pretty much a basic SQL query but I need to translate it to R and I have some difficulties. Also, I am not sure if there is a function like CONCAT that can basically unite 2 different columns into one so the name and surname don't appear separately.

Can anyone assist me, please?

答:
You can accomplish this using only functions in base R.

The paste() function has the same action as CONCAT.  The merge() function has the same action as the JOIN statements--you will probably find it easiest to merge the data frames before selecting rows and columns.  The %in% operator has the same action as the IN expression.

You don't need a GROUP BY clause because you're not using an aggregate function.

The sqldf package would allow you to apply a SQL statement to the merged data frame, which may shorten the R learning curve.

Body:
SELECT CONCAT(a.name,' ', a.surname) as "Deluxe drivers", m.producer, m.model
from employer a
INNER JOIN Driver s on s.iddriver=a.idemployer
INNER JOIN Taxi t ON t.idtaxi=s.idtaxi
INNER JOIN Model m ON m.idmodelcar=t.idmodelcar
WHERE m.producer IN ('Audi','Skoda','Honda','Hyundai') AND m.year>2010
GROUP BY a.name, a.surname, m.producer, m.model
ORDER BY 2,3

So this is pretty much a basic SQL query but I need to translate it to R and I have some difficulties. Also, I am not sure if there is a function like CONCAT that can basically unite 2 different columns into one so the name and surname don't appear separately.

Can anyone assist me, please?


问:
How can I access props in a component wrapped with custom HOC?
I created a simple HOC, which uses custom hook to track mouse position. I use the hook in the HOC function, and with it I want to pass that value to the wrapped component.

And that's OK, I pass the function as prop, and I can console.log that prop just with this.props. I get the output {position: {…}} in the console, as expected. When I expand that log object, I can see the output position: {x: 479, y: 396}, which is exactly what I want.

But, when I want to access the actual object with this.props.position, it just throws me an error:

```<code>TypeScript error in /Users/dvidovic/Projects/hooks-in-classes/src/components/HooksHOC.tsx(6,28):
Property 'position' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.  TS2339
</code>```

Here's the HOC:

```<code>import React from 'react';
import { useMousePosition } from '../hooks/useMousePosition';

export const withHooksHOC = (Component: any) => {
  return (props: any) => {
    return <Component position={useMousePosition()} {...props} />;
  };
};
</code>```

And here's the wrapped component:

```<code>import React from 'react';
import { withHooksHOC } from './withHooksHOC';

class HooksHOC extends React.Component {
  render() {
    console.log(this.props); // this works
    console.log(this.props.position); // this throws an error
    return (
      <div style={{ marginTop: '100px', fontSize: '72px' }}>Some text</div>
    );
  }
}

export default withHooksHOC(HooksHOC);
</code>```

What do I have to change to access the position object?

答:
You need to pass a generic with an interface of your props to React.Component:

```<code>interface HooksHOCProps {
    position: {
        x: number;
        y: number;
    }
}

class HooksHOC extends React.Component<HooksHOCProps> {
...
</code>```

Body:
I created a simple HOC, which uses custom hook to track mouse position. I use the hook in the HOC function, and with it I want to pass that value to the wrapped component.

And that's OK, I pass the function as prop, and I can console.log that prop just with this.props. I get the output {position: {…}} in the console, as expected. When I expand that log object, I can see the output position: {x: 479, y: 396}, which is exactly what I want.

But, when I want to access the actual object with this.props.position, it just throws me an error:

TypeScript error in /Users/dvidovic/Projects/hooks-in-classes/src/components/HooksHOC.tsx(6,28):
Property 'position' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.  TS2339

Here's the HOC:

import React from 'react';
import { useMousePosition } from '../hooks/useMousePosition';

export const withHooksHOC = (Component: any) => {
  return (props: any) => {
    return <Component position={useMousePosition()} {...props} />;
  };
};

And here's the wrapped component:

import React from 'react';
import { withHooksHOC } from './withHooksHOC';

class HooksHOC extends React.Component {
  render() {
    console.log(this.props); // this works
    console.log(this.props.position); // this throws an error
    return (

Some text

    );
  }
}

export default withHooksHOC(HooksHOC);

What do I have to change to access the position object?

Body:
You need to pass a generic with an interface of your props to React.Component:

interface HooksHOCProps {
    position: {
        x: number;
        y: number;
    }
}

class HooksHOC extends React.Component<HooksHOCProps> {
...


问:
queryStarting(atValue not working as intended?
I am wondering how I could use firebase ordering queries to make pagination work in my app.

So I have tried the following:

```<code>    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if indexPath.row == postArray.count - 1 {
        //we are at last cell load more content
        //Do some logic here I think like
        limit += 10
         getRecentPosts(limit)
        //self.perform(#selector(reloadData), with: nil, afterDelay: 1.0)
    }
}

@objc func reloadData() {
    self.collectionView.reloadData()
}
</code>```

And:
 I do this for it to work. But It does not, I expand on this below.

```<code>  ref.child("Timeline").child((Auth.auth().currentUser?.uid)!)
  .queryStarting(atValue: "\(postArray[postArray.count-1].user.userID!):\(postArray[postArray.count-1].media[0].postID!)")//here is a sample val: KVDB2sNMgUN90tpkmQKfjrroOmt1:post:580367065
  .queryLimited(toLast: UInt(limit)).observeSingleEvent(of: .value, with: { (snapshot) in
</code>```

My fetch fucntion looks like this:

```<code>        } else {
        print("ffdsafsfsdfasdfsd?????", postArray.count)
        print("\(postArray[postArray.count-1].user.userID!):\(postArray[postArray.count-1].media[0].postID!)", "  fhdskagfakshgfjdshflkahflkjashlkjfhslkj")

        ref.child("Timeline").child((Auth.auth().currentUser?.uid)!)
            .queryStarting(atValue: "\(postArray[postArray.count-1].user.userID!):\(postArray[postArray.count-1].media[0].postID!)")
            .queryLimited(toLast: UInt(limit)).observeSingleEvent(of: .value, with: { (snapshot) in
                print("resulst here?????????")
                if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
                    print(snapshots, " this is the snapshot of the people you follow", snapshots.count)

                    for child in snapshots.reversed() {

                        let keyValue = child.key
                        let uid = keyValue.split(separator: ":")[0]
                        let postIDDoubleVal = keyValue.split(separator: ":")[2]

                        self.fetchUsersPost(uid: String(uid), postID: "post:\(postIDDoubleVal)")
                    }
                }
            })
    }
}
</code>```

Update:

I have found that the logic works as needed but that inside the place where i print :

```<code>                    if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
                    print(snapshots, " this is the snapshot of the people you follow", snapshots.count)
</code>```

I get the following output:

```<code>[]  this is the snapshot of the people you follow 0
</code>```

Why is this? i checked the DB for the starting point I gave it and it does exist

答:
I don't fully understand the query in the question so let's see if we can produce an answer via an example.

Let's take a structure of posts

```<code>Timeline
   uid_0
      post_0: "a"
      post_1: "b"
      post_2: "c"
      post_3: "d"
      post_4: "e"
      post_5: "f"
      post_6: "g"
      post_7: "h"
      post_8: "i"
      post_9: "j"
</code>```

There are multiple ways this can be paginated but let's use two simple examples.

In this first example, suppose we want three posts starting at post_3, so we want d, e and f, and we know the actual key to start with, post_3.

```<code>func paginationByKey() {
    let ref = self.ref.child("Timeline").child("uid_0")
    let q0 = ref.queryOrderedByKey() //they will be ordered by key
    let q1 = q0.queryStarting(atValue: "post_3").queryLimited(toFirst: 3)
    q1.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot)
    })
}
</code>```

this will return

```<code>Snap (uid_0) {
    "post_3" = d;
    "post_4" = e;
    "post_5" = f;
}
</code>```

In this second example, in many cases the node keys are generated with a push() or .childByAutoId so you won't know the key. However, you would know the starting value, like a date or timestamp for example. Also, the data could really be stored in any order in the database. To handle that we know the first value we want to read in is 'd' followed by 'e' and 'f'

```<code>func paginationByValue() {
    let ref = self.ref.child("Timeline").child("uid_0")
    let q0 = ref.queryOrderedByValue() //ordering the data by child value
    let q1 = q0.queryStarting(atValue: "d").queryLimited(toFirst: 3)
    q1.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot)
    })
}
</code>```

and the output is

```<code>Snap (uid_0) {
    "post_3" = d;
    "post_4" = e;
    "post_5" = f;
}
</code>```

To paginate, since you know the last node loaded had a value of 'f', the next set of data would start with 'g'. There are a couple of ways to handle that:

One way is to actually load in 4 nodes and display 3. The 4th node is the starting point for the next set of data, so you would perhaps keep that in a class var for reference.

Another option is to start the query at the last node of the set of nodes just loaded, 'f' in this case' but throw out the first one (which will be 'f') of the new set as it was already in the prior set.

Body:
I am wondering how I could use firebase ordering queries to make pagination work in my app.

So I have tried the following:

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if indexPath.row == postArray.count - 1 {
        //we are at last cell load more content
        //Do some logic here I think like
        limit += 10
         getRecentPosts(limit)
        //self.perform(#selector(reloadData), with: nil, afterDelay: 1.0)
    }
}

@objc func reloadData() {
    self.collectionView.reloadData()
}

And:
 I do this for it to work. But It does not, I expand on this below.

  ref.child("Timeline").child((Auth.auth().currentUser?.uid)!)
  .queryStarting(atValue: "\(postArray[postArray.count-1].user.userID!):\(postArray[postArray.count-1].media[0].postID!)")//here is a sample val: KVDB2sNMgUN90tpkmQKfjrroOmt1:post:580367065
  .queryLimited(toLast: UInt(limit)).observeSingleEvent(of: .value, with: { (snapshot) in

My fetch fucntion looks like this:

        } else {
        print("ffdsafsfsdfasdfsd?????", postArray.count)
        print("\(postArray[postArray.count-1].user.userID!):\(postArray[postArray.count-1].media[0].postID!)", "  fhdskagfakshgfjdshflkahflkjashlkjfhslkj")

        ref.child("Timeline").child((Auth.auth().currentUser?.uid)!)
            .queryStarting(atValue: "\(postArray[postArray.count-1].user.userID!):\(postArray[postArray.count-1].media[0].postID!)")
            .queryLimited(toLast: UInt(limit)).observeSingleEvent(of: .value, with: { (snapshot) in
                print("resulst here?????????")
                if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
                    print(snapshots, " this is the snapshot of the people you follow", snapshots.count)

                    for child in snapshots.reversed() {

                        let keyValue = child.key
                        let uid = keyValue.split(separator: ":")[0]
                        let postIDDoubleVal = keyValue.split(separator: ":")[2]

                        self.fetchUsersPost(uid: String(uid), postID: "post:\(postIDDoubleVal)")
                    }
                }
            })
    }
}

Update:

I have found that the logic works as needed but that inside the place where i print :

                    if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
                    print(snapshots, " this is the snapshot of the people you follow", snapshots.count)

I get the following output:

[]  this is the snapshot of the people you follow 0

Why is this? i checked the DB for the starting point I gave it and it does exist

Body:
I don't fully understand the query in the question so let's see if we can produce an answer via an example.

Let's take a structure of posts

Timeline
   uid_0
      post_0: "a"
      post_1: "b"
      post_2: "c"
      post_3: "d"
      post_4: "e"
      post_5: "f"
      post_6: "g"
      post_7: "h"
      post_8: "i"
      post_9: "j"

There are multiple ways this can be paginated but let's use two simple examples.

In this first example, suppose we want three posts starting at post_3, so we want d, e and f, and we know the actual key to start with, post_3.

func paginationByKey() {
    let ref = self.ref.child("Timeline").child("uid_0")
    let q0 = ref.queryOrderedByKey() //they will be ordered by key
    let q1 = q0.queryStarting(atValue: "post_3").queryLimited(toFirst: 3)
    q1.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot)
    })
}

this will return

Snap (uid_0) {
    "post_3" = d;
    "post_4" = e;
    "post_5" = f;
}

In this second example, in many cases the node keys are generated with a push() or .childByAutoId so you won't know the key. However, you would know the starting value, like a date or timestamp for example. Also, the data could really be stored in any order in the database. To handle that we know the first value we want to read in is 'd' followed by 'e' and 'f'

func paginationByValue() {
    let ref = self.ref.child("Timeline").child("uid_0")
    let q0 = ref.queryOrderedByValue() //ordering the data by child value
    let q1 = q0.queryStarting(atValue: "d").queryLimited(toFirst: 3)
    q1.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot)
    })
}

and the output is

Snap (uid_0) {
    "post_3" = d;
    "post_4" = e;
    "post_5" = f;
}

To paginate, since you know the last node loaded had a value of 'f', the next set of data would start with 'g'. There are a couple of ways to handle that:

One way is to actually load in 4 nodes and display 3. The 4th node is the starting point for the next set of data, so you would perhaps keep that in a class var for reference.

Another option is to start the query at the last node of the set of nodes just loaded, 'f' in this case' but throw out the first one (which will be 'f') of the new set as it was already in the prior set.


问:
Why does React Hooks Axios API call return twice?
Why does React Hooks Axios API Call return twice.. even with a check if it's loaded?

I am used to this.setState but trying to understand the reason behind this why it's showing up twice inside my console log.

My code:

```<code>import React, { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
  const [users, setUsers] = useState({ results: [] });
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);

      await axios
        .get("https://jsonplaceholder.typicode.com/users/")
        .then(result => setUsers(result));

      setIsLoading(false);
    };

    fetchData();
  }, []);

  console.log(
    users.status === 200 && users.data.map(name => console.log(name))
  );

  return <h2>App</h2>;
};

export default App;
</code>```

答:
For the fire twice, perhaps is one time from componentDidMount, and the other one from componentDidUpdate

https://reactjs.org/docs/hooks-effect.html

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

You did not check 'isLoading' before you fire the API call

```<code>    // Only load when is not loading
    if (!isLoading) {
        fetchData();
    }
</code>```

Body:
Why does React Hooks Axios API Call return twice.. even with a check if it's loaded?

I am used to this.setState but trying to understand the reason behind this why it's showing up twice inside my console log.

My code:

import React, { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
  const [users, setUsers] = useState({ results: [] });
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);

      await axios
        .get("https://jsonplaceholder.typicode.com/users/")
        .then(result => setUsers(result));

      setIsLoading(false);
    };

    fetchData();
  }, []);

  console.log(
    users.status === 200 && users.data.map(name => console.log(name))
  );

  return
App
;
};

export default App;

Body:
For the fire twice, perhaps is one time from componentDidMount, and the other one from componentDidUpdate

https://reactjs.org/docs/hooks-effect.html

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

You did not check 'isLoading' before you fire the API call

    // Only load when is not loading
    if (!isLoading) {
        fetchData();
    }