问:
How to update an observable array inside a component from the main ViewModel?
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}</code>```

<!DOCTYPE html>

 -

```
  </body>
</html></code>```

答:
Inspired by implementation of pauseableComputed and observable withPausing I have created pauseableObservable and pauseableObservableArray that have abilities to stop notifications to subscribers and than resume when needed. Also it work recursively for all nested pauseable properties.

You can play with it HERE on Codepen (was provided example base on code from your question).
Also I place code of extensions that reaching the goal:

PauseableObservable:

```<code>// PauseableObservable - it's observable that have functions to 'pause' and 'resume' notifications to subscribers (pause/resume work recursive for all pauseable child).

ko.isPauseableObservable = function(instance) {
    return ko.isObservable(instance) && instance.hasOwnProperty("pause");
}

ko.pauseableObservable = function(value) {
    var that = ko.observable(value);

    function getPauseableChildren() {
        var properties = Object.getOwnPropertyNames(that());
        var currentValue = that();
        var pauseables = properties.filter((property) => {
            return ko.isPauseableObservable(currentValue[property]);
        });
        return pauseables.map((property) => {
            return currentValue[property];
        });
    }

    that.pauseNotifications = false;
    that.isDirty = false;

    that.notifySubscribers = function() {
        if (!that.pauseNotifications) {
            ko.subscribable.fn.notifySubscribers.apply(that, arguments);
            that.isDirty = false;
        } else {
            that.isDirty = true;
        }
    };

    that.pause = function() {
        that.pauseNotifications = true;
        var pauseableChildren = getPauseableChildren();
        pauseableChildren.forEach((child) => { child.pause(); });
    }

    that.resume = function() {
        that.pauseNotifications = false;

        if (that.isDirty) {
            that.valueHasMutated();
        }

        var pauseableChildren = getPauseableChildren();
        pauseableChildren.forEach((child)=> { child.resume(); });
    }

    return that;
}
</code>```

PauseableObservableArray

```<code>// PauseableObservableArray - simply use pauseable functionality of his items.
// Extension for stop notifications about added/removed items is out of scope.
ko.pauseableObservableArray = function(items) {
    var that = ko.observableArray(items);

    that.pause = function () {
        var items = that();
        items.forEach(function(item) {
            if(ko.isPauseableObservable(item)) {
                item.pause();
            }
        });
    }

    that.resume = function () {
        var items = that();
        items.forEach(function(item) {
            if(ko.isPauseableObservable(item)) {
                item.resume();
            }
        });
    }

    that.refresh = function () {
        that.resume();
        that.pause();
    }

    return that;
}
</code>```

Usage example:

```<code>var firstItem = ko.pauseableObservable("Hello");
var secondItem = ko.pauseableObservable("World");
var items = [
    firstItem,
    secondItem
];
var array = ko.pauseableObservable(items);

// Stop notifications from specific observable
firstItem.pause();
// Change won't raise notification to subscribers
firstItem("Hi");
// Resume notifications
firstItem.resume();

