问:
Import data to ragged array
As an exercise, I have build a simple program that, given a text file of N lowercase words and whitespaces, populates a ragged array char *en[N].

It works without great problems, apart for one: it populates the ragged array with only the last word of the input.

```<code>#include<stdio.h>
#include<ctype.h>

int main(int argc, char *argv[]){
    int i = 0, j = 0;
    char *en[100];
    char temp[20];

    FILE *p = fopen(argv[1], "r");
    char single;

    while((single = fgetc(p)) != EOF){
        if(!isspace(single))          /* Temporary store a single word */
            temp[i++] = single;
        else{
            temp[i] = '\0';
            en[j++] = temp;           /* Save stored word in ragged array */
            i = 0;
        }
    }

    printf("%s\n", en[0]);    /* Return the same than en[1] and en[99] */
    printf("%s\n", en[1]);
    printf("%s\n", en[99]);

    return 0;
}
</code>```

I cannot understand why it goes down to the end of the input file. I am unable of detecting major issues that could suggest a wrong approach.

Edit:

The reasoning behind my approach was that an array of *char can be initialized with this form:

```<code>p[0] = "abc";
</code>```

reasoning that I wrongly tried to translate in the error above, that @coderredoc brilliantly caught. As far as the dimensions of single words and inputs are concerned, I admit I did not put many attention in them. The exercise is centered on a different topic. In any case, thanks a lot your your valuable suggestions!

答:
Your array of charcaters are all pointing to the same char array and then the content of the array at last changes to the last word. And you get only the last word.

A possible solution

```<code>en[j++] = temp;
</code>```

to

```<code>en[j++] = strdup(temp);
</code>```

Then you will achieve the behavior you want your program to have.

Title: Import data to ragged array

Body:
As an exercise, I have build a simple program that, given a text file of N lowercase words and whitespaces, populates a ragged array char *en[N].

It works without great problems, apart for one: it populates the ragged array with only the last word of the input.

#include<stdio.h>
#include<ctype.h>

int main(int argc, char *argv[]){
    int i = 0, j = 0;
    char *en[100];
    char temp[20];

    FILE *p = fopen(argv[1], "r");
    char single;

    while((single = fgetc(p)) != EOF){
        if(!isspace(single))          /* Temporary store a single word */
            temp[i++] = single;
        else{
            temp[i] = '\0';
            en[j++] = temp;           /* Save stored word in ragged array */
            i = 0;
        }
    }

    printf("%s\n", en[0]);    /* Return the same than en[1] and en[99] */
    printf("%s\n", en[1]);
    printf("%s\n", en[99]);

    return 0;
}

I cannot understand why it goes down to the end of the input file. I am unable of detecting major issues that could suggest a wrong approach.

Edit:

The reasoning behind my approach was that an array of *char can be initialized with this form:

p[0] = "abc";

reasoning that I wrongly tried to translate in the error above, that @coderredoc brilliantly caught. As far as the dimensions of single words and inputs are concerned, I admit I did not put many attention in them. The exercise is centered on a different topic. In any case, thanks a lot your your valuable suggestions!

Body:
Your array of charcaters are all pointing to the same char array and then the content of the array at last changes to the last word. And you get only the last word.

A possible solution

en[j++] = temp;

to

en[j++] = strdup(temp);

Then you will achieve the behavior you want your program to have.


来源: stackexchange

问:
OpenGL ES rotate the world
How i can rotate the all world by 15 degrees on the Z axis? </p>

答:
The solution is:</p>

```<code>gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();

        GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100.0f);

        GLU.gluLookAt(gl, 0, -5, 0,   0.0f, 0.0f, -15.0f,    0.0f, 1.0f, 0.0f);
</code>```

ContentLicense: CC BY-SA 2.5

Title: OpenGL ES rotate the world

Body:
The solution is:

gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();

        GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100.0f);

        GLU.gluLookAt(gl, 0, -5, 0,   0.0f, 0.0f, -15.0f,    0.0f, 1.0f, 0.0f);


问:
Call back function in modal of bootstrap3
Im a little bit confuse about firing a call back function in javascript modal of bootstrap3. In normal jquery.post you can do it like,

```<code>$.post('path', { something: something }, function(data) {
  console.log(data);
});
</code>```

But in bootstrap 3 modal I fires the modal through script and I do it like this base on how I understand the explanation in their website.

```<code>$('selector').modal('show', function() {
  //here comes the problem, I have a button in the modal in the html, my code
  //if the button was clicked inside this modal is..

  $('#myButton').on('click', function() {
     console.log("this is a try");
  });
});
</code>```

But sad to say if I click the button, nothing is happening, nothing was logged in the console. How do I call a callback function in a modal of bootstrap 3?

答:
I think better will be, to use "shown.bs.modal" it is fiered when modal is allready loaded. Bootstrap modal events</p>

```<code>$('#myModal').on('shown.bs.modal', function (e) {
    alert('modal is allready shown');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im a little bit confuse about firing a call back function in javascript modal of bootstrap3. In normal jquery.post you can do it like,

$.post('path', { something: something }, function(data) {
  console.log(data);
});

But in bootstrap 3 modal I fires the modal through script and I do it like this base on how I understand the explanation in their website.

$('selector').modal('show', function() {
  //here comes the problem, I have a button in the modal in the html, my code
  //if the button was clicked inside this modal is..

  $('#myButton').on('click', function() {
     console.log("this is a try");
  });
});

But sad to say if I click the button, nothing is happening, nothing was logged in the console. How do I call a callback function in a modal of bootstrap 3?

Body:
I think better will be, to use "shown.bs.modal" it is fiered when modal is allready loaded. Bootstrap modal events

$('#myModal').on('shown.bs.modal', function (e) {
    alert('modal is allready shown');
});


问:
Jekyll multiversion documentation
I'm using Jekyll for documentation website, and now I have to support multiple versions. The idea is very simple:

```<code>_posts/
    v1.0.0/
        page1.md
        page2.md
    v1.0.1/
        page1.md
        page2.md
</code>```

In this case I want to see these pages at the final website:

```<code>https://URL/v1.0.0/page1/
https://URL/v1.0.0/page2/

https://URL/v1.0.1/page1/
https://URL/v1.0.1/page2/
</code>```

And I do not want to add /v1.0.0/ in permalink: by myself: all .md-pages in subdirectory (for example, in v1.0.0) should contain name of this subdirectory as a prefix in the final URL.

答:
Do not use the posts folder, use directories and pages directly.

```<code>v1.0.0/
   page1.md
   page2.md
 v1.0.1/
   page1.md
   page2.md
</code>```

That would generate the desired output without using permalinks in front matter.

Title: Jekyll multiversion documentation

Body:
I'm using Jekyll for documentation website, and now I have to support multiple versions. The idea is very simple:

_posts/
    v1.0.0/
        page1.md
        page2.md
    v1.0.1/
        page1.md
        page2.md

In this case I want to see these pages at the final website:

https://URL/v1.0.0/page1/
https://URL/v1.0.0/page2/

https://URL/v1.0.1/page1/
https://URL/v1.0.1/page2/

And I do not want to add /v1.0.0/ in permalink: by myself: all .md-pages in subdirectory (for example, in v1.0.0) should contain name of this subdirectory as a prefix in the final URL.

Body:
Do not use the posts folder, use directories and pages directly.

v1.0.0/
   page1.md
   page2.md
 v1.0.1/
   page1.md
   page2.md

That would generate the desired output without using permalinks in front matter.


问:
Java: Curious ImmutableList add
I don't understand this method implementation. It's

```<code>public static <T> List<T> add(List<T> list, T element) {
    final int size = list.size();
    if (size == 0) {
        return ImmutableList.of(element);
    } else if (list instanceof ImmutableList) {
        if (size == 1) {
            final T val = list.get(0);
            list = Lists.newArrayList();
            list.add(val);
        } else {
            list = Lists.newArrayList(list);
        }
    }
    list.add(element);
    return list;
}
</code>```

Why not a straightforward list.add(element)?

答:
This method is an anti-pattern, and should not be used. It munges mutable and immutable data structures, providing the worst of both implementations.

If you're using an immutable data structure you should make that clear in your types - casting to List loses that important context. See the "Interfaces" not implementations section of ImmutableCollection.

If you're using a mutable data you should avoid doing linear-time copies and instead take advantage of the data structure's mutability (carefully).

It generally does not make sense to use the two types interchangeably - if you want to add things to an existing collection use a mutable collection you own. If you intend for the collection to be immutable, don't try to add things to it. This method discards that intent and will lead to runtime errors and/or reduced performance.

Title: Java: Curious ImmutableList add

Body:
I don't understand this method implementation. It's

public static <T> List<T> add(List<T> list, T element) {
    final int size = list.size();
    if (size == 0) {
        return ImmutableList.of(element);
    } else if (list instanceof ImmutableList) {
        if (size == 1) {
            final T val = list.get(0);
            list = Lists.newArrayList();
            list.add(val);
        } else {
            list = Lists.newArrayList(list);
        }
    }
    list.add(element);
    return list;
}

Why not a straightforward list.add(element)?


问:
Problems with Feature Branches In Git
The following description is looking for help with improving my day to day workflow with git and solving an issue I'm not having with additional work.

Let's say I create a remote feature branch from Jira. Then I track it so that it creates a local copy of that remote branch on my local repo. After I complete it that feature, I push that remote version of that feature branch and then make a pull request into the remote development branch. My issue is I've been given the green light to go in and refactor code because this project code is all over the place. However, if I create a branch off of my local dev its not going to be my changes from the local feature branches that I've done. Should I push my local feature branches into my local dev branch?

```<code>Branches

Local

   - Development
   - Feature 1
   - Feature 2

Remote

   - Master
   - Development
   - Feature 1
   - Feature 2
