问:
How can an array be grouped by two properties?
Ex:

```<code>const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];
</code>```

Expected Result: const result = groupBy(arr, 'group', 'question.templateId');

```<code>const result = [
  [{
    group: 1,
    question: {
      templateId: 100
    }
  }, {
    group: 1,
    question: {
      templateId: 100
    }
  }],
  [{
    group: 1,
    question: {
      templateId: 300
    }
  }],
  [{
    group: 2,
    question: {
      templateId: 200
    }
  }]
];
</code>```

So far: I am able to group the result by a single property using Array.prototype.reduce().

function groupBy(arr, key) {
  return [...arr.reduce((accumulator, currentValue) => {
    const propVal = currentValue[key],
      group = accumulator.get(propVal) || [];
    group.push(currentValue);
    return accumulator.set(propVal, group);
  }, new Map()).values()];
}

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

const result = groupBy(arr, 'group');

console.log(result);```

答:
@Bergi's answer is really practical but I'll show you how building a multi-value "key" can be possible using JavaScript primitives – don't take this to mean Bergi's answer is bad in anyway; in fact, it's actually a lot better because of it's practicality. If anything, this answer exists to show you how much work is saved by using an approach like his.

I'm going to go over the code bit-by-bit and then I'll have a complete runnable demo at the end.

compound data equality

Comparing compound data in JavaScript is a little tricky, so we're gonna need to figure out a way around this first:

console.log([1,2] === [1,2]) // false```
</div>
</div>
</p>

<p>I want to cover <em>a</em> solution for the multi-value key because our entire answer will be based upon it - here I'm calling it a <code>CollationKey</code>. Our key holds some value and defines its own equality function which is used for comparing keys</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const CollationKey = eq => x => ({
  x,
  eq: ({x: y}) => eq(x, y)
})

const myKey = CollationKey (([x1, x2], [y1, y2]) =>
  x1 === y1 && x2 === y2)

const k1 = myKey([1, 2])
const k2 = myKey([1, 2])
console.log(k1.eq(k2)) // true
console.log(k2.eq(k1)) // true

const k3 = myKey([3, 4])
console.log(k1.eq(k3)) // false</code>```

wishful thinking

Now that we have a way to compare compound data, I want to make a custom reducing function that uses our multi-value key to group values. I'll call this function collateBy

```<code>// key = some function that makes our key
// reducer = some function that does our reducing
// xs = some input array
const collateBy = key => reducer => xs => {
  // ...?
}

// our custom key;
// equality comparison of `group` and `question.templateId` properties
const myKey = CollationKey ((x, y) =>
  x.group === y.group
    && x.question.templateId === y.question.templateId)

const result =
  collateBy (myKey) // multi-value key
            ((group=[], x) => [...group, x]) // reducing function: (accumulator, elem)
            (arr) // input array
</code>```

So now that we know how we want collateBy to work, let's implement it

```<code>const collateBy = key => reducer => xs => {
  return xs.reduce((acc, x) => {
    const k = key(x)
    return acc.set(k, reducer(acc.get(k), x))
  }, Collation())
}
</code>```

Collation data container

Ok, so we were being a little optimistic there too using Collation() as the starting value for the xs.reduce call. What should Collation be?

What we know:

someCollation.set accepts a CollationKey and some value, and returns a new Collation

someCollation.get accepts a CollationKey and returns some value

Well let's get to work!

```<code>const Collation = (pairs=[]) => ({
  has (key) {
    return pairs.some(([k, v]) => key.eq(k))
  },
  get (key) {
    return (([k, v]=[]) => v)(
      pairs.find(([k, v]) => k.eq(key))
    )
  },
  set (key, value) {
    return this.has(key)
      ? Collation(pairs.map(([k, v]) => k.eq(key) ? [key, value] : [k, v]))
      : Collation([...pairs, [key, value]])
  },
})
</code>```

finishing up

So far our collateBy function returns a Collation data container which is internally implemented with an array of [key, value] pairs, but what we really want back (according to your question) is just an array of values

Let's modify collateBy in the slightest way that extracts the values – changes in bold

```<code>const collateBy = key => reducer => xs => {
  return xs.reduce((acc, x) => {
    let k = key(x)
    return acc.set(k, reducer(acc.get(k), x))
  }, Collation())<b>.values()</b>
}</code>```

So now we will add the values method to our Collation container

```<code>values () {
  return pairs.map(([k, v]) => v)
}
</code>```

runnable demo

That's everything, so let's see it all work now – I used JSON.stringify in the output so that the deeply nested objects would display all content

// data containers
const CollationKey = eq => x => ({
  x,
  eq: ({x: y}) => eq(x, y)
})

const Collation = (pairs=[]) => ({
  has (key) {
    return pairs.some(([k, v]) => key.eq(k))
  },
  get (key) {
    return (([k, v]=[]) => v)(
      pairs.find(([k, v]) => k.eq(key))
    )
  },
  set (key, value) {
    return this.has(key)
      ? Collation(pairs.map(([k, v]) => k.eq(key) ? [key, value] : [k, v]))
      : Collation([...pairs, [key, value]])
  },
  values () {
    return pairs.map(([k, v]) => v)
  }
})

// collateBy
const collateBy = key => reducer => xs => {
  return xs.reduce((acc, x) => {
    const k = key(x)
    return acc.set(k, reducer(acc.get(k), x))
  }, Collation()).values()
}

// custom key used for your specific collation
const myKey =
  CollationKey ((x, y) =>
    x.group === y.group
      && x.question.templateId === y.question.templateId)

// your data
const arr = [ { group: 1, question: { templateId: 100 } }, { group: 2, question: { templateId: 200 } }, { group: 1, question: { templateId: 100 } }, { group: 1, question: { templateId: 300 } } ]

// your answer
const result =
  collateBy (myKey) ((group=[], x) => [...group, x]) (arr)

console.log(result)
// [
//   [
//     {group:1,question:{templateId:100}},
//     {group:1,question:{templateId:100}}
//   ],
//   [
//     {group:2,question:{templateId:200}}
//   ],
//   [
//     {group:1,question:{templateId:300}}
//   ]
// ]```

summary

We made a custom collation function which uses a multi-value key for grouping our collated values. This was done using nothing but JavaScript primitives and higher-order functions. We now have a way to iterate thru a data set and collate it in an arbitrary way using keys of any complexity.

If you have any questions about this, I'm happy to answer them ^_^

Body:
Ex:

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

Expected Result: const result = groupBy(arr, 'group', 'question.templateId');

const result = [
  [{
    group: 1,
    question: {
      templateId: 100
    }
  }, {
    group: 1,
    question: {
      templateId: 100
    }
  }],
  [{
    group: 1,
    question: {
      templateId: 300
    }
  }],
  [{
    group: 2,
    question: {
      templateId: 200
    }
  }]
];

So far: I am able to group the result by a single property using Array.prototype.reduce().

function groupBy(arr, key) {
  return [...arr.reduce((accumulator, currentValue) => {
    const propVal = currentValue[key],
      group = accumulator.get(propVal) || [];
    group.push(currentValue);
    return accumulator.set(propVal, group);
  }, new Map()).values()];
}

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

const result = groupBy(arr, 'group');

console.log(result);

Body:
@Bergi's answer is really practical but I'll show you how building a multi-value "key" can be possible using JavaScript primitives – don't take this to mean Bergi's answer is bad in anyway; in fact, it's actually a lot better because of it's practicality. If anything, this answer exists to show you how much work is saved by using an approach like his.

I'm going to go over the code bit-by-bit and then I'll have a complete runnable demo at the end.

compound data equality

Comparing compound data in JavaScript is a little tricky, so we're gonna need to figure out a way around this first:

console.log([1,2] === [1,2]) // false

I want to cover a solution for the multi-value key because our entire answer will be based upon it - here I'm calling it a CollationKey. Our key holds some value and defines its own equality function which is used for comparing keys

const CollationKey = eq => x => ({
  x,
  eq: ({x: y}) => eq(x, y)
})

const myKey = CollationKey (([x1, x2], [y1, y2]) =>
  x1 === y1 && x2 === y2)

const k1 = myKey([1, 2])
const k2 = myKey([1, 2])
console.log(k1.eq(k2)) // true
console.log(k2.eq(k1)) // true

const k3 = myKey([3, 4])
console.log(k1.eq(k3)) // false

wishful thinking

Now that we have a way to compare compound data, I want to make a custom reducing function that uses our multi-value key to group values. I'll call this function collateBy

// key = some function that makes our key
// reducer = some function that does our reducing
// xs = some input array
const collateBy = key => reducer => xs => {
  // ...?
}

// our custom key;
// equality comparison of `group` and `question.templateId` properties
const myKey = CollationKey ((x, y) =>
  x.group === y.group
    && x.question.templateId === y.question.templateId)

const result =
  collateBy (myKey) // multi-value key
            ((group=[], x) => [...group, x]) // reducing function: (accumulator, elem)
            (arr) // input array

So now that we know how we want collateBy to work, let's implement it

const collateBy = key => reducer => xs => {
  return xs.reduce((acc, x) => {
    const k = key(x)
    return acc.set(k, reducer(acc.get(k), x))
  }, Collation())
}

Collation data container

Ok, so we were being a little optimistic there too using Collation() as the starting value for the xs.reduce call. What should Collation be?

What we know:

someCollation.set accepts a CollationKey and some value, and returns a new Collation

someCollation.get accepts a CollationKey and returns some value

Well let's get to work!

const Collation = (pairs=[]) => ({
  has (key) {
    return pairs.some(([k, v]) => key.eq(k))
  },
  get (key) {
    return (([k, v]=[]) => v)(
      pairs.find(([k, v]) => k.eq(key))
    )
  },
  set (key, value) {
    return this.has(key)
      ? Collation(pairs.map(([k, v]) => k.eq(key) ? [key, value] : [k, v]))
      : Collation([...pairs, [key, value]])
  },
})

finishing up