// Stop notifications from all items of array
array.pause();
// Change won't raise notification to subscribers
array()[0]("Hi");
// Resume notifications
array.resume();
</code>```

I know that implementation isn't perfect and I haven't time to test it well, however I hope that it will help you to find inspiration and improve it.

Body:
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);

pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}

<!DOCTYPE html>

 -

Body:
Inspired by implementation of pauseableComputed and observable withPausing I have created pauseableObservable and pauseableObservableArray that have abilities to stop notifications to subscribers and than resume when needed. Also it work recursively for all nested pauseable properties.

You can play with it HERE on Codepen (was provided example base on code from your question).
Also I place code of extensions that reaching the goal:

PauseableObservable:

// PauseableObservable - it's observable that have functions to 'pause' and 'resume' notifications to subscribers (pause/resume work recursive for all pauseable child).

ko.isPauseableObservable = function(instance) {
    return ko.isObservable(instance) && instance.hasOwnProperty("pause");
}

ko.pauseableObservable = function(value) {
    var that = ko.observable(value);

    function getPauseableChildren() {
        var properties = Object.getOwnPropertyNames(that());
        var currentValue = that();
        var pauseables = properties.filter((property) => {
            return ko.isPauseableObservable(currentValue[property]);
        });
        return pauseables.map((property) => {
            return currentValue[property];
        });
    }

    that.pauseNotifications = false;
    that.isDirty = false;

    that.notifySubscribers = function() {
        if (!that.pauseNotifications) {
            ko.subscribable.fn.notifySubscribers.apply(that, arguments);
            that.isDirty = false;
        } else {
            that.isDirty = true;
        }
    };

    that.pause = function() {
        that.pauseNotifications = true;
        var pauseableChildren = getPauseableChildren();
        pauseableChildren.forEach((child) => { child.pause(); });
    }

    that.resume = function() {
        that.pauseNotifications = false;

        if (that.isDirty) {
            that.valueHasMutated();
        }

        var pauseableChildren = getPauseableChildren();
        pauseableChildren.forEach((child)=> { child.resume(); });
    }

    return that;
}

PauseableObservableArray

// PauseableObservableArray - simply use pauseable functionality of his items.
// Extension for stop notifications about added/removed items is out of scope.
ko.pauseableObservableArray = function(items) {
    var that = ko.observableArray(items);

    that.pause = function () {
        var items = that();
        items.forEach(function(item) {
            if(ko.isPauseableObservable(item)) {
                item.pause();
            }
        });
    }

    that.resume = function () {
        var items = that();
        items.forEach(function(item) {
            if(ko.isPauseableObservable(item)) {
                item.resume();
            }
        });
    }

    that.refresh = function () {
        that.resume();
        that.pause();
    }

    return that;
}

Usage example:

var firstItem = ko.pauseableObservable("Hello");
var secondItem = ko.pauseableObservable("World");
var items = [
    firstItem,
    secondItem
];
var array = ko.pauseableObservable(items);

// Stop notifications from specific observable
firstItem.pause();
// Change won't raise notification to subscribers
firstItem("Hi");
// Resume notifications
firstItem.resume();

// Stop notifications from all items of array
array.pause();
// Change won't raise notification to subscribers
array()[0]("Hi");
// Resume notifications
array.resume();

I know that implementation isn't perfect and I haven't time to test it well, however I hope that it will help you to find inspiration and improve it.


来源: stackexchange

问:
Angular2 Final release Http Post not working in MVC
I am not able to call a MVC APIController from the Angular Service. Can anybody help. Thank you.

My Route.Config is as shown below.I am allowing all routes.

```<code>public class RouteConfig
  {
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{*anything}",     //"{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
</code>```

When i am calling the post from the Application its not working not throwing any error also.

Code from forms.service.ts file

```<code>    createForm(post: myForm) {

    console.log('Actual object: ' + JSON.stringify(post));
    console.log(JSON.stringify(post));
    return this._http.post(this._posturl, JSON.stringify(post)).map(response => response.json());
    }
</code>```

Code from API Controller

```<code>  public class MinPostController : ApiController
{
   public MinPostController()
    {

    }

    [System.Web.Http.HttpPost]
    public ActionResult CreateForm([FromBody] PostFormModel input)
    {
         //Check if the post is hitting.
         bool status = false;
    }

}
</code>```

When i post the Json using the Fiddler it works fine as shown below.Please find the images below.

答:
This is the answer. I have to create a observable and then subscribe it.

https://stackoverflow.com/a/34948742/6707243

ContentLicense: CC BY-SA 3.0

Body:
I am not able to call a MVC APIController from the Angular Service. Can anybody help. Thank you.

My Route.Config is as shown below.I am allowing all routes.

public class RouteConfig
  {
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{*anything}",     //"{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

When i am calling the post from the Application its not working not throwing any error also.

Code from forms.service.ts file

    createForm(post: myForm) {

    console.log('Actual object: ' + JSON.stringify(post));
    console.log(JSON.stringify(post));
    return this._http.post(this._posturl, JSON.stringify(post)).map(response => response.json());
    }

Code from API Controller

  public class MinPostController : ApiController
{
   public MinPostController()
    {

    }

    [System.Web.Http.HttpPost]
    public ActionResult CreateForm([FromBody] PostFormModel input)
    {
         //Check if the post is hitting.
         bool status = false;
    }

}

When i post the Json using the Fiddler it works fine as shown below.Please find the images below.


问:
Missing entities after insertion in Google Cloud DataStore
After inserting 29447 entities of a single kind in Google Cloud DataStore I wait about 30 seconds and go and check how many entities are there for that particular kind. The surprising thing is that I notice some of them missing (getCurrentKeys returns a bit less than 29447 entities). When I check after a longer period of time (~1 hour), I can then see that all of the entities are there (getCurrentKeys returns the expected 29447 entities).

The code used to read the number of entities is the following:

```<code>const runQuery = (query) => {
  return new Promise((resolve, reject) => {
    datastore.runQuery(query)
      .then(results => {
        const entities = results[0];
        resolve(entities);
      })
      .catch(e => reject(e));
  });
};

const getCurrentKeys = () => {
  const query = datastore.createQuery(KIND)
    .select('__key__');
  return runQuery(query);
};

async function main() {
  const currentKeys = await getCurrentKeys();
  console.log(`currentKeys: ${currentKeys.length}`);
}

main();
</code>```

Any ideas of what could be happening?

Thanks in advance

答:
Non ancestor queries are eventually consistent.  It will take a while before all the rows will show up.

This article should explain more:

https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore/

Body:
After inserting 29447 entities of a single kind in Google Cloud DataStore I wait about 30 seconds and go and check how many entities are there for that particular kind. The surprising thing is that I notice some of them missing (getCurrentKeys returns a bit less than 29447 entities). When I check after a longer period of time (~1 hour), I can then see that all of the entities are there (getCurrentKeys returns the expected 29447 entities).

The code used to read the number of entities is the following:

const runQuery = (query) => {
  return new Promise((resolve, reject) => {
    datastore.runQuery(query)
      .then(results => {
        const entities = results[0];
        resolve(entities);
      })
      .catch(e => reject(e));
  });
};

const getCurrentKeys = () => {
  const query = datastore.createQuery(KIND)
    .select('__key__');
  return runQuery(query);
};

async function main() {
  const currentKeys = await getCurrentKeys();
  console.log(`currentKeys: ${currentKeys.length}`);
}

main();

Any ideas of what could be happening?

Thanks in advance


问:
GetComponent returning "null" instead of null
I'm confused about the return value of GetComponent if the requested component is not attached to the object.  According to the Unity documentation, GetComponent should return null.  However, what appears to be happening is that GetComponent is returning a "null" object of the requested type, rather than the value null.

In this example, my game object does not have a CircleCollider2D attached to it.  When I set a breakpoint on the line CircleCollider2D x = GetComponent<CircleCollider2D>();, I get this result

Why is the returned value not null?

EDIT:

Here's a full screenshot of the code and the values in the debugger.

ANOTHER EDIT:

Could it be that Unity has overloaded the == operator so that GetComponent always returns a object, but the object can have an internal "null" state which returns true when compared to null?  I can see the following declarations in the UnityEngine namespace

```<code>public static bool operator ==(Object x, Object y);
public static bool operator !=(Object x, Object y);
</code>```

答:
It seems like GetComponent<T>() doesnt return TRUE null. Instead it returns new T with default values that fires MissingComponentException when using any null field. GetInstanceID() and GetHashCode() work because they only use int m_InstanceID which is set to default 0. Not sure how ToString() works but it probably returns "null" when m_InstanceID == 0.

Proof:

```<code>void Start()
    {
        CircleCollider2D getComponent = GetComponent<CircleCollider2D>();
        CircleCollider2D empty = null;
        CircleCollider2D newCC = new CircleCollider2D();
        Debug.LogFormat("getComponent.GetInstanceID() {0}", getComponent.GetInstanceID());
        Debug.LogFormat("newCC.GetInstanceID() {0}", newCC.GetInstanceID());
        try
        {
            Debug.LogFormat("empty.GetInstanceID() {0}", empty.GetInstanceID());
        }
        catch (System.NullReferenceException e)
        {
            Debug.Log("empty.GetInstanceID() doesnt work, im true null");
        }
        try
        {
            string t = getComponent.name;
        }
        catch (System.Exception e)
        {
            Debug.Log(string.Format("getComponent fires {0} when any field is null",
                e.ToString()));
        }
        try
        {
            string t = newCC.name;
        }
        catch (System.Exception e)
        {
            Debug.Log(string.Format("newCC fires {0} when any field is null",
                e.ToString()));
        }
    }
</code>```

Results:

```<code>getComponent.GetInstanceID() 0
newCC.GetInstanceID() 0
empty.GetInstanceID() doesnt work, im true null
getComponent fires UnityEngine.MissingComponentException
newCC fires System.NullReferenceException
</code>```

Also:

```<code>getComponent.GetHashCode() = 0
getComponent.ToString() = "null"
</code>```

Why getComponent == null is true? Usually it's just:

```<code>`getComponent.GetInstanceID() == otherComponent.GetInstanceID()`
</code>```

In o == null case it's:

```<code>return !(
o.GetCachedPtr() != IntPtr.Zero || (!(o is MonoBehaviour) &&
!(o is ScriptableObject) &&
Object.DoesObjectWithInstanceIDExist(o.GetInstanceID())));
</code>```

So i guess object with InstanceID = 0 never exists.
Search for decompiled UnityEngine/UnityEngine/Object.cs if u want to know more.

Body:
I'm confused about the return value of GetComponent if the requested component is not attached to the object.  According to the Unity documentation, GetComponent should return null.  However, what appears to be happening is that GetComponent is returning a "null" object of the requested type, rather than the value null.

In this example, my game object does not have a CircleCollider2D attached to it.  When I set a breakpoint on the line CircleCollider2D x = GetComponent<CircleCollider2D>();, I get this result

Why is the returned value not null?

EDIT:

Here's a full screenshot of the code and the values in the debugger.

ANOTHER EDIT:

Could it be that Unity has overloaded the == operator so that GetComponent always returns a object, but the object can have an internal "null" state which returns true when compared to null?  I can see the following declarations in the UnityEngine namespace

public static bool operator ==(Object x, Object y);
public static bool operator !=(Object x, Object y);

Body:
It seems like GetComponent<T>() doesnt return TRUE null. Instead it returns new T with default values that fires MissingComponentException when using any null field. GetInstanceID() and GetHashCode() work because they only use int m_InstanceID which is set to default 0. Not sure how ToString() works but it probably returns "null" when m_InstanceID == 0.

Proof:

void Start()
    {
        CircleCollider2D getComponent = GetComponent<CircleCollider2D>();
        CircleCollider2D empty = null;
        CircleCollider2D newCC = new CircleCollider2D();
        Debug.LogFormat("getComponent.GetInstanceID() {0}", getComponent.GetInstanceID());
        Debug.LogFormat("newCC.GetInstanceID() {0}", newCC.GetInstanceID());
        try
        {
            Debug.LogFormat("empty.GetInstanceID() {0}", empty.GetInstanceID());
        }
        catch (System.NullReferenceException e)
        {
            Debug.Log("empty.GetInstanceID() doesnt work, im true null");
        }
        try
        {
            string t = getComponent.name;
        }
        catch (System.Exception e)
        {
            Debug.Log(string.Format("getComponent fires {0} when any field is null",
                e.ToString()));
        }
        try
        {
            string t = newCC.name;
        }
        catch (System.Exception e)
        {
            Debug.Log(string.Format("newCC fires {0} when any field is null",
                e.ToString()));
        }
    }

Results:

getComponent.GetInstanceID() 0
newCC.GetInstanceID() 0
empty.GetInstanceID() doesnt work, im true null
getComponent fires UnityEngine.MissingComponentException
newCC fires System.NullReferenceException

Also:

getComponent.GetHashCode() = 0
getComponent.ToString() = "null"

Why getComponent == null is true? Usually it's just:

`getComponent.GetInstanceID() == otherComponent.GetInstanceID()`

In o == null case it's:

return !(
o.GetCachedPtr() != IntPtr.Zero || (!(o is MonoBehaviour) &&
!(o is ScriptableObject) &&
Object.DoesObjectWithInstanceIDExist(o.GetInstanceID())));

So i guess object with InstanceID = 0 never exists.
Search for decompiled UnityEngine/UnityEngine/Object.cs if u want to know more.


问:
NAs are not allowed in subscripted assignments: error in predicting probability
I am getting the following error when using the predict on a model that predicts probability of choosing a set of binary mutually exclusive outcomes.  Using the multinom function of the nnet package.

Error in predict.multinom(model_name, df.predict, "probs") :
  NAs are not allowed in subscripted assignments In addition: Warning
  message: 'newdata' had 5 rows but variables found have 100 rows

Here is a reproducible example:

```<code>require(nnet)

response1 <- sample(runif(100))
response2 <- 1-response1
responses <- as.matrix(data.frame(response1 = response1, response2 = response2))

train <- data.matrix(data.frame(var1 = runif(100), var2 = runif(100)))

multinom.mod <- multinom(responses ~ train)

test.df <- data.frame(var1 = runif(5), var2 = runif(5))
predict.vec <- predict(multinom.mod, test.df)
</code>```

As you can see, the problem is that my response consists of 2 variables.  It appears than when I predict on a smaller number of rows than in the training set, the function tried to join the response variables from the training set with the test set.

UPDATE:

The following works with a new predict set. However, the response variables are being treated as categorical variables and so the prediction is incorrect:

```<code>require(nnet)

train <- data.frame(response1 = sample(runif(100)), response2 = 1-response1, var1 = runif(100), var2 = runif(100))

multinom.mod <- multinom(response1 + response2 ~ ., train, type = "probs")

test.df <- data.frame(var1 = runif(5), var2 = runif(5))

predict.vec <- predict(multinom.mod, test.df)
</code>```

答:
If you would like to predict the probability of each category of response, you should use:

```<code>predict.vec <- predict(multinom.mod, test.df, type = "probs")
</code>```

otherwise, the prediction is on class by default, type = class.

Update, a complete usage (training and predicting) should look like this:

```<code>require(nnet)

response1 <- sample(runif(100))
response2 <- 1 - response1

train <- data.frame(var1 = runif(100), var2 = runif(100))
# train with matrix
responses <- cbind(response1, response2)
multinom.mod <- multinom(responses ~ var1 + var2, train, type = "probs")
# train with category
train$response <- ifelse(response1 > response2, "response1", "response2")
multinom.mod1 <- multinom(response ~ var1 + var2, train)

test.df <- data.frame(var1 = runif(5), var2 = runif(5))
# no matter which training method you use,
# you can predict class (default) or probability
predict.cvec <- predict(multinom.mod, test.df, type = "class")
predict.pvec <- predict(multinom.mod, test.df, type = "probs")

predict.cvec1 <- predict(multinom.mod1, test.df, type = "class")
predict.pvec1 <- predict(multinom.mod1, test.df, type = "probs")
</code>```

Body:
I am getting the following error when using the predict on a model that predicts probability of choosing a set of binary mutually exclusive outcomes.  Using the multinom function of the nnet package.

Error in predict.multinom(model_name, df.predict, "probs") :
  NAs are not allowed in subscripted assignments In addition: Warning
  message: 'newdata' had 5 rows but variables found have 100 rows

Here is a reproducible example:

require(nnet)

response1 <- sample(runif(100))
response2 <- 1-response1
responses <- as.matrix(data.frame(response1 = response1, response2 = response2))

train <- data.matrix(data.frame(var1 = runif(100), var2 = runif(100)))

multinom.mod <- multinom(responses ~ train)

test.df <- data.frame(var1 = runif(5), var2 = runif(5))
predict.vec <- predict(multinom.mod, test.df)

As you can see, the problem is that my response consists of 2 variables.  It appears than when I predict on a smaller number of rows than in the training set, the function tried to join the response variables from the training set with the test set.

UPDATE:

The following works with a new predict set. However, the response variables are being treated as categorical variables and so the prediction is incorrect:

require(nnet)

train <- data.frame(response1 = sample(runif(100)), response2 = 1-response1, var1 = runif(100), var2 = runif(100))

multinom.mod <- multinom(response1 + response2 ~ ., train, type = "probs")

test.df <- data.frame(var1 = runif(5), var2 = runif(5))

predict.vec <- predict(multinom.mod, test.df)

Body:
If you would like to predict the probability of each category of response, you should use:

predict.vec <- predict(multinom.mod, test.df, type = "probs")

otherwise, the prediction is on class by default, type = class.

Update, a complete usage (training and predicting) should look like this:

require(nnet)

response1 <- sample(runif(100))
response2 <- 1 - response1

train <- data.frame(var1 = runif(100), var2 = runif(100))
# train with matrix
responses <- cbind(response1, response2)
multinom.mod <- multinom(responses ~ var1 + var2, train, type = "probs")
# train with category
train$response <- ifelse(response1 > response2, "response1", "response2")
multinom.mod1 <- multinom(response ~ var1 + var2, train)

test.df <- data.frame(var1 = runif(5), var2 = runif(5))
# no matter which training method you use,
# you can predict class (default) or probability
predict.cvec <- predict(multinom.mod, test.df, type = "class")
predict.pvec <- predict(multinom.mod, test.df, type = "probs")

predict.cvec1 <- predict(multinom.mod1, test.df, type = "class")
predict.pvec1 <- predict(multinom.mod1, test.df, type = "probs")


问:
Problems executing selenium on ubuntu server
I am trying to execute Selenium on Ubuntu Server but I have always problem with driver version. I don't know more options to check it so I am here to try to solve this.

First the environment:

Maven : Apache Maven 3.3.9

  Java : 1.8

  Chrome : Google Chrome 59.0.3071.115

  Chrome driver :  ChromeDriver 2.30.477691

When I try to execute mvn clean test, it returns this ERROR:

Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'

  System info: host: 'ubuntu-2gb-lon1-01', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-81-generic', java.version: '1.8.0_131'

  Driver info: driver.version: ChromeDriver

The simple java code is this:

```<code>System.setProperty("webdriver.chrome.driver", "chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://google.es");
driver.quit();
</code>```

Could anyone help to me to install a Chrome driver version to solve this?

I think that I am not doing this correctly.

Regards!

答:
System.setProperty("webdriver.chrome.driver", "Driver Path");

Here you have to pass the path where your driver is located in your disk.

Body:
I am trying to execute Selenium on Ubuntu Server but I have always problem with driver version. I don't know more options to check it so I am here to try to solve this.

First the environment:

Maven : Apache Maven 3.3.9

  Java : 1.8

  Chrome : Google Chrome 59.0.3071.115

  Chrome driver :  ChromeDriver 2.30.477691

When I try to execute mvn clean test, it returns this ERROR:

Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'

  System info: host: 'ubuntu-2gb-lon1-01', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-81-generic', java.version: '1.8.0_131'

  Driver info: driver.version: ChromeDriver

The simple java code is this:

System.setProperty("webdriver.chrome.driver", "chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://google.es");
driver.quit();

Could anyone help to me to install a Chrome driver version to solve this?

I think that I am not doing this correctly.

Regards!


问:
What is the actual MSMQ address used by the respective WCF binding?
This question is related to this one.

Given that WCF binding uses net.msmq:// URL, for instance net.msmq://server/private/nc_queue, how can one know what is the actual MSMQ address to which this URL is translated? Is there some kind of a trace that can be activated? Or an external tool that would help one capture the address?

Thanks.

EDIT1

OK, I owe a clarification. One can talk directly to MSMQ through the respective .NET API. In the case of MSMQ over its native port 1801, I would use this MSMQ address:

```<code>FormatName:Direct=OS:server\private$\nc_queue
</code>```

When MSMQ is configured over HTTP, the address changes to something like this:

```<code>FormatName:Direct=http://server/msmq/nc_queue
</code>```

But the WCF binding uses a standard URL to describe the address, like:

```<code>net.msmq://server/private/nc_queue
</code>```

So, how can I know what is the actual MSMQ address (the one with the FormatName) to which the net.msmq:// is translated?

答:
I don't really understand your question.... if you use the WCF netMsmqBinding, you're basically dropping off MSMQ messages into an MSMQ queue. So what you really have is a queue name that you're dealing with - not a URL.....

```<code>net.msmq://server/private/nc_queue
</code>```

This translates into a MSMQ private queue called nc_queue on server - so what is it really that you're trying to do?? I'm not getting it..... care to clarify??

In the meantime, check out Tom Hollander's three-part blog post series on MSMQ, WCF and IIS:

MSMQ, WCF and IIS: Getting them to play nice (part 1 of 3)

MSMQ, WCF and IIS: Getting them to play nice (part 2 of 3)

MSMQ, WCF and IIS: Getting them to play nice (part 3 of 3)

Update: I think I'm beginning to understand your issues - if you're using the WCF netMsmqBinding, you're connecting to MSMQ directly - this is not "MSMQ-over-HTTP". If you want to set up and use MSMQ-over-HTTP from a WCF client, from what I understand, you'd be talking to a straight regular HTTP service, so you'd have to use basicHttpBinding (or wsHttpBinding) - not the specific netMsmqBinding.

ContentLicense: CC BY-SA 2.5

Body:
This question is related to this one.

Given that WCF binding uses net.msmq:// URL, for instance net.msmq://server/private/nc_queue, how can one know what is the actual MSMQ address to which this URL is translated? Is there some kind of a trace that can be activated? Or an external tool that would help one capture the address?

Thanks.

EDIT1

OK, I owe a clarification. One can talk directly to MSMQ through the respective .NET API. In the case of MSMQ over its native port 1801, I would use this MSMQ address:

FormatName:Direct=OS:server\private$\nc_queue

When MSMQ is configured over HTTP, the address changes to something like this:

FormatName:Direct=http://server/msmq/nc_queue

But the WCF binding uses a standard URL to describe the address, like:

net.msmq://server/private/nc_queue

So, how can I know what is the actual MSMQ address (the one with the FormatName) to which the net.msmq:// is translated?

Body:
I don't really understand your question.... if you use the WCF netMsmqBinding, you're basically dropping off MSMQ messages into an MSMQ queue. So what you really have is a queue name that you're dealing with - not a URL.....

net.msmq://server/private/nc_queue

This translates into a MSMQ private queue called nc_queue on server - so what is it really that you're trying to do?? I'm not getting it..... care to clarify??

In the meantime, check out Tom Hollander's three-part blog post series on MSMQ, WCF and IIS:

MSMQ, WCF and IIS: Getting them to play nice (part 1 of 3)

MSMQ, WCF and IIS: Getting them to play nice (part 2 of 3)

MSMQ, WCF and IIS: Getting them to play nice (part 3 of 3)

Update: I think I'm beginning to understand your issues - if you're using the WCF netMsmqBinding, you're connecting to MSMQ directly - this is not "MSMQ-over-HTTP". If you want to set up and use MSMQ-over-HTTP from a WCF client, from what I understand, you'd be talking to a straight regular HTTP service, so you'd have to use basicHttpBinding (or wsHttpBinding) - not the specific netMsmqBinding.


问:
Implementing a function similar to EXCEL Lookup in VB.net
I have a lot of code that requires random numbers to be generated and then options selected based on percentage.  I have it working without issue by simply using an implementation of the Mersenne Twister and generating a double between 0 and 100, then assigning results by percentage with select case.  It works fine, but it's very cumbersome and truth be told, I'm tired of continuously writing this out everytime.

I'd much prefer something similar to EXCEL's Lookup Function where you give two arrays such as LOOKUP(5, {1,10,20,30,40}, {"1-10", "11-20", "21-30","31-40"})

Which in this case would return: "1-10" since 5 is between 1-10.

Is there an easy way to implement a C#/VB.Net version of this using LINQ?  I'm sure there must be but I'm at a loss for how to implement something like this.  It would be far easier to write this one line of code than long select case statements.

If there is a better way than implementing an equivalent of an EXCEL lookup function, I'd love to know that as well...

答:
I am assuming your are doing the second form of lookup, as the first would throw an error if the first argument doesn't exactly match an element in the array passed in the second argument.

This should work:

```<code>Public Function LookUp(Of T)(ByVal value As IComparable, ByVal Values() As IComparable, ByVal Result() As T) As Object
    If Values Is Nothing Then Throw New ArgumentException("Values cannot be nothing")
    If Values.Length = 0 Then Throw New ArgumentException("Values can not be empty")
    If Result Is Nothing Then Throw New ArgumentException("Result cannot be nothing")
    If Values.Length = 0 Then Throw New ArgumentException("Result can not be empty")
    If Values.Length <> Result.Length Then Throw New ArgumentException("Values and Result must have the same length")
    Dim i As Integer = 0
    While i < Values.Length AndAlso value.CompareTo(Values(i)) < 0
        i += 1
    End While
    if i = Values.Length Then i-=1
    Return Result(i)
End Function
</code>```

Usage:

```<code>Dim Result as string = LOOKUP(5, {1,10,20,30,40}, {"1-10", "11-20", "21-30","31-40"})
</code>```

Body:
I am assuming your are doing the second form of lookup, as the first would throw an error if the first argument doesn't exactly match an element in the array passed in the second argument.

This should work:

Public Function LookUp(Of T)(ByVal value As IComparable, ByVal Values() As IComparable, ByVal Result() As T) As Object
    If Values Is Nothing Then Throw New ArgumentException("Values cannot be nothing")
    If Values.Length = 0 Then Throw New ArgumentException("Values can not be empty")
    If Result Is Nothing Then Throw New ArgumentException("Result cannot be nothing")
    If Values.Length = 0 Then Throw New ArgumentException("Result can not be empty")
    If Values.Length <> Result.Length Then Throw New ArgumentException("Values and Result must have the same length")
    Dim i As Integer = 0
    While i < Values.Length AndAlso value.CompareTo(Values(i)) < 0
        i += 1
    End While
    if i = Values.Length Then i-=1
    Return Result(i)
End Function

Usage:

Dim Result as string = LOOKUP(5, {1,10,20,30,40}, {"1-10", "11-20", "21-30","31-40"})


问:
Change Angular 2/4 Material default styles for "md-menu"
I'm trying to change default Angular Material styles of md-menu. The problem is the Angular Material generates elements dynamically and I can't get access to them from my HTML.

Here is my DOM:

And here is my component HTML (md-menu generates that DOM):

```<code><md-toolbar color="primary">
  <h1>Logo</h1>
  <span class="spacer"></span>
  <img src="../../../images/avatar-default.png" class="avatar" [mdMenuTriggerFor]="userMenu" />

  <md-menu #userMenu="mdMenu">
    <button md-menu-item>{{username}}</button>
    <button md-menu-item>Log Out</button>
  </md-menu>
</md-toolbar>
</code>```

I know that I can get access to that div (selected on the picture) from global styles using .mat-menu-content {...}, but it will affect other elements with such classes. And I'm unable to set styles to this div from component CSS, because the element is outside component scope. So I'm trying to find the way to change styles of this element from component CSS and without affecting other elements with such style.

If there is a way to implement it, please, let me know.

答:
Check if using /deep/ is an option for you.

Component styles normally apply only to the HTML in the component's
  own template.

Use the /deep/ selector to force a style down through the child
  component tree into all the child component views. The /deep/ selector
  works to any depth of nested components, and it applies to both the
  view children and content children of the component.

Doc

component.css:

```<code>/deep/ .mat-menu-content {
    background: skyblue !important;
    border-top: solid 1px black;
    border-bottom: solid 1px black;
}

/deep/ .mat-menu-item {
    padding: 0 0 0 0 !important;
}
</code>```

demo

Body:
I'm trying to change default Angular Material styles of md-menu. The problem is the Angular Material generates elements dynamically and I can't get access to them from my HTML.

Here is my DOM:

And here is my component HTML (md-menu generates that DOM):

<md-toolbar color="primary">

Logo

  <md-menu #userMenu="mdMenu">
    <button md-menu-item>{{username}}</button>
    <button md-menu-item>Log Out</button>
  </md-menu>
</md-toolbar>

I know that I can get access to that div (selected on the picture) from global styles using .mat-menu-content {...}, but it will affect other elements with such classes. And I'm unable to set styles to this div from component CSS, because the element is outside component scope. So I'm trying to find the way to change styles of this element from component CSS and without affecting other elements with such style.

If there is a way to implement it, please, let me know.

Body:
Check if using /deep/ is an option for you.

Component styles normally apply only to the HTML in the component's
  own template.

Use the /deep/ selector to force a style down through the child
  component tree into all the child component views. The /deep/ selector
  works to any depth of nested components, and it applies to both the
  view children and content children of the component.

Doc

component.css:

/deep/ .mat-menu-content {
    background: skyblue !important;
    border-top: solid 1px black;
    border-bottom: solid 1px black;
}

/deep/ .mat-menu-item {
    padding: 0 0 0 0 !important;
}

demo


问:
docker: gitlab + traefik & port 22
I need to set up Gitlb behind Traefik.

Everything works except authentication to the app via command line - I don't know how to expose port 22 via traefik.

Any idea how to set it up? How to expose port 22 of a docker container (via traefik)?

I changed the default port from 22 to 10022.

I'm getting via netstat -tulpn

```<code>Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1132/sshd
tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      1126/systemd-resolv
tcp6       0      0 :::22                   :::*                    LISTEN      1132/sshd
tcp6       0      0 :::443                  :::*                    LISTEN      1590/docker-proxy
tcp6       0      0 :::10022                :::*                    LISTEN      1440/docker-proxy
tcp6       0      0 :::5355                 :::*                    LISTEN      1126/systemd-resolv
tcp6       0      0 :::80                   :::*                    LISTEN      1602/docker-proxy
tcp6       0      0 :::8080                 :::*                    LISTEN      1578/docker-proxy
udp        0      0 127.0.0.53:53           0.0.0.0:*                           1126/systemd-resolv
udp        0      0 0.0.0.0:68              0.0.0.0:*                           864/dhclient
udp        0      0 0.0.0.0:5355            0.0.0.0:*                           1126/systemd-resolv
udp6       0      0 :::5355                 :::*                                1126/systemd-resolv
</code>```

I don't understand why 10022 is connected to docker-proxy.

When I try:

```<code>git push --set-upstream origin master
ssh: connect to host git.myserver.com port 10022: Connection refused
fatal: Could not read from remote repository.
</code>```

Thank you very much

答: Traefik is an HTTP reverse proxy, and ssh is not an HTTP protocol. So you'll need to simply publish the container's ssh port on an unused port on the host.</p>

Title: docker: gitlab + traefik & port 22

Body:
I need to set up Gitlb behind Traefik.

Everything works except authentication to the app via command line - I don't know how to expose port 22 via traefik.

Any idea how to set it up? How to expose port 22 of a docker container (via traefik)?

I changed the default port from 22 to 10022.

I'm getting via netstat -tulpn

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1132/sshd
tcp        0      0 0.0.0.0:5355            0.0.0.0:*               LISTEN      1126/systemd-resolv
tcp6       0      0 :::22                   :::*                    LISTEN      1132/sshd
tcp6       0      0 :::443                  :::*                    LISTEN      1590/docker-proxy
tcp6       0      0 :::10022                :::*                    LISTEN      1440/docker-proxy
tcp6       0      0 :::5355                 :::*                    LISTEN      1126/systemd-resolv
tcp6       0      0 :::80                   :::*                    LISTEN      1602/docker-proxy
tcp6       0      0 :::8080                 :::*                    LISTEN      1578/docker-proxy
udp        0      0 127.0.0.53:53           0.0.0.0:*                           1126/systemd-resolv
udp        0      0 0.0.0.0:68              0.0.0.0:*                           864/dhclient
udp        0      0 0.0.0.0:5355            0.0.0.0:*                           1126/systemd-resolv
udp6       0      0 :::5355                 :::*                                1126/systemd-resolv

I don't understand why 10022 is connected to docker-proxy.

When I try:

git push --set-upstream origin master
ssh: connect to host git.myserver.com port 10022: Connection refused
fatal: Could not read from remote repository.

Thank you very much


问:
How to copy files from google compute engine to local directory
I am trying to copy files from my instance to my local directory using following command

```<code>gcloud compute scp <instance-name>:~/<file-name> ~/Documents/
</code>```

However, it is showing error as mentioned below

$USER/Documents/: Is a directory

ERROR: (gcloud.compute.scp) [/usr/bin/scp] exited with return code [1].

Copying from local directory to GCE works fine.

I have checked Stanford's tutorial and Google's documentation as well.

I have one another instance where there is no issue like this.

I somewhat believe it might be issue with SSH keys.

What might have gone wrong?

答:
Your command is correct if your source and destination paths are correct

The command as you've posted in your question works for me when copying a file from the Google Compute Engine VM to my local machine.

```<code>$ gcloud compute scp vm1:~/.bashrc ~/Documents/
.bashrc                                          100% 3515     3.4KB/s   00:00
</code>```

I also tried doing the copy from other side (i.e. from my local machine to GCE VM) and it works:

```<code>$ gcloud compute scp ~/Documents/.bashrc vm1:~/temp/
.bashrc                                          100% 3515     3.4KB/s   00:00

$ gcloud compute scp ~/Documents/.bashrc vm1:~/.bashrc-new
.bashrc                                          100% 3515     3.4KB/s   00:00
</code>```

gcloud relies on the scp executable present in your PATH. The arguments you provide to the gcloud scp command are passed through to the scp binary. Assuming your source and destination paths are correct, it should work.

Recursive copying using scp

Based on your particular error message though, I've seen that variation only appear when the source path you're trying to copy from is a directory instead of file. For that particular case, you can pass a --recurse argument (similar to the -r argument supported by regular scp) which will recursively copy all files and directories under the specified directory.

gcloud compute scp --recurse SRC_PATH DEST_PATH

Body:
I am trying to copy files from my instance to my local directory using following command

gcloud compute scp <instance-name>:~/<file-name> ~/Documents/

However, it is showing error as mentioned below

$USER/Documents/: Is a directory

ERROR: (gcloud.compute.scp) [/usr/bin/scp] exited with return code [1].

Copying from local directory to GCE works fine.

I have checked Stanford's tutorial and Google's documentation as well.

I have one another instance where there is no issue like this.

I somewhat believe it might be issue with SSH keys.

What might have gone wrong?

Body:
Your command is correct if your source and destination paths are correct

The command as you've posted in your question works for me when copying a file from the Google Compute Engine VM to my local machine.

$ gcloud compute scp vm1:~/.bashrc ~/Documents/
.bashrc                                          100% 3515     3.4KB/s   00:00

I also tried doing the copy from other side (i.e. from my local machine to GCE VM) and it works:

$ gcloud compute scp ~/Documents/.bashrc vm1:~/temp/
.bashrc                                          100% 3515     3.4KB/s   00:00

$ gcloud compute scp ~/Documents/.bashrc vm1:~/.bashrc-new
.bashrc                                          100% 3515     3.4KB/s   00:00

gcloud relies on the scp executable present in your PATH. The arguments you provide to the gcloud scp command are passed through to the scp binary. Assuming your source and destination paths are correct, it should work.

Recursive copying using scp

Based on your particular error message though, I've seen that variation only appear when the source path you're trying to copy from is a directory instead of file. For that particular case, you can pass a --recurse argument (similar to the -r argument supported by regular scp) which will recursively copy all files and directories under the specified directory.

gcloud compute scp --recurse SRC_PATH DEST_PATH


问:
What is the difference here?
I am learning python and here is a small code that instructions want me to write.

First, def a function called cube that takes an argument called
  number. Don't forget the parentheses and the colon! Make that function
  return the cube of that number (i.e. that number multiplied by itself
  and multiplied by itself once again). Define a second function called
  by_three that takes an argument called number.

if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.

What I did first was;

```<code>def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        cube(number)
        return number
    else:
        return False
</code>```

but apparently in this, by_three(number) returns number itself. so to my understandings, the cube(Number) and return number doesnt work by line order?

this works:

```<code>def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        return cube(number)
    else:
        return False
</code>```

I know why this works, but I dont get why the other one doesnt.

答:
Explanation

The first one doesn't work because variables in functions are not global. What does this mean? Look at the following code:

```<code>def add(number):
    return number + 3

add(number)
print(number)
</code>```

If you try this code, you will get NameError: name 'number' is not defined. This is because the variable number is a LOCAL variable. It stays inside the function, having fun, and then it dies after the function ends. This also means that if you switch by_three(number) with by_three(number2)...

```<code>def cube(number):
    return number ** 3

def by_three(number2):
    if number % 3 == 0:
        cube(number2)
        return number
    else:
        return False
</code>```

It will show the error name 'number' is not defined.. When you use number instead, you are getting the output of the number you put in by_three(number), not cube(number). Thus, return cube(number) works because the number in cube(number) is different from the number in by_three(number).

Possible Approaches

If you still want to do a similar process like this, you can make a variable equal to the function cube(number). Example:

```<code>if number2 % 3 == 0:
    cubedNumber = cube(number2)
    return cubedNumber
else
    return False
</code>```

Now by_three(3) shows 27 instead.

Assigning a Global Variable

A global variable is default when outside a function; as a local variable if otherwise. To make a variable global, simply put global variable_name. However, you can't just do global variable = "something"; you must make it a global variable before assigning it. Anyways, in this scenario, it's not recommended, and I don't even bother putting a couple lines of code just to make the function work, because it will be global for the rest of the code.

Title: What is the difference here?

Body:
I am learning python and here is a small code that instructions want me to write.

First, def a function called cube that takes an argument called
  number. Don't forget the parentheses and the colon! Make that function
  return the cube of that number (i.e. that number multiplied by itself
  and multiplied by itself once again). Define a second function called
  by_three that takes an argument called number.

if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.

What I did first was;

def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        cube(number)
        return number
    else:
        return False

but apparently in this, by_three(number) returns number itself. so to my understandings, the cube(Number) and return number doesnt work by line order?

this works:

def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        return cube(number)
    else:
        return False

I know why this works, but I dont get why the other one doesnt.

Body:
Explanation

The first one doesn't work because variables in functions are not global. What does this mean? Look at the following code:

def add(number):
    return number + 3

add(number)
print(number)

If you try this code, you will get NameError: name 'number' is not defined. This is because the variable number is a LOCAL variable. It stays inside the function, having fun, and then it dies after the function ends. This also means that if you switch by_three(number) with by_three(number2)...

def cube(number):
    return number ** 3

def by_three(number2):
    if number % 3 == 0:
        cube(number2)
        return number
    else:
        return False

It will show the error name 'number' is not defined.. When you use number instead, you are getting the output of the number you put in by_three(number), not cube(number). Thus, return cube(number) works because the number in cube(number) is different from the number in by_three(number).

Possible Approaches

If you still want to do a similar process like this, you can make a variable equal to the function cube(number). Example:

if number2 % 3 == 0:
    cubedNumber = cube(number2)
    return cubedNumber
else
    return False

Now by_three(3) shows 27 instead.

Assigning a Global Variable

A global variable is default when outside a function; as a local variable if otherwise. To make a variable global, simply put global variable_name. However, you can't just do global variable = "something"; you must make it a global variable before assigning it. Anyways, in this scenario, it's not recommended, and I don't even bother putting a couple lines of code just to make the function work, because it will be global for the rest of the code.


问:
Sharing Firebase authentication/token across two iOS apps
I have an iOS app, App1, using a Firebase backend, and the user can sign in/create an account with using:

Firebase account (email/password)

Facebook (swap for Firebase credential after authentication)

Google (swap for Firebase credential after authentication)

This works fine.

I have another iOS app, App2, using a Firebase backend, that allows a user to sign in/create an account using the exact same options as App1 (App2 uses the exact same core code App1 uses), and, in addition, a 4th sign in/create account option:

Firebase account (email/password)

Facebook (swap for Firebase credential after authentication)

Google (swap for Firebase credential after authentication)

Scan a QR code displayed on another device App1 is running on

To use option 4, QR code sign in, the user on App1 clicks a button, "Generate QR Code", the data for the generated QR code on App1 contains the Firebase credential uid and displayName.

This all works fine. App2 can read the data in the App1 QR code, App2 easily now has the uid and displayName for the logged in user on App1.

Now for the first problem I ran into on App2 when later trying to update the Firebase Database using the uid from the App1 QR code, Firebase error: "Permission Denied":

Understood, have to be authenticated, my Database rules clearly express this, I didn't know this prior to my QR code strategy of course:

```<code>{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}
</code>```

Yet, I do not want to switch my Firebase rules to Public, that would allow anyone access. So next I thought, no problem, I will just put the user entered email/password as data in the generated QR code on App1, my apps does not have high security concerns, then, when App2 scans the App1 QR code, App2 can just login into Firebase using the email/password it read from the data in the App1 QR code.

There is one problem with my solution, it will not work for users that sign into App1 with Google or Facebook. I will not have their email or password in this case.

Another solution I was pondering but I am pretty sure will not work for me, refer above to the Firebase "Permission Denied" is Firebase's signInAnonymously, this will not work for me because the Firebase user exists, that user signed in on App1, has their own uid, which is not the uid created by signInAnonymously obviously.

Another solution I am pondering is using NSUbiquitousKeyValueStore
 to share the Firebase credential from App1 with App2 but I am not sure what I will need in the Firebase credential to recreate it on App2. I think I would still have to call Auth.auth().signIn on App2 to create a new valid Firebase session on App2 even if I shared a valid Firebase credential/token from App1 via NSUbiquitousKeyValueStore...or other suggestions please...

答:
Thanks to information here and here I realized I could add a Firebase account that had a "role" as an Administrator. This way, when I retrieve the uid and displayName from the QR code (the QR code must include the displayName in addition to the uid as you cannot retrieve it later even with full access to the Firebase database) I can just login as my Administrator Firebase account and I can write and read for the QR code passed in uid with the following database rule changes, please note I do have a "users" database I created and that is where I store my role:</p>

```<code>{
  "rules": {
    "users": {
      ".read": "root.child('users').child(auth.uid).child('role').val() == 'admin'",
      ".write": "root.child('users').child(auth.uid).child('role').val() == 'admin'",
      "$uid": {
        ".read": "auth.uid == $uid",
        ".write": "auth.uid == $uid"
      }
    }
  }
}
</code>```

Body:
I have an iOS app, App1, using a Firebase backend, and the user can sign in/create an account with using:

Firebase account (email/password)

Facebook (swap for Firebase credential after authentication)

Google (swap for Firebase credential after authentication)

This works fine.

I have another iOS app, App2, using a Firebase backend, that allows a user to sign in/create an account using the exact same options as App1 (App2 uses the exact same core code App1 uses), and, in addition, a 4th sign in/create account option:

Firebase account (email/password)

Facebook (swap for Firebase credential after authentication)

Google (swap for Firebase credential after authentication)

Scan a QR code displayed on another device App1 is running on

To use option 4, QR code sign in, the user on App1 clicks a button, "Generate QR Code", the data for the generated QR code on App1 contains the Firebase credential uid and displayName.

This all works fine. App2 can read the data in the App1 QR code, App2 easily now has the uid and displayName for the logged in user on App1.

Now for the first problem I ran into on App2 when later trying to update the Firebase Database using the uid from the App1 QR code, Firebase error: "Permission Denied":

Understood, have to be authenticated, my Database rules clearly express this, I didn't know this prior to my QR code strategy of course:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Yet, I do not want to switch my Firebase rules to Public, that would allow anyone access. So next I thought, no problem, I will just put the user entered email/password as data in the generated QR code on App1, my apps does not have high security concerns, then, when App2 scans the App1 QR code, App2 can just login into Firebase using the email/password it read from the data in the App1 QR code.

There is one problem with my solution, it will not work for users that sign into App1 with Google or Facebook. I will not have their email or password in this case.

Another solution I was pondering but I am pretty sure will not work for me, refer above to the Firebase "Permission Denied" is Firebase's signInAnonymously, this will not work for me because the Firebase user exists, that user signed in on App1, has their own uid, which is not the uid created by signInAnonymously obviously.

Another solution I am pondering is using NSUbiquitousKeyValueStore
 to share the Firebase credential from App1 with App2 but I am not sure what I will need in the Firebase credential to recreate it on App2. I think I would still have to call Auth.auth().signIn on App2 to create a new valid Firebase session on App2 even if I shared a valid Firebase credential/token from App1 via NSUbiquitousKeyValueStore...or other suggestions please...

Body:
Thanks to information here and here I realized I could add a Firebase account that had a "role" as an Administrator. This way, when I retrieve the uid and displayName from the QR code (the QR code must include the displayName in addition to the uid as you cannot retrieve it later even with full access to the Firebase database) I can just login as my Administrator Firebase account and I can write and read for the QR code passed in uid with the following database rule changes, please note I do have a "users" database I created and that is where I store my role:

{
  "rules": {
    "users": {
      ".read": "root.child('users').child(auth.uid).child('role').val() == 'admin'",
      ".write": "root.child('users').child(auth.uid).child('role').val() == 'admin'",
      "$uid": {
        ".read": "auth.uid == $uid",
        ".write": "auth.uid == $uid"
      }
    }
  }
}


问:
rassigning variables in python when they do and dont
I am confused as to when variables get reassigned in my code and when they remain constant. I have used print statements to narrow down which custom function is causing the problem I just can't find the line. I'm trying to make a store in Python using more or less beginner code.

```<code>def buy(vx, vy, p, cash,price):
if cash >= price:
    if (box_range(vx, vy, 670, 960, 430, 540) and p == 1)and len(shopping_list)>= 1:
        for i in range(0, len(shopping_list)):
            my_items.append(shopping_list[i])
        print "The computer appended " + str(len(shopping_list)) + " items."
        print "my items are now " + str(my_items)
        cash -= price
        if p == 1:
            print "balance is " + str(cash)
        return cash
elif cash < price and (box_range(vx, vy, 670, 960, 430, 540) and p == 1)and len(shopping_list)>= 1:
    print "you don't have enough money"
    return cash
else:
    return cash
</code>```

The vx and vy variables relate to the position of the mouse, p refers to whether or not the mouse was pressed, assume price is 0, shopping list is a list of classes, my items is a list of classes and the value of cash imputed into the function is 1000, however, sometimes it returns None and I can't figure out why.

答:
The fundamental problem is that the inner if returns cash-price if the condition is satisfied but it returns nothing (meaning None) when the condition (box_range(vx, vy, 670, 960, 430, 540) and p == 1) and len(shopping_list)>= 1 is not satisfied:

```<code>if cash >= price:
    if (box_range(vx, vy, 670, 960, 430, 540) and p == 1)and len(shopping_list)>= 1:
        for i in range(0, len(shopping_list)):
            my_items.append(shopping_list[i])
        print "The computer appended " + str(len(shopping_list)) + " items."
        print "my items are now " + str(my_items)
        cash -= price
        if p == 1:
            print "balance is " + str(cash)
        return cash
    else: # what should be returned when, e.g., len(shopping_list) < 1???
        return SOMETHING
elif ...
</code>```

Specify the value to be returned when the condition (box_range(vx, vy, 670, 960, 430, 540) and p == 1) and len(shopping_list)>= 1 is not satisfied.

Body:
I am confused as to when variables get reassigned in my code and when they remain constant. I have used print statements to narrow down which custom function is causing the problem I just can't find the line. I'm trying to make a store in Python using more or less beginner code.

def buy(vx, vy, p, cash,price):
if cash >= price:
    if (box_range(vx, vy, 670, 960, 430, 540) and p == 1)and len(shopping_list)>= 1:
        for i in range(0, len(shopping_list)):
            my_items.append(shopping_list[i])
        print "The computer appended " + str(len(shopping_list)) + " items."
        print "my items are now " + str(my_items)
        cash -= price
        if p == 1:
            print "balance is " + str(cash)
        return cash
elif cash < price and (box_range(vx, vy, 670, 960, 430, 540) and p == 1)and len(shopping_list)>= 1:
    print "you don't have enough money"
    return cash
else:
    return cash

The vx and vy variables relate to the position of the mouse, p refers to whether or not the mouse was pressed, assume price is 0, shopping list is a list of classes, my items is a list of classes and the value of cash imputed into the function is 1000, however, sometimes it returns None and I can't figure out why.

Body:
The fundamental problem is that the inner if returns cash-price if the condition is satisfied but it returns nothing (meaning None) when the condition (box_range(vx, vy, 670, 960, 430, 540) and p == 1) and len(shopping_list)>= 1 is not satisfied:

if cash >= price:
    if (box_range(vx, vy, 670, 960, 430, 540) and p == 1)and len(shopping_list)>= 1:
        for i in range(0, len(shopping_list)):
            my_items.append(shopping_list[i])
        print "The computer appended " + str(len(shopping_list)) + " items."
        print "my items are now " + str(my_items)
        cash -= price
        if p == 1:
            print "balance is " + str(cash)
        return cash
    else: # what should be returned when, e.g., len(shopping_list) < 1???
        return SOMETHING
elif ...

Specify the value to be returned when the condition (box_range(vx, vy, 670, 960, 430, 540) and p == 1) and len(shopping_list)>= 1 is not satisfied.


问:
Use dollar sign in PHP sprintf function with a %s string
This involves Wordpress syntax but I figured it was mainly a PHP problem.

I'm using this function:

```<code>$subject = sprintf( '%s New Customer Order %s for %s on %s', $blogname, $order->id, $order->get_total, $order->order_date );
</code>```

to produce something like:
"SiteName New Customer Order #3715 for $40.00 on July 5th"

The problem is the $order_total outputs as a plain integer without dollar sign. Using $%s or \$%s doesn't work.. how can I append a dollar sign to the second %s variable?

答:
You can actually concatenate the dollar sign $ before the get_total variable. Like this:

```<code><?php

  //Test class
  class Order{
    public $id = "3333";
    public $get_total = "50.00";
    public $order_date = "07-06-2017";
  }
  $order = new Order();

  // Concatenate the dollar sign $ before the $order->get_total variable
  echo sprintf( '%s New Customer Order %s for %s on %s', "Test name", $order->id, "$" . $order->get_total, $order->order_date );

?>
</code>```

Working example: http://sandbox.onlinephpfunctions.com/code/648e6873ebfe9ffc68eb54e61cc2e953be612dca

Body:
This involves Wordpress syntax but I figured it was mainly a PHP problem.

I'm using this function:

$subject = sprintf( '%s New Customer Order %s for %s on %s', $blogname, $order->id, $order->get_total, $order->order_date );

to produce something like:
"SiteName New Customer Order #3715 for $40.00 on July 5th"

The problem is the $order_total outputs as a plain integer without dollar sign. Using $%s or \$%s doesn't work.. how can I append a dollar sign to the second %s variable?

Body:
You can actually concatenate the dollar sign $ before the get_total variable. Like this:

<?php

  //Test class
  class Order{
    public $id = "3333";
    public $get_total = "50.00";
    public $order_date = "07-06-2017";
  }
  $order = new Order();

  // Concatenate the dollar sign $ before the $order->get_total variable
  echo sprintf( '%s New Customer Order %s for %s on %s', "Test name", $order->id, "$" . $order->get_total, $order->order_date );

?>

Working example: http://sandbox.onlinephpfunctions.com/code/648e6873ebfe9ffc68eb54e61cc2e953be612dca


问:
Removing specific integers from columns in a dataframe using R
Here is what my current dataframe looks like:

```<code>Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("001001", "001002", "001002", "002002")
Loc2 <- c("001002", "002002", "001002", "001001")
Loc3 <- c("002002", "001002", "001002", "001001")
dat <- data.frame(Name, Loc1, Loc2, Loc3)
dat
</code>```

And this is my desired result:

```<code>Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("11", "12", "12", "22")
Loc2 <- c("12", "22", "12", "11")
Loc3 <- c("22", "12", "12", "11")
result <- data.frame(Name, Loc1, Loc2, Loc3)
result
</code>```

Note that the number remain the same, but I am looking for a way fro remove the "0" characters from multiple columns and leave behind other integers. I have tried using various incarnations of the strstring() and substr() functions for this, but seem to keep getting stuck because  "0" is not recognized as a character. It seems a fairly simple problem but I need some advice. Thanks in advance.

答:
Here is an option with tidyverse

```<code>library(tidyverse)
dat %>%
     mutate_at(vars(matches("Loc")), funs(str_replace_all(., "0", "")))
#    Name Loc1 Loc2 Loc3
#1   John   11   12   22
#2   Paul   12   22   12
#3  Ringo   12   12   12
#4 George   22   11   11
</code>```

Body:
Here is what my current dataframe looks like:

Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("001001", "001002", "001002", "002002")
Loc2 <- c("001002", "002002", "001002", "001001")
Loc3 <- c("002002", "001002", "001002", "001001")
dat <- data.frame(Name, Loc1, Loc2, Loc3)
dat

And this is my desired result:

Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("11", "12", "12", "22")
Loc2 <- c("12", "22", "12", "11")
Loc3 <- c("22", "12", "12", "11")
result <- data.frame(Name, Loc1, Loc2, Loc3)
result

Note that the number remain the same, but I am looking for a way fro remove the "0" characters from multiple columns and leave behind other integers. I have tried using various incarnations of the strstring() and substr() functions for this, but seem to keep getting stuck because  "0" is not recognized as a character. It seems a fairly simple problem but I need some advice. Thanks in advance.

Body:
Here is an option with tidyverse

library(tidyverse)
dat %>%
     mutate_at(vars(matches("Loc")), funs(str_replace_all(., "0", "")))
#    Name Loc1 Loc2 Loc3
#1   John   11   12   22
#2   Paul   12   22   12
#3  Ringo   12   12   12
#4 George   22   11   11


问:
SQLite table with Git merging
I have a log file stored in an SQLite database which I would like to distribute in a git repository.

Later on I would like changes to the log file to be merge automatically with the original.

Is this going to work? Will an automatic binary merge into an SQLite file blow up more often than not?

答:
Even though this question was asked 8+ years ago, I've released a tool that does exactly what you're asking for. It uses a custom diff driver leveraging the sqlite projects tool 'sqldiff', UUIDs as primary keys, and leaves off the sqlite rowid. It is still in alpha so feedback is appreciated.

https://github.com/cannadayr/git-sqlite

OwnerDisplayName: git-noob

Title: SQLite table with Git merging


答:
What went wrong:

This is because you didn't store the result of cube(number) in any variable. and when the program proceeds to the next line return number it returns the number.

Example:

```<code>def example(number):
  number + 5
  return number

print(example(7))
</code>```

the result is: 7

since I didn't do anything to store my result of number + 5 when I call example(5) I get the number itself back

but now consider:

```<code>def example(number):
  number = number + 5
  return number

print(example(7))
</code>```

the result is: 12

This is because I updated number with the result of number + 5.

I hope this helps you get a better understanding of what was wrong with your code. Welcome to StackOverflow. If you find this answer of any other helpful and solves your problem please mark it as the solution. That way it will help the community and fellow programmers who run into the same question as you in the future. Cheers

Title: What is the difference here?

Body:
What went wrong:

This is because you didn't store the result of cube(number) in any variable. and when the program proceeds to the next line return number it returns the number.

Example:

def example(number):
  number + 5
  return number

print(example(7))

the result is: 7

since I didn't do anything to store my result of number + 5 when I call example(5) I get the number itself back

but now consider:

def example(number):
  number = number + 5
  return number

print(example(7))

the result is: 12

This is because I updated number with the result of number + 5.

I hope this helps you get a better understanding of what was wrong with your code. Welcome to StackOverflow. If you find this answer of any other helpful and solves your problem please mark it as the solution. That way it will help the community and fellow programmers who run into the same question as you in the future. Cheers


问:
using jsftp to upload files results in files of zero size on server
I'm trying to put files on my server with jsftp. Everytime I run my code I do get a file written to the server but it has 0 bytes. I'm certain that the user: host: etc are correct.

Here's the code.

```<code>function uploadHours() {
var jsftp = require("jsftp");

var ftp = new jsftp({
host: localStorage.host,
port: Number(localStorage.port), // defaults to 21
user: localStorage.user, // defaults to "anonymous"
pass: localStorage.ftpPass // defaults to "@anonymous"
});

ftp.auth(localStorage.user, localStorage.ftpPass, function(hadErr) {
if (!hadErr)
alert("auth succesfull")
});
;
ftp.put('C:/Program Files/Adobe/Adobe After Effects CC 2014/Support Files/Hours Tracker/index2.html', '/public_html/indexTester2.html', function(hadErr) {
  if (!hadError)
alert("File transferred successfully!");
});
}
</code>```

答:
I have the same question.(using jsftp to upload files results in files of zero size on vsftpd server)

make sure use console.error to print the error.

```<code>Ftp.put(buffer, remote, function(err) {
         if (err) {
             console.error(err);
             callback(err);
         }
         else {
             alert(file + " - uploaded successfuly");
             callback();
         }
     });
</code>```

the error like that

```<code>{ [Error: connect ETIMEDOUT **192.168.0.4:64953**]
  code: 'ETIMEDOUT',
  errno: 'ETIMEDOUT',
  syscall: 'connect',
  address: '192.168.0.4',
  port: 64953 }
</code>```

because of my vsftpd using the PASV model,so when it return the port .jsftp modified the ip .I resolve this problem :
modify jsftp.js (jsftp/lib/jsftp.js)

```<code>var fixhost;

var Ftp = module.exports = function(cfg) {
    ...
    this.useList = cfg.useList || false;
    fixhost=this.host;//add
}

 Ftp.prototype.getPasvSocket = function(callback) {
    ...
    options.host=fixhost;//add
    var socket = self._pasvSocket = Net.createConnection(options);
}
</code>```

Body:
I'm trying to put files on my server with jsftp. Everytime I run my code I do get a file written to the server but it has 0 bytes. I'm certain that the user: host: etc are correct.

Here's the code.

function uploadHours() {
var jsftp = require("jsftp");

var ftp = new jsftp({
host: localStorage.host,
port: Number(localStorage.port), // defaults to 21
user: localStorage.user, // defaults to "anonymous"
pass: localStorage.ftpPass // defaults to "@anonymous"
});

ftp.auth(localStorage.user, localStorage.ftpPass, function(hadErr) {
if (!hadErr)
alert("auth succesfull")
});
;
ftp.put('C:/Program Files/Adobe/Adobe After Effects CC 2014/Support Files/Hours Tracker/index2.html', '/public_html/indexTester2.html', function(hadErr) {
  if (!hadError)
alert("File transferred successfully!");
});
}

Body:
I have the same question.(using jsftp to upload files results in files of zero size on vsftpd server)

make sure use console.error to print the error.

Ftp.put(buffer, remote, function(err) {
         if (err) {
             console.error(err);
             callback(err);
         }
         else {
             alert(file + " - uploaded successfuly");
             callback();
         }
     });

the error like that

{ [Error: connect ETIMEDOUT **192.168.0.4:64953**]
  code: 'ETIMEDOUT',
  errno: 'ETIMEDOUT',
  syscall: 'connect',
  address: '192.168.0.4',
  port: 64953 }

because of my vsftpd using the PASV model,so when it return the port .jsftp modified the ip .I resolve this problem :
modify jsftp.js (jsftp/lib/jsftp.js)

var fixhost;

var Ftp = module.exports = function(cfg) {
    ...
    this.useList = cfg.useList || false;
    fixhost=this.host;//add
}

 Ftp.prototype.getPasvSocket = function(callback) {
    ...
    options.host=fixhost;//add
    var socket = self._pasvSocket = Net.createConnection(options);
}


问:
regarding converting sql to hql
how to select column's value as null in hql?

ex: In sql

```<code> select null as empname from emp; in sql

   In hql
</code>```

ex: select emp.empname as col1 from Employee emp;

I want to select empname' value as null as explained in the above sql query

An

答:
You can use cast function. Like this,

```<code>select cast(null as char) as hede from emp e
</code>```

Or use quotes and change your controls to empty checks.

```<code>select '' as hede from emp e
</code>```

Title: regarding converting sql to hql

Body:
how to select column's value as null in hql?

ex: In sql

 select null as empname from emp; in sql

   In hql

ex: select emp.empname as col1 from Employee emp;

I want to select empname' value as null as explained in the above sql query

An

Body:
You can use cast function. Like this,

select cast(null as char) as hede from emp e

Or use quotes and change your controls to empty checks.

select '' as hede from emp e


问:
Why is Array.IndexOf not checking for IEquatable like List<T> does?
Consider this code:

```<code>public static void Main()
{
    var item = new Item { Id = 1 };

    IList list = new List<Item> { item };
    IList array = new[] { item };

    var newItem = new Item { Id = 1 };

    var lIndex = list.IndexOf(newItem);
    var aIndex = array.IndexOf(newItem);

    Console.WriteLine(lIndex);
    Console.WriteLine(aIndex);
}

public class Item : IEquatable<Item>
{
    public int Id { get; set; }

    public bool Equals(Item other) => other != null && other.Id == Id;

}
</code>```

Results:

```<code>0
-1
</code>```

Why are the results different between List<T> and Array? I guess this is by design, but why?

Looking at the code of List<T>.IndexOf makes me wonder even more, since it's porting to Array.IndexOf.

答:
Because generic object collections use the IEquatable<T> interface when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove.

An Array knows nothing about <T> so it can't implement or use the IEquatable interface.

An Array instead holds objects that are not generic. It will call Equals to compare one object to another as all objects have an Equals method which you are free to override.

Body:
Consider this code:

public static void Main()
{
    var item = new Item { Id = 1 };

    IList list = new List<Item> { item };
    IList array = new[] { item };

    var newItem = new Item { Id = 1 };

    var lIndex = list.IndexOf(newItem);
    var aIndex = array.IndexOf(newItem);

    Console.WriteLine(lIndex);
    Console.WriteLine(aIndex);
}

public class Item : IEquatable<Item>
{
    public int Id { get; set; }

    public bool Equals(Item other) => other != null && other.Id == Id;

}

Results:

0
-1

Why are the results different between List<T> and Array? I guess this is by design, but why?

Looking at the code of List<T>.IndexOf makes me wonder even more, since it's porting to Array.IndexOf.


问:
How to apply a function on every possible combination of two columns in two matrices in R
I have two matrices each has 300 columns; M1 and M2 I am applying a simple ifelse function on them as following:

```<code>result<-ifelse(M1[-nrow(M1),]<M2[-nrow(M2),],1,4)

tail(result)

                    X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17
2017-06-26 04:00:00  4  1  1  4  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 05:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 06:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 07:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 08:00:00  4  1  1  1  1  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 09:00:00  4  1  1  1  1  1  4  4  4   4   4   4   4   4   4   4   4
</code>```

In this case the ifelse function applied on every column in M1 with it's matching column in M2

How can I apply the ifelse function on every possible combination of columns in M1 and M2 and save the results into one big matrix (90000 columns in this case) or list of matrices?

答:
Using expand.grid to get a cartesian product of the column indices would help.

```<code>m1 <- matrix(1:9, ncol=3)
m2 <- matrix(4:12, ncol=3)
g <- expand.grid(1:nrow(m1), 1:ncol(m2))
ans <- ifelse(m1[, g[, 1]] < m2[, g[, 2]], 1, 4)
</code>```

Body:
I have two matrices each has 300 columns; M1 and M2 I am applying a simple ifelse function on them as following:

result<-ifelse(M1[-nrow(M1),]<M2[-nrow(M2),],1,4)

tail(result)

                    X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17
2017-06-26 04:00:00  4  1  1  4  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 05:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 06:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 07:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 08:00:00  4  1  1  1  1  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 09:00:00  4  1  1  1  1  1  4  4  4   4   4   4   4   4   4   4   4

In this case the ifelse function applied on every column in M1 with it's matching column in M2

How can I apply the ifelse function on every possible combination of columns in M1 and M2 and save the results into one big matrix (90000 columns in this case) or list of matrices?

Body:
Using expand.grid to get a cartesian product of the column indices would help.

m1 <- matrix(1:9, ncol=3)
m2 <- matrix(4:12, ncol=3)
g <- expand.grid(1:nrow(m1), 1:ncol(m2))
ans <- ifelse(m1[, g[, 1]] < m2[, g[, 2]], 1, 4)


问:
Use angular 2 services within functions of components
Here is an example of how I'm getting foursquare information within one of my components:

```<code>import {Component} from 'angular2/core';
import {FoursquareService} from '../../services/foursquare'

@Component({
  templateUrl : 'app/components/new-listing/new-listing.html',
  providers : [FoursquareService]
})

export class NewListingComponent {

  venues : Array<Object> = [];

  constructor(foursquareApi : FoursquareService) {

    //Foursquare api
    foursquareApi.foursquareGet('&ll=51.5255168,-0.0858669&query=xoyo')
    .subscribe(data => {
      this.venues = data.response.venues;
      console.log(this.venues);
    });

  }

}
</code>```

This logs related objects to console on page load, however I want to achieve same functionality on click of a button or while users are typing, hence have it in separate function, however every time I remove foursquareApi : FoursquareService from constructor I get various errors.

答:
Make the service protected in constructor and do whatever call with the service in constructor for on load.

When you want to use for onClick or some action you can refer to the service inside onClick function .

```<code> constructor(private myService: MyService) { //Do call with on load for this.
 }
 toggleHobbies() {
   this.showHobbies = !this.showHobbies;
   console.log(this.myService.getPosts());
   console.log(1);
 }
</code>```

Body:
Here is an example of how I'm getting foursquare information within one of my components:

import {Component} from 'angular2/core';
import {FoursquareService} from '../../services/foursquare'

@Component({
  templateUrl : 'app/components/new-listing/new-listing.html',
  providers : [FoursquareService]
})

export class NewListingComponent {

  venues : Array<Object> = [];

  constructor(foursquareApi : FoursquareService) {

    //Foursquare api
    foursquareApi.foursquareGet('&ll=51.5255168,-0.0858669&query=xoyo')
    .subscribe(data => {
      this.venues = data.response.venues;
      console.log(this.venues);
    });

  }

}

This logs related objects to console on page load, however I want to achieve same functionality on click of a button or while users are typing, hence have it in separate function, however every time I remove foursquareApi : FoursquareService from constructor I get various errors.

Body:
Make the service protected in constructor and do whatever call with the service in constructor for on load.

When you want to use for onClick or some action you can refer to the service inside onClick function .

 constructor(private myService: MyService) { //Do call with on load for this.
 }
 toggleHobbies() {
   this.showHobbies = !this.showHobbies;
   console.log(this.myService.getPosts());
   console.log(1);
 }

ContentLicense: CC BY-SA 4.0


问:
How do prototypes work under the hood?

"Put functions on a prototype object when you're going to create lots
  of copies of a particular kind of object and they all need to share
  common behaviors. By doing so, you'll save some memory by having just
  one copy of each function, but that's only the simplest benefit."

How exactly does this work under the hood?

答:
The key is what used to be a hidden property (and is now standard) __proto__.

```<code>var z = { weight: "Too much" };
var a = { name: "Bob", age: 32 };
var b = { name: "Doug" };

a.__proto__ = z;
b.__proto__ = a;

b.age; // 32 -- doesn't have one, so it checks __proto__.age
b.name; // Doug -- has its own, so it doesn't look it up
b.weight; // Too much -- __proto__.__proto__.weight
</code>```

All of the different helpers in libraries or in standard methods/syntax are really just ways of hiding this.

When you apply this to ES constructor functions:

```<code>function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.weight = "That's rather personal";

var bob = new Person("Bob", 32);
bob.__proto__ === Person.prototype; // true
</code>```

So you can sort of think of three invisible lines at the start of your constructor function:

```<code>function Person (name, age) {
  /*
    this = {};
    this.constructor = Person;
    this.__proto__ = Person.prototype;
  */
  this.name = name;
  this.age = age;
  // return this;
}
</code>```

ES6 classes are really just a prettier wrapper around this constructor behaviour, which hide all of the zaniness people had to do to make class inheritance work.

Title: How do prototypes work under the hood?

Body:
The key is what used to be a hidden property (and is now standard) __proto__.

var z = { weight: "Too much" };
var a = { name: "Bob", age: 32 };
var b = { name: "Doug" };

a.__proto__ = z;
b.__proto__ = a;

b.age; // 32 -- doesn't have one, so it checks __proto__.age
b.name; // Doug -- has its own, so it doesn't look it up
b.weight; // Too much -- __proto__.__proto__.weight

All of the different helpers in libraries or in standard methods/syntax are really just ways of hiding this.

When you apply this to ES constructor functions:

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.weight = "That's rather personal";

var bob = new Person("Bob", 32);
bob.__proto__ === Person.prototype; // true

So you can sort of think of three invisible lines at the start of your constructor function:

function Person (name, age) {
  /*
    this = {};
    this.constructor = Person;
    this.__proto__ = Person.prototype;
  */
  this.name = name;
  this.age = age;
  // return this;
}

ES6 classes are really just a prettier wrapper around this constructor behaviour, which hide all of the zaniness people had to do to make class inheritance work.


答:
List<T> can make use of the IEquatable<T> interface, so that one works as expected.

The array is using the Equals method from Object and you are not overriding that one, but rather just implementing IEquatable.

Try defining Equals like:

```<code>public override bool Equals(Object other) => other != null && (other as Item).Id == Id;
</code>```

That would work for both cases in the same way.

Title: Why is Array.IndexOf not checking for IEquatable like List<T> does?

Body:
List<T> can make use of the IEquatable<T> interface, so that one works as expected.

The array is using the Equals method from Object and you are not overriding that one, but rather just implementing IEquatable.

Try defining Equals like:

public override bool Equals(Object other) => other != null && (other as Item).Id == Id;

That would work for both cases in the same way.


问:
cut off image in ratingbar
I made own ratingbar. There are 4 sizes of flowers images (xdpi, hdpi, etc) from 24pxx24px to 64x64px.

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background"
          android:drawable="@drawable/ic_rating_flowers_empty" />
    <item android:id="@+android:id/secondaryProgress"
          android:drawable="@drawable/ic_rating_flowers_empty" />
    <item android:id="@+android:id/progress"
          android:drawable="@drawable/ic_rating_flowers" />
</layer-list>
</code>```

rating_flowers.xml in drawable floder

```<code><style name="flowersRating" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/rating_flowers</item>
    <item name="android:minHeight">24dip</item>
    <item name="android:maxHeight">64dip</item>
</style>
</code>```

in styles.xml

```<code><TableRow
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <TextView
        android:text="@string/mood_headache" />

    <RatingBar
        android:id="@+id/moodHeadacheRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="3"
        android:stepSize="1.0"
        android:rating="0"
        style="@style/flowersRating" />

 </TableRow>
</code>```

and activity

And what I see

and images from drawable-ldpi

答:
set   android:layout_height="0dp"

https://stackoverflow.com/a/44992485/4238544

Title: cut off image in ratingbar

Body:
I made own ratingbar. There are 4 sizes of flowers images (xdpi, hdpi, etc) from 24pxx24px to 64x64px.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background"
          android:drawable="@drawable/ic_rating_flowers_empty" />
    <item android:id="@+android:id/secondaryProgress"
          android:drawable="@drawable/ic_rating_flowers_empty" />
    <item android:id="@+android:id/progress"
          android:drawable="@drawable/ic_rating_flowers" />
</layer-list>

rating_flowers.xml in drawable floder

in styles.xml

<TableRow
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <TextView
        android:text="@string/mood_headache" />

    <RatingBar
        android:id="@+id/moodHeadacheRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="3"
        android:stepSize="1.0"
        android:rating="0"
        style="@style/flowersRating" />

 </TableRow>

and activity

And what I see

and images from drawable-ldpi


问:
Right way of tracking a sqlite3 binary file in git?
I maintain a fork of a repo.

That repo which has been tracking a binary file (which is a sqlite3 file).

Every time I pull from that repo, I experience merge conflict due to that binary file.

What is the right way to solve this kind of merge conflict?

What is the right way to manage binary files (like this sqlite3 *.db file) in git?

答:
I've released a tool that does what you're asking for. It uses a custom diff driver leveraging the sqlite projects tool 'sqldiff', UUIDs as primary keys, and leaves off the sqlite rowid. It is still in alpha so feedback is appreciated.

https://github.com/cannadayr/git-sqlite


问:
Need of disabling HiveServer2 Impersonation for sentry
I have configured the Hive Authorization though Sentry and did all the needed changes. One of the change is to Disable HiveServer2 Impersonation by setting below property:

```<code>hive.server2.enable.doAs to false
</code>```

This is mandatory requirement for Sentry as mention in cloudera Doc here. So what is the need for doing that as it is a very standard requirements wrt BI tools. Where one user will be launching the application and that will be impersonating the logged in user. Please let me know if there is some aspect which i am missing due to this restriction is needed.

答: Impersonation turned off in this case suggests that the query will run as the hive user. In fact, the underlying HDFS directory within the Hive warehouse managing the table(s) for this query will be owned by the hive user. However, an Access Control List (ACL) will entitle the 'real' user to perform read, write, and/or execute operations against the underlying HDFS file.  Also, the 'real' user will be entitled to operations against the table or columns within the table.  The ACLs and the table/column entitlements constitute what's called the Sentry policy. Since that policy is in place as part of the Hive query execution, there is no need to impersonate the 'real' user. Consider the Sentry policy file to be an RBAC (i.e. role-based access control) permission set. With those permissions in place, impersonation is not needed.</p>

Body:
I have configured the Hive Authorization though Sentry and did all the needed changes. One of the change is to Disable HiveServer2 Impersonation by setting below property:

hive.server2.enable.doAs to false

This is mandatory requirement for Sentry as mention in cloudera Doc here. So what is the need for doing that as it is a very standard requirements wrt BI tools. Where one user will be launching the application and that will be impersonating the logged in user. Please let me know if there is some aspect which i am missing due to this restriction is needed.


问:
MKL: failed to observe the effect of threading
I'd like to call cblas_drot at some point of my code, which is not in a parallel region. Then I get confused that the execution time for this call is basically the same in single thread mode and 24-thread. I set the number of threads by mkl_set_num_threads() before the function call. Anyone has any idea of what might happened?

The cpu is 2*Xeon E5 2620v3 and OS is Ubuntu 16.04.2.

答:
Probably you are saturating the memory bandwidth. The computational intensity of that function is very low and the performances are mostly dictated by the timings of memory accesses. Actually the scalability results strongly depend on the increments incX and incY. Assuming N = 10000000, I found that (CPU E5-2670):

```<code>N threads |  time for incX=incY=1  | time for incX=incY=32
1         |  0.026271              |  1.243775
2         |  0.020599              |  0.555945
4         |  0.017871              |  0.301370
8         |  0.021367              |  0.152756
16        |  0.021729              |  0.175500
</code>```

That shows that the speed-up is decent up to 8 threads (and still there at 16 threads) when incX/Y is different from 1. When incX/Y=1, a very well optimized version of the function (with significant usage of AVX functions) uses the major part of the available memory bandwidth making the results of the OpenMP parallelization very poor. I am just guessing what is happening: to confirm that, you might consider the usage of a low-level profiler.

Body:
Probably you are saturating the memory bandwidth. The computational intensity of that function is very low and the performances are mostly dictated by the timings of memory accesses. Actually the scalability results strongly depend on the increments incX and incY. Assuming N = 10000000, I found that (CPU E5-2670):

N threads |  time for incX=incY=1  | time for incX=incY=32
1         |  0.026271              |  1.243775
2         |  0.020599              |  0.555945
4         |  0.017871              |  0.301370
8         |  0.021367              |  0.152756
16        |  0.021729              |  0.175500

That shows that the speed-up is decent up to 8 threads (and still there at 16 threads) when incX/Y is different from 1. When incX/Y=1, a very well optimized version of the function (with significant usage of AVX functions) uses the major part of the available memory bandwidth making the results of the OpenMP parallelization very poor. I am just guessing what is happening: to confirm that, you might consider the usage of a low-level profiler.