</code>```

答:
The best course of action would be to ask your project lead what they would do. That way, the fault of doing it wrongly won't lie with you. :)

If that's not an option, I would try to follow the git flow approach. What this means in detail comes down to what you mean by this statement:

I've been given the green light to go in and refactor code because this project code is all over the place.

Does this mean refactoring everything that's currently in the Development branch? If so, your approach should be as follows:

Create a new feature branch that branches off of Development

Using that feature branch, refactor the code base

Create a pull request to merge your feature branch into Development

However, if I create a branch off of my local dev its not going to be my changes from the local feature branches that I've done.

That's true, and you have two options here:

Do the refactoring of Development first. As soon as that is done, refactor the code for your new feature on your local feature branch, then open a pull request to merge it into Development.

Open the pull request to merge it into Development first - as soon as it is merged into Development, you can begin the refactoring of Development (which then includes refactoring the code introduced for your new feature as well, of course).

The former approach might save you some work in terms of refactoring, but the latter approach will get the feature out quicker. Once again, depending on how much time is necessary to refactor the code base, this question might be suited for your project lead.

Title: Problems with Feature Branches In Git

Body:
The following description is looking for help with improving my day to day workflow with git and solving an issue I'm not having with additional work.

Let's say I create a remote feature branch from Jira. Then I track it so that it creates a local copy of that remote branch on my local repo. After I complete it that feature, I push that remote version of that feature branch and then make a pull request into the remote development branch. My issue is I've been given the green light to go in and refactor code because this project code is all over the place. However, if I create a branch off of my local dev its not going to be my changes from the local feature branches that I've done. Should I push my local feature branches into my local dev branch?

Branches

Local

   - Development
   - Feature 1
   - Feature 2

Remote

   - Master
   - Development
   - Feature 1
   - Feature 2


问:
JS - video.play() only play for some seconds then stops, no error in console
The play() function does not play the video till the end, the evcentlistener is closed and in console i have no error that could help me.

Here is the full version:

https://codepen.io/apistol/pen/LOgaWw?editors=1010

```<code>var video = document.getElementById("bgvid");
var fclick = document.getElementById("first-click");
var pauseButton = document.querySelector(".pause-button");

function addShowClass() {
  var element = document.getElementById("fclick");
  element.classList.add("display-inherit");
}

function vidPlay() {
  video.play();
}
video.addEventListener("timeupdate", function() {
  if (this.currentTime >= 5) {
    this.pause();
    addShowClass();
    this.removeEventListener("timeupdate", arguments.calee);
  }
});
pauseButton.addEventListener("click", function() {
  if (video.paused) {
    video.play();
    pauseButton.innerHTML = "Pause";
  } else {
    video.pause();
    pauseButton.innerHTML = "Paused";
  }
})
</code>```

答:
Fixed it.

```<code>var video = document.getElementById("bgvid");
var fclick = document.getElementById("first-click");
var pauseButton = document.querySelector(".pause-button");

function addShowClass() {
   var element = document.getElementById("fclick");
   element.classList.add("display-inherit");
}

function vidPlay() {
         video.play();
 }

video.addEventListener("timeupdate", function() {
  if(this.currentTime >= 5.00 ){
      this.pause();
      addShowClass();
      this.removeEventListener("timeupdate", arguments.callee);
    }
});

pauseButton.addEventListener("click", function() {

  if(video.paused) {
    video.play();
    pauseButton.innerHTML = "Pause";
  } else {
    video.pause();
    pauseButton.innerHTML = "Paused";
  }

})
</code>```

There's nothing wrong with your attempt. You just had a typo:

You wrote

```<code>this.removeEventListener("timeupdate", arguments.calee);
</code>```

But it should be

```<code>this.removeEventListener("timeupdate", arguments.callee);
</code>```

(note the double l in callee)

This is why the removeEventListener could not remove the event. I don't know why it doesn't tell you that in the console...

Body:
The play() function does not play the video till the end, the evcentlistener is closed and in console i have no error that could help me.

Here is the full version:

https://codepen.io/apistol/pen/LOgaWw?editors=1010

var video = document.getElementById("bgvid");
var fclick = document.getElementById("first-click");
var pauseButton = document.querySelector(".pause-button");

function addShowClass() {
  var element = document.getElementById("fclick");
  element.classList.add("display-inherit");
}

function vidPlay() {
  video.play();
}
video.addEventListener("timeupdate", function() {
  if (this.currentTime >= 5) {
    this.pause();
    addShowClass();
    this.removeEventListener("timeupdate", arguments.calee);
  }
});
pauseButton.addEventListener("click", function() {
  if (video.paused) {
    video.play();
    pauseButton.innerHTML = "Pause";
  } else {
    video.pause();
    pauseButton.innerHTML = "Paused";
  }
})

Body:
Fixed it.

var video = document.getElementById("bgvid");
var fclick = document.getElementById("first-click");
var pauseButton = document.querySelector(".pause-button");

function addShowClass() {
   var element = document.getElementById("fclick");
   element.classList.add("display-inherit");
}

function vidPlay() {
         video.play();
 }

video.addEventListener("timeupdate", function() {
  if(this.currentTime >= 5.00 ){
      this.pause();
      addShowClass();
      this.removeEventListener("timeupdate", arguments.callee);
    }
});

pauseButton.addEventListener("click", function() {

  if(video.paused) {
    video.play();
    pauseButton.innerHTML = "Pause";
  } else {
    video.pause();
    pauseButton.innerHTML = "Paused";
  }

})

There's nothing wrong with your attempt. You just had a typo:

You wrote

this.removeEventListener("timeupdate", arguments.calee);

But it should be

this.removeEventListener("timeupdate", arguments.callee);

(note the double l in callee)

This is why the removeEventListener could not remove the event. I don't know why it doesn't tell you that in the console...


问:
How does async-await allow for responsiveness in an application that uses an event loop, such as Windows Forms?
As I understand, UI applications have a main thread that has a loop equivalent to

```<code>while(true)
{
   var e = events.Dequeue(); // get event from the queue
   e(); // run event
}
</code>```

I'm confused about e() will be "unblocked" if it is at the top of an async-await chain. Let's say that e() eventually calls

```<code>public async Task WaitOneSecondAsync()
{
    await Task.Delay(1000);
    Console.WriteLine("Done waiting 1 second!");
}
</code>```

Once the main thread hits await Task.Delay(1000); it won't "move on" to the next iteration of the while loop. So can you explain how this unblocks? Perhaps with a code sample?

答:
Once the main thread hits await Task.Delay(1000); it won't "move on" to the next iteration of the while loop

Yes, it will.

Remember, Task.Delay is not Thread.Sleep.  Sleep shuts down your thread and doesn't return until it's awake again.  Task.Delay immediately returns a task which represents a delay.

So can you explain how this unblocks?

await has the following behaviour:

Check the task to see if it is completed. If yes, and it completed with an exception, throw the exception. If yes, and it completed normally, produce the value, if any, and continue executing normally.

The task is not completed. Make a delegate whose action is to start running this method again at the point of the await. (This is the tricky bit for the compiler to do; see any article on the details of the await codegen for an explanation.)  Sign up that delegate as the continuation of the task, and return to your caller.

If this is the first await encountered in the method, the thing that is returned is a task representing the workflow of the method, so that the caller can in turn await it.

```<code>public async Task WaitOneSecondAsync()
{
    await Task.Delay(1000);
    Console.WriteLine("Done waiting 1 second!");
}
</code>```

has these pseudocode semantics:

```<code>    Task thisTask = a new task;
    Action completion = () => {
      Console.WriteLine("Done...");
      mark thisTask as complete
    };
    Task delayTask = Task.Delay(1000);
    if (delayTask has already completed normally)
    {
        completion();
        return thisTask; // Return a completed task.
    }
    else if (delayTask completed with an exception)
        throw the exception
    else
        assign completion as the completion of delayTask
        return thisTask;
</code>```

See how that works? If the delay is not already complete then the method signs up a delegate as the completion of the delay and returns to the caller.  If the caller is the message loop, then the message loop gets to run again.

What happens when the delay completes?  It queues up a message that says to call its completion, and the completion runs at some point in the future.

Of course the real codegen is much, much more complicated than the little pseudocode I've shown here; that's just to get the idea across. The real codegen is complicated by the fact that exception handling is more difficult than just throwing the exception, and by a variety of optimizations that delay generating objects on the heap when possible.

Body:
As I understand, UI applications have a main thread that has a loop equivalent to

while(true)
{
   var e = events.Dequeue(); // get event from the queue
   e(); // run event
}

I'm confused about e() will be "unblocked" if it is at the top of an async-await chain. Let's say that e() eventually calls

public async Task WaitOneSecondAsync()
{
    await Task.Delay(1000);
    Console.WriteLine("Done waiting 1 second!");
}

Once the main thread hits await Task.Delay(1000); it won't "move on" to the next iteration of the while loop. So can you explain how this unblocks? Perhaps with a code sample?

Body:
Once the main thread hits await Task.Delay(1000); it won't "move on" to the next iteration of the while loop

Yes, it will.

Remember, Task.Delay is not Thread.Sleep.  Sleep shuts down your thread and doesn't return until it's awake again.  Task.Delay immediately returns a task which represents a delay.

So can you explain how this unblocks?

await has the following behaviour:

Check the task to see if it is completed. If yes, and it completed with an exception, throw the exception. If yes, and it completed normally, produce the value, if any, and continue executing normally.

The task is not completed. Make a delegate whose action is to start running this method again at the point of the await. (This is the tricky bit for the compiler to do; see any article on the details of the await codegen for an explanation.)  Sign up that delegate as the continuation of the task, and return to your caller.

If this is the first await encountered in the method, the thing that is returned is a task representing the workflow of the method, so that the caller can in turn await it.

public async Task WaitOneSecondAsync()
{
    await Task.Delay(1000);
    Console.WriteLine("Done waiting 1 second!");
}

has these pseudocode semantics:

    Task thisTask = a new task;
    Action completion = () => {
      Console.WriteLine("Done...");
      mark thisTask as complete
    };
    Task delayTask = Task.Delay(1000);
    if (delayTask has already completed normally)
    {
        completion();
        return thisTask; // Return a completed task.
    }
    else if (delayTask completed with an exception)
        throw the exception
    else
        assign completion as the completion of delayTask
        return thisTask;

See how that works? If the delay is not already complete then the method signs up a delegate as the completion of the delay and returns to the caller.  If the caller is the message loop, then the message loop gets to run again.

What happens when the delay completes?  It queues up a message that says to call its completion, and the completion runs at some point in the future.

Of course the real codegen is much, much more complicated than the little pseudocode I've shown here; that's just to get the idea across. The real codegen is complicated by the fact that exception handling is more difficult than just throwing the exception, and by a variety of optimizations that delay generating objects on the heap when possible.


问:
Unity Prefab won't instantiate into the game scene
Having a bit of trouble with unity. I have had two different builds for firing and movement systems, now I am porting them together although I encounter some issues when I do this. The 'bullet' prefab in the assets folder is asked to be spawned into the game scene but never is. But what is more intriguing is the other functions of the 'bullet' and script take place, so it is only the prefab not showing in the scene.

THe following is the code from the script which instaniates the prefab:

```<code>public bool isFiring; // Boolean to check if the player is firing
public bool isReloading = false; // Boolean to check if the player is reloading