So far our collateBy function returns a Collation data container which is internally implemented with an array of [key, value] pairs, but what we really want back (according to your question) is just an array of values

Let's modify collateBy in the slightest way that extracts the values – changes in bold

const collateBy = key => reducer => xs => {
  return xs.reduce((acc, x) => {
    let k = key(x)
    return acc.set(k, reducer(acc.get(k), x))
  }, Collation()).values()
}

So now we will add the values method to our Collation container

values () {
  return pairs.map(([k, v]) => v)
}

runnable demo

That's everything, so let's see it all work now – I used JSON.stringify in the output so that the deeply nested objects would display all content

// data containers
const CollationKey = eq => x => ({
  x,
  eq: ({x: y}) => eq(x, y)
})

const Collation = (pairs=[]) => ({
  has (key) {
    return pairs.some(([k, v]) => key.eq(k))
  },
  get (key) {
    return (([k, v]=[]) => v)(
      pairs.find(([k, v]) => k.eq(key))
    )
  },
  set (key, value) {
    return this.has(key)
      ? Collation(pairs.map(([k, v]) => k.eq(key) ? [key, value] : [k, v]))
      : Collation([...pairs, [key, value]])
  },
  values () {
    return pairs.map(([k, v]) => v)
  }
})

// collateBy
const collateBy = key => reducer => xs => {
  return xs.reduce((acc, x) => {
    const k = key(x)
    return acc.set(k, reducer(acc.get(k), x))
  }, Collation()).values()
}

// custom key used for your specific collation
const myKey =
  CollationKey ((x, y) =>
    x.group === y.group
      && x.question.templateId === y.question.templateId)

// your data
const arr = [ { group: 1, question: { templateId: 100 } }, { group: 2, question: { templateId: 200 } }, { group: 1, question: { templateId: 100 } }, { group: 1, question: { templateId: 300 } } ]

// your answer
const result =
  collateBy (myKey) ((group=[], x) => [...group, x]) (arr)

console.log(result)
// [
//   [
//     {group:1,question:{templateId:100}},
//     {group:1,question:{templateId:100}}
//   ],
//   [
//     {group:2,question:{templateId:200}}
//   ],
//   [
//     {group:1,question:{templateId:300}}
//   ]
// ]

summary

We made a custom collation function which uses a multi-value key for grouping our collated values. This was done using nothing but JavaScript primitives and higher-order functions. We now have a way to iterate thru a data set and collate it in an arbitrary way using keys of any complexity.

If you have any questions about this, I'm happy to answer them ^_^


来源: stackexchange

问:
GoogleMap Uncaught TypeError: Cannot set property 'position' of undefined
I am trying to display google map using backbonejs below.

```<code>define([
'require',
'backbone',
'text!../templates/list.html',
], function(Require, Backbone, Template){
    return Backbone.View.extend({
        tagName: 'div',
        template: _.template(Template),
        initialize: function(){
            this.render();
        },
        render: function(){
            var self = this;
            this.$el.html(this.template());
            self.initMap();
        },
        initMap: function(){
            var target = { lat: 1.098706, lng: 104.026971 };
            var mapOption = {zoom: 12, center: target };
            var mapElem = $(".container").find("#map-canvas");
            var map = new google.maps.Map(mapElem, mapOption);
            var marker = new google.maps.Marker({
                position: target,
                map: map
            });
        },
    });
</code>```

});

After render finish, I got this error:

Uncaught TypeError: Cannot set property 'position' of undefined

I am still confused about where 'position' came from.
I've tried some solutions from here and here

Have you some ideas to fix it?
Thanks.

答:
Try changing

```<code>var mapElem = $(".container").find("#map-canvas");
</code>```

to

```<code>var mapElem = $(".container").find("#map-canvas")[0];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to display google map using backbonejs below.

define([
'require',
'backbone',
'text!../templates/list.html',
], function(Require, Backbone, Template){
    return Backbone.View.extend({
        tagName: 'div',
        template: _.template(Template),
        initialize: function(){
            this.render();
        },
        render: function(){
            var self = this;
            this.$el.html(this.template());
            self.initMap();
        },
        initMap: function(){
            var target = { lat: 1.098706, lng: 104.026971 };
            var mapOption = {zoom: 12, center: target };
            var mapElem = $(".container").find("#map-canvas");
            var map = new google.maps.Map(mapElem, mapOption);
            var marker = new google.maps.Marker({
                position: target,
                map: map
            });
        },
    });

});

After render finish, I got this error:

Uncaught TypeError: Cannot set property 'position' of undefined

I am still confused about where 'position' came from.
I've tried some solutions from here and here

Have you some ideas to fix it?
Thanks.

Body:
Try changing

var mapElem = $(".container").find("#map-canvas");

to

var mapElem = $(".container").find("#map-canvas")[0];


问:
Is the batch size specified for each GPU in tensorflow
In Tensorflow models example (slim) , when we specify the batch size is it per GPU or is that the total batch size split among the gpus ?

python train_image_classifier.py     --dataset_name=flowers     --dataset_split_name=train     --dataset_dir=/tmp/flowers-data     --model_name=inception_v3     --log_every_n_steps=10   --batch_size=64     --max_number_of_steps=100     --num_clones=4

答: That depends on how the specific model was implemented. In this case I believe it's the per-gpu batch size, but that's only if you're using the model I'm thinking of. The source code should be clearer.</p>


问:
NOT EXIST clause
I am trying to find Products that have never been ordered. My 2 tables look like this.

```<code>CREATE TABLE Orders
(OrderNum    NUMBER(10)      NOT NULL,
 OrderDate   DATE            NOT NULL,
 Cust        NUMBER(10),
 Rep         NUMBER(10),
 Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Qty         NUMBER(5)       NOT NULL,
 Amount      NUMBER(9,2)     NOT NULL,
 CONSTRAINT OrdersPK
      PRIMARY KEY (OrderNum));

CREATE TABLE Products
(Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Description VARCHAR2(20)    NOT NULL,
 Price       NUMBER(9,2)     NOT NULL,
 QtyOnHand   NUMBER(5),
 CONSTRAINT ProductsPK
      PRIMARY KEY (Mfr, Product));
</code>```

The code I currently have looks like this.

```<code>SELECT Mfr, Product
FROM Products
WHERE NOT EXISTS (SELECT Products.Mfr
                  FROM Orders, Products
                  WHERE Orders.Mfr = Products.Mfr);
</code>```

Although I am not getting any errors there are also no results showing up.

**EDIT: There are 26 Products and 19 of them have been ordered. I am expecting to get 7 Results but I am getting 0.

答:
Try this one</p>

```<code>SELECT Mfr, Product
FROM Products
WHERE NOT EXISTS (SELECT Orders.Mfr
                  FROM Orders
                  WHERE Orders.Mfr = Products.Mfr AND Orders.Product = Products.Product);
</code>```

Title: NOT EXIST clause

Body:
I am trying to find Products that have never been ordered. My 2 tables look like this.

CREATE TABLE Orders
(OrderNum    NUMBER(10)      NOT NULL,
 OrderDate   DATE            NOT NULL,
 Cust        NUMBER(10),
 Rep         NUMBER(10),
 Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Qty         NUMBER(5)       NOT NULL,
 Amount      NUMBER(9,2)     NOT NULL,
 CONSTRAINT OrdersPK
      PRIMARY KEY (OrderNum));

CREATE TABLE Products
(Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Description VARCHAR2(20)    NOT NULL,
 Price       NUMBER(9,2)     NOT NULL,
 QtyOnHand   NUMBER(5),
 CONSTRAINT ProductsPK
      PRIMARY KEY (Mfr, Product));

The code I currently have looks like this.

SELECT Mfr, Product
FROM Products
WHERE NOT EXISTS (SELECT Products.Mfr
                  FROM Orders, Products
                  WHERE Orders.Mfr = Products.Mfr);

Although I am not getting any errors there are also no results showing up.

**EDIT: There are 26 Products and 19 of them have been ordered. I am expecting to get 7 Results but I am getting 0.

Body:
Try this one

SELECT Mfr, Product
FROM Products
WHERE NOT EXISTS (SELECT Orders.Mfr
                  FROM Orders
                  WHERE Orders.Mfr = Products.Mfr AND Orders.Product = Products.Product);


问:
controller not sending data back to ajax request codeigniter
I have developed a login system using ajax the problem is when i send the ajax request everything is working and validating fine i just need to pass data back to my ajax request I am using echo json_encode("true"); but somehow it is just echoing the value true in the controller and not going back in the view!

HTML

```<code>  <form onsubmit="return validate()" method="post" action="<?php echo base_url(); ?>admin/admin_login">
        <input class="md-input" placeholder="username" type="text" name = 'login_username'  id = 'login_username' />
        <input class="md-input" placeholder="password" type="password" name= 'login_password'  id= 'login_password' />
        <button type='submit' class="btn btn-primary btn-block btn-large">Login</button>
    </form>
</code>```

AJAX

```<code><script>

    function validate(){
        if(!$("#login_username").val()){
            alert("username is required");
            return false;
        }
        if(!$("#login_password").val()){
            alert("Password is required");
            return false;
        }
        return true;
        var data={
            "login_username" : $("#login_username").val(),
            "login_password" : $("#login_password").val()
        };
        $.ajax({
            type: 'post',
            url: '<?=base_url()?>Admin/admin_login',
            dataType: 'json',
            data:data,
            success: function (data) {
                if(data=="true"){
                    alert("ok");
                }
                else
                {
                    alert("not ok");
                }
            }
        });
    }
</script>
</code>```

admin_login controller

```<code> public function admin_login(){
        $data = $this->input->post();
        $status=$this->admin_validate->validate($data);
        if($status){
            $session=array(
                "admin"=>$this->input->post("login_username"),
            );

            $this->session->set_userdata($session);
            //redirect("Admin/contact");
            header('Content-Type: application/json');
            echo json_encode("true");
        }
        else
        {
            header('Content-Type: application/json');
            echo json_encode("false");
            //redirect("Admin");
        }
    }