public BulletController bullet; // Reference another script
public float bulletSpeed; // bullet speed - changed in bullet controller

public float timeBetweenShots; // time between shots can be fired
private float shotCounter; // Tempoary time holder - ensures no bullet spam

public Transform firePoint; // The fire point in the game attached to the gun

public static int ammoRemaining = 3; // Ammo left for the player to fire

public static int maxAmmo = 3;
public Text ammoText;

public Rigidbody cannonballInstance;
public BulletController projectile;

[Range(10f, 80f)]
public float angle = 45f;

// Use this for initialization
void Awake () {
    isReloading = false;
    timeBetweenShots = 0.3f;
    ammoRemaining = maxAmmo;
}

// Update is called once per frame
void Update () {

    if (ammoRemaining == 0 && isReloading == false)
    {
        StartCoroutine(Reload());

    }

    else if (isFiring == true && isReloading == false)
    {
        shotCounter -= Time.deltaTime;
        if(shotCounter <= 0 && ammoRemaining > 0 && isReloading == false)
        {
            shotCounter = timeBetweenShots;

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                FireCannonAtPoint(hitInfo.point);
            }

            ammoRemaining -= 1;
            ammoText.text = "Ammo:" + ammoRemaining;

        }

    }
    else if (Input.GetKey(KeyCode.R))
    {
        StartCoroutine(Reload());
    }

    else
    {
        shotCounter = 0;

    }

}

private void FireCannonAtPoint(Vector3 point)
{
    Vector3 randomAccuracy;

    randomAccuracy = new Vector3(Random.Range(-2.0f, 2f), 0, Random.Range(-2f, 2f));

    var velocity = BallisticVelocity(point + randomAccuracy, angle);
    Debug.Log("Firing at " + (point + randomAccuracy) + " velocity " + velocity);

    Rigidbody rg = Instantiate(cannonballInstance, transform.position, transform.rotation);
    Debug.Log("Firing at" + transform.position);
    Debug.Log(rg.transform);
    BulletController newProjectile = rg.GetComponent<BulletController>();

    newProjectile.speed = velocity;
    Debug.Log(newProjectile.speed);

    // cannonballInstance.transform.position = transform.position ;
    // cannonballInstance.velocity = velocity;
}

private Vector3 BallisticVelocity(Vector3 destination, float angle)
{
    Vector3 direction = destination - transform.position; // get Target Direction
    float height = direction.y; // get height difference
    direction.y = 0; // retain only the horizontal difference
    float distance = direction.magnitude; // get horizontal direction
    float AngleRadians = angle * Mathf.Deg2Rad; // Convert angle to radians
    direction.y = distance * Mathf.Tan(AngleRadians); // set direction to the elevation angle.
    distance += height / Mathf.Tan(AngleRadians); // Correction for small height differences

    // Calculate the velocity magnitude
    float velocity = Mathf.Sqrt(distance * Physics.gravity.magnitude / Mathf.Sin(2 * AngleRadians));
    Debug.Log(velocity);
    return velocity * direction.normalized; // Return a normalized vector.

}

public IEnumerator Reload()
{
    isReloading = true;
    ammoText.text = "REL...";

    yield return new WaitForSeconds(2);
    ammoRemaining = maxAmmo;
    isReloading = false;
    ammoText.text = "Ammo:" + ammoRemaining;

}
}
</code>```

Everything is the same in the two seperate version but it just the spawning in of the prefab which doesn't work.

Any ideas/suggestions are much appreciated.

答:
From your code:

```<code>public Rigidbody cannonballInstance;

[...]

Rigidbody rg = Instantiate(cannonballInstance, transform.position, transform.rotation);
</code>```

You are Instantiating a Rigidbody where I think you expect to instantiate a GameObject

try with:

```<code>Rigidbody rg = Instantiate(cannonballInstance.gameObject, transform.position, transform.rotation).GetComponent<Rigidbody>();
</code>```

Body:
Having a bit of trouble with unity. I have had two different builds for firing and movement systems, now I am porting them together although I encounter some issues when I do this. The 'bullet' prefab in the assets folder is asked to be spawned into the game scene but never is. But what is more intriguing is the other functions of the 'bullet' and script take place, so it is only the prefab not showing in the scene.

THe following is the code from the script which instaniates the prefab:

public bool isFiring; // Boolean to check if the player is firing
public bool isReloading = false; // Boolean to check if the player is reloading

public BulletController bullet; // Reference another script
public float bulletSpeed; // bullet speed - changed in bullet controller

public float timeBetweenShots; // time between shots can be fired
private float shotCounter; // Tempoary time holder - ensures no bullet spam

public Transform firePoint; // The fire point in the game attached to the gun

public static int ammoRemaining = 3; // Ammo left for the player to fire

public static int maxAmmo = 3;
public Text ammoText;

public Rigidbody cannonballInstance;
public BulletController projectile;

[Range(10f, 80f)]
public float angle = 45f;

// Use this for initialization
void Awake () {
    isReloading = false;
    timeBetweenShots = 0.3f;
    ammoRemaining = maxAmmo;
}

// Update is called once per frame
void Update () {

    if (ammoRemaining == 0 && isReloading == false)
    {
        StartCoroutine(Reload());

    }

    else if (isFiring == true && isReloading == false)
    {
        shotCounter -= Time.deltaTime;
        if(shotCounter <= 0 && ammoRemaining > 0 && isReloading == false)
        {
            shotCounter = timeBetweenShots;

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                FireCannonAtPoint(hitInfo.point);
            }

            ammoRemaining -= 1;
            ammoText.text = "Ammo:" + ammoRemaining;

        }

    }
    else if (Input.GetKey(KeyCode.R))
    {
        StartCoroutine(Reload());
    }

    else
    {
        shotCounter = 0;

    }

}

private void FireCannonAtPoint(Vector3 point)
{
    Vector3 randomAccuracy;

    randomAccuracy = new Vector3(Random.Range(-2.0f, 2f), 0, Random.Range(-2f, 2f));

    var velocity = BallisticVelocity(point + randomAccuracy, angle);
    Debug.Log("Firing at " + (point + randomAccuracy) + " velocity " + velocity);

    Rigidbody rg = Instantiate(cannonballInstance, transform.position, transform.rotation);
    Debug.Log("Firing at" + transform.position);
    Debug.Log(rg.transform);
    BulletController newProjectile = rg.GetComponent<BulletController>();

    newProjectile.speed = velocity;
    Debug.Log(newProjectile.speed);

    // cannonballInstance.transform.position = transform.position ;
    // cannonballInstance.velocity = velocity;
}

private Vector3 BallisticVelocity(Vector3 destination, float angle)
{
    Vector3 direction = destination - transform.position; // get Target Direction
    float height = direction.y; // get height difference
    direction.y = 0; // retain only the horizontal difference
    float distance = direction.magnitude; // get horizontal direction
    float AngleRadians = angle * Mathf.Deg2Rad; // Convert angle to radians
    direction.y = distance * Mathf.Tan(AngleRadians); // set direction to the elevation angle.
    distance += height / Mathf.Tan(AngleRadians); // Correction for small height differences

    // Calculate the velocity magnitude
    float velocity = Mathf.Sqrt(distance * Physics.gravity.magnitude / Mathf.Sin(2 * AngleRadians));
    Debug.Log(velocity);
    return velocity * direction.normalized; // Return a normalized vector.

}

public IEnumerator Reload()
{
    isReloading = true;
    ammoText.text = "REL...";

    yield return new WaitForSeconds(2);
    ammoRemaining = maxAmmo;
    isReloading = false;
    ammoText.text = "Ammo:" + ammoRemaining;

}
}

Everything is the same in the two seperate version but it just the spawning in of the prefab which doesn't work.

Any ideas/suggestions are much appreciated.

Body:
From your code:

public Rigidbody cannonballInstance;

[...]

Rigidbody rg = Instantiate(cannonballInstance, transform.position, transform.rotation);

You are Instantiating a Rigidbody where I think you expect to instantiate a GameObject

try with:

Rigidbody rg = Instantiate(cannonballInstance.gameObject, transform.position, transform.rotation).GetComponent<Rigidbody>();


问:
vtk error: extension `GL_EXT_gpu_shader4' unsupported in fragment shader
I have XUBUNTU 16.04 32 bits. I am a beginner with VTK libraries. I have built and istalled VTK 7.1.1 from source. I followed the instructions from https://www.vtk.org/Wiki/VTK/Configure_and_Build
The installation is ok. No errors.
I download the simplest example: CylinderRenderingProperties.
Then, I compile the example. No errors. But, when I run the program

```<code>./CylinderRenderingProperties
</code>```

there is an error:

```<code>VTK-7.1.1/Rendering/OpenGL2/vtkShaderProgram.cxx, line 395 vtkShaderProgram (0x9fd1510): 0:39(12): error: extension `GL_EXT_gpu_shader4' unsupported in fragment shader
</code>```

I don't know what is wrong. Could be related with any graphic driver? This is the information of my graphics hardware:

```<code>inxi -G
Graphics:  Card: Intel Mobile 4 Series Integrated Graphics Controller
       Display Server: X.Org 1.19.3 drivers: (unloaded: fbdev,vesa)
       Resolution: 1280x800@60.00hz, 1280x1024@60.02hz
       GLX Renderer: Mesa DRI Mobile Intel GM45 Express x86/MMX/SSE2 GLX Version: 2.1 Mesa 17.0.7
</code>```

答: Yes. I don't need to do complex rendering. The solution was to change the VTK's CMake variable VTK_RENDERING_BACKEND from openGL2 to openGL and then build VTK again.</p>

Body:
I have XUBUNTU 16.04 32 bits. I am a beginner with VTK libraries. I have built and istalled VTK 7.1.1 from source. I followed the instructions from https://www.vtk.org/Wiki/VTK/Configure_and_Build
The installation is ok. No errors.
I download the simplest example: CylinderRenderingProperties.
Then, I compile the example. No errors. But, when I run the program

./CylinderRenderingProperties

there is an error:

VTK-7.1.1/Rendering/OpenGL2/vtkShaderProgram.cxx, line 395 vtkShaderProgram (0x9fd1510): 0:39(12): error: extension `GL_EXT_gpu_shader4' unsupported in fragment shader