</code>```

答:
Have you tried sending true or false without the quotation marks?, if not try creating an array and then passing it to the echo json_encode(); something like:

```<code>$result = array();
array_push($result, true);

echo json_encode($result);
</code>```

on your ajax you will have to read it as follow

```<code>if(data[0] == true){
    alert("Ok");
}else{
    alert("Not OK");
}
</code>```

Hope it helps

ContentLicense: CC BY-SA 4.0

Body:
I have developed a login system using ajax the problem is when i send the ajax request everything is working and validating fine i just need to pass data back to my ajax request I am using echo json_encode("true"); but somehow it is just echoing the value true in the controller and not going back in the view!

HTML

  <form onsubmit="return validate()" method="post" action="<?php echo base_url(); ?>admin/admin_login">
        <input class="md-input" placeholder="username" type="text" name = 'login_username'  id = 'login_username' />
        <input class="md-input" placeholder="password" type="password" name= 'login_password'  id= 'login_password' />
        <button type='submit' class="btn btn-primary btn-block btn-large">Login</button>
    </form>

AJAX

admin_login controller

 public function admin_login(){
        $data = $this->input->post();
        $status=$this->admin_validate->validate($data);
        if($status){
            $session=array(
                "admin"=>$this->input->post("login_username"),
            );

            $this->session->set_userdata($session);
            //redirect("Admin/contact");
            header('Content-Type: application/json');
            echo json_encode("true");
        }
        else
        {
            header('Content-Type: application/json');
            echo json_encode("false");
            //redirect("Admin");
        }
    }

Body:
Have you tried sending true or false without the quotation marks?, if not try creating an array and then passing it to the echo json_encode(); something like:

$result = array();
array_push($result, true);

echo json_encode($result);

on your ajax you will have to read it as follow

if(data[0] == true){
    alert("Ok");
}else{
    alert("Not OK");
}

Hope it helps


问:
Array in Ruby on rails, undefined method `minimum'
```<code>@click = Missing.select{|d| d.click < 10000}

find = @click.minimum(:id)
@data = Missing.where(id: find)
dataSize = @data.size
@renderData = @data[dataSize - 1]
render :json => @renderData
</code>```

Errors:

```<code>undefined method `minimum' for #<Array:0x00000004acd678>

Error code : find = @click.minimum(:id)
</code>```

I have no idea why it is wrong.

render :json = @click is working.
 find = Missing.minimum(:id) is working.

答:
@click = Missing.select{|d| d.click < 10000} is returning an array of active record instances. This is why minimum can not be called against an array.

If you want the first record in the @click set then use @click.first.id. If you want the smallest (min) id then use @click.map(&:id).min. Looking at your code i'm not sure what you are trying to achieve?

On a side note, i'd avoid calling Missing.select{|d| d.click < 10000} because that is doing a full table scan on your Missing model's table. As Ruby Racer says, better to query with active record.

Body:
@click = Missing.select{|d| d.click < 10000}

find = @click.minimum(:id)
@data = Missing.where(id: find)
dataSize = @data.size
@renderData = @data[dataSize - 1]
render :json => @renderData

Errors:

undefined method `minimum' for #<Array:0x00000004acd678>

Error code : find = @click.minimum(:id)

I have no idea why it is wrong.

render :json = @click is working.
 find = Missing.minimum(:id) is working.


问:
Cake NuGetRestore always wants MSBuild14?
While trying to rig up a solution to build with Cake v0.19.1 on a machine that has only ever known Visual Studio 2017, I can't seem to get NuGetRestore to accept a setting of MSBuildVersion = NuGetMSBuildVersion.MSBuild15.

Is there some magic step to getting a specific MSBuild version into NuGetRestore that I am missing?

Output

```<code>...

========================================
RestoreNuGet
========================================
Executing task: RestoreNuGet
Failed to load msbuild Toolset
  Could not load file or assembly 'Microsoft.Build, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
An error occurred when executing task 'RestoreNuGet'.
Error: NuGet: Process returned an error (exit code 1).
</code>```

Trimmed-down build.cake

```<code>var target = Argument("target", "Default");
var solution = "./some-random.sln";

Task("Default")
.Does(() => {
    NuGetRestore(
        solution,
        new NuGetRestoreSettings {
            MSBuildVersion = NuGetMSBuildVersion.MSBuild15,
        }
    );
});

RunTarget(target);
</code>```

Update: getting NuGet v4

Per @devlead's answer, I pointed the build.ps1 file at the v4.0.0 of NuGet and got this output.

```<code>Cannot find the specified version of msbuild: '15'
An error occurred when executing task 'RestoreNuGet'.
Error: NuGet: Process returned an error (exit code 1).
</code>```

In my full build.cake, I use vswhere for later MSBuildSettings which I can get to dump out the MSBuild path it found (and I confirmed that exe exists in Explorer).

```<code>C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/MSBuild/15.0/Bin/amd64/MSBuild.exe
</code>```

答:
What you could try is to use the MSBuild alias with the restore target, latest version of MSBuild should have build in NuGet support.</p>

```<code>MSBuild(
    "./some.sln",
    configurator => configurator.WithTarget("restore"));
</code>```

Body:
While trying to rig up a solution to build with Cake v0.19.1 on a machine that has only ever known Visual Studio 2017, I can't seem to get NuGetRestore to accept a setting of MSBuildVersion = NuGetMSBuildVersion.MSBuild15.

Is there some magic step to getting a specific MSBuild version into NuGetRestore that I am missing?

Output

...

========================================
RestoreNuGet
========================================
Executing task: RestoreNuGet
Failed to load msbuild Toolset
  Could not load file or assembly 'Microsoft.Build, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
An error occurred when executing task 'RestoreNuGet'.
Error: NuGet: Process returned an error (exit code 1).

Trimmed-down build.cake

var target = Argument("target", "Default");
var solution = "./some-random.sln";

Task("Default")
.Does(() => {
    NuGetRestore(
        solution,
        new NuGetRestoreSettings {
            MSBuildVersion = NuGetMSBuildVersion.MSBuild15,
        }
    );
});

RunTarget(target);

Update: getting NuGet v4

Per @devlead's answer, I pointed the build.ps1 file at the v4.0.0 of NuGet and got this output.

Cannot find the specified version of msbuild: '15'
An error occurred when executing task 'RestoreNuGet'.
Error: NuGet: Process returned an error (exit code 1).

In my full build.cake, I use vswhere for later MSBuildSettings which I can get to dump out the MSBuild path it found (and I confirmed that exe exists in Explorer).

C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/MSBuild/15.0/Bin/amd64/MSBuild.exe

Body:
What you could try is to use the MSBuild alias with the restore target, latest version of MSBuild should have build in NuGet support.

MSBuild(
    "./some.sln",
    configurator => configurator.WithTarget("restore"));


问:
using a var as a number and then skip if value is less then x
I am trying to develop a 1 script does many jobs - it is to stop applications within our system etc.

So in this script I want the ability to stop 10 applications, so in the script I am passing a var -  genesysNumApps: "{{ genesysNumApps }}" - this is defined in the ansible command.

But then I want to say in the script if this value is equal or less then 5, do not do the following command.

Is this possible?

I am not a expert in this stuff, we have just been given these tasks and I do not want 20 scripts doing the same things but for different applications.

Many thanks, and sorry if I have not explained it clearly

Sorry guys - learning about this forum to lol

The script is running Linux commands and is using a Genesys command interface to stop certain applications

vars:

```<code>genesysNumApps: "{{ genesysNumApps }}"
</code>```

action: skip

only_if: '{{ genesysNumApps }}' = '5'

Martin

答:
I'm not quite positive I understand but you can have conditionals on tasks like this:</p>

```<code>- debug:
    msg: "Run this task if genesysNumApps is 5."
  when: genesysNumApps == 5
</code>```

Body:
I am trying to develop a 1 script does many jobs - it is to stop applications within our system etc.

So in this script I want the ability to stop 10 applications, so in the script I am passing a var -  genesysNumApps: "{{ genesysNumApps }}" - this is defined in the ansible command.

But then I want to say in the script if this value is equal or less then 5, do not do the following command.

Is this possible?

I am not a expert in this stuff, we have just been given these tasks and I do not want 20 scripts doing the same things but for different applications.

Many thanks, and sorry if I have not explained it clearly

Sorry guys - learning about this forum to lol

The script is running Linux commands and is using a Genesys command interface to stop certain applications

vars:

genesysNumApps: "{{ genesysNumApps }}"

action: skip

only_if: '{{ genesysNumApps }}' = '5'

Martin

Body:
I'm not quite positive I understand but you can have conditionals on tasks like this:

- debug:
    msg: "Run this task if genesysNumApps is 5."
  when: genesysNumApps == 5


问:
Cannot get data from related models in Rails
I have 2 models in different namespace.

```<code>class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end
</code>```

The Membership model is in different folder with AuthorizationRole model (I don't know what is called)

When run Admin::Membership.find(:all), the data from AuthorizationRole model is not included. I've create membership_id field on authorization_roles table, but I still can't get both models related. Is something wrong in this code? Sorry if I'm missing something basic here.

答:
I've never used namespaced models and I don't think you need to... but maybe you'll have to specify the class name in AuthorizationRole, something like:

```<code>belongs_to :membership, :class_name => 'Admin::Membership'
</code>```

UPDATE:

Assuming you have:

```<code>class Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end
</code>```

You have added an integer column called membership_id to authorization_roles and you've run the migrations. Now you should be able to create authorization_roles like this @membership.authorization_roles.create( ... ) and fetch them @membership.authorization_roles

ContentLicense: CC BY-SA 2.5

Body:
I have 2 models in different namespace.

class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end

The Membership model is in different folder with AuthorizationRole model (I don't know what is called)

When run Admin::Membership.find(:all), the data from AuthorizationRole model is not included. I've create membership_id field on authorization_roles table, but I still can't get both models related. Is something wrong in this code? Sorry if I'm missing something basic here.

Body:
I've never used namespaced models and I don't think you need to... but maybe you'll have to specify the class name in AuthorizationRole, something like:

belongs_to :membership, :class_name => 'Admin::Membership'

UPDATE:

Assuming you have:

class Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end

You have added an integer column called membership_id to authorization_roles and you've run the migrations. Now you should be able to create authorization_roles like this @membership.authorization_roles.create( ... ) and fetch them @membership.authorization_roles


问:
File output was overwritten using tee within Bash Shell script
I was trying to learn how exec and tee work and encountered something I could not understand:

```<code># create a log.out file in current directory
log=$(echo $(pwd)/log.out)

# start redirect
# 3 holds stdout, 4 holds stderr
# 1 & 2 points to log.out
exec 3>&1 4>&2 &>${log}

# print 'Have a good day everyone!' to both log.out and stdout
echo 'Have a good day everyone!' | tee ${log} 1>&3
echo 'Ciao!'
echo 'Bye!'

# end redirect
exec 1>&3 2>&4 3>&- 4>&-
</code>```

When I went into log.out file, I got this:

```<code>Ciao!
Bye!
 day everyone!
</code>```

I was expecting:

```<code>Have a good day everyone!
Ciao!
Bye!
</code>```

Please help me understand what is going on here and how to resolve this.

Thank you.

If this is duplicate, please close and give me the link to the solution.

答:
What's happening here is that while tee is adding content to your file, the existing open file pointer created by exec &>log.out is still back at the beginning of that file. Thus, when you start writing to that file pointer, those writes start at the beginning, despite other contents having been written by tee.

If you want to ensure that content is always added to the end of the file, even if other software has modified where that end-of-the-file location is, then you should ensure that the O_APPEND flag is used on open.

To do this, use >> rather than > for your redirection:

```<code>exec 3>&1 4>&2 &>>${log}
</code>```

Body:
I was trying to learn how exec and tee work and encountered something I could not understand:

# create a log.out file in current directory
log=$(echo $(pwd)/log.out)

# start redirect
# 3 holds stdout, 4 holds stderr
# 1 & 2 points to log.out
exec 3>&1 4>&2 &>${log}

# print 'Have a good day everyone!' to both log.out and stdout
echo 'Have a good day everyone!' | tee ${log} 1>&3
echo 'Ciao!'
echo 'Bye!'

# end redirect
exec 1>&3 2>&4 3>&- 4>&-

When I went into log.out file, I got this:

Ciao!
Bye!
 day everyone!

I was expecting:

Have a good day everyone!
Ciao!
Bye!

Please help me understand what is going on here and how to resolve this.

Thank you.

If this is duplicate, please close and give me the link to the solution.

Body:
What's happening here is that while tee is adding content to your file, the existing open file pointer created by exec &>log.out is still back at the beginning of that file. Thus, when you start writing to that file pointer, those writes start at the beginning, despite other contents having been written by tee.

If you want to ensure that content is always added to the end of the file, even if other software has modified where that end-of-the-file location is, then you should ensure that the O_APPEND flag is used on open.

To do this, use >> rather than > for your redirection:

exec 3>&1 4>&2 &>>${log}


问:
Stale Element reference error on finding the element -> when navigates back to previous page
My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.

It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.

Code is :

```<code>public class EcommerceSearchResult {

public static WebDriver driver ;

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow
    = driver.findElements
    (By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count);
        for(int i = 0 ; i<count ; i++)
        {
            List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
            System.out.println(gridrow.get(i).getText());
            listingelementinloop.get(i).click();
            driver.navigate().back();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        }

    }
}
</code>```

答:
In the loop you need to replace following line:

```<code>System.out.println(gridrow.get(i).getText());
</code>```

With

```<code>System.out.println(listingelementinloop.get(i).getText());
</code>```

As, elements in the gridrow list will become stale once you click on 'Back' button of browser.

Alternatively, following is another way of performing the same task:

```<code>public static WebDriver driver ;

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow
    = driver.findElements
    (By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count);
    for(int i = 1 ; i<=count ; i++)
        {
            WebElement element =
                driver.findElement(By.xpath(".//*[@id='grid_view_products_page_container']/div/div[" + i + "]"));
            System.out.println(element.getText());
            element.click();
            driver.navigate().back();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        }

}

}
</code>```

Let me know, if you have any further queries.

Body:
My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.

It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.

Code is :

public class EcommerceSearchResult {

public static WebDriver driver ;

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow
    = driver.findElements
    (By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count);
        for(int i = 0 ; i<count ; i++)
        {
            List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
            System.out.println(gridrow.get(i).getText());
            listingelementinloop.get(i).click();
            driver.navigate().back();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        }

    }
}

Body:
In the loop you need to replace following line:

System.out.println(gridrow.get(i).getText());

With

System.out.println(listingelementinloop.get(i).getText());

As, elements in the gridrow list will become stale once you click on 'Back' button of browser.

Alternatively, following is another way of performing the same task:

public static WebDriver driver ;

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow
    = driver.findElements
    (By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count);
    for(int i = 1 ; i<=count ; i++)
        {
            WebElement element =
                driver.findElement(By.xpath(".//*[@id='grid_view_products_page_container']/div/div[" + i + "]"));
            System.out.println(element.getText());
            element.click();
            driver.navigate().back();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        }

}

}

Let me know, if you have any further queries.


问:
Tensorflow "DataLossError: Checksum does not match" when used with supervisor
I've been using tensorflow with tf.train.Supervisor -

```<code>sv = tf.train.Supervisor(logdir=path, save_model_secs=900)
with sv.managed_session() as sess:
    if not sv.should_stop():
        #Rest of the code
</code>```

Recently, it crashed during training and since then it has been throwing the below error at the with sv.managed_session() line above -

DataLossError (see above for traceback): Checksum does not match: stored 1057608875 vs. calculated on the restored bytes 763056116

[[Node: save/RestoreV2_31 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/RestoreV2_31/tensor_names, save/RestoreV2_31/shape_and_slices)]]

Is it possible to fix it?

答: This means your checkpoint file got corrupted. Delete the latest version (i.e. the one with the largest global_step number) and try again and it should work.

Body:
I've been using tensorflow with tf.train.Supervisor -

sv = tf.train.Supervisor(logdir=path, save_model_secs=900)
with sv.managed_session() as sess:
    if not sv.should_stop():
        #Rest of the code

Recently, it crashed during training and since then it has been throwing the below error at the with sv.managed_session() line above -

DataLossError (see above for traceback): Checksum does not match: stored 1057608875 vs. calculated on the restored bytes 763056116

[[Node: save/RestoreV2_31 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/RestoreV2_31/tensor_names, save/RestoreV2_31/shape_and_slices)]]

Is it possible to fix it?


问:
Error when creating a new user account
I'm trying to insert a new collection into the database when a user creates their account for the first time, however, I'm getting an error.

Exception while invoking method 'createUser' TypeError: Cannot read property 'insert' of undefined

I've used similar code in the past and not had this problem.

Path: imports/startup/server/newUser.js

```<code>import { Meteor } from 'meteor/meteor';
import { Roles } from 'meteor/alanning:roles';
import { Accounts } from 'meteor/accounts-base';
import { Documents } from '../../api/documents/documents.js';

Accounts.onCreateUser((options, user) => {
      if (options.profile) {
        user.profile = options.profile;
      }

      Documents.insert({
        title: "Test Title",
        body: "Test Body"
      })

      return user;
    });
</code>```

Path: imports/api/documents/documents.js

```<code>import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { Factory } from 'meteor/dburles:factory';

const Documents = new Mongo.Collection('Documents');
export default Documents;

Documents.allow({
  insert: () => false,
  update: () => false,
  remove: () => false,
});

Documents.deny({
  insert: () => true,
  update: () => true,
  remove: () => true,
});

Documents.schema = new SimpleSchema({
  title: {
    type: String,
    label: 'The title of the document.',
  },
  body: {
    type: String,
    label: 'The body of the document.',
  },
});

Documents.attachSchema(Documents.schema);
</code>```

答:
So the answer to this was very simple. I posted this on the meteor forums and @jamgold provided the solution. Find answer here.

I used:

import { Documents } from '../../api/documents/documents.js';

Importing with brackets was incorrect becuase I was using the export default Documents. It should have been:

import Documents from '../../api/documents/documents.js';

Title: Error when creating a new user account

Body:
I'm trying to insert a new collection into the database when a user creates their account for the first time, however, I'm getting an error.

Exception while invoking method 'createUser' TypeError: Cannot read property 'insert' of undefined

I've used similar code in the past and not had this problem.

Path: imports/startup/server/newUser.js

import { Meteor } from 'meteor/meteor';
import { Roles } from 'meteor/alanning:roles';
import { Accounts } from 'meteor/accounts-base';
import { Documents } from '../../api/documents/documents.js';

Accounts.onCreateUser((options, user) => {
      if (options.profile) {
        user.profile = options.profile;
      }

      Documents.insert({
        title: "Test Title",
        body: "Test Body"
      })

      return user;
    });

Path: imports/api/documents/documents.js

import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { Factory } from 'meteor/dburles:factory';

const Documents = new Mongo.Collection('Documents');
export default Documents;

Documents.allow({
  insert: () => false,
  update: () => false,
  remove: () => false,
});

Documents.deny({
  insert: () => true,
  update: () => true,
  remove: () => true,
});

Documents.schema = new SimpleSchema({
  title: {
    type: String,
    label: 'The title of the document.',
  },
  body: {
    type: String,
    label: 'The body of the document.',
  },
});

Documents.attachSchema(Documents.schema);


问:
Arduino LCD2004D Sketch for Mega
I've been hunting this down for a couple of days now and simply haven't been making any headway.

I have a http://reprap.org/wiki/RepRapDiscount_Smart_Controller it came with a kit from china.