I don't know what is wrong. Could be related with any graphic driver? This is the information of my graphics hardware:

inxi -G
Graphics:  Card: Intel Mobile 4 Series Integrated Graphics Controller
       Display Server: X.Org 1.19.3 drivers: (unloaded: fbdev,vesa)
       Resolution: 1280x800@60.00hz, 1280x1024@60.02hz
       GLX Renderer: Mesa DRI Mobile Intel GM45 Express x86/MMX/SSE2 GLX Version: 2.1 Mesa 17.0.7


问:
Start countdown after php page load
I am trying to create a browser training button. When the user clicks the " Brench Press" button his "Strength" increases by a php file that i've set in the form action and it checks some values and inserts values to the database that shows up.

What my problem and what i would like some help with is to implement my clock function that sets a countdown from 30 seconds to 0. This should be a countdown that the users has to watch and wait for untill he can "train" again. So somehow i need to write this clock function to output after the php file has been loaded and not onclick on the button as of now. And also for the clock not to refresh it's countdown on page refresh but keep going.

What i tried to do is to create a session with the function call inside and send it to the site so it loads after the php file has loaded but it doesn't seem to work.

```<code>$_SESSION['CountDownBenchPress'] = "<script> countdown(); </script>";
</code>```

var time = 30;
function countdown()
{
  if(time==0)
  {
    window.location.reload();
  }
  else
  {
    tmptime = time;
    dayTime = 24*60*60;
    hourTime = 60*60;
    minutesTime = 60;

    days = Math.floor(tmptime/dayTime);
    tmptime = tmptime - days*dayTime;

    hours = Math.floor(tmptime/hourTime);
    tmptime = tmptime - hours*hourTime;

    minutes = Math.floor(tmptime/minutesTime);
    tmptime = tmptime - minutes*minutesTime;

    seconds = tmptime;
    tidtext="";
    if(days>0)
      tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else if(hours>0)
      tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else
      tidtext =  minutes + " minutes " + seconds + " seconds";

    document.getElementById('timer').innerHTML = tidtext;
    time--;
    setTimeout("countdown()", 1000);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="" action="" method="">
            <td data-th="Workout"><input type="submit" onclick="countdown()" name="" value="Bench Press"></td>

            <div id="timer"></div>

          </form></code>```

答:
var time = 30;
function countdown()
{
  if(time==0)
  {
    window.location.reload();
  }
  else
  {
    tmptime = time;
    dayTime = 24*60*60;
    hourTime = 60*60;
    minutesTime = 60;

    days = Math.floor(tmptime/dayTime);
    tmptime = tmptime - days*dayTime;

    hours = Math.floor(tmptime/hourTime);
    tmptime = tmptime - hours*hourTime;

    minutes = Math.floor(tmptime/minutesTime);
    tmptime = tmptime - minutes*minutesTime;

    seconds = tmptime;
    tidtext="";
    if(days>0)
      tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else if(hours>0)
      tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else
      tidtext =  minutes + " minutes " + seconds + " seconds";

    document.getElementById('timer').innerHTML = tidtext;
    time--;
    setTimeout("countdown()", 1000);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="" action="" method="">
            <td data-th="Workout"><input type="button" onclick="countdown()" name="" value="Bench Press"></td>

            <div id="timer"></div>

          </form></code>```

you must put input type="button" instead of submit. That's because the submit redirects you to the action page that you wrote in the form (in your case, nothing)

EDIT I didn't notice the auto-click part. To solve it, you must modify the body tag as it follows

```<code><body onload="document.getElementById('clickme').click()">
</code>```

and the button like this

```<code><input type="button" id="clickme" onclick="countdown()" name="" value="Bench Press">
</code>```

Title: Start countdown after php page load

Body:
I am trying to create a browser training button. When the user clicks the " Brench Press" button his "Strength" increases by a php file that i've set in the form action and it checks some values and inserts values to the database that shows up.

What my problem and what i would like some help with is to implement my clock function that sets a countdown from 30 seconds to 0. This should be a countdown that the users has to watch and wait for untill he can "train" again. So somehow i need to write this clock function to output after the php file has been loaded and not onclick on the button as of now. And also for the clock not to refresh it's countdown on page refresh but keep going.

What i tried to do is to create a session with the function call inside and send it to the site so it loads after the php file has loaded but it doesn't seem to work.

$_SESSION['CountDownBenchPress'] = "";

var time = 30;
function countdown()
{
  if(time==0)
  {
    window.location.reload();
  }
  else
  {
    tmptime = time;
    dayTime = 24*60*60;
    hourTime = 60*60;
    minutesTime = 60;

    days = Math.floor(tmptime/dayTime);
    tmptime = tmptime - days*dayTime;

    hours = Math.floor(tmptime/hourTime);
    tmptime = tmptime - hours*hourTime;

    minutes = Math.floor(tmptime/minutesTime);
    tmptime = tmptime - minutes*minutesTime;

    seconds = tmptime;
    tidtext="";
    if(days>0)
      tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else if(hours>0)
      tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else
      tidtext =  minutes + " minutes " + seconds + " seconds";

    document.getElementById('timer').innerHTML = tidtext;
    time--;
    setTimeout("countdown()", 1000);
  }
}

<form class="" action="" method="">
            <input type="submit" onclick="countdown()" name="" value="Bench Press">

          </form>

Body:
var time = 30;
function countdown()
{
  if(time==0)
  {
    window.location.reload();
  }
  else
  {
    tmptime = time;
    dayTime = 24*60*60;
    hourTime = 60*60;
    minutesTime = 60;

    days = Math.floor(tmptime/dayTime);
    tmptime = tmptime - days*dayTime;

    hours = Math.floor(tmptime/hourTime);
    tmptime = tmptime - hours*hourTime;

    minutes = Math.floor(tmptime/minutesTime);
    tmptime = tmptime - minutes*minutesTime;

    seconds = tmptime;
    tidtext="";
    if(days>0)
      tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else if(hours>0)
      tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
    else
      tidtext =  minutes + " minutes " + seconds + " seconds";

    document.getElementById('timer').innerHTML = tidtext;
    time--;
    setTimeout("countdown()", 1000);
  }
}

<form class="" action="" method="">
            <td data-th="Workout"><input type="button" onclick="countdown()" name="" value="Bench Press"></td>

            <div id="timer"></div>

          </form>

you must put input type="button" instead of submit. That's because the submit redirects you to the action page that you wrote in the form (in your case, nothing)

EDIT I didn't notice the auto-click part. To solve it, you must modify the body tag as it follows

<body onload="document.getElementById('clickme').click()">

and the button like this

<input type="button" id="clickme" onclick="countdown()" name="" value="Bench Press">


问:
Equality between functional and inductive definitions
I have an inductive definition of the proposition P (or repeats l) that a lists contains repeating elements, and a functional definition of it's negation Q (or no_repeats l).

I want to show that P <-> ~ Q  and ~ P <-> Q.  I have been able to show three of the four implications, but ~ Q -> P seems to be different, because I'm unable to extract data from ~Q.

```<code>Require Import List.
Variable A : Type.

Inductive repeats : list A -> Prop :=            (*   repeats  *)
  repeats_hd l x : In x l    -> repeats (x::l)
| repeats_tl l x : repeats l -> repeats (x::l).

Fixpoint no_repeats (l: list A): Prop :=
  match l with nil => True | a::l' =>  ~ In a l' /\ no_repeats l' end.

Lemma not_no_repeats_repeats: forall l, (~ no_repeats l) -> repeats l.
  induction l; simpl. tauto. intros.
</code>```

After doing induction on l, the second case is

```<code>  IHl : ~ no_repeats l -> repeats l
  H : ~ (~ In a l /\ no_repeats l)
  ============================
  repeats (a :: l)
</code>```

Is it possible to deduce In a l \/ ~ no_repeats l (which is sufficient) from this?

答:
Your statement implies that equality on A supports double negation elimination:

```<code>Require Import List.
Import ListNotations.

Variable A : Type.

Inductive repeats : list A -> Prop :=            (*   repeats  *)
  repeats_hd l x : In x l    -> repeats (x::l)
| repeats_tl l x : repeats l -> repeats (x::l).

Fixpoint no_repeats (l: list A): Prop :=
  match l with nil => True | a::l' =>  ~ In a l' /\ no_repeats l' end.

Hypothesis not_no_repeats_repeats: forall l, (~ no_repeats l) -> repeats l.

Lemma eq_nn_elim (a b : A) : ~ a <> b -> a = b.
Proof.
  intros H.
  assert (H' : ~ no_repeats [a; b]).
  { simpl. intuition. }
  apply not_no_repeats_repeats in H'.
  inversion H'; subst.
  { subst. simpl in *. intuition; tauto. }
  inversion H1; simpl in *; subst; intuition.
  inversion H2.
Qed.
</code>```

Not every type supports eq_nn_elim, which means that you can only prove not_no_repeats_repeats by placing additional hypotheses on A.  It should suffice to assume that A has decidable equality; that is:

```<code>Hypothesis eq_dec a b : a = b \/ a <> b.
</code>```

Body:
I have an inductive definition of the proposition P (or repeats l) that a lists contains repeating elements, and a functional definition of it's negation Q (or no_repeats l).

I want to show that P <-> ~ Q  and ~ P <-> Q.  I have been able to show three of the four implications, but ~ Q -> P seems to be different, because I'm unable to extract data from ~Q.

Require Import List.
Variable A : Type.

Inductive repeats : list A -> Prop :=            (*   repeats  *)
  repeats_hd l x : In x l    -> repeats (x::l)
| repeats_tl l x : repeats l -> repeats (x::l).

Fixpoint no_repeats (l: list A): Prop :=
  match l with nil => True | a::l' =>  ~ In a l' /\ no_repeats l' end.

Lemma not_no_repeats_repeats: forall l, (~ no_repeats l) -> repeats l.
  induction l; simpl. tauto. intros.

After doing induction on l, the second case is

  IHl : ~ no_repeats l -> repeats l
  H : ~ (~ In a l /\ no_repeats l)
  ============================
  repeats (a :: l)

Is it possible to deduce In a l \/ ~ no_repeats l (which is sufficient) from this?

Body:
Your statement implies that equality on A supports double negation elimination:

Require Import List.
Import ListNotations.

Variable A : Type.

Inductive repeats : list A -> Prop :=            (*   repeats  *)
  repeats_hd l x : In x l    -> repeats (x::l)
| repeats_tl l x : repeats l -> repeats (x::l).

Fixpoint no_repeats (l: list A): Prop :=
  match l with nil => True | a::l' =>  ~ In a l' /\ no_repeats l' end.

Hypothesis not_no_repeats_repeats: forall l, (~ no_repeats l) -> repeats l.

Lemma eq_nn_elim (a b : A) : ~ a <> b -> a = b.
Proof.
  intros H.
  assert (H' : ~ no_repeats [a; b]).
  { simpl. intuition. }
  apply not_no_repeats_repeats in H'.
  inversion H'; subst.
  { subst. simpl in *. intuition; tauto. }
  inversion H1; simpl in *; subst; intuition.
  inversion H2.
Qed.

Not every type supports eq_nn_elim, which means that you can only prove not_no_repeats_repeats by placing additional hypotheses on A.  It should suffice to assume that A has decidable equality; that is:

Hypothesis eq_dec a b : a = b \/ a <> b.


问:
How can I build a node project and a spring-boot project at the same time through a maven
I have created a web application with a spring-boot/java backend and an angular/node front end that is encapsulated in a maven wrapper. I would like to launch both parts of the application in sync using the maven wrapper.

When starting the project, I want to execute  npm install and npm start on the node project and spring-boot:run on the spring boot project. Is there a maven plugin that I can use in my maven wrapper to make this possible?

What is the optimal way of linking these projects and running them simultaneously?

答:
You will use this maven plugin to call node npm yarn or other like this </p>

```<code>  <plugin>
                        <groupId>com.github.eirslett</groupId>
                        <artifactId>frontend-maven-plugin</artifactId>
                        <version>${frontend-maven-plugin.version}</version>
                        <executions>
                            <execution>
                                <id>install node and yarn</id>
                                <goals>
                                    <goal>install-node-and-yarn</goal>
                                </goals>
                                <configuration>
                                    <nodeVersion>${node.version}</nodeVersion>
                                    <yarnVersion>${yarn.version}</yarnVersion>
                                </configuration>
                            </execution>
                            <execution>
                                <id>yarn install</id>
                                <goals>
                                    <goal>yarn</goal>
                                </goals>
                                <configuration>
                                    <arguments>install</arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>webpack build test</id>
                                <goals>
                                    <goal>yarn</goal>
                                </goals>
                                <phase>test</phase>
                                <configuration>
                                    <arguments>run webpack:test</arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>webpack build prod</id>
                                <goals>
                                    <goal>yarn</goal>
                                </goals>
                                <phase>generate-resources</phase>
                                <configuration>
                                    <arguments>run webpack:prod</arguments>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
</code>```

Body:
You will use this maven plugin to call node npm yarn or other like this

  <plugin>
                        <groupId>com.github.eirslett</groupId>
                        <artifactId>frontend-maven-plugin</artifactId>
                        <version>${frontend-maven-plugin.version}</version>
                        <executions>
                            <execution>
                                <id>install node and yarn</id>
                                <goals>
                                    <goal>install-node-and-yarn</goal>
                                </goals>
                                <configuration>
                                    <nodeVersion>${node.version}</nodeVersion>
                                    <yarnVersion>${yarn.version}</yarnVersion>
                                </configuration>
                            </execution>
                            <execution>
                                <id>yarn install</id>
                                <goals>
                                    <goal>yarn</goal>
                                </goals>
                                <configuration>
                                    <arguments>install</arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>webpack build test</id>
                                <goals>
                                    <goal>yarn</goal>
                                </goals>
                                <phase>test</phase>
                                <configuration>
                                    <arguments>run webpack:test</arguments>
                                </configuration>
                            </execution>
                            <execution>
                                <id>webpack build prod</id>
                                <goals>
                                    <goal>yarn</goal>
                                </goals>
                                <phase>generate-resources</phase>
                                <configuration>
                                    <arguments>run webpack:prod</arguments>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>


问:
Delegate method for open the "Notification Center" in iOS 11
Which delegate method are going to be called when I open the Notification Center in iOS 11 (swipe down from the top of the display)?

In earlier versions up to iOS 10 the delegate method func applicationWillResignActive(_ application: UIApplication) was called.

Thank you!

Illustration: open Notification Center

答:
Rashwan L is correct. But there is more to this, at least in iOS 11 (I have not gone back to see if this behaviour is new in iOS 11).

When the swipe down is initiated there's an immediate call to applicationWillResignActive().

If you do not commit the swipe (if you begin but don't go far enough or you swipe back up to release it) there's an immediate call to applicationDidBecomeActive().

That's reasonable and expected behaviour. However, if you fully commit the swipe (you swipe far enough down so that the notification center remains when you release) the callbacks look like this...

```<code>applicationWillResignActive <- happens immediately

...the user is still dragging here...
...now the swipe is complete...

applicationDidBecomeActive
applicationWillResignActive
</code>```

There is, unfortunately, an unexpected callback to applicationDidBecomeActive(). I think this is a bug but regardless, if you are taking action based on these events you need to be aware.

Body:
Rashwan L is correct. But there is more to this, at least in iOS 11 (I have not gone back to see if this behaviour is new in iOS 11).

When the swipe down is initiated there's an immediate call to applicationWillResignActive().

If you do not commit the swipe (if you begin but don't go far enough or you swipe back up to release it) there's an immediate call to applicationDidBecomeActive().

That's reasonable and expected behaviour. However, if you fully commit the swipe (you swipe far enough down so that the notification center remains when you release) the callbacks look like this...

applicationWillResignActive <- happens immediately

...the user is still dragging here...
...now the swipe is complete...

applicationDidBecomeActive
applicationWillResignActive

There is, unfortunately, an unexpected callback to applicationDidBecomeActive(). I think this is a bug but regardless, if you are taking action based on these events you need to be aware.


问:
Microsoft Bot Framework - very high response times
I have 10 seconds response times through any channel. (WebChat and Facebook)
My endpoint is a PAAS instance located in the western United States.
The WebApp has an S3 size and the response times are constant (even if there is only one conversation).

I have the following questions:
Is there any way to optimize this?
What are the Azure Bot Framework SLAs?

答:
As bot framework is a preview product, there is no current SLAs.

Are you using the default state storage? If so, part of the slow down you mentioned is probably related.  We highly recommend implementing your own state service.  There is a blog article here discussing the implementations there is also a repository here with samples.  This is probably not 100% of your issue but it is probably at least part of it.

Another thing to keep in mind is where your bot is located in relationship to your WebChat client and what instance of the Bot Connector you are using this blog may provide more info.  Please see the "Geographic Direct Line endpoints" section.


问:
How to set a downloadable font for a whole application as default font?
In my previous projects, I have used Calligraphy library to set a font for a whole application. But it requires storing font file in assets which makes APK size bigger. Now I am wondering is it possible to set a downloadable font as default for a whole application.

I could set a downloadable font for only ONE TextView.

```<code><TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/text_margin"
    android:fontFamily="@font/lato"
    android:text="@string/large_text" />
</code>```

Yes, I know I could create MyTextView class and set downloadable font programmatically. But I do not think it is a good idea as text can be anywhere in EditText, Spinner item, Toast.

So my question is how to set a downloadable font for a whole application as default font?

答:
A library to help with custom fonts and text sizes

The goal of this library is to allow your app to support multiple FontFamilies (e.g. lato, roboto, etc.) with their own styles (e.g. normal, bold, italic) in an easily-configurable way.

Body:
In my previous projects, I have used Calligraphy library to set a font for a whole application. But it requires storing font file in assets which makes APK size bigger. Now I am wondering is it possible to set a downloadable font as default for a whole application.

I could set a downloadable font for only ONE TextView.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/text_margin"
    android:fontFamily="@font/lato"
    android:text="@string/large_text" />

Yes, I know I could create MyTextView class and set downloadable font programmatically. But I do not think it is a good idea as text can be anywhere in EditText, Spinner item, Toast.

So my question is how to set a downloadable font for a whole application as default font?


问:
Why would an ALU's ouput change asynchronously in response to input changes?
Wikipedia states "An ALU is a combinational logic circuit, meaning that its outputs will change asynchronously in response to input changes."

But, the definition of a combinational logic circuit is: "combinational logic ... where the output is a pure function of the present input only."

If the output of a combinational logic circuit is purely determined by present input, is Wikipedia stating that it's asynchronous because of the time it takes for an electrical signal to travel through the circuit (~light speed right?)?

答:
The two statements say the same thing.  The output is a pure function of the input, so the output will change ONLY when the input changes.  It's asynchronous because there's no timing or clock involved -- it doesn't matter when the input changes, and each change in an input will result in corresponding changes in the output irrespective of clock signals.

Now for any real circuit, there will be a delay between input changes and output changes, and there may be jitter/settling issues, but that is a whole other problem.


问:
Should I always return promises in all functions in JavaScript?
I am thinking could it be a good approach to always return promises in functions in JavaScript?

Let's imagine the case where we have a function that validates a username. A master function simply utilises 2 other functions that perform different checks.

Please note, all functions names are just examples.

```<code>// Returns a boolean
function validateUsername (username) {
  return validateUsernameFormat(username) &&
    isUsernameReserved(username);
}

// Returns a boolean
function validateUsernameFormat (username) {
  return typeOf(username) === 'string' &&
    username.match(/^\[a-z0-9]{8,20}$/);
}

// Returns a boolean
function isUsernameNotReserved (username) {
  return ['igor', 'kristina'].indexOf(username) === -1;
}
</code>```

Now let's imagine we augment our validation in the future by calling API to check if a given username already exists in our database.

```<code>// Now returns a promise
function isUsernameNotReserved (username) {
  return API.checkIfUserNameAlreadyExists(username);
}
</code>```

This would mean we will also now have to change the master validateUsername function since it now also needs to return promise. This would also probably mean we will have to modify all functions that use validateUsername function.

But what If we had all function in promises from scratch?

Option A - All functions return promises

```<code>// Returns a promise
function validateUsername (username) {
  return validateUsernameFormat(username)
    .then(() => {
      return isUsernameReserved(username);
    });
}

// Returns a promise
function validateUsernameFormat (username) {
  return (
    typeOf(username) === 'string' && username.match(/^\[a-z0-9]{8,20}$/) ?
    Promise.resolve() : Promise.reject()
  );
}

// Returns a promise
function isUsernameNotReserved (username) {
  return (
    ['igor', 'kristina'].indexOf(username) === -1 ?
    Promise.resolve() : Promise.reject()
  );
}
</code>```

Now if we want to augment isUsernameNotReserved with asynchronous API call, we don't need to change anything else.

Option B - Only functions calling another functions return promises

Also, another option would be write functions in promises that call another functions. In that case, only validateUsername should be written as a promise from scratch.

Is this a good approach? What could be the drawbacks apart from performance?

Upd: ran a simple performance test and though running consequent promises is slower, it practically should not make any difference since running 100000 consequent functions takes ~200ms, while running 1000 takes ~3ms in Chrome. Fiddle here https://jsfiddle.net/igorpavlov/o7nb71np/2/

答:
Should I always return promises in all functions in JavaScript?

No.

If you have a function that performs an asynchronous operation or may perform an asynchronous operation, then it is reasonable and generally good design to return a promise from that function.

But, if your function is entirely synchronous and no reasonable amount of forethought thinks this will sometime soon contain an asynchronous operation, then there are a bunch of reason why you should not return a promise from it:

Asynchronous code writing and testing is more complicated than synchronous code writing and testing.  So, you really don't want to make code harder to write and test than it needs to be.  If your code can be synchronous (and just return a normal value), then you should do so.

Every .then() handler gets called on the next tick (guaranteed asynchronously) so if you take a whole series of synchronous operations and force each function to wait until the next tick of the event loop, you're slowing down code execution.  In addition, you're adding to the work of the garbage collector for every single function call (since there's now a promise object associated with every single function call).

Losing the ability to return a normal value from a synchronous function is a huge step backwards in the language tools that you can conveniently use to write normal code.  You really don't want to give that up on every single function.

Now if we want to augment isUsernameNotReserved with asynchronous API call, we don't need to change anything else.

A good API design would anticipate whether an asynchronous API is relevant or likely useful in the near future and make the API async only in that case.  Because asynchronous APIs are more work to write, use and test, you don't want to unnecessarily just make everything async "just in case".  But, it would be wise to anticipate if you are likely to want to use an async operation in your API in the future or not.  You just don't want to go overboard here.  Remember, APIs can be added to or extended in the future to support new async things that come along so you don't have to over complicate things in an effort to pre-anticipate everything that ever might happen in the future.  You want to draw a balance.

"Balance" seems like the right word here.  You want to balance the likely future needs of your API with developer simplicity.  Making everything return a promise does not draw a proper balance, as it chooses infinite flexibility in the future while over complicating things that don't need to be as complicated.

In looking at a couple of your particular examples:

validateUsernameFormat() does not seem likely to ever need to be asynchronous so I see no reason for it to return a promise.

isUsernameNotReserved() does seem like it may need to be asynchronous at some point since you may need to look some data up in a database in order to determine if the user name is available.

Though, I might point out that checking if a user name is available before trying to just create it can create a race condition.  This type of check may still be used as UI feedback, but when actually creating the name, you generally need to create it in an atomic way such that two requests looking for the same name can't collide.  Usually this is done by creating the name in the database with settings that will cause it to succeed if the name does not already exist, but fail if it does.  Then, the burden is on the database (where it belongs) to handle concurrency issues for two requests both trying to create the same user name.

Body:
I am thinking could it be a good approach to always return promises in functions in JavaScript?

Let's imagine the case where we have a function that validates a username. A master function simply utilises 2 other functions that perform different checks.

Please note, all functions names are just examples.

// Returns a boolean
function validateUsername (username) {
  return validateUsernameFormat(username) &&
    isUsernameReserved(username);
}

// Returns a boolean
function validateUsernameFormat (username) {
  return typeOf(username) === 'string' &&
    username.match(/^\[a-z0-9]{8,20}$/);
}

// Returns a boolean
function isUsernameNotReserved (username) {
  return ['igor', 'kristina'].indexOf(username) === -1;
}

Now let's imagine we augment our validation in the future by calling API to check if a given username already exists in our database.

// Now returns a promise
function isUsernameNotReserved (username) {
  return API.checkIfUserNameAlreadyExists(username);
}

This would mean we will also now have to change the master validateUsername function since it now also needs to return promise. This would also probably mean we will have to modify all functions that use validateUsername function.

But what If we had all function in promises from scratch?

Option A - All functions return promises

// Returns a promise
function validateUsername (username) {
  return validateUsernameFormat(username)
    .then(() => {
      return isUsernameReserved(username);
    });
}

// Returns a promise
function validateUsernameFormat (username) {
  return (
    typeOf(username) === 'string' && username.match(/^\[a-z0-9]{8,20}$/) ?
    Promise.resolve() : Promise.reject()
  );
}

// Returns a promise
function isUsernameNotReserved (username) {
  return (
    ['igor', 'kristina'].indexOf(username) === -1 ?
    Promise.resolve() : Promise.reject()
  );
}

Now if we want to augment isUsernameNotReserved with asynchronous API call, we don't need to change anything else.

Option B - Only functions calling another functions return promises

Also, another option would be write functions in promises that call another functions. In that case, only validateUsername should be written as a promise from scratch.

Is this a good approach? What could be the drawbacks apart from performance?

Upd: ran a simple performance test and though running consequent promises is slower, it practically should not make any difference since running 100000 consequent functions takes ~200ms, while running 1000 takes ~3ms in Chrome. Fiddle here https://jsfiddle.net/igorpavlov/o7nb71np/2/


问:
Using For loop in Pandas with groupby function
unGrouped is a dataframe that looks like this:

```<code>         date        borough
969609  01/01/2014       BROOKLYN
967983  01/01/2014          BRONX
967982  01/01/2014         QUEENS
865943  01/01/2014       BROOKLYN
967981  01/01/2014      MANHATTAN
967980  01/01/2014       BROOKLYN
967979  01/01/2014         QUEENS
967984  01/01/2014          BRONX
967978  01/01/2014         QUEENS
967976  01/01/2014       BROOKLYN
967975  01/01/2014       BROOKLYN
</code>```

I have the following code:

```<code>for row in unGrouped:
if unGrouped['borough'][row]=='BRONX':
    bronxCount+=1
    print bronxCount
</code>```

And it gives me a Key Error: date.
I would like to iterate through the column borough, increment bronxCount whenever it comes across BRONX, and store that value for each row in a column called `bronxCount', to eventually get a count of crimes in the bronx for each day. If anyone could get this loop to work I would greatly appreciate it. Thanks for the help!

答:
You can sum up after filtering:

```<code>>>> (unGrouped.borough == 'BRONX').sum()
2
</code>```

To get the counts per date just group by date  and boroug before counting:

```<code>>>> unGrouped.groupby(['date', 'borough']).size()
date        borough
01/01/2014  BRONX        2
            BROOKLYN     5
            MANHATTAN    1
            QUEENS       3
dtype: int64
</code>```

or if you only want BRONXwith a date index.

```<code>>>> unGrouped.groupby(['borough', 'date']).size().loc['BRONX']
date
01/01/2014    2
dtype: int64
</code>```

Body:
unGrouped is a dataframe that looks like this:

         date        borough
969609  01/01/2014       BROOKLYN
967983  01/01/2014          BRONX
967982  01/01/2014         QUEENS
865943  01/01/2014       BROOKLYN
967981  01/01/2014      MANHATTAN
967980  01/01/2014       BROOKLYN
967979  01/01/2014         QUEENS
967984  01/01/2014          BRONX
967978  01/01/2014         QUEENS
967976  01/01/2014       BROOKLYN
967975  01/01/2014       BROOKLYN

I have the following code:

for row in unGrouped:
if unGrouped['borough'][row]=='BRONX':
    bronxCount+=1
    print bronxCount

And it gives me a Key Error: date.
I would like to iterate through the column borough, increment bronxCount whenever it comes across BRONX, and store that value for each row in a column called `bronxCount', to eventually get a count of crimes in the bronx for each day. If anyone could get this loop to work I would greatly appreciate it. Thanks for the help!

Body:
You can sum up after filtering:

>>> (unGrouped.borough == 'BRONX').sum()
2

To get the counts per date just group by date  and boroug before counting:

>>> unGrouped.groupby(['date', 'borough']).size()
date        borough
01/01/2014  BRONX        2
            BROOKLYN     5
            MANHATTAN    1
            QUEENS       3
dtype: int64

or if you only want BRONXwith a date index.

>>> unGrouped.groupby(['borough', 'date']).size().loc['BRONX']
date
01/01/2014    2
dtype: int64


问:
Multiple dispatch on multiple parametric types
In Julia, can I achieve the behavior:

```<code>f(a::String, b::Int) = false
f(b::Int, a::String) = false
f(a::Int, b::Int) = a+b
f(a::String, b::String) = "woohoo!"
</code>```

Using parametric types for the first two functions? Something like:

f(a::T, b::S) where {T!=S} = false

Or something like this.

答:
I think this is what you are looking for.  Julia will always dispatch to the least ambiguous method.</p>

```<code>f(a::T,b::S) where {T,S} = T==S
f(a::T,b::T) where {T<:Number} = a+b
f(a::T,b::T) where {T<:String} = "woohoo!"
</code>```

Body:
In Julia, can I achieve the behavior:

f(a::String, b::Int) = false
f(b::Int, a::String) = false
f(a::Int, b::Int) = a+b
f(a::String, b::String) = "woohoo!"

Using parametric types for the first two functions? Something like:

f(a::T, b::S) where {T!=S} = false

Or something like this.

Body:
I think this is what you are looking for.  Julia will always dispatch to the least ambiguous method.

f(a::T,b::S) where {T,S} = T==S
f(a::T,b::T) where {T<:Number} = a+b
f(a::T,b::T) where {T<:String} = "woohoo!"


问:
crash using ACEAutocompleteBar in swift:
I followed the instructions in Customizing QuickType Suggestions in iOS.
 I get a crash with error

setAutocompleteWithDataSource:delegate:customize:]: unrecognized
  selector sent to instance 0x7fe8c981bc00'

The relevant code is simply:

```<code>@IBOutlet weak var brand: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    . . .
    self.brand.setAutocompleteWith(self, delegate: self, customize: { inputView in
            inputView?.isHidden = false
        })
}
</code>```

I'm using Xcode 9.1, and swift 3.  I don't grok the syntax for closures when used with objective C.  Can you see my error?

Note that I added the context of the call to setAutocompleteWith. Is viewDidLoad() a good place do do the call?

答:
It looks like you didn't type the function name properly.  </p>

<p>Try this instead:  </p>

```<code>@IBOutlet weak var brand: UITextField!

self.brand.setAutocompleteWithDataSource(self, delegate: self, customize: { inputView in
            inputView?.isHidden = false
        })
</code>```

Body:
I followed the instructions in Customizing QuickType Suggestions in iOS.
 I get a crash with error

setAutocompleteWithDataSource:delegate:customize:]: unrecognized
  selector sent to instance 0x7fe8c981bc00'

The relevant code is simply:

@IBOutlet weak var brand: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    . . .
    self.brand.setAutocompleteWith(self, delegate: self, customize: { inputView in
            inputView?.isHidden = false
        })
}

I'm using Xcode 9.1, and swift 3.  I don't grok the syntax for closures when used with objective C.  Can you see my error?

Note that I added the context of the call to setAutocompleteWith. Is viewDidLoad() a good place do do the call?

Body:
It looks like you didn't type the function name properly.

Try this instead:

@IBOutlet weak var brand: UITextField!

self.brand.setAutocompleteWithDataSource(self, delegate: self, customize: { inputView in
            inputView?.isHidden = false
        })


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
Programs absolutely can be proven to be correct.  Lousy programs are hard to prove.  To do it even reasonably well, you have to evolve the program and proof hand-in-hand.

You can't automate the proof because of the halting problem.  You can, however, manually prove the post-conditions and preconditions of any arbitrary statement, or sequence of statements.

You must read Dijsktra's A Discipline of Programming.

Then, you must read Gries' The Science of Programming.

Then you'll know how to prove programs correct.

Title: Why can't programs be proven?


问:
Can CQRS be used for a site like StackOverflow?
Can you use the CQRS (Command-Query Responsibility Segregation) architectural pattern to build a site like StackOverflow?  I'm relatively new to CQRS and DDD (Domain Driven Design) and am exploring the pattern and trying to model sites that I'm familiar with to the pattern.  While I can see CQRS being useful for many aspects for a site like StackOverflow, there are a few areas that I'm not sure are possible (or, at least, I can't figure out immediately).  Specifically:

Asking questions  When I create a question, I see it
immediately and can edit it.  In
CQRS, I issue a command like
'AskQuestion' and an event is created
called 'QuestionAsked'.  Eventually,
the question gets pushed to the
denormalized data store.   But SO's
experience is immediate.  Is this
possible with CQRS?

Voting  My votes
are reflected immediately.  In CQRS,
I would imagine these commands/events
eventually moving through the event
bus to the read store.  But SO gives
me the information immediately.

My concerns are really around the concept of immediate feedback that SO provides.  Can CQRS provide this?  If so, how would this be done?  Are there good examples out there that illustrate how to handle this?

If it helps, my environment is VS2010/C#/SQL2008R2, but I'm open to other options like SQLite, etc.  I'm also looking at NCQRS and LOKAD's frameworks, along with Mark Nijhof's sample and am planning on downloading Greg Young's sample.  I didn't find much else out there for CQRS samples.

Thanks!

答:
By fake or trick, you might think of the event as a "pending event", something that is likely to succeed in the commit/publish phase, but could fail.  The more validation you perform clientside, prior to initial submit for commit, the more likely it will succeed.  So if you intend to rely on a pending commit, plan for a thicker client in terms of validation and business rule exposure.

One could then allow the user to continue to use the data (for further modification) by marking or tagging the data within the UI as relying on "pending commit".  It would be a meta attribute of the object or attribute.  Of course adding and using that meta attribute will increase the complexity, but depending on application might be a necessary use-case.

Client-side command queues/histories might be one way to help handle situations where subsequent events relied on an ultimately failed pending commit.  In other words, anything that relies on a pending commit could be part of a history that could be rolled up, saved while corrections are made to the failed pending commit, unrolled and reapplied to the changed and resubmitted pending event again, and once notification that the pending event was successful in commit, all subsequent client side history would start to unwind, submitted the next item in the queue, marking it as the now pending event.


问:
Antd: Is it possible to change the row expand icon
The default is: [+] and [-]. Could not find a way to change it to other icon. For example down and right from https://ant.design/components/icon/.

My users are very very picky.

Thanks!

答:
Found it:</p>

```<code>  .ant-table-row-expand-icon-cell {

    position: relative;

    .ant-table-row-collapsed:after {
      content : "\E61D";
      font-family: "anticon" !important;
      font-style: normal;
      vertical-align: baseline;
      text-align: center;
      text-transform: none;
      text-rendering: auto;

      right: 16px;
      top: 0;
      display: inline-block;
      transform: scale(0.66666667) rotate(0deg);
      transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      zoom: 1;
    }

    .ant-table-row-expanded:after {
      content : "\E61D";
      font-family: "anticon" !important;
      font-style: normal;
      vertical-align: baseline;
      text-align: center;
      text-transform: none;
      text-rendering: auto;

      right: 16px;
      top: 0;
      display: inline-block;
      transform: rotate(180deg) scale(0.75);
      transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      zoom: 1;
    }
</code>```

Body:
Found it:

  .ant-table-row-expand-icon-cell {

    position: relative;

    .ant-table-row-collapsed:after {
      content : "\E61D";
      font-family: "anticon" !important;
      font-style: normal;
      vertical-align: baseline;
      text-align: center;
      text-transform: none;
      text-rendering: auto;

      right: 16px;
      top: 0;
      display: inline-block;
      transform: scale(0.66666667) rotate(0deg);
      transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      zoom: 1;
    }

    .ant-table-row-expanded:after {
      content : "\E61D";
      font-family: "anticon" !important;
      font-style: normal;
      vertical-align: baseline;
      text-align: center;
      text-transform: none;
      text-rendering: auto;

      right: 16px;
      top: 0;
      display: inline-block;
      transform: rotate(180deg) scale(0.75);
      transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      zoom: 1;
    }


问:
PackageNotFoundError: Packages missing in current channels:
I cannot download packages from Anaconda cloud because of company policy with cloud downloads.  Therefore, I tried a workaround downloading the bioconda pysftp-0.2.9-py36_0.tar win64 version from Anaconda's website while not on the network and put it on my flash drive.  However, I am still getting a cannot found package error.  When I run the install code, I am in the directory that the tar file is in.

This code throws error below:

```<code>$ conda install pysftp-0.2.9-py36_0.tar

Fetching package metadata .............

PackageNotFoundError: Packages missing in current channels:

  - pysftp-0.2.9-py36_0.tar

We have searched for the packages in the following channels:

  - https://repo.continuum.io/pkgs/main/win-64
  - https://repo.continuum.io/pkgs/main/noarch
  - https://repo.continuum.io/pkgs/free/win-64
  - https://repo.continuum.io/pkgs/free/noarch
  - https://repo.continuum.io/pkgs/r/win-64
  - https://repo.continuum.io/pkgs/r/noarch
  - https://repo.continuum.io/pkgs/pro/win-64
  - https://repo.continuum.io/pkgs/pro/noarch

  Need help installing the package locally.
-->
</code>```

答:
You're looking for a slight tweak to your command:

```<code>conda install --use-local pysftp-0.2.9-py36_0.tar
</code>```

In addition, you'll need to put the downloaded file into

```<code>~/anaconda/conda-bld/<platform>
</code>```

or something similar or specify an absolute path to the file.

I have this same issue at work.  In my case, they have a few proxy servers set up that I can point the environment variables HTTP_PROXY and HTTPS_PROXY to prior to running the conda install <x> or pip install <x> in order to bypass the issue.  Do you have anything similar?

Body:
I cannot download packages from Anaconda cloud because of company policy with cloud downloads.  Therefore, I tried a workaround downloading the bioconda pysftp-0.2.9-py36_0.tar win64 version from Anaconda's website while not on the network and put it on my flash drive.  However, I am still getting a cannot found package error.  When I run the install code, I am in the directory that the tar file is in.

This code throws error below:

$ conda install pysftp-0.2.9-py36_0.tar

Fetching package metadata .............

PackageNotFoundError: Packages missing in current channels:

  - pysftp-0.2.9-py36_0.tar

We have searched for the packages in the following channels:

  - https://repo.continuum.io/pkgs/main/win-64
  - https://repo.continuum.io/pkgs/main/noarch
  - https://repo.continuum.io/pkgs/free/win-64
  - https://repo.continuum.io/pkgs/free/noarch
  - https://repo.continuum.io/pkgs/r/win-64
  - https://repo.continuum.io/pkgs/r/noarch
  - https://repo.continuum.io/pkgs/pro/win-64
  - https://repo.continuum.io/pkgs/pro/noarch

  Need help installing the package locally.
-->

Body:
You're looking for a slight tweak to your command:

conda install --use-local pysftp-0.2.9-py36_0.tar

In addition, you'll need to put the downloaded file into

~/anaconda/conda-bld/<platform>

or something similar or specify an absolute path to the file.

I have this same issue at work.  In my case, they have a few proxy servers set up that I can point the environment variables HTTP_PROXY and HTTPS_PROXY to prior to running the conda install <x> or pip install <x> in order to bypass the issue.  Do you have anything similar?


问:
Error: Cannot find module "@firebase/polyfill"
I am facing the below mentioned error on Mac:

```<code>Error: Cannot find module "@firebase/polyfill"
    at webpackMissingModule (http://localhost:8100/build/vendor.js:71203:65)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:71203:160)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:71154:71)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:109392:79)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:109376:72)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:36504:70)
</code>```

Working environment:
cli packages: (/usr/local/lib/node_modules)

```<code>@ionic/cli-utils  : 1.19.0
ionic (Ionic CLI) : 3.19.0
</code>```

global packages:

```<code>cordova (Cordova CLI) : 7.1.0
</code>```

local packages:

```<code>@ionic/app-scripts : 2.1.4
Cordova Platforms  : none
Ionic Framework    : ionic-angular 3.9.2
</code>```

System:

```<code>Node  : v8.9.1
npm   : 5.1.0
OS    : macOS Sierra
Xcode : Xcode 9.1 Build version 9B55
</code>```

Is there any solution to this problem?

答:
This error is fixed.

npm install @firebase/polyfill

Body:
I am facing the below mentioned error on Mac:

Error: Cannot find module "@firebase/polyfill"
    at webpackMissingModule (http://localhost:8100/build/vendor.js:71203:65)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:71203:160)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:71154:71)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:109392:79)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:109376:72)
    at __webpack_require__ (http://localhost:8100/build/vendor.js:55:30)
    at Object.<anonymous> (http://localhost:8100/build/vendor.js:36504:70)

Working environment:
cli packages: (/usr/local/lib/node_modules)

@ionic/cli-utils  : 1.19.0
ionic (Ionic CLI) : 3.19.0

global packages:

cordova (Cordova CLI) : 7.1.0

local packages:

@ionic/app-scripts : 2.1.4
Cordova Platforms  : none
Ionic Framework    : ionic-angular 3.9.2

System:

Node  : v8.9.1
npm   : 5.1.0
OS    : macOS Sierra
Xcode : Xcode 9.1 Build version 9B55

Is there any solution to this problem?


问:
How to use FCM sendToTopic from a cloud function using the admin SDK?
I need to break up a time consuming process into multiple cloud functions, because in total it would take more then 9mins (the max execution time). To do this I would like one (entry) cloud function, triggered by a pub/sub topic, to write messages to other topics, which in turn trigger the other pub/sub cloud functions.

I am testing these via firebase experimental:functions:shell. Triggering the entry function is not a problem, but when that functions calls admin.messaging().sendToTopic(...) I get the following error:

An error occurred when trying to authenticate to the FCM servers. Make
  sure the credential used to authenticate this SDK has the proper
  permissions. See https://firebase.google.com/docs/admin/setup for
  setup instructions.

I am not sure if this is because I'm testing it locally, but I couldn't find any easy way to send a message to a topic. The firebase console has the "notifications" section where you can easily format and send messages, but these only seem to target client apps (ios/android/web).

I can't find anything in the docs about configuring credentials for FCM use in cloud functions. I am using the standard credentials. My functions have no problem writing to my Firestore instance for example.

The docs for using FCM in the admin SDK don't seem to mention anything about this either.

答:
Firebase (Google) Cloud Messaging and Google Cloud Pub/Sub are different messaging systems, as explained here:

Both are systems to deliver messages, but Google Cloud Messaging is
  used to deliver messages to and from end-user devices, while Google
  Cloud Pub/Sub is used to communicate between servers. Google Cloud
  Messaging is designed to scale to a very large number of delivery end
  points, but has low throughput (messages per second per channel).
  Pub/Sub does not have limits on throughput and has a more generic API.

Although they share the concept of topics, a message sent to an FCM topic will not trigger a Pub/Sub Cloud Function.

You can publish a Pub/Sub message from a Cloud Function using @google-cloud/pubsub.  The documentation is here.

The two functions below demonstrate publishing and receiving a simple string message.

```<code>const pubsub = require('@google-cloud/pubsub')();

exports.testWrite = functions.database.ref('/test').onWrite(event => {
   var topic = pubsub.topic('test-topic');

  // Publish a message to the topic.
  var publisher = topic.publisher();
  var message = Buffer.from('Hello World!');

  return publisher.publish(message);
});

exports.helloPubSub = functions.pubsub.topic('test-topic').onPublish(event => {
  const buffer = Buffer.from(event.data.data, 'base64');
  console.log('message=', buffer.toString('utf8'));
  return null;
});
</code>```

Body:
Firebase (Google) Cloud Messaging and Google Cloud Pub/Sub are different messaging systems, as explained here:

Both are systems to deliver messages, but Google Cloud Messaging is
  used to deliver messages to and from end-user devices, while Google
  Cloud Pub/Sub is used to communicate between servers. Google Cloud
  Messaging is designed to scale to a very large number of delivery end
  points, but has low throughput (messages per second per channel).
  Pub/Sub does not have limits on throughput and has a more generic API.

Although they share the concept of topics, a message sent to an FCM topic will not trigger a Pub/Sub Cloud Function.

You can publish a Pub/Sub message from a Cloud Function using @google-cloud/pubsub.  The documentation is here.

The two functions below demonstrate publishing and receiving a simple string message.

const pubsub = require('@google-cloud/pubsub')();

exports.testWrite = functions.database.ref('/test').onWrite(event => {
   var topic = pubsub.topic('test-topic');

  // Publish a message to the topic.
  var publisher = topic.publisher();
  var message = Buffer.from('Hello World!');

  return publisher.publish(message);
});

exports.helloPubSub = functions.pubsub.topic('test-topic').onPublish(event => {
  const buffer = Buffer.from(event.data.data, 'base64');
  console.log('message=', buffer.toString('utf8'));
  return null;
});


问:
Operator precedence in C Definitions
Wikipedia claims that the [] operator precedes the * operator in evaluation.

Then, why does the following statement:

```<code>char *a[3];
</code>```

declare an array of 3 character pointers, rather than a pointer to an array of 3 characters as per the operator precedence?

答:
Because, as Wikipedia says, [] has higher precedence than *?

Processing the declaration, the a[3] is processed as 'array of 3' before you process the *.

To declare a pointer to an array of three characters, you have to use parentheses to override the default precedence:

```<code>char (*a)[3];
</code>```

Now the parentheses take precedence over the array.

Title: Operator precedence in C Definitions

Body:
Wikipedia claims that the [] operator precedes the * operator in evaluation.

Then, why does the following statement:

char *a[3];

declare an array of 3 character pointers, rather than a pointer to an array of 3 characters as per the operator precedence?

Body:
Because, as Wikipedia says, [] has higher precedence than *?

Processing the declaration, the a[3] is processed as 'array of 3' before you process the *.

To declare a pointer to an array of three characters, you have to use parentheses to override the default precedence:

char (*a)[3];

Now the parentheses take precedence over the array.


问:
Saving images to S3 per bucket or pure Type with Ruby gem
I am just starting to write several images to S3. I will have 4 to 10 images per case per user.

```<code>User > Case > images
</code>```

My plan is to create a bucket per case, but wondering if I should instead save all images with a prefix in the key and have all images for all cases in one bucket?

```<code>MyBucket > 2sk67o3/waiver/image1-big.jpg
MyBucket > 2sk67o3/waiver/image1-small.jpg
MyBucket > 2sk67o3/merchandise/image1-big.jpg
MyBucket > 2sk67o3/merchandise/image1-small.jpg
</code>```

OR

```<code>MyBucket_2sk67o3 > waiver/image1-big.jpg
MyBucket_2sk67o3 > waiver/image1-small.jpg
MyBucket_2sk67o3 > merchandise/image1-big.jpg
MyBucket_2sk67o3 > merchandise/image1-small.jpg
</code>```

I am thinking the last version is correct in that I can use the "with_prefix" provided by the Ruby gem to find images easier to delete or replace them? For instance, to delete the "waiver" I will, of course, want to delete both the big and small image.

```<code>bucket.objects.with_prefix('waiver').collect(&:key)
</code>```

I guess I could just do the first way, above, and search the prefix '2sk67o3/merchandise'. So the question remains better, easier, standard for a bucket per Case or one giant bucket?

答:
You should use a single bucket using predictable keys so they're easy to find. Something like</p>

```<code>"MyBucket/waivers/#{WaverModelInstanceOrWhatever.id}/large/image_1.jpg"
"MyBucket/waivers/#{WaverModelInstanceOrWhatever.id}/small/image_1.jpg"
"MyBucket/merchandise/#{MerchandiseModelInstanceOrWhatever.id}/large/image_1.jpg"
"MyBucket/merchandise/#{MerchandiseModelInstanceOrWhatever.id}/small/image_1.jpg"
</code>```

Body:
I am just starting to write several images to S3. I will have 4 to 10 images per case per user.

User > Case > images

My plan is to create a bucket per case, but wondering if I should instead save all images with a prefix in the key and have all images for all cases in one bucket?

MyBucket > 2sk67o3/waiver/image1-big.jpg
MyBucket > 2sk67o3/waiver/image1-small.jpg
MyBucket > 2sk67o3/merchandise/image1-big.jpg
MyBucket > 2sk67o3/merchandise/image1-small.jpg

OR

MyBucket_2sk67o3 > waiver/image1-big.jpg
MyBucket_2sk67o3 > waiver/image1-small.jpg
MyBucket_2sk67o3 > merchandise/image1-big.jpg
MyBucket_2sk67o3 > merchandise/image1-small.jpg

I am thinking the last version is correct in that I can use the "with_prefix" provided by the Ruby gem to find images easier to delete or replace them? For instance, to delete the "waiver" I will, of course, want to delete both the big and small image.

bucket.objects.with_prefix('waiver').collect(&:key)

I guess I could just do the first way, above, and search the prefix '2sk67o3/merchandise'. So the question remains better, easier, standard for a bucket per Case or one giant bucket?

Body:
You should use a single bucket using predictable keys so they're easy to find. Something like

"MyBucket/waivers/#{WaverModelInstanceOrWhatever.id}/large/image_1.jpg"
"MyBucket/waivers/#{WaverModelInstanceOrWhatever.id}/small/image_1.jpg"
"MyBucket/merchandise/#{MerchandiseModelInstanceOrWhatever.id}/large/image_1.jpg"
"MyBucket/merchandise/#{MerchandiseModelInstanceOrWhatever.id}/small/image_1.jpg"


问:
Is there a way to get an alert when the azure cloud service is unresponsive or busy?
Is there a way to get an alert when the cloud service is Unresponsive or Busy? I've only seen options on how to create an alert about metrics but not really on status. </p>

<p>Thanks </p>

答:
As per my knowledge, Azure do not provide such alerts and you need to manually troubleshoot Cloud Services roles that fail to start.

You may leave your feedback here:

https://feedback.azure.com/forums/169386-cloud-services-web-and-worker-role

All of the feedback you share in these forums will be monitored and reviewed by the Microsoft engineering teams responsible for building Azure.

Alternatively, if you're open to using the third party services, such as AzureWatch. It can alert your instance becomes Unresponsive or busy.

CloudMonix tracks and visualizes key performance indicators for Cloud Services, and sends automatic notifications whenever issues arise or individual instances are unavailable. Additionally, it provides highly sophisticated automation platform that allows to add or remove Cloud Role instances according to the demand or reboot existing instances on a daily schedule or after crash.

Body:
Is there a way to get an alert when the cloud service is Unresponsive or Busy? I've only seen options on how to create an alert about metrics but not really on status.

Thanks