I'm trying to interact with the LCD, and the SD card reader.

Every single piece of info I can find tells me to use LiquidCrystal.h, All of them tell me what pins to use on an Uno, and every time I find someone with a Mega, the person is having the same problem as me, there's something hard coded somewhere, that does not translate to an Arduino Mega.

So simply put, can someone who has some experience with this, give a sketch for the MEGA + RAMPS1.4 + LCD2004D + SD Card Reader

This is what I have managed to get so far

```<code>#define LCD_RS 16
#define LCD_ENABLE 17
#define LCD_D1 23
#define LCD_D2 25
#define LCD_D3 27
#define LCD_D4 29

 //encoder pins
#define BTN_EN1 31
#define BTN_EN2 33
#define BTN_ENC 35

 //beeper
#define BEEPER 37

 //SD card detect pin
#define SDCARDDETECT 49

#define SDPOWER            -1
#define MOSI  51
#define MISO  50
#define SCK   52
#define SDSlaveSelect 53
</code>```

I have confirmed that these ARE the correct pins as connected via the RAMPS1.4 jumper board and EXT 1 and EXT 2 connectors, though I can't confirm that they are linked to what I have written here, since there's no real info for this that I can get my hands on.

And Please Please Please if you can help, or do help, make your answer easy to decode, because I will be working with the LCD Controller for now, and may upgrade later, so I hopefully will learn something here for when I switch controllers then!

(or a working sketch would be AweSome!)

Thank you anyone in advance.

答:
Here is the lcd 1602 model which is the smaller brother of the 2004,
https://www.sunfounder.com/learn/Super-Kit-V2-0-for-Arduino/lesson-8-lcd1602-super-kit.html
it illustrates how to connect and program for Arduino using the parallel connection which is similar to the 2004 model.

A lot of the lcds that i have seen for the 2004 model have a serial to parallel driver board which could be an option as driving an i2c board is easier to implement and uses less pins.

For example http://www.ebay.com/itm/IIC-I2C-TWI-SP-I-Serial-Interface-Board-Module-LCD1602-2004-Display-For-Arduino-/172591106177?hash=item282f3b4881:g:jDoAAOSw4CFY1JTI

i hope this has given you some ideas to try out.

Title: Arduino LCD2004D Sketch for Mega

Body:
I've been hunting this down for a couple of days now and simply haven't been making any headway.

I have a http://reprap.org/wiki/RepRapDiscount_Smart_Controller it came with a kit from china.

I'm trying to interact with the LCD, and the SD card reader.

Every single piece of info I can find tells me to use LiquidCrystal.h, All of them tell me what pins to use on an Uno, and every time I find someone with a Mega, the person is having the same problem as me, there's something hard coded somewhere, that does not translate to an Arduino Mega.

So simply put, can someone who has some experience with this, give a sketch for the MEGA + RAMPS1.4 + LCD2004D + SD Card Reader

This is what I have managed to get so far

#define LCD_RS 16
#define LCD_ENABLE 17
#define LCD_D1 23
#define LCD_D2 25
#define LCD_D3 27
#define LCD_D4 29

 //encoder pins
#define BTN_EN1 31
#define BTN_EN2 33
#define BTN_ENC 35

 //beeper
#define BEEPER 37

 //SD card detect pin
#define SDCARDDETECT 49

#define SDPOWER            -1
#define MOSI  51
#define MISO  50
#define SCK   52
#define SDSlaveSelect 53

I have confirmed that these ARE the correct pins as connected via the RAMPS1.4 jumper board and EXT 1 and EXT 2 connectors, though I can't confirm that they are linked to what I have written here, since there's no real info for this that I can get my hands on.

And Please Please Please if you can help, or do help, make your answer easy to decode, because I will be working with the LCD Controller for now, and may upgrade later, so I hopefully will learn something here for when I switch controllers then!

(or a working sketch would be AweSome!)

Thank you anyone in advance.


问:
Pythonic way of setting a label in matplotlib
I am iterating over many lists of gpx data to create a plot of cumulative training for 2016. To do so, I set up a loop as follows, where paces is a list of lists of smoothed pacing data from each gpx file and total_distances the associated distances computed from the coordinate data.

```<code>for i in range(0, len(paces)):

    if i == 0:
        # need offset on paces from filtered data/NaN
        plt.plot(total_distances[i:i+1][0],
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1],
                 linewidth=.5, ls='-', color='#00FF00', label = 'all runs')
    else:
        plt.plot(total_distances[i:i+1][0],
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1],
                 linewidth=.5, ls='-', color='#00FF00')
</code>```

If I do not use the above conditional, the label gets printed as many times as there are lists.

Any suggestions for a my pythonic way of doing this?

答:
Not having the actual data, I cannot test my answer, but I believe you should use this code:</p>

```<code>for i,(distance,pace) in enumerate(zip(total_distances, paces)):
    plt.plot(distance, pace[10:],
             linewidth=.5, ls='-', color='#00FF00',
             label='' if i else 'all runs')
</code>```

Body:
I am iterating over many lists of gpx data to create a plot of cumulative training for 2016. To do so, I set up a loop as follows, where paces is a list of lists of smoothed pacing data from each gpx file and total_distances the associated distances computed from the coordinate data.

for i in range(0, len(paces)):

    if i == 0:
        # need offset on paces from filtered data/NaN
        plt.plot(total_distances[i:i+1][0],
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1],
                 linewidth=.5, ls='-', color='#00FF00', label = 'all runs')
    else:
        plt.plot(total_distances[i:i+1][0],
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1],
                 linewidth=.5, ls='-', color='#00FF00')

If I do not use the above conditional, the label gets printed as many times as there are lists.

Any suggestions for a my pythonic way of doing this?

Body:
Not having the actual data, I cannot test my answer, but I believe you should use this code:

for i,(distance,pace) in enumerate(zip(total_distances, paces)):
    plt.plot(distance, pace[10:],
             linewidth=.5, ls='-', color='#00FF00',
             label='' if i else 'all runs')


问:
Mercurial v Git v Subversion
I need to choose a VCS to embed within a Java application I'm developing. The Java application will interact with the VCS via an API, but the user will also interact with it directly via an Eclipse plugin.

3 candidate VCS have been identified: Mercurial, Git and Subversion. I need to choose one based on the following criteria (in no particular order):

Java API. This is not 100% necessary, because the application could issue VCS commands via the command-line if no Java API is available. However, an API would obviously be preferable

Eclipse plugin

Simplicity. The people using the VCS (indirectly via the application or directly via Eclipse), will be software developers, but probably not the most sophisticated of the species.

Licensing. The license must permit to use of the VCS (in the manner described above) in a commercial application

There may be other considerations I've overlooked, I'll update the question if any more spring to mind.

Thanks!

答:
Java API: Subversion has bindings for Java, and there is some kind of reimplementation of Mercurial in Java going on (see the dev mailing list).

Eclipse Plugin: There are plugins that support all three for Eclipse.

Simplicity: Subversion arguably has a simpler model being centralised. Mercurial tends to be simpler than Git to learn and use, while otherwise being quite close in features.

Licensing: Git and Mercurial are GPLed, but you can invoke them via the command line with no licensing implications. Subversion uses the Apache license, which is not copyleft.

Now - why not write an interface that abstracts the differences so you can support all three?  Mercurial and Git are very similar, so it should be relatively straightforward to at least support these two.

Title: Mercurial v Git v Subversion


问:
Count sent sms messages for a single thread
I'm looking for the count of sent sms messages in a particular thread (say, with id 15). I found this How do I get the count of SMS messages per contact into a textview? <-- but it doesn't solve my issue, as it counts both sent and received sms messages. Is it possible to count only sent messages? I think I could query "content://sms/sent" and walk through each SMS, but I wonder if there's a more efficient way.

Thanks

答:
You can query Sms.Conversations with your thread ID, and a selection that restricts the TYPE column to MESSAGE_TYPE_SENT. Since you just want the count, we can do a SELECT COUNT() query, so there's no resources wasted building a Cursor with unused values. For example:

```<code>private int getThreadSentCount(String threadId) {
    final Uri uri = Sms.Conversations.CONTENT_URI
                    .buildUpon()
                    .appendEncodedPath(threadId)
                    .build();
    final String[] projection = {"COUNT(1)"};
    final String selection = Sms.TYPE + "=" + Sms.MESSAGE_TYPE_SENT;

    int count = -1;
    Cursor cursor = null;
    try {
        cursor = getContentResolver().query(uri,
                                            projection,
                                            selection,
                                            null,
                                            null);
        if (cursor != null && cursor.moveToFirst()) {
            count = cursor.getInt(0);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return count;
}
</code>```

The Sms class used above is in the android.provider.Telephony class.

```<code>import android.provider.Telephony.Sms;
</code>```

For reference, Sms.Conversations.CONTENT_URI is equivalent to Uri.parse("content://sms/conversations"), Sms.TYPE is "type", and Sms.MESSAGE_TYPE_SENT is 2.

Body:
You can query Sms.Conversations with your thread ID, and a selection that restricts the TYPE column to MESSAGE_TYPE_SENT. Since you just want the count, we can do a SELECT COUNT() query, so there's no resources wasted building a Cursor with unused values. For example:

private int getThreadSentCount(String threadId) {
    final Uri uri = Sms.Conversations.CONTENT_URI
                    .buildUpon()
                    .appendEncodedPath(threadId)
                    .build();
    final String[] projection = {"COUNT(1)"};
    final String selection = Sms.TYPE + "=" + Sms.MESSAGE_TYPE_SENT;

    int count = -1;
    Cursor cursor = null;
    try {
        cursor = getContentResolver().query(uri,
                                            projection,
                                            selection,
                                            null,
                                            null);
        if (cursor != null && cursor.moveToFirst()) {
            count = cursor.getInt(0);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return count;
}

The Sms class used above is in the android.provider.Telephony class.

import android.provider.Telephony.Sms;

For reference, Sms.Conversations.CONTENT_URI is equivalent to Uri.parse("content://sms/conversations"), Sms.TYPE is "type", and Sms.MESSAGE_TYPE_SENT is 2.


问:
Kendo UI Grid with Angular Web Api Multi-dimensional model
I am trying to use serverPaging with the Kendo UI grid.  In order to pass the total pages.  I am passing a model which consists of the data list, and the total count.  My problem is that I can't figure out how to parse the model in the Kendo grid.

Here is my Controller code:

```<code>$scope.mainGridOptions = {
  dataSource: {
      transport: {
          read: {
              url: '/SSQV4/SSQV5/Search/GetSearch',
              type: "GET"
          }
      },
      schema: {
          total: "Total"
      },
      pageSize: 25,
      serverPaging: true

  },
  sortable: true,
  pageable: true,
  resizable: true,

  columns: [{
      field: "CompanyID",
      title: "Company ID"

  }, {
      field: "CompanyName"

  }, {
      field: "City"

  }, {
      field: "State"

  }, {
      field: "Deficiencies"
  }]
</code>```

};

The data returned is a list ("results"), and the recordcount ("Total").  Normally, I would use a service to get the data and parse the two like below:

```<code>    myService.GetSearch()
.success(function(data)){
$scope.myDataList = data.results;
$scope.myDataCount = data.Total;
})
</code>```

I cannot figure out how to use "results" and "Total" in the Kendo Grid when it is returned by my web api.

Any assistance is greatly appreciated.

答:
I figured this one out.  I had to add "results" to the schema.  This worked:

```<code>$scope.mainGridOptions = {
    dataSource: {
        transport: {
            read: {
                url: '/SSQV4/SSQV5/Search/GetSearch',
                type: "GET"
            }
        },
        schema: {
            data: "results",
            total: "Total"
        },
        pageSize: 25,
        serverPaging: true

    },
  sortable: true,
  pageable: true,
  resizable: true,

  columns: [{
      field: "CompanyID",
      title: "Company ID"

  }, {
      field: "CompanyName"

  }, {
      field: "City"

  }, {
      field: "State"

  }, {
      field: "Deficiencies"
  }]
</code>```

};

Body:
I am trying to use serverPaging with the Kendo UI grid.  In order to pass the total pages.  I am passing a model which consists of the data list, and the total count.  My problem is that I can't figure out how to parse the model in the Kendo grid.

Here is my Controller code:

$scope.mainGridOptions = {
  dataSource: {
      transport: {
          read: {
              url: '/SSQV4/SSQV5/Search/GetSearch',
              type: "GET"
          }
      },
      schema: {
          total: "Total"
      },
      pageSize: 25,
      serverPaging: true

  },
  sortable: true,
  pageable: true,
  resizable: true,

  columns: [{
      field: "CompanyID",
      title: "Company ID"

  }, {
      field: "CompanyName"

  }, {
      field: "City"

  }, {
      field: "State"

  }, {
      field: "Deficiencies"
  }]

};

The data returned is a list ("results"), and the recordcount ("Total").  Normally, I would use a service to get the data and parse the two like below:

    myService.GetSearch()
.success(function(data)){
$scope.myDataList = data.results;
$scope.myDataCount = data.Total;
})

I cannot figure out how to use "results" and "Total" in the Kendo Grid when it is returned by my web api.

Any assistance is greatly appreciated.

Body:
I figured this one out.  I had to add "results" to the schema.  This worked:

$scope.mainGridOptions = {
    dataSource: {
        transport: {
            read: {
                url: '/SSQV4/SSQV5/Search/GetSearch',
                type: "GET"
            }
        },
        schema: {
            data: "results",
            total: "Total"
        },
        pageSize: 25,
        serverPaging: true

    },
  sortable: true,
  pageable: true,
  resizable: true,

  columns: [{
      field: "CompanyID",
      title: "Company ID"

  }, {
      field: "CompanyName"

  }, {
      field: "City"

  }, {
      field: "State"

  }, {
      field: "Deficiencies"
  }]

};


问:
When do I need to use a $ to refer to a variable in Bash?
For example, in my code sometime I do

```<code>$var
</code>```

and sometimes I just do

```<code>var
</code>```

Here is a more concrete example:

```<code>upstream() {
    push server_shared_shortname
    ssh $server_shared -t "cd  ~/public_html; git pull -q ~/root.git master"
}
</code>```

答:
On assigning to a variable, you do not use the $ prefix; e.g. var=1

This also applies to assignments in the contexts of variable-declaring builtins declare, local, and export.

On referencing a variable (its value) you do use $; e.g., echo "$var"

As an exception, there are arithmetic contexts in which you can and generally should reference variables without the $ prefix - see below.

Do note that this exception applies only to variables whose values are / can be interpreted as integers (Bash only supports integer arithmetic).

As in the example above, you should typically double-quote $-prefixed variable references (expansions) to prevent unwanted modification of the resulting value by the shell by way of its shell expansions, notably by splitting the value into multiple arguments by whitespace (word-splitting) and interpreting the value as a filename pattern (globbing).

Using the form ${...} (curly braces around the name / expansion expression) is necessary in the following cases:

Disambiguate the variable name in (expandable) strings where characters immediately follow the variable name that Bash would otherwise consider part of the variable name; e.g., echo "${HOME}grown".

Parameter expansions that transform the expanded value, such as by prefix and suffix trimming, string replacement, or substring extraction; e.g., echo "${HOME%/*}" yields something like /home, with the shortest suffix (%) matching pattern /* getting trimmed from the value of $HOME; in other words: the last path component is removed.

Arithmetic contexts, in which integer[-interpretable] variables generally need no $ prefix:

Explicit arithmetic contexts:

$(( ... )) (arithmetic expansion; a POSIX-compliant feature)

echo $(( var )) prints 1, the value of $var.

(( ... )) (arithmetic expression; a Bash extension)

Used as a conditional: (( var )) && echo 'yes' prints yes, because value 1, the value of $var, interpreted (conceptually) as a Boolean, is (conceptually) true.

Used to assign the result of a calculation to a variable:

(( sum = var + var )); echo "$sum" prints 2[1]

Implicit arithmetic contexts (all of which are Bash extensions):

Inside array indices:

arr=( one two ); ndx=0; echo "${arr[ndx+1]}" yields two

Inside substring / array-slicing operations (index and offset):

str='one'; ndx=0; echo "${str:ndx+1}" yields ne

arr=( one two three ); ndx=0; echo "${arr[@]: 0: ndx + 2 }" yields one two

Inside [[ ... ]] with arithmetic operators:

[[ 1 -eq var ]] && echo 'yes' yields yes.

Assignments to variables declared with declare -i or local -i, which marks them as integers:

declare -i sum; sum=var; echo "$sum" yields 1

declare -i sum=1; sum+=var; echo "$sum" yields 2

Caveat: Typically, it doesn't matter whether you reference variables in these contexts with or without the $ prefix - but there are subtle differences; in short, use the $ prefix in arithmetic contexts only in the following case:

You need a nonzero default value that you provide via a parameter expansion; e.g., ${var:-2} defaults to 2 if $var is unset or empty.

[1] (( ... )) has an older equivalent, the obsolescent let.

(( ... )) is preferable, because it doesn't require quoting and is more easily recognized as being related to

$(( ... )) (as well as being visually more distinctive).

Compare (( sum = var + var )) to let 'sum = var + var'

Body:
For example, in my code sometime I do

$var

and sometimes I just do

var

Here is a more concrete example:

upstream() {
    push server_shared_shortname
    ssh $server_shared -t "cd  ~/public_html; git pull -q ~/root.git master"
}


问:
How to mimic a "callback with promise" function parameter in rxjs?
I'm an absolute rxjs beginner. For me to start learning to think in observables, I need to translate concepts through code examples. I feel like if I can see the code for this, I can start to do this on my own with other concepts.

I do NOT want to CONVERT a promise to an observable, I want to make a new implementation using Observable that can behave like a promise. How would I re-write the following using Observables?

```<code> constructor(){
    let makeMessage2 = function(){
        return new Promise(resolve, reject){
           setTimeout(()=>{
                  var r = Math.random();
                  resolve("message two plus random value: " + r );
           }, 1000);
        }
    }
    this.logMessageAndResultOfCallback("message one!", makeMessage2);
}
private sideEffect1:string = "";
private sideEffect2:string = "";

logMessageAndResultOfCallback( message1:string, callback:Function ){
    console.log(message1);
    this.sideEffect1 = message1;

    callback().then((message2)=>{
          console.log(message2);
          this.sideEffect2 = message2;
    }
}
</code>```

I guess the part I don't understand is how to define the "callback" function, how to invoke it. I understand I would wait for the complete or emit handlers, like makeMessage2().subscribe(message2 => console.log(message2)); but I don't have any clue how to define makeMessage2.

This may be totally clueless question, but I've read about 10 different intros to rxjs and this hasn't quite clicked. I just need to map this scenario to observable pattern and I think I can understand it.

Basically, I want to define an observable function myObs() that does not "execute immediately" but "executes" whenever the someMethod(message:string,obs:Observable) is executed. When myObs is executed, it should do something ansynchronously within it (like get the result of a HTTP request) then set the next value, then fire a complete() so my observer defined in someMethod can handle the complete and do something with the result.

Edit: I'm not concerned with the timer or native equivalents in rxjs, this is just to simulate any async action, like getting data from the server.

答:
The code that you wrote and want to 'translate' to observables probably would not work. callback is a promise, not a function, so you can't write callback().

Did you try this introduction too? It worked for many people.

To answer your question, you could write

```<code>Rx.Observable.of(""message one!", "message two!")
  .map(console.log.bind(console)) // would be better to use `do` operator actually, for semantic reasons, but that works the same here
  .subscribe(noop, noop, noop)
</code>```

or

```<code>Rx.Observable.of(""message one!", "message two!")
  .subscribe(console.log.bind(console), noop, noop)
</code>```

where noop is a function that does not do anything, i.e. function noop(){}

In short, your stream emits data, that data flow through a series of operators, and the data flow is started by .subscribe. In your case, you have nothing interesting to do on subscription, because all you do is logging.

Rxjs Streams are in fact callback-based under the hood. You want to check this answer to understand it.

Body:
I'm an absolute rxjs beginner. For me to start learning to think in observables, I need to translate concepts through code examples. I feel like if I can see the code for this, I can start to do this on my own with other concepts.

I do NOT want to CONVERT a promise to an observable, I want to make a new implementation using Observable that can behave like a promise. How would I re-write the following using Observables?

 constructor(){
    let makeMessage2 = function(){
        return new Promise(resolve, reject){
           setTimeout(()=>{
                  var r = Math.random();
                  resolve("message two plus random value: " + r );
           }, 1000);
        }
    }
    this.logMessageAndResultOfCallback("message one!", makeMessage2);
}
private sideEffect1:string = "";
private sideEffect2:string = "";

logMessageAndResultOfCallback( message1:string, callback:Function ){
    console.log(message1);
    this.sideEffect1 = message1;

    callback().then((message2)=>{
          console.log(message2);
          this.sideEffect2 = message2;
    }
}

I guess the part I don't understand is how to define the "callback" function, how to invoke it. I understand I would wait for the complete or emit handlers, like makeMessage2().subscribe(message2 => console.log(message2)); but I don't have any clue how to define makeMessage2.

This may be totally clueless question, but I've read about 10 different intros to rxjs and this hasn't quite clicked. I just need to map this scenario to observable pattern and I think I can understand it.

Basically, I want to define an observable function myObs() that does not "execute immediately" but "executes" whenever the someMethod(message:string,obs:Observable) is executed. When myObs is executed, it should do something ansynchronously within it (like get the result of a HTTP request) then set the next value, then fire a complete() so my observer defined in someMethod can handle the complete and do something with the result.

Edit: I'm not concerned with the timer or native equivalents in rxjs, this is just to simulate any async action, like getting data from the server.

Body:
The code that you wrote and want to 'translate' to observables probably would not work. callback is a promise, not a function, so you can't write callback().

Did you try this introduction too? It worked for many people.

To answer your question, you could write

Rx.Observable.of(""message one!", "message two!")
  .map(console.log.bind(console)) // would be better to use `do` operator actually, for semantic reasons, but that works the same here
  .subscribe(noop, noop, noop)

or

Rx.Observable.of(""message one!", "message two!")
  .subscribe(console.log.bind(console), noop, noop)

where noop is a function that does not do anything, i.e. function noop(){}

In short, your stream emits data, that data flow through a series of operators, and the data flow is started by .subscribe. In your case, you have nothing interesting to do on subscription, because all you do is logging.

Rxjs Streams are in fact callback-based under the hood. You want to check this answer to understand it.


问:
Issue with Pandas DataFrame creating
I created a successful df, however, there's something wrong with the column names. they are not on the same row.

Anyone can give some advices? Appreciate it.

答:
The first "Column" isn't a column.  It's an index.

pandas wants to differentiate between the name of the index "Industry" and the name of the columns "YTD_change".  So it put's them on different lines.  It's purely formatting.

Try:

```<code>df.reset_index()
</code>```

Title: Issue with Pandas DataFrame creating

Body:
The first "Column" isn't a column.  It's an index.

pandas wants to differentiate between the name of the index "Industry" and the name of the columns "YTD_change".  So it put's them on different lines.  It's purely formatting.

Try:

df.reset_index()


问:
Keras (+tensorflow) cannot predict with only part of the sequential
I am now working on building a stereo matching network using Keras with tensorflow as backend. The network has the following structure:

After training the whole network, I need to test it. However, training phase and testing phase are quite different. I have to split the model into two parts. The first part is CNN+Concatenate which only needs to be run once, while the fully-connected part (actually I modify it to be fully-conv form when testing) needs to be run for d times with slightly different input, where d varies from 100 to 228.

The first part network code:

```<code># input image dimensions
img_rows, img_cols = X1.shape[0], X1.shape[1]
input_shape = (img_rows, img_cols, 1)
X1 = X1.reshape(1, img_rows, img_cols, 1)
X2 = X2.reshape(1, img_rows, img_cols, 1)

# number of conv filters to use
nb_filters = 112

# CNN kernel size
kernel_size = (3,3)

left_branch = Sequential()
left_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same', input_shape=input_shape))
left_branch.add(Activation('relu'))
left_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
left_branch.add(Activation('relu'))
left_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
left_branch.add(Activation('relu'))
left_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
left_branch.add(Activation('relu'))

right_branch = Sequential()
right_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same', input_shape=input_shape))
right_branch.add(Activation('relu'))
right_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
right_branch.add(Activation('relu'))
right_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
right_branch.add(Activation('relu'))
right_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
right_branch.add(Activation('relu'))
merged = Merge([left_branch, right_branch], mode='concat')

cnn = Sequential()
cnn.add(merged)
</code>```

I load the weights gained from training phase into the first part of the network and try to get prediction of it.

```<code>def load_cnn_weights(filepath):
    f = h5py.File(filepath, mode='r')
    weights = []
    for i in range(1, 9):
        weights.append(f['model_weights/conv2d_{}/conv2d_{}/kernel:0'.format(i, i)][()])
        weights.append(f['model_weights/conv2d_{}/conv2d_{}/bias:0'.format(i, i)][()])
    f.close()
    return weights

weights = load_cnn_weights("/home/users/shixin.li/segment/Lecun_stereo_rebuild/weights.hdf5")
cnn.set_weights(weights)
output_cnn = cnn.predict([X1, X2])
</code>```

I already check that the weights are read successfully and can fit into the network according to calling get_weights() function. X1 and X2 are not zero, they are normalized gray scale image matrix. I even tried compile the network before predict. But the result output_cnn gives all zero.

I didn't see anyone have this problem and I am stuck for two days. The part which really confuses me is that the input and weights are all not zero, then why the result is zero? If you could help, I would really appreciate that!

答: You might want to try using tfdbg to find out exactly what the inputs to the op with all-zero outputs are, to try to understand what is going on.</p>

Body:
I am now working on building a stereo matching network using Keras with tensorflow as backend. The network has the following structure:

After training the whole network, I need to test it. However, training phase and testing phase are quite different. I have to split the model into two parts. The first part is CNN+Concatenate which only needs to be run once, while the fully-connected part (actually I modify it to be fully-conv form when testing) needs to be run for d times with slightly different input, where d varies from 100 to 228.

The first part network code:

# input image dimensions
img_rows, img_cols = X1.shape[0], X1.shape[1]
input_shape = (img_rows, img_cols, 1)
X1 = X1.reshape(1, img_rows, img_cols, 1)
X2 = X2.reshape(1, img_rows, img_cols, 1)

# number of conv filters to use
nb_filters = 112

# CNN kernel size
kernel_size = (3,3)

left_branch = Sequential()
left_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same', input_shape=input_shape))
left_branch.add(Activation('relu'))
left_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
left_branch.add(Activation('relu'))
left_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
left_branch.add(Activation('relu'))
left_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
left_branch.add(Activation('relu'))

right_branch = Sequential()
right_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same', input_shape=input_shape))
right_branch.add(Activation('relu'))
right_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
right_branch.add(Activation('relu'))
right_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
right_branch.add(Activation('relu'))
right_branch.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='same'))
right_branch.add(Activation('relu'))
merged = Merge([left_branch, right_branch], mode='concat')

cnn = Sequential()
cnn.add(merged)

I load the weights gained from training phase into the first part of the network and try to get prediction of it.

def load_cnn_weights(filepath):
    f = h5py.File(filepath, mode='r')
    weights = []
    for i in range(1, 9):
        weights.append(f['model_weights/conv2d_{}/conv2d_{}/kernel:0'.format(i, i)][()])
        weights.append(f['model_weights/conv2d_{}/conv2d_{}/bias:0'.format(i, i)][()])
    f.close()
    return weights

weights = load_cnn_weights("/home/users/shixin.li/segment/Lecun_stereo_rebuild/weights.hdf5")
cnn.set_weights(weights)
output_cnn = cnn.predict([X1, X2])

I already check that the weights are read successfully and can fit into the network according to calling get_weights() function. X1 and X2 are not zero, they are normalized gray scale image matrix. I even tried compile the network before predict. But the result output_cnn gives all zero.

I didn't see anyone have this problem and I am stuck for two days. The part which really confuses me is that the input and weights are all not zero, then why the result is zero? If you could help, I would really appreciate that!


问:
Element changes in DOM in Chrome but doesn't appear on page
I am attempting to add an ajax loading message into Single Page application.  The code works by updating a DOM element when the first http request goes out, and adds an sequence number to an array, which gets added as an http header.  The application then monitors the header of requests coming back, removing items from the array, and when the array is empty, the loading message is changed.  The code below shows how the code is added and then removed from the array (it's an angular2 app, but this is done in plain javascript/typescript).  The code behaves perfectly in Firefox, however in Chrome, amazingly, even though the DOM updates (I can see the code change and the text of the element change to 'Loading' in devtools web inspector) the change never appears on the page  --   it stays as 'Not Loading anymore'. I'm wondering if this is possibly a bug in Chrome.

Below is the code for adding the DOM item.  This gets called immediately before a request is sent out to our API

```<code> private setSequenceId:number(){
        //if the array of requests is not created, add now
        if (window["lsRequestIds"]===undefined )
        {
            window["lsRequestIds"]=[];
        }
        //if there are no current requests, update this element to show loading text
        if( window["lsRequestIds"].length===0)
        {
            document.querySelector("#top-container").innerHTML="<h1>loading</h1>";

        }

        //generate the new number by incrementing, this will be added to the array, and sent as a request header to track the requests
         let currentId = this.requestSequence++;
        window["lsRequestIds"].push(currentId);
        return currentId;
    }
</code>```

The code below listens for the incoming requests, inspecting the header of each one, and then removing the sequence number from the request. If there are no items left in the array, all the items have returned and the loading symbol is removed.

```<code>(function (open) {

    XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
        this.addEventListener("readystatechange", function () {
           //capture the sequence id from the header
            var sequenceExp = /X-LS-Sequence:\s([0-9]*)/
            var headers = this.getAllResponseHeaders();
            if (headers) {

                var sequenceMatches = headers.match(sequenceExp)
                if(sequenceMatches && sequenceMatches.length>1)
                {
                    //remove the sequence id from the array
                    window.lsRequestIds = window.lsRequestIds.filter(function(seq){return seq.toString() !== sequenceMatches[1]})
                    console.log(window.lsRequestIds);
                    if(window.lsRequestIds.length===0)
                    {
                         let container = document.querySelector("#top-container");
                         if(container!==null)
                         {
                            //when the array is empty, all requests have returned -- remove the item from the DOM
                             container.innerHTML="<h1>Not Loading anymore</h1>";
                         }
                    }
                }

        }, false);

        open.call(this, method, url, async, user, pass);
    };

})(XMLHttpRequest.prototype.open);
</code>```

答:
It could be due to the fact that readystatechange event called multiple times for the same request and array of ids is cleared up more quickly. The request passes multiple states before it may be considered as done. Try to wrap your code like so:

```<code>this.addEventListener("readystatechange", function () {
    if (this.readyState === XMLHttpRequest.DONE) {
        // ...
    }
}
</code>```

Also it would not hurt if you add "case insensitive" flag to regular expression: var sequenceExp = /X-LS-Sequence:\s([0-9]*)/i;

UPDATE:

Cause: Synchronous XHR request (in Chrome user agent) freezes UI thread causing unpaint/unreflected DOM updates until its finished.
Passing async: true argument to XHR open function solved the problem.

Body:
I am attempting to add an ajax loading message into Single Page application.  The code works by updating a DOM element when the first http request goes out, and adds an sequence number to an array, which gets added as an http header.  The application then monitors the header of requests coming back, removing items from the array, and when the array is empty, the loading message is changed.  The code below shows how the code is added and then removed from the array (it's an angular2 app, but this is done in plain javascript/typescript).  The code behaves perfectly in Firefox, however in Chrome, amazingly, even though the DOM updates (I can see the code change and the text of the element change to 'Loading' in devtools web inspector) the change never appears on the page  --   it stays as 'Not Loading anymore'. I'm wondering if this is possibly a bug in Chrome.

Below is the code for adding the DOM item.  This gets called immediately before a request is sent out to our API

 private setSequenceId:number(){
        //if the array of requests is not created, add now
        if (window["lsRequestIds"]===undefined )
        {
            window["lsRequestIds"]=[];
        }
        //if there are no current requests, update this element to show loading text
        if( window["lsRequestIds"].length===0)
        {
            document.querySelector("#top-container").innerHTML="
loading
";

        }

        //generate the new number by incrementing, this will be added to the array, and sent as a request header to track the requests
         let currentId = this.requestSequence++;
        window["lsRequestIds"].push(currentId);
        return currentId;
    }

The code below listens for the incoming requests, inspecting the header of each one, and then removing the sequence number from the request. If there are no items left in the array, all the items have returned and the loading symbol is removed.

(function (open) {

    XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
        this.addEventListener("readystatechange", function () {
           //capture the sequence id from the header
            var sequenceExp = /X-LS-Sequence:\s([0-9]*)/
            var headers = this.getAllResponseHeaders();
            if (headers) {

                var sequenceMatches = headers.match(sequenceExp)
                if(sequenceMatches && sequenceMatches.length>1)
                {
                    //remove the sequence id from the array
                    window.lsRequestIds = window.lsRequestIds.filter(function(seq){return seq.toString() !== sequenceMatches[1]})
                    console.log(window.lsRequestIds);
                    if(window.lsRequestIds.length===0)
                    {
                         let container = document.querySelector("#top-container");
                         if(container!==null)
                         {
                            //when the array is empty, all requests have returned -- remove the item from the DOM
                             container.innerHTML="
Not Loading anymore
";
                         }
                    }
                }

        }, false);

        open.call(this, method, url, async, user, pass);
    };

})(XMLHttpRequest.prototype.open);

Body:
It could be due to the fact that readystatechange event called multiple times for the same request and array of ids is cleared up more quickly. The request passes multiple states before it may be considered as done. Try to wrap your code like so:

this.addEventListener("readystatechange", function () {
    if (this.readyState === XMLHttpRequest.DONE) {
        // ...
    }
}

Also it would not hurt if you add "case insensitive" flag to regular expression: var sequenceExp = /X-LS-Sequence:\s([0-9]*)/i;

UPDATE:

Cause: Synchronous XHR request (in Chrome user agent) freezes UI thread causing unpaint/unreflected DOM updates until its finished.
Passing async: true argument to XHR open function solved the problem.


问:
Jenkins Pipeline as Code with Docker Error
For one of my projects that I have on GitHub, I wanted to build it as a docker image and push it to my docker hub. The project is a sbt one with a Scala codebase.

Here is how my JenkinsFile is defined:

```<code>#!groovy

node {
  // set this in Jenkins server under Manage Jenkins > Credentials > System > Global Credentials
  docker.withRegistry('https://hub.docker.com/', 'joesan-docker-hub-credentials') {
    git credentialsId: '630bd271-01e7-48c3-bc5f-5df059c1abb8', url: 'https://github.com/joesan/monix-samples.git'

    sh "git rev-parse HEAD > .git/commit-id"
    def commit_id = readFile('.git/commit-id').trim()
    println comit_id

    stage "build" {
      def app = docker.build "Monix-Sample"
    }

    stage "publish" {
      app.push 'master'
      app.push "${commit_id}"
    }
  }
}
</code>```

When I tried to run this from my Jenkins server, I get the following error:

```<code>java.io.FileNotFoundException
    at jenkins.plugins.git.GitSCMFile$3.invoke(GitSCMFile.java:167)
    at jenkins.plugins.git.GitSCMFile$3.invoke(GitSCMFile.java:159)
    at jenkins.plugins.git.GitSCMFileSystem$3.invoke(GitSCMFileSystem.java:161)
    at org.jenkinsci.plugins.gitclient.AbstractGitAPIImpl.withRepository(AbstractGitAPIImpl.java:29)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.withRepository(CliGitAPIImpl.java:65)
    at jenkins.plugins.git.GitSCMFileSystem.invoke(GitSCMFileSystem.java:157)
    at jenkins.plugins.git.GitSCMFile.content(GitSCMFile.java:159)
    at jenkins.scm.api.SCMFile.contentAsString(SCMFile.java:338)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:101)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:59)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:232)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:404)
Finished: FAILURE
</code>```

Since this is running inside a VM on Azure, I thought the VM was not able to reach outside, but that seems not to be the case as I was able to ssh into the VM and git pull from the Git repo. So what is the problem here? How could I make this work?

答:
I experienced the exact same error. My setting:

Pipeline build inside a dockerized Jenkins (version 2.32.3)

In the configuration of the job, I specified a check out into a subdirectory: Open the configuration, e.g. https://myJenkins/job/my-job/configure. At the bottom, see section Pipeline -> Additional Behaviours -> Check out into a sub-directory with Local subdirectory for repo set to, e.g., my-sub-dir.

Expectation: Upon check out, the Jenkinsfile ends up in my-sub-dir/Jenkinsfile.

Via the option Script path, you configure the location of the Jenkinsfile so that Jenkins can start the build. I put my-sub-dir/Jenkinsfile as value.

I then received the exception you pasted in your question. I fixed it by setting Script Path to Jenkinsfile. If you don't specify a sub-directory for check out, then still try double checking values for Script Path.

Note: I have another Jenkins instance at work. There I have to specify Script Path including the custom check out sub-directory (as mentioned in Expectation above).

Body:
For one of my projects that I have on GitHub, I wanted to build it as a docker image and push it to my docker hub. The project is a sbt one with a Scala codebase.

Here is how my JenkinsFile is defined:

#!groovy

node {
  // set this in Jenkins server under Manage Jenkins > Credentials > System > Global Credentials
  docker.withRegistry('https://hub.docker.com/', 'joesan-docker-hub-credentials') {
    git credentialsId: '630bd271-01e7-48c3-bc5f-5df059c1abb8', url: 'https://github.com/joesan/monix-samples.git'

    sh "git rev-parse HEAD > .git/commit-id"
    def commit_id = readFile('.git/commit-id').trim()
    println comit_id

    stage "build" {
      def app = docker.build "Monix-Sample"
    }

    stage "publish" {
      app.push 'master'
      app.push "${commit_id}"
    }
  }
}

When I tried to run this from my Jenkins server, I get the following error:

java.io.FileNotFoundException
    at jenkins.plugins.git.GitSCMFile$3.invoke(GitSCMFile.java:167)
    at jenkins.plugins.git.GitSCMFile$3.invoke(GitSCMFile.java:159)
    at jenkins.plugins.git.GitSCMFileSystem$3.invoke(GitSCMFileSystem.java:161)
    at org.jenkinsci.plugins.gitclient.AbstractGitAPIImpl.withRepository(AbstractGitAPIImpl.java:29)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.withRepository(CliGitAPIImpl.java:65)
    at jenkins.plugins.git.GitSCMFileSystem.invoke(GitSCMFileSystem.java:157)
    at jenkins.plugins.git.GitSCMFile.content(GitSCMFile.java:159)
    at jenkins.scm.api.SCMFile.contentAsString(SCMFile.java:338)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:101)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:59)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:232)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:404)
Finished: FAILURE

Since this is running inside a VM on Azure, I thought the VM was not able to reach outside, but that seems not to be the case as I was able to ssh into the VM and git pull from the Git repo. So what is the problem here? How could I make this work?