问:
SQL fetch two different rows side by side
I am getting back this result set from a SQL query:

```<code>TypeID  Address   CityID    Zip          isPreferred
----------------------------------------------------
  1     SA-09     17986     897464654         0
  2     FF-31     17987     564646656         0
</code>```

And the SQL query is

```<code>SELECT
    rAdrs.ContactTypeID, rAdrs.StreetAddress,
    rAdrs.CityID, rAdrs.Zip,  rAdrs.isPreferred
FROM
    [Address] AS rAdrs
WHERE
    rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1

UNION

SELECT
    mAdrs.ContactTypeID, mAdrs.StreetAddress,
    mAdrs.CityID, mAdrs.Zip,  mAdrs.isPreferred
FROM
    [Address] AS mAdrs
WHERE
    mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
</code>```

BUT the result I want in this format:

```<code>TypeID  Address  CityID   Zip       TypeID    Address   CityID   Zip        Preferred
----------------------------------------------------------------------------------------
  1     SA-09    17986    897464654   2       FF-31     17987    564646656  2
</code>```

答:
Use CROSS APPLY

```<code>select a.*,b.*
from (
SELECT
rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip,  rAdrs.isPreferred
FROM [Address] AS rAdrs
WHERE rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1
) a
cross apply
(
SELECT
mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip,  mAdrs.isPreferred
FROM [Address] AS mAdrs
WHERE mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
) b
</code>```

demo

```<code>declare @t1 table(id smallint,str char(2))
insert into @t1 values (1,'aa')

declare @t2 table(id smallint,str char(2))
insert into @t2 values (2,'bb')

select a.*,b.*
from
(select * from @t1) a
cross apply
(select * from @t2) b
</code>```

or

```<code>select a.*,b.*
from @t1 a
cross apply
(
select * from @t2
) b
</code>```

Result

```<code>id  str id  str
1   aa  2   bb
</code>```

Body:
I am getting back this result set from a SQL query:

TypeID  Address   CityID    Zip          isPreferred
----------------------------------------------------
  1     SA-09     17986     897464654         0
  2     FF-31     17987     564646656         0

And the SQL query is

SELECT
    rAdrs.ContactTypeID, rAdrs.StreetAddress,
    rAdrs.CityID, rAdrs.Zip,  rAdrs.isPreferred
FROM
    [Address] AS rAdrs
WHERE
    rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1

UNION

SELECT
    mAdrs.ContactTypeID, mAdrs.StreetAddress,
    mAdrs.CityID, mAdrs.Zip,  mAdrs.isPreferred
FROM
    [Address] AS mAdrs
WHERE
    mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2

BUT the result I want in this format:

TypeID  Address  CityID   Zip       TypeID    Address   CityID   Zip        Preferred
----------------------------------------------------------------------------------------
  1     SA-09    17986    897464654   2       FF-31     17987    564646656  2

Body:
Use CROSS APPLY

select a.*,b.*
from (
SELECT
rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip,  rAdrs.isPreferred
FROM [Address] AS rAdrs
WHERE rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1
) a
cross apply
(
SELECT
mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip,  mAdrs.isPreferred
FROM [Address] AS mAdrs
WHERE mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
) b

demo

declare @t1 table(id smallint,str char(2))
insert into @t1 values (1,'aa')

declare @t2 table(id smallint,str char(2))
insert into @t2 values (2,'bb')

select a.*,b.*
from
(select * from @t1) a
cross apply
(select * from @t2) b

or

select a.*,b.*
from @t1 a
cross apply
(
select * from @t2
) b

Result

id  str id  str
1   aa  2   bb


来源: stackexchange

问:
Concatenate varbinary values and ignore the null ones?
The following code

```<code>select hashbytes('SHA1', cast(a as varbinary(max))) FROM (select 0 a, null b) t
</code>```

returns 0x9069CA78E7450A285173431B3E52C5C25299E473.

And the following code return null.

```<code>select hashbytes('SHA1', cast(a as varbinary(max))
    + cast(b as varbinary(max))
    + cast(c as varbinary(max))
FROM (select 0 a, null b, null c) t -- There may be many columns
</code>```

I tried to convert the null to 0, but the hash changed.

```<code>select hashbytes('SHA1', cast(a as varbinary(max))
    + isnull(cast(b as varbinary(max)), 0))
    + isnull(cast(c as varbinary(max)), 0))
FROM (select 0 a, null b, null c) t
</code>```

How to ignore the null varbinary values when concatenating?

答:
You need to change the location of isnull() calls like this:

select hashbytes('SHA1', cast(isnull(a, '') as varbinary(max)) + cast(isnull(b, '') as varbinary(max)) + cast(isnull(c, '') as varbinary(max))) FROM (select 0 a, null b, null c) t;

I have tested it in SQL Server 2012.

ContentLicense: CC BY-SA 3.0

Body:
The following code

select hashbytes('SHA1', cast(a as varbinary(max))) FROM (select 0 a, null b) t

returns 0x9069CA78E7450A285173431B3E52C5C25299E473.

And the following code return null.

select hashbytes('SHA1', cast(a as varbinary(max))
    + cast(b as varbinary(max))
    + cast(c as varbinary(max))
FROM (select 0 a, null b, null c) t -- There may be many columns

I tried to convert the null to 0, but the hash changed.

select hashbytes('SHA1', cast(a as varbinary(max))
    + isnull(cast(b as varbinary(max)), 0))
    + isnull(cast(c as varbinary(max)), 0))
FROM (select 0 a, null b, null c) t

How to ignore the null varbinary values when concatenating?


问:
Embedding Xamarin Forms or native embedding
I will make an app where I need the native map. Either I do the app with Xamarin native and Embedding Xamarin.Forms in Xamarin Native on all pages without the page with the map. Or if it's possible I'll do an Xamarin Forms app and embedding the native map control, if it's possible? I read Adding Platform-Specific Controls to a Xamarin.Forms Layout but is the map included? Or is it only "small" controls as the label?

What should I use?

答:
You can embed any native control in a xamarin forms app. This is a feature already released while the xamarin.forms embedding into a native app is still in preview.

I would either embed the native map as you suggested or do a custom renderer for the map control already available in forms.


问:
Repeating an Array Looping in jQuery
I am trying to get a jQuery snippet to loop around and keep displaying the messages in the array. This is what I have so far and it works, it just won't loop round after once even though I used setTimeout function.

What am I doing wrong? What would be best practice and why?

Thanks in advance

```<code>    var obj = $("div");
    var arr = $.makeArray(obj);
    var len = arr.length;
    var i = 0;

    function printloop() {
        arr[i].style.display = "block";
        i++;
        if (i < len) {
            setTimeout(printloop, 2000);
        } else {
            setTimeout(function() {
                    $("div").css("display", "none");
            },1000);
        };
    }
    printloop();

    setInterval(prinloop, 20000);
</code>```

答:
You only need setInterval() read the documentation:

setTimeout(function, milliseconds)

Executes a function, after waiting a specified number of milliseconds.

setInterval(function, milliseconds)

Same as setTimeout(), but repeats the execution of the function continuously.

Use this, I hope help you.

var obj = $("div");
        var arr = $.makeArray(obj);
        var len = arr.length;
        var i = 0;

        function printloop() {
            if (i >= len) {
                i = 0
                $("div").css("display", "none");
            };
            arr[i].style.display = "block";
            i++;
        }
        printloop();

        setInterval(printloop, 2000); // setInterval(prinloop, 20000); not work because prinloop is undefined```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{ display: none;}</code>```

H

E

L

L

O

```

Title: Repeating an Array Looping in jQuery

Body:
I am trying to get a jQuery snippet to loop around and keep displaying the messages in the array. This is what I have so far and it works, it just won't loop round after once even though I used setTimeout function.

What am I doing wrong? What would be best practice and why?

Thanks in advance

    var obj = $("div");
    var arr = $.makeArray(obj);
    var len = arr.length;
    var i = 0;

    function printloop() {
        arr[i].style.display = "block";
        i++;
        if (i < len) {
            setTimeout(printloop, 2000);
        } else {
            setTimeout(function() {
                    $("div").css("display", "none");
            },1000);
        };
    }
    printloop();

    setInterval(prinloop, 20000);

Body:
You only need setInterval() read the documentation:

setTimeout(function, milliseconds)

Executes a function, after waiting a specified number of milliseconds.

setInterval(function, milliseconds)

Same as setTimeout(), but repeats the execution of the function continuously.

Use this, I hope help you.

var obj = $("div");
        var arr = $.makeArray(obj);
        var len = arr.length;
        var i = 0;

        function printloop() {
            if (i >= len) {
                i = 0
                $("div").css("display", "none");
            };
            arr[i].style.display = "block";
            i++;
        }
        printloop();

        setInterval(printloop, 2000); // setInterval(prinloop, 20000); not work because prinloop is undefined

div{ display: none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
H
</div>
<div>
E
</div>
<div>
L
</div>
<div>
L
</div>
<div>
O
</div>


问:
Appending separate div to cloned draggable
I am trying to append a separate div to a cloned draggable div.

This jsfiddle:
http://jsfiddle.net/kdfiddle/26fuvqxe/

Does exactly what I want it to - EXCEPT - I want the draggables to be cloned.

The Problem
is when I use helper: 'clone', and try to append the separate div to the clone:
http://jsfiddle.net/kdfiddle/o446vwas/

The div I want to have appended - does not attach - unless you click and drag the same Box# twice. On the second click and drag it then does what I expect it to.

答:
The idea here is to append when you start drag, clone and add draggable to the cloned div when you stop.

$(document).ready(function() {

  $(".box").draggable({
    helper: 'clone',
    start: function(event, ui) {
      $(ui.helper).append($("#appendable_div"));
    },
    stop: function(event, ui) {
      $(ui.helper).addClass('box-cloned').clone(true).appendTo('body');
      $(".box-cloned").on('mouseover', function() {
        $(this).draggable({
          start: function(event, ui) {
            $(ui.helper).append($("#appendable_div"));
          }
        });
      });
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#draggables {
  width: 200px;
  height: 100px;
  padding: 2em;
  margin: 10px;
  border: 1px solid;
}

.box, .box-cloned {
  border: 1px solid;
  background-color: grey;
  width: 150px;
}

#appendable_div {
  position: absolute;
  top: 2px;
  left: 2px;
  background-color: red;
  width: 100px;
  height: 50px;
}</code>```

  appendable div

Box #1

Box #2

Box #3

Box #4

Drag a box above, to have the appendable div ... append to the box being dragged```

Body:
The idea here is to append when you start drag, clone and add draggable to the cloned div when you stop.

$(document).ready(function() {

  $(".box").draggable({
    helper: 'clone',
    start: function(event, ui) {
      $(ui.helper).append($("#appendable_div"));
    },
    stop: function(event, ui) {
      $(ui.helper).addClass('box-cloned').clone(true).appendTo('body');
      $(".box-cloned").on('mouseover', function() {
        $(this).draggable({
          start: function(event, ui) {
            $(ui.helper).append($("#appendable_div"));
          }
        });
      });
    }
  });

});

#draggables {
  width: 200px;
  height: 100px;
  padding: 2em;
  margin: 10px;
  border: 1px solid;
}

.box, .box-cloned {
  border: 1px solid;
  background-color: grey;
  width: 150px;
}

#appendable_div {
  position: absolute;
  top: 2px;
  left: 2px;
  background-color: red;
  width: 100px;
  height: 50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>

<div id="appendable_div">
  appendable div
</div>

<br><br><br><br><br><br><br>
<div id="draggables">

  <div class="box">Box #1</div>
  <div class="box">Box #2</div>
  <div class="box">Box #3</div>
  <div class="box">Box #4</div>

</div>
Drag a box above, to have the appendable div ... append to the box being dragged


问:
Pricing of Azure Cloud services (or how is usage calculated)
So, I'm looking making a cloud service using the Azure platform (here), looked at the pricing and saw it was calculated per hour (or per minutes according to the banner). So I was wondering, in the case of what I want to do, the service will be doing stuff every (for example) 15 minutes, then will sleep for the rest of the duration. Does that mean I'm only gonna be charged for a couple minutes every hour, or will still count the thread sleep as being active, thus counting in the usage? If it's the latter, is there another way to avoid this (part of the service framework maybe?), short of shutting down the service of course?</p>

答:
There are ways on azure to be billed dynamically.  For example,  If you create a function then it will only be provisioned when it is called and you will only be billed for that time.if you use a vm image or website then you will be billed for the whole time it is running even if it is not in use.
Here is a link to the azure functions billing page that describes the details:
https://azure.microsoft.com/en-us/pricing/details/functions/?cdn=disable</p>


问:
How do I pass command line arguments to a Node.js program?
I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:

```<code>$ node server.js folder
</code>```

here server.js is my server code. Node.js help says this is possible:

```<code>$ node -h
Usage: node [options] script.js [arguments]
</code>```

How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.

答:
A simple snippet if any need it:</p>

```<code>var fs = require('fs'), objMod = {};

process.argv.slice(2).map(function(y, i) {
  y = y.split('=');
  if (y[0] && y[1]) objMod[y[0]] = y[1];
  else console.log('Error in argument number ' + (i+1));
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:

$ node server.js folder

here server.js is my server code. Node.js help says this is possible:

$ node -h
Usage: node [options] script.js [arguments]

How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.

Body:
A simple snippet if any need it:

var fs = require('fs'), objMod = {};

process.argv.slice(2).map(function(y, i) {
  y = y.split('=');
  if (y[0] && y[1]) objMod[y[0]] = y[1];
  else console.log('Error in argument number ' + (i+1));
});


问:
Create a property index for all nodes in Cypher
I have 1 rule for my database. EVERYTHING must have an 'id'. Since this is my primary key field, I want to index it, but it seems the only way to create an index is to specify a label.

So with this dataset

```<code>CREATE (:TEST1{id:"<uuid>"}),
(:RAWR{id:"<uuid>"}),
(:FOO:BAR{id:"<uuid>"}),
({id:"<uuid>"})
</code>```

I would like to use an index to find the unlabeled node by its UUID.

Is this possible in Cypher? Or is my ONLY option to inject a 'node' label onto EVERYTHING entering the database? (It feels wrong to create a label and then assign it to everything. And to hijack all create requests to add that additional label feels like I'm asking for trouble.)

答:
A node can have multiple labels. So, in addition to your existing labels, you could assign a common label to all your nodes and then create an index using that common label and id.

However, since you intend the id value to be globally unique, instead of creating an index you should create a uniqueness constraint (which automatically creates an index for you as a side effect). That would tell neo4j to enforce id uniqueness for you.

Body:
I have 1 rule for my database. EVERYTHING must have an 'id'. Since this is my primary key field, I want to index it, but it seems the only way to create an index is to specify a label.

So with this dataset

CREATE (:TEST1{id:"<uuid>"}),
(:RAWR{id:"<uuid>"}),
(:FOO:BAR{id:"<uuid>"}),
({id:"<uuid>"})

I would like to use an index to find the unlabeled node by its UUID.

Is this possible in Cypher? Or is my ONLY option to inject a 'node' label onto EVERYTHING entering the database? (It feels wrong to create a label and then assign it to everything. And to hijack all create requests to add that additional label feels like I'm asking for trouble.)


问:
JavaScript private methods
To make a JavaScript class with a public method I'd do something like:

```<code>function Restaurant() {}

Restaurant.prototype.buy_food = function(){
   // something here
}

Restaurant.prototype.use_restroom = function(){
   // something here
}
</code>```

That way users of my class can:

```<code>var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
</code>```

How do I create a private method that can be called by the buy_food and use_restroom methods but not externally by users of the class?

In other words, I want my method implementation to be able to do:

```<code>Restaurant.prototype.use_restroom = function() {
   this.private_stuff();
}
</code>```

But this shouldn't work:

```<code>var r = new Restaurant();
r.private_stuff();
</code>```

How do I define private_stuff as a private method so both of these hold true?

I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.

答:
Personally, I prefer the following pattern for creating classes in JavaScript :

```<code>var myClass = (function() {
    // Private class properties go here

    var blueprint = function() {
        // Private instance properties go here
        ...
    };

    blueprint.prototype = {
        // Public class properties go here
        ...
    };

    return  {
         // Public class properties go here
        create : function() { return new blueprint(); }
        ...
    };
})();
</code>```

As you can see, it allows you to define both class properties and instance properties, each of which can be public and private.

Demo

var Restaurant = function() {
    var totalfoodcount = 0;        // Private class property
    var totalrestroomcount  = 0;   // Private class property

    var Restaurant = function(name){
        var foodcount = 0;         // Private instance property
        var restroomcount  = 0;    // Private instance property

        this.name = name

        this.incrementFoodCount = function() {
            foodcount++;
            totalfoodcount++;
            this.printStatus();
        };
        this.incrementRestroomCount = function() {
            restroomcount++;
            totalrestroomcount++;
            this.printStatus();
        };
        this.getRestroomCount = function() {
            return restroomcount;
        },
        this.getFoodCount = function() {
            return foodcount;
        }
    };

    Restaurant.prototype = {
        name : '',
        buy_food : function(){
           this.incrementFoodCount();
        },
        use_restroom : function(){
           this.incrementRestroomCount();
        },
        getTotalRestroomCount : function() {
            return totalrestroomcount;
        },
        getTotalFoodCount : function() {
            return totalfoodcount;
        },
        printStatus : function() {
           document.body.innerHTML
               += '
Buying food at '+this.name+'
'
               + '
'
               + '
Restroom count at ' + this.name + ' : '+ this.getRestroomCount() + '
'
               + '
Food count at ' + this.name + ' : ' + this.getFoodCount() + '
'
               + '
Total restroom count : '+ this.getTotalRestroomCount() + '
'
               + '
Total food count : '+ this.getTotalFoodCount() + '
'
               + '
';
        }
    };

    return  { // Singleton public properties
        create : function(name) {
            return new Restaurant(name);
        },
        printStatus : function() {
          document.body.innerHTML
              += '
'
              + '
Overview
'
              + '
'
              + '
Total restroom count : '+ Restaurant.prototype.getTotalRestroomCount() + '
'
              + '
Total food count : '+ Restaurant.prototype.getTotalFoodCount() + '
'
              + '
'
              + '
';
        }
    };
}();

var Wendys = Restaurant.create("Wendy's");
var McDonalds = Restaurant.create("McDonald's");
var KFC = Restaurant.create("KFC");
var BurgerKing = Restaurant.create("Burger King");

Restaurant.printStatus();

Wendys.buy_food();
Wendys.use_restroom();
KFC.use_restroom();
KFC.use_restroom();
Wendys.use_restroom();
McDonalds.buy_food();
BurgerKing.buy_food();

Restaurant.printStatus();

BurgerKing.buy_food();
Wendys.use_restroom();
McDonalds.buy_food();
KFC.buy_food();
Wendys.buy_food();
BurgerKing.buy_food();
McDonalds.buy_food();

Restaurant.printStatus();```

See also this Fiddle.

OwnerDisplayName: Wayne

Title: JavaScript private methods

Body:
To make a JavaScript class with a public method I'd do something like:

function Restaurant() {}

Restaurant.prototype.buy_food = function(){
   // something here
}

Restaurant.prototype.use_restroom = function(){
   // something here
}

That way users of my class can:

var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();

How do I create a private method that can be called by the buy_food and use_restroom methods but not externally by users of the class?

In other words, I want my method implementation to be able to do:

Restaurant.prototype.use_restroom = function() {
   this.private_stuff();
}

But this shouldn't work:

var r = new Restaurant();
r.private_stuff();

How do I define private_stuff as a private method so both of these hold true?

I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.

LastEditorDisplayName: Rob

Body:
Personally, I prefer the following pattern for creating classes in JavaScript :

var myClass = (function() {
    // Private class properties go here

    var blueprint = function() {
        // Private instance properties go here
        ...
    };

    blueprint.prototype = {
        // Public class properties go here
        ...
    };

    return  {
         // Public class properties go here
        create : function() { return new blueprint(); }
        ...
    };
})();

As you can see, it allows you to define both class properties and instance properties, each of which can be public and private.

Demo

var Restaurant = function() {
    var totalfoodcount = 0;        // Private class property
    var totalrestroomcount  = 0;   // Private class property

    var Restaurant = function(name){
        var foodcount = 0;         // Private instance property
        var restroomcount  = 0;    // Private instance property

        this.name = name

        this.incrementFoodCount = function() {
            foodcount++;
            totalfoodcount++;
            this.printStatus();
        };
        this.incrementRestroomCount = function() {
            restroomcount++;
            totalrestroomcount++;
            this.printStatus();
        };
        this.getRestroomCount = function() {
            return restroomcount;
        },
        this.getFoodCount = function() {
            return foodcount;
        }
    };

    Restaurant.prototype = {
        name : '',
        buy_food : function(){
           this.incrementFoodCount();
        },
        use_restroom : function(){
           this.incrementRestroomCount();
        },
        getTotalRestroomCount : function() {
            return totalrestroomcount;
        },
        getTotalFoodCount : function() {
            return totalfoodcount;
        },
        printStatus : function() {
           document.body.innerHTML
               += '<h3>Buying food at '+this.name+'</h3>'
               + '<ul>'
               + '<li>Restroom count at ' + this.name + ' : '+ this.getRestroomCount() + '</li>'
               + '<li>Food count at ' + this.name + ' : ' + this.getFoodCount() + '</li>'
               + '<li>Total restroom count : '+ this.getTotalRestroomCount() + '</li>'
               + '<li>Total food count : '+ this.getTotalFoodCount() + '</li>'
               + '</ul>';
        }
    };

    return  { // Singleton public properties
        create : function(name) {
            return new Restaurant(name);
        },
        printStatus : function() {
          document.body.innerHTML
              += '<hr />'
              + '<h3>Overview</h3>'
              + '<ul>'
              + '<li>Total restroom count : '+ Restaurant.prototype.getTotalRestroomCount() + '</li>'
              + '<li>Total food count : '+ Restaurant.prototype.getTotalFoodCount() + '</li>'
              + '</ul>'
              + '<hr />';
        }
    };
}();

var Wendys = Restaurant.create("Wendy's");
var McDonalds = Restaurant.create("McDonald's");
var KFC = Restaurant.create("KFC");
var BurgerKing = Restaurant.create("Burger King");

Restaurant.printStatus();

Wendys.buy_food();
Wendys.use_restroom();
KFC.use_restroom();
KFC.use_restroom();
Wendys.use_restroom();
McDonalds.buy_food();
BurgerKing.buy_food();

Restaurant.printStatus();

BurgerKing.buy_food();
Wendys.use_restroom();
McDonalds.buy_food();
KFC.buy_food();
Wendys.buy_food();
BurgerKing.buy_food();
McDonalds.buy_food();

Restaurant.printStatus();

See also this Fiddle.


问:
convert the columns into Horizontal PIVOT
I have 3 column file with ID,name and value .

```<code>1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running
</code>```

I'm trying to convert this into a horizontal format based on the column 1 and column 2.

It's similar to the Pivot table with text values printed, it can't be done using Excel pivot it will allow only sum/count of values.

Can this be generated in UNIX?

```<code>,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue/white,,,,,shoe,blue,
5,Sports/Running,,,,,,,,M
</code>```

答:
Python 2.7

Assuming that list.csv is:

```<code>1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running
</code>```

Python code in un.py:

```<code># up.py
#
import csv
rowid={};  colid={};  tab={};  rowTitle=[];  colTitle=[]
with open('list.csv', 'rb') as csvfile:
  v = csv.reader(csvfile)
  for row in v:
    rowid[row[0]]=1;  colid[row[1]]=1;  k=row[0]+"@"+row[1]
    if tab.has_key(k):
      tab[k]=tab[k]+"/"+row[2]
    else:
      tab[k]=row[2]

rowTitle=rowid.keys(); colTitle=colid.keys()
rowTitle.sort();  colTitle.sort();

s=""
for j in colTitle: s=s+","+j
print s
for i in rowTitle:
  s=i
  for j in colTitle:
    k=i+"@"+j
    s=s+","
    if tab.has_key(k):
      s=s+tab[k]
  print s
</code>```

py un.py output is:

```<code>,Brand,Color,Fits,Gender,Logo,catgegory,primarycolor,size,width
1,sports,White,,Male,yes,,,,10
3,,blue/white,,,,shoe,blue,,
4,Running,,Lose,,,,,,12
5,Sports/Running,,,,,,,M,
</code>```

Body:
I have 3 column file with ID,name and value .

1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running

I'm trying to convert this into a horizontal format based on the column 1 and column 2.

It's similar to the Pivot table with text values printed, it can't be done using Excel pivot it will allow only sum/count of values.

Can this be generated in UNIX?

,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue/white,,,,,shoe,blue,
5,Sports/Running,,,,,,,,M

Body:
Python 2.7

Assuming that list.csv is:

1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running

Python code in un.py:

# up.py
#
import csv
rowid={};  colid={};  tab={};  rowTitle=[];  colTitle=[]
with open('list.csv', 'rb') as csvfile:
  v = csv.reader(csvfile)
  for row in v:
    rowid[row[0]]=1;  colid[row[1]]=1;  k=row[0]+"@"+row[1]
    if tab.has_key(k):
      tab[k]=tab[k]+"/"+row[2]
    else:
      tab[k]=row[2]

rowTitle=rowid.keys(); colTitle=colid.keys()
rowTitle.sort();  colTitle.sort();

s=""
for j in colTitle: s=s+","+j
print s
for i in rowTitle:
  s=i
  for j in colTitle:
    k=i+"@"+j
    s=s+","
    if tab.has_key(k):
      s=s+tab[k]
  print s

py un.py output is:

,Brand,Color,Fits,Gender,Logo,catgegory,primarycolor,size,width
1,sports,White,,Male,yes,,,,10
3,,blue/white,,,,shoe,blue,,
4,Running,,Lose,,,,,,12
5,Sports/Running,,,,,,,M,


问:
Order of evaluation
I wonder if construction like this (initialization list) has well defined EO (evaluation order):

```<code>struct MemoryManager
    {
        Pair* firstPair_;//<-beg
        Pair* currentPair_;
        Pair* lastPair_;//<-end

        MemoryManager():lastPair_(currentPair_ = firstPair_ = nullptr)
            {/*e.b.*/}
};
</code>```

If yes I personally would prefer this way to the more conventional:

```<code>    MemoryManager():firstPair_(nullptr),
                    currentPair_(nullptr),
                    lastPair_(nullptr)
    {/*e.b*/}
</code>```

答:
As John Dibling has remarked, your construct is technically correct for the given concrete example, but it's brittle and it's hard to understand for many programmers.

Brittleness:

Can fail if order of declaration is changed.

Can fail if the init list is changed.

To evaluate such constructs on your own, keep this idea foremost in your mind: code is not about instructing the compiler to do your bidding, it is about communicating your intent to others (and perhaps your later self).

Hence, try to write clear code.

Cheers & hth.,

ContentLicense: CC BY-SA 2.5

Title: Order of evaluation

Body:
I wonder if construction like this (initialization list) has well defined EO (evaluation order):

struct MemoryManager
    {
        Pair* firstPair_;//<-beg
        Pair* currentPair_;
        Pair* lastPair_;//<-end

        MemoryManager():lastPair_(currentPair_ = firstPair_ = nullptr)
            {/*e.b.*/}
};

If yes I personally would prefer this way to the more conventional:

    MemoryManager():firstPair_(nullptr),
                    currentPair_(nullptr),
                    lastPair_(nullptr)
    {/*e.b*/}


问:
React ES6 Scope of Function Declaration
I've looked around for several days and cannot seem to solve this. I have a form that handles a file upload via an XMLHTTPRequestUpload, I have an onProgress callback that I would like to call and update visually what's happening in the UI, but I can't seem to make any successful function calls from inside "onProgress".

I tried to use console.log to find the scope in which my function updateProgress is defined. 'this' inside of the uploadFile, onProgress call is the XMLHTTP request itself. So I tried it for 'AddShow', the class itself. It doesn't report an error, and lists that updateProgress is a member function of the class, but when trying to call it, I still get

```<code>AddShow.updateProgress is not a function
    at XMLHttpRequestUpload.onProgress
</code>```

So where's waldo? How do I call my function?

Here's my entire React Component Class:

```<code>export class AddShow extends React.Component {
  constructor(props) {
    super(props);

    this.handleTextChange = this.handleTextChange.bind(this);
    this.uploadFile = this.uploadFile.bind(this);
    this.updateProgress = this.updateProgress.bind(this);
  }

  // function that updates the state of the form input
  handleTextChange(evt) {
    this.props.dispatch(actions.changeShowTitleText(evt.target.value));
  }

  //function that show the progress of file upload
  updateProgress(progress) {
    progress = Math.floor(progress * 100);
    //call the dispatch actions to update redux state
    this.props.dispatch(actions.changeCompleteValue(progress));
    this.props.dispatch(actions.changeCompleteText(progress + '%'));
    this.props.dispatch(actions.changeCompleteARIA(progress + ' percent'));

    // this.props.complete = progress;
    // this.props.completeText = progress + '%';
    // this.props.ariaCompleteText = progress + ' percent';
  }

  // when 'add show' is pressed, validate form and upload
  onSubmit(e) {
    e.preventDefault();
    let titleText = this.props.showTitle;
    if (titleText < 1) {
      alert("Please provide a Show Title.");
    } else {
      // a title has been typed in, call upload with that info.
      this.uploadFile(titleText);
    }
  }

  //function that finally uploads the file given all the information
  uploadFile(title) {
    var uploader = new VimeoUpload({
      name: title,
      file: selectedFile,
      token: process.env.ACCESS_TOKEN,
      onProgress: function(data) {
        var percent = data.loaded / data.total;
        AddShow.updateProgress(percent);
      },
      onComplete: function(videoId, index) {
        var url = 'https://vimeo.com/' + videoId
      }
    });

    uploader.upload();
  }

  // set the global file variable if the input changes
  handleFileSelect(file) {
    console.log("These are the files retrieved", file.target.files[0]);
    selectedFile = file.target.files[0];
  }

  render() {
    var {dispatch, showTitle, complete, completeText, ariaCompleteText} = this.props;
    completeText = '0%';
    ariaCompleteText = "0 percent";

    return(
      <div className="row">
        <div className="column small-centered small-11 medium-8 large-6">
          <div className="container">
            <p>Drag the Video You Want to Upload to Screen</p>
            <form ref="form" onSubmit={this.onSubmit.bind(this)} className="add-show-form">
              <input type="file" placeholder="Select Video File" onChange={(evt) => this.handleFileSelect(evt)}/>
              <p ref="alertText"></p>
              <input type="text" value={this.props.showTitle} onChange={this.handleTextChange} placeholder="Show Title"/>
              <button className="button expanded">Add Show</button>
            </form>
            <div className="progress" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuetext={this.props.ariaCompleteText} aria-valuemax="100">
              <span className="progress-meter" style={{width: this.props.complete + '%'}}>
                <p className="progress-meter-text">{this.props.completeText}</p>
              </span>
            </div>
          </div>
        </div>
      </div>
    );
  }
};
</code>```

答:
You need to maintain a reference to the outer scope (i.e. the outer this) within the new scope of the onProgress callback.  The traditional (ES5) way to approach this was to create a reference to it within a variable (typically named self), then use that to call the method within the callback:

```<code>  uploadFile(title) {
    // self now references the outer this
    var self = this;
    var uploader = new VimeoUpload({
      name: title,
      file: selectedFile,
      token: process.env.ACCESS_TOKEN,
      onProgress: function(data) {
        var percent = data.loaded / data.total;

        // we can access the outer scope on self here
        self.updateProgress(percent);
      },
      onComplete: function(videoId, index) {
        var url = 'https://vimeo.com/' + videoId
      }
    });

    uploader.upload();
  }
</code>```

Given that you are using classes in your code, I would assume you are happy to use ES6 code, so the more elegant way to achieve the same effect is to use a lambda (or fat-arrow) function.  This means declaring your functions with this syntax:

```<code>const someFunction = (anArgument) => {
    return aResult;
}
</code>```

Which is (roughly) equivalent to:

```<code>function someFunction(anArgument) {
    return aResult;
}
</code>```

The difference is that when you declare a function with lambda syntax, a new scope is not created.  Effectively, the this inside the function is the same as the this outside it.  We can then write the uploadFile handler as:

```<code>  uploadFile(title) {
    var uploader = new VimeoUpload({
      name: title,
      file: selectedFile,
      token: process.env.ACCESS_TOKEN,
      onProgress: (data) => {
        var percent = data.loaded / data.total;
        this.updateProgress(percent);
      },
      onComplete: (videoId, index) => {
        var url = 'https://vimeo.com/' + videoId
      }
    });

    uploader.upload();
  }
</code>```

Title: React ES6 Scope of Function Declaration

Body:
I've looked around for several days and cannot seem to solve this. I have a form that handles a file upload via an XMLHTTPRequestUpload, I have an onProgress callback that I would like to call and update visually what's happening in the UI, but I can't seem to make any successful function calls from inside "onProgress".

I tried to use console.log to find the scope in which my function updateProgress is defined. 'this' inside of the uploadFile, onProgress call is the XMLHTTP request itself. So I tried it for 'AddShow', the class itself. It doesn't report an error, and lists that updateProgress is a member function of the class, but when trying to call it, I still get

AddShow.updateProgress is not a function
    at XMLHttpRequestUpload.onProgress

So where's waldo? How do I call my function?

Here's my entire React Component Class:

export class AddShow extends React.Component {
  constructor(props) {
    super(props);

    this.handleTextChange = this.handleTextChange.bind(this);
    this.uploadFile = this.uploadFile.bind(this);
    this.updateProgress = this.updateProgress.bind(this);
  }

  // function that updates the state of the form input
  handleTextChange(evt) {
    this.props.dispatch(actions.changeShowTitleText(evt.target.value));
  }

  //function that show the progress of file upload
  updateProgress(progress) {
    progress = Math.floor(progress * 100);
    //call the dispatch actions to update redux state
    this.props.dispatch(actions.changeCompleteValue(progress));
    this.props.dispatch(actions.changeCompleteText(progress + '%'));
    this.props.dispatch(actions.changeCompleteARIA(progress + ' percent'));

    // this.props.complete = progress;
    // this.props.completeText = progress + '%';
    // this.props.ariaCompleteText = progress + ' percent';
  }

  // when 'add show' is pressed, validate form and upload
  onSubmit(e) {
    e.preventDefault();
    let titleText = this.props.showTitle;
    if (titleText < 1) {
      alert("Please provide a Show Title.");
    } else {
      // a title has been typed in, call upload with that info.
      this.uploadFile(titleText);
    }
  }

  //function that finally uploads the file given all the information
  uploadFile(title) {
    var uploader = new VimeoUpload({
      name: title,
      file: selectedFile,
      token: process.env.ACCESS_TOKEN,
      onProgress: function(data) {
        var percent = data.loaded / data.total;
        AddShow.updateProgress(percent);
      },
      onComplete: function(videoId, index) {
        var url = 'https://vimeo.com/' + videoId
      }
    });

    uploader.upload();
  }

  // set the global file variable if the input changes
  handleFileSelect(file) {
    console.log("These are the files retrieved", file.target.files[0]);
    selectedFile = file.target.files[0];
  }

  render() {
    var {dispatch, showTitle, complete, completeText, ariaCompleteText} = this.props;
    completeText = '0%';
    ariaCompleteText = "0 percent";

    return(

Drag the Video You Want to Upload to Screen

            <form ref="form" onSubmit={this.onSubmit.bind(this)} className="add-show-form">
              <input type="file" placeholder="Select Video File" onChange={(evt) => this.handleFileSelect(evt)}/>

              <input type="text" value={this.props.showTitle} onChange={this.handleTextChange} placeholder="Show Title"/>
              <button className="button expanded">Add Show</button>
            </form>

{this.props.completeText}

    );
  }
};

Body:
You need to maintain a reference to the outer scope (i.e. the outer this) within the new scope of the onProgress callback.  The traditional (ES5) way to approach this was to create a reference to it within a variable (typically named self), then use that to call the method within the callback:

  uploadFile(title) {
    // self now references the outer this
    var self = this;
    var uploader = new VimeoUpload({
      name: title,
      file: selectedFile,
      token: process.env.ACCESS_TOKEN,
      onProgress: function(data) {
        var percent = data.loaded / data.total;

        // we can access the outer scope on self here
        self.updateProgress(percent);
      },
      onComplete: function(videoId, index) {
        var url = 'https://vimeo.com/' + videoId
      }
    });

    uploader.upload();
  }

Given that you are using classes in your code, I would assume you are happy to use ES6 code, so the more elegant way to achieve the same effect is to use a lambda (or fat-arrow) function.  This means declaring your functions with this syntax:

const someFunction = (anArgument) => {
    return aResult;
}

Which is (roughly) equivalent to:

function someFunction(anArgument) {
    return aResult;
}

The difference is that when you declare a function with lambda syntax, a new scope is not created.  Effectively, the this inside the function is the same as the this outside it.  We can then write the uploadFile handler as:

  uploadFile(title) {
    var uploader = new VimeoUpload({
      name: title,
      file: selectedFile,
      token: process.env.ACCESS_TOKEN,
      onProgress: (data) => {
        var percent = data.loaded / data.total;
        this.updateProgress(percent);
      },
      onComplete: (videoId, index) => {
        var url = 'https://vimeo.com/' + videoId
      }
    });

    uploader.upload();
  }


问:
Obtaining the runtime type of a derived template instantiation
I can use say typeid or dynamic_cast to switch between derived base class instances. For example:

```<code>struct B { virtual ~B() {} };

struct D1 : B {};
struct D2 : B {};

void doit(B &b) {
  if      (dynamic_cast<D1 *>(&b)) foo1();
  else if (dynamic_cast<D2 *>(&b)) foo2();
}
</code>```

How can I continue in this vein when the derived type is a template instantiation? For example, how could I extend the doit function above to handle four cases; perhaps using the DT1 and DT2 classes below, instantiated with arbitrary types?

```<code>template <typename T>
struct DT1 : B {};

template <typename T>
struct DT2 : B {};
</code>```

答:
Instead of hardcoding the list of derived classes in the doit function you could maintain some sort of registry of foo functions to call for each type. In the simplest form this could just be a vector of std::function<void(B&)> and you just loop through and call each of them. Each std::function would be responsible for checking if the type matches:

```<code>auto& doitRegistry(){
  static std::vector<std::function<void(B&)>> registry;
  return registry;
}

void doit(B &b) {
  for (auto& f : doitRegistry()) {
    f(b);
  }
}
</code>```

If you wanted to be smarter the registry could be something like a std::unordered_map<std::type_index, std::function<void(B&)>> so that you don't have to loop through the whole registry but as long as you don't have a huge number of derived classes it probably doesn't matter much.

Then you just have to register each type of derived class in the registry. You can create a helper class that registers a function in the registry in its constructor:

```<code>struct DoItRegistration {
  DoItRegistration(std::function<void(B&)> foo) {
     doitRegistry().push_back(std::move(foo));
  }
};
</code>```

And create a static instance of this class per derived class:

```<code>template <typename T>
struct DT1 : B {
  DT1() {
        registerWithDoIt();
  }
  static DoItRegistration& registerWithDoIt() {
      static DoItRegistration registration([](B &b){
        if (dynamic_cast<DT1<T>*>(&b)){
         foo1();
        }
      });
      return registration;
  }
};
</code>```

So that on first use of a derived class it registers itself with the doit registry and will be called when needed:

```<code>int main() {
    DT1<double> d1;
    DT1<int> d2;
    DT2<double> d3;
    DT1<double> dupeType;

    doit(d3);  // calls foo2()
}
</code>```

Live demo.

Body:
I can use say typeid or dynamic_cast to switch between derived base class instances. For example:

struct B { virtual ~B() {} };

struct D1 : B {};
struct D2 : B {};

void doit(B &b) {
  if      (dynamic_cast<D1 *>(&b)) foo1();
  else if (dynamic_cast<D2 *>(&b)) foo2();
}

How can I continue in this vein when the derived type is a template instantiation? For example, how could I extend the doit function above to handle four cases; perhaps using the DT1 and DT2 classes below, instantiated with arbitrary types?

template <typename T>
struct DT1 : B {};

template <typename T>
struct DT2 : B {};

Body:
Instead of hardcoding the list of derived classes in the doit function you could maintain some sort of registry of foo functions to call for each type. In the simplest form this could just be a vector of std::function<void(B&)> and you just loop through and call each of them. Each std::function would be responsible for checking if the type matches:

auto& doitRegistry(){
  static std::vector<std::function<void(B&)>> registry;
  return registry;
}

void doit(B &b) {
  for (auto& f : doitRegistry()) {
    f(b);
  }
}

If you wanted to be smarter the registry could be something like a std::unordered_map<std::type_index, std::function<void(B&)>> so that you don't have to loop through the whole registry but as long as you don't have a huge number of derived classes it probably doesn't matter much.

Then you just have to register each type of derived class in the registry. You can create a helper class that registers a function in the registry in its constructor:

struct DoItRegistration {
  DoItRegistration(std::function<void(B&)> foo) {
     doitRegistry().push_back(std::move(foo));
  }
};

And create a static instance of this class per derived class:

template <typename T>
struct DT1 : B {
  DT1() {
        registerWithDoIt();
  }
  static DoItRegistration& registerWithDoIt() {
      static DoItRegistration registration([](B &b){
        if (dynamic_cast<DT1<T>*>(&b)){
         foo1();
        }
      });
      return registration;
  }
};

So that on first use of a derived class it registers itself with the doit registry and will be called when needed:

int main() {
    DT1<double> d1;
    DT1<int> d2;
    DT2<double> d3;
    DT1<double> dupeType;

    doit(d3);  // calls foo2()
}

Live demo.


问:
Why can we supply a Comparator to TreeSet but not something like Hasher to HashSet?
In Java 6, my understanding is that you can supply a Comparator to a TreeSet when creating it to override the "natural ordering" of the objects in the set.

Do you have any thoughts why Java doesn't support supplying a "Hasher" that overrides the "natural hashing" of objects in the set as well?

EDIT:
Getting input from you might help me when designing APIs in the future.

Thanks.

答: It has already been asked.</p>

Body: It has already been asked.


问:
Hide elements within tabs dynamically in jQuery
Before I developed a functionality for when you have only one set of tabs. Now the aApp is growing and that tabs functionality is failing since there are more sets of tabs.

The first time the function was like this:

```<code>var iconTabs = function () {

    $('#icons-tabs a:not(:first)').addClass('inactive');
    $('.icons-container').hide();
    $('.icons-container:first').show();

    $('#icons-tabs a').click(function(){
        var t = $(this).attr('id');
        if($(this).hasClass('inactive')) {
            $('#icons-tabs a').addClass('inactive');
            $(this).removeClass('inactive');
            $('.icons-container').hide();
            $('#'+ t + 'C').fadeIn('slow');
        }
    });
};
</code>```

And the html:

```<code><div id="fragment-1" class="fragments text-center">
    <div class="icons-container" id="tab1C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="tab2C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab1"></a>
                <a href="#" class="item" id="tab2"></a>
                <a href="#" class="item" id="tab3"></a>
                <a href="#" class="item" id="tab4"></a>
            </div>
        </div>
    </div>
</div>
</code>```

Now the html has a second section and I still have to add 3 more, so now it is like this:

```<code><div id="fragment-1" class="fragments text-center">
    <div class="icons-container" id="tab1C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="tab2C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab1"></a>
                <a href="#" class="item" id="tab2"></a>
            </div>
        </div>
    </div>
</div>

<div id="fragment-2" class="fragments text-center">
    <div class="icons-container" id="tab5C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="ta62C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab5"></a>
                <a href="#" class="item" id="tab6"></a>
            </div>
        </div>
    </div>
</div>
</code>```

I have created a JSFiddle in case you want to play:

http://jsfiddle.net/ju3a9zx5/

My mission is to do it dynamic and that every set of tabs has separate behaviour. As you may see in the JSFiddle: the second set of tabs doesn't work, and I want them to have the same behaviour as the first one, but separate, one set of tabs don't have to interfere with the others.

答:
You are going to want to use classes instead of ids to target your tabs. If you see my example below, there are only a few changes:

I replaced id="tabs" and id="tabs2" with class="tabs"

I changed the event handlers to target the class instead of the ids

When finding the related a tags I use siblings()

When finding the related .container I use .nextUntil() to find the container beneath in the DOM

When showing the initial container classes. I use $('.tabs').next('.container')

$(document).ready(function() {

  $('.tabs a:not(:first)').addClass('inactive');
  $('.container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().nextUntil(':not(.container)').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}</code>```

  test1
  test2
  test3
  test4

1Some content

2Some content

3Some content

4Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content
```

Body:
Before I developed a functionality for when you have only one set of tabs. Now the aApp is growing and that tabs functionality is failing since there are more sets of tabs.

The first time the function was like this:

var iconTabs = function () {

    $('#icons-tabs a:not(:first)').addClass('inactive');
    $('.icons-container').hide();
    $('.icons-container:first').show();

    $('#icons-tabs a').click(function(){
        var t = $(this).attr('id');
        if($(this).hasClass('inactive')) {
            $('#icons-tabs a').addClass('inactive');
            $(this).removeClass('inactive');
            $('.icons-container').hide();
            $('#'+ t + 'C').fadeIn('slow');
        }
    });
};

And the html:

        {{!-- Content --}}

        {{!-- Content --}}

Now the html has a second section and I still have to add 3 more, so now it is like this:

        {{!-- Content --}}

        {{!-- Content --}}

        {{!-- Content --}}

        {{!-- Content --}}

I have created a JSFiddle in case you want to play:

http://jsfiddle.net/ju3a9zx5/

My mission is to do it dynamic and that every set of tabs has separate behaviour. As you may see in the JSFiddle: the second set of tabs doesn't work, and I want them to have the same behaviour as the first one, but separate, one set of tabs don't have to interfere with the others.

Body:
You are going to want to use classes instead of ids to target your tabs. If you see my example below, there are only a few changes:

I replaced id="tabs" and id="tabs2" with class="tabs"

I changed the event handlers to target the class instead of the ids

When finding the related a tags I use siblings()

When finding the related .container I use .nextUntil() to find the container beneath in the DOM

When showing the initial container classes. I use $('.tabs').next('.container')

$(document).ready(function() {

  $('.tabs a:not(:first)').addClass('inactive');
  $('.container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().nextUntil(':not(.container)').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});

.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="tabs">

  <a id="tab1">test1</a>
  <a id="tab2">test2</a>
  <a id="tab3">test3</a>
  <a id="tab4">test4</a>

</div>
<div class="container" id="tab1C">1Some content</div>
<div class="container" id="tab2C">2Some content</div>
<div class="container" id="tab3C">3Some content</div>
<div class="container" id="tab4C">4Some content</div>

<div class="tabs">

  <a id="tab5">test1</a>
  <a id="tab6">test2</a>
  <a id="tab7">test3</a>
  <a id="tab8">test4</a>

</div>
<div class="container" id="tab5C">5Some content</div>
<div class="container" id="tab6C">6Some content</div>
<div class="container" id="tab7C">7Some content</div>
<div class="container" id="tab8C">8Some content</div>


问:
How can I use SFINAE to prevent narrowing in a template function?
I am trying to implement basic arithmetic operations for a Vector class and would like to support mixing underlying types while preventing narrowing from occurring.

```<code>template <typename T1,typename T2>
Vector<T1> operator+( Vector<T1> lhs, const Vector<T2>& rhs, std::enable_if< ! is_narrowing_conversion<T2,T1>::value >::type* = nullptr )
{ return lhs += rhs; }
</code>```

I would like to implement is_narrowing_conversion so that it will only allow the conversion if the types do not narrow. Here are some examples:

```<code>Vector<double> a = Vector<double>() + Vector<float>(); //OK
Vector<float> a = Vector<float> + Vector<double>; //Fails to find the operator+ function
</code>```

In the end I would like to write a second template operator+ function that will handle the inverse case by returning a Vector.

I found this post with an incomplete example. But it is insufficient as he notes that it disallows uint8_t to uint64_t conversions.

I also discovered Daniel Krügler's paper on fixing is_constructible. Specifically in this paper he mentions using list-initialization which already has the narrowing semantics working but I'm not sure how to convert what he mentions into a proper trait that I can use for SFINAE template deduction.

答:
You can use the {} constructor and let it detects narrowing conversions for you.

You can do that with something like this:

```<code>template<typename T>
struct Vector {
    T value;
};

template <typename T1, typename T2>
auto operator+(Vector<T1>, const Vector<T2>& rhs)
-> decltype(T1{rhs.value}, Vector<T1>{})
{ return {}; }

int main() {
    auto a = Vector<double>{} + Vector<float>{};
    //auto b = Vector<float>{} + Vector<double>{};
    (void)a;
}
</code>```

That is, you can use the usual form for sfinae'd expressions involving a trailing return type.

In case your Vector class template hasn't a default constructor, you can still work around it with std::declval:

```<code>-> decltype(T1{rhs.value}, std::declval<Vector<T1>>())
</code>```

Note that, because of [dcl.init.list]/7.2 and the other bullets that follow, you can't simply do this in the code above:

```<code>-> decltype(T1{T2{}}, Vector<T1>{})
</code>```

Otherwise, in your specific example, the following would be valid:

```<code>auto b = Vector<float>{} + Vector<double>{};
</code>```

Therefore you must use the actual value provided along with rhs and (let me say) test it with the actual type used to specialize lhs.

As long as the contained value is accessible (either it is valid or the operator is a friend of your class) this shouldn't be a problem.

As a side note, you can't correctly define a is_narrowing_conversion that works properly in your case by using only the types T1 and T2.

As an example, consider [dcl.init.list]/7.2 (emphasis mine) and the test code you proposed:

[...] or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly) [...]

For you don't have actual values with which to make a test, all what you can do is trying something like T1{T2{}}. Anyway this wouldn't work. In other words, float{double{}} would be accepted without errors because of the bullet above mentioned.

Something similar applies to few other types.

Another valid approach is to use std::common_type.

Anyway, there is already a pretty good answer that proposes it. It wouldn't worth repeating the example code once more.

Body:
I am trying to implement basic arithmetic operations for a Vector class and would like to support mixing underlying types while preventing narrowing from occurring.

template <typename T1,typename T2>
Vector<T1> operator+( Vector<T1> lhs, const Vector<T2>& rhs, std::enable_if< ! is_narrowing_conversion<T2,T1>::value >::type* = nullptr )
{ return lhs += rhs; }

I would like to implement is_narrowing_conversion so that it will only allow the conversion if the types do not narrow. Here are some examples:

Vector<double> a = Vector<double>() + Vector<float>(); //OK
Vector<float> a = Vector<float> + Vector<double>; //Fails to find the operator+ function

In the end I would like to write a second template operator+ function that will handle the inverse case by returning a Vector.

I found this post with an incomplete example. But it is insufficient as he notes that it disallows uint8_t to uint64_t conversions.

I also discovered Daniel Krügler's paper on fixing is_constructible. Specifically in this paper he mentions using list-initialization which already has the narrowing semantics working but I'm not sure how to convert what he mentions into a proper trait that I can use for SFINAE template deduction.

Body:
You can use the {} constructor and let it detects narrowing conversions for you.

You can do that with something like this:

template<typename T>
struct Vector {
    T value;
};

template <typename T1, typename T2>
auto operator+(Vector<T1>, const Vector<T2>& rhs)
-> decltype(T1{rhs.value}, Vector<T1>{})
{ return {}; }

int main() {
    auto a = Vector<double>{} + Vector<float>{};
    //auto b = Vector<float>{} + Vector<double>{};
    (void)a;
}

That is, you can use the usual form for sfinae'd expressions involving a trailing return type.

In case your Vector class template hasn't a default constructor, you can still work around it with std::declval:

-> decltype(T1{rhs.value}, std::declval<Vector<T1>>())

Note that, because of [dcl.init.list]/7.2 and the other bullets that follow, you can't simply do this in the code above:

-> decltype(T1{T2{}}, Vector<T1>{})

Otherwise, in your specific example, the following would be valid:

auto b = Vector<float>{} + Vector<double>{};

Therefore you must use the actual value provided along with rhs and (let me say) test it with the actual type used to specialize lhs.

As long as the contained value is accessible (either it is valid or the operator is a friend of your class) this shouldn't be a problem.

As a side note, you can't correctly define a is_narrowing_conversion that works properly in your case by using only the types T1 and T2.

As an example, consider [dcl.init.list]/7.2 (emphasis mine) and the test code you proposed:

[...] or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly) [...]

For you don't have actual values with which to make a test, all what you can do is trying something like T1{T2{}}. Anyway this wouldn't work. In other words, float{double{}} would be accepted without errors because of the bullet above mentioned.

Something similar applies to few other types.

Another valid approach is to use std::common_type.

Anyway, there is already a pretty good answer that proposes it. It wouldn't worth repeating the example code once more.


问:
Spotify API getting artist track data returning error unauthorized
Currently trying to fetch KD Rusha to get current tracks. Display it on his website and show play button when every someone hover over the song image to play it. What am I doing wrong here?

My Steps:

Want to fetch for KD Rusha top albums on spotify.

Limit them to only 9 tracks.

Add play button on top of each track to play 30 sec of the song.

Artist ID https://api.spotify.com/v1/artists/{id} Give Me  401 (Unauthorized)

```<code>import React from 'react';
require('dotenv').config();

export default class SpotifyComponent extends React.Component {

constructor(props){
    super(props);
    this.state = {
       artist: null,
    };
}

componentWillMount() {
    var request = new Request('https://api.spotify.com/v1/artists/5JLWikpo5DFPqvIRi43v5y', {
      method: 'GET',
      headers: new Headers({
      'Accept': 'application/json',
      'Content-Type': 'text/plain',

      'Authorization': 'Bearer <big blob of token here>'
      })
});

  fetch(request)// fetch the Spotify date from KD Rusha Account
    .then((response) => {
      var result = response.json()
        this.setState({// State artist albums
          albums: result,
          selectedTrack: [0]
        });
                console.log(response.json());
    if (response.status >= 400) {
      throw new Error("Bad response from server");
    }
    return response.json();
  });
}

  render(){
    return(
      <section className="spotify-cantainer">
              <img src="{albums}" alt="kdrusha" />
      </section>
    );
  }

}
</code>```

答:
This might be entirely wrong, but since no one has replied to you yet and I have found a solution for a very similar problem thanks to your code, I will try to help. Here is my code, a function hooked to an input that will search for an artist using my Spotify login:

```<code>search () {
const BASE_URL = 'https://api.spotify.com/v1/search?';
const FETCH_URL = `${BASE_URL}q=${this.state.query}&type=artist&limit=1`;

fetch(FETCH_URL, {
  method: 'GET',
  headers: new Headers({
    Accept: "application/json",
    Authorization: "Bearer <long token here>"
  })
})
.then(response => response.json())
.then(json => console.log('json', json));
}
</code>```

One difference is that the keys in my Headers dict are not in quotes. The function returns a json object with all the information regarding the artist from {this.state.quesry}.

Best of luck and I hope this helps!

Body:
Currently trying to fetch KD Rusha to get current tracks. Display it on his website and show play button when every someone hover over the song image to play it. What am I doing wrong here?

My Steps:

Want to fetch for KD Rusha top albums on spotify.

Limit them to only 9 tracks.

Add play button on top of each track to play 30 sec of the song.

Artist ID https://api.spotify.com/v1/artists/{id} Give Me  401 (Unauthorized)

import React from 'react';
require('dotenv').config();

export default class SpotifyComponent extends React.Component {

constructor(props){
    super(props);
    this.state = {
       artist: null,
    };
}

componentWillMount() {
    var request = new Request('https://api.spotify.com/v1/artists/5JLWikpo5DFPqvIRi43v5y', {
      method: 'GET',
      headers: new Headers({
      'Accept': 'application/json',
      'Content-Type': 'text/plain',

      'Authorization': 'Bearer <big blob of token here>'
      })
});

  fetch(request)// fetch the Spotify date from KD Rusha Account
    .then((response) => {
      var result = response.json()
        this.setState({// State artist albums
          albums: result,
          selectedTrack: [0]
        });
                console.log(response.json());
    if (response.status >= 400) {
      throw new Error("Bad response from server");
    }
    return response.json();
  });
}

  render(){
    return(

    );
  }

}

Body:
This might be entirely wrong, but since no one has replied to you yet and I have found a solution for a very similar problem thanks to your code, I will try to help. Here is my code, a function hooked to an input that will search for an artist using my Spotify login:

search () {
const BASE_URL = 'https://api.spotify.com/v1/search?';
const FETCH_URL = `${BASE_URL}q=${this.state.query}&type=artist&limit=1`;

fetch(FETCH_URL, {
  method: 'GET',
  headers: new Headers({
    Accept: "application/json",
    Authorization: "Bearer <long token here>"
  })
})
.then(response => response.json())
.then(json => console.log('json', json));
}

One difference is that the keys in my Headers dict are not in quotes. The function returns a json object with all the information regarding the artist from {this.state.quesry}.

Best of luck and I hope this helps!


问:
Difference between 'get' and 'get set' in Swift
I understand that 'get' is used to give instructions on value for the variable 'numberOfWheels' is acquired. However, I do not understand what 'get set' is supposed to achieve in the code below. Does it mean that value can be acquired from the class, enum, or struct AND can also be acquired by a parameter passed on?</p>

```<code>protocol WheeledVehicle: Vehicle {
  var numberOfWheels: Int { get }
  var wheelSize: Double { get set }
}
</code>```

答:
This protocols requires conforming types (classes, structs or enums) to have two properties:

numberOfWheels, which must provide at least a getter. This means it's either a let property, a var property, or a computed property with at least a getter (the setter is optional).

wheelSize, which must provide a getter and a setter. This means it has to be either a var property, or a computer property with both a getter and a setter.

Body:
I understand that 'get' is used to give instructions on value for the variable 'numberOfWheels' is acquired. However, I do not understand what 'get set' is supposed to achieve in the code below. Does it mean that value can be acquired from the class, enum, or struct AND can also be acquired by a parameter passed on?

protocol WheeledVehicle: Vehicle {
  var numberOfWheels: Int { get }
  var wheelSize: Double { get set }
}


问:
Coqide 8.5: No syntax highlighting on Linux
I installed Coqide 8.5 w/ nix. Unfortunately, the text is blakc in all panels; there's no syntax highlighting of any kind (otherwise, 8.5 seems a big improvement over 8.4, which I've installed as well). I also get the following:

```<code>(coqide:17272): GtkSourceView-WARNING **: Unknown parent scheme 'classic' in scheme 'coq_style'

(coqide:17272): GtkSourceView-WARNING **: Failed to load '/nix/store/2sxcqfc4q3ls4g2q13n1zwfhnydvgq-coq-8.5pl1/share/coq/coq.lang': could not find the RelaxNG schema file
</code>```

The output of cat ~/.nix-profile/share/coq/coq_style.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<style-scheme id="coq_style" _name="Coq highlighting based on Ssr manual"
          parent-scheme="classic" version="1.0">
<author>The Coq Dev Team</author>
<_description>Coq/Ssreflect color scheme for the vernacular language</_description>

<style name="coq:comment" foreground="#brown"/>
<style name="coq:coqdoc" foreground="#brown" italic="true"/>
<style name="coq:vernac-keyword" bold="true" foreground="#dark violet"/>
<style name="coq:gallina-keyword" bold="true" foreground="#orange red"/>
<style name="coq:identifier" foreground="#navy"/>
<style name="coq:constr-keyword" foreground="#dark green"/>
<style name="coq:constr-sort" foreground="#008080"/>

<style name="coq-ssreflect:comment" foreground="#b22222"/>
<style name="coq-ssreflect:coqdoc" foreground="#b22222" italic="true"/>
<style name="coq-ssreflect:vernac-keyword" bold="true" foreground="#a021f0"/>
<style name="coq-ssreflect:gallina-keyword" bold="true" foreground="#a021f0"/>
<style name="coq-ssreflect:identifier" bold="true" foreground="#0000ff"/>
<style name="coq-ssreflect:constr-keyword" foreground="#228b22"/>
<style name="coq-ssreflect:constr-sort" foreground="#228b22"/>
<style name="coq-ssreflect:tactic" foreground="#101092"/>
<style name="coq-ssreflect:endtactic" foreground="#ff3f3f"/>
<style name="coq-ssreflect:iterator" foreground="#be6ad4"/>
<style name="coq-ssreflect:string" foreground="#8b2252"/>
</style-scheme>
</code>```

Given the first warning, I guess there should be something else instead of "classic" but what

答:
I just ran into this same issue with coqide installed via nix (in the coq-8.6 package).

Here's a script that installs symlinks to some files in your homedir to work around several warning messages:

## Find the nix-installed version of the GTK SourceView 2.0 library
sourceview="$(nix-env -q coq --no-name --out-path |
    xargs nix-store -q --references |
    grep -- -gtksourceview-)"

## Link files into the correct hierarchical folders in your home dir:
share=share/gtksourceview-2.0
for file in language-specs/language2.rng \
    language-specs/def.lang \
    styles/classic.xml
do
    target="$HOME/.local/$share/$file"
    mkdir -vp "$(dirname "$target")"
    ln -vfns "$sourceview/$share/$file" "$target"
done
```

<p>This fixes the following <code>GtkSourceView-WARNING</code>s:</p>

<pre class="lang-config prettyprint-override"><code>## fixed by language-specs/language2.rng
Failed to load '.../share/coq/coq.lang': could not find the RelaxNG schema file

## fixed by language-specs/def.lang
in file .../share/coq/coq.lang: style 'def:comment' not defined
Failed to load '.../share/coq/coq.lang': unable to resolve language 'def'

## fixed by styles/classic.xml
Unknown parent scheme 'classic' in scheme 'coq_style'
</code>```

I'll likely try to fix the coq derivation at some point to avoid needing this workaround.  I suspect either or both of the following would need to be done:

Fix how coq sets up the GTK SourceView search paths (since it includes the language definition)

Fix how gnome2.gtksourceview exports its search path(s) for other programs to use

Body:
I installed Coqide 8.5 w/ nix. Unfortunately, the text is blakc in all panels; there's no syntax highlighting of any kind (otherwise, 8.5 seems a big improvement over 8.4, which I've installed as well). I also get the following:

(coqide:17272): GtkSourceView-WARNING **: Unknown parent scheme 'classic' in scheme 'coq_style'

(coqide:17272): GtkSourceView-WARNING **: Failed to load '/nix/store/2sxcqfc4q3ls4g2q13n1zwfhnydvgq-coq-8.5pl1/share/coq/coq.lang': could not find the RelaxNG schema file

The output of cat ~/.nix-profile/share/coq/coq_style.xml:

<?xml version="1.0" encoding="UTF-8"?>

Given the first warning, I guess there should be something else instead of "classic" but what

Body:
I just ran into this same issue with coqide installed via nix (in the coq-8.6 package).

Here's a script that installs symlinks to some files in your homedir to work around several warning messages:

## Find the nix-installed version of the GTK SourceView 2.0 library
sourceview="$(nix-env -q coq --no-name --out-path |
    xargs nix-store -q --references |
    grep -- -gtksourceview-)"

## Link files into the correct hierarchical folders in your home dir:
share=share/gtksourceview-2.0
for file in language-specs/language2.rng \
    language-specs/def.lang \
    styles/classic.xml
do
    target="$HOME/.local/$share/$file"
    mkdir -vp "$(dirname "$target")"
    ln -vfns "$sourceview/$share/$file" "$target"
done

This fixes the following GtkSourceView-WARNINGs:

## fixed by language-specs/language2.rng
Failed to load '.../share/coq/coq.lang': could not find the RelaxNG schema file

## fixed by language-specs/def.lang
in file .../share/coq/coq.lang: style 'def:comment' not defined
Failed to load '.../share/coq/coq.lang': unable to resolve language 'def'

## fixed by styles/classic.xml
Unknown parent scheme 'classic' in scheme 'coq_style'

I'll likely try to fix the coq derivation at some point to avoid needing this workaround.  I suspect either or both of the following would need to be done:

Fix how coq sets up the GTK SourceView search paths (since it includes the language definition)

Fix how gnome2.gtksourceview exports its search path(s) for other programs to use


问:
Yii model and custom fields
I'm creating a app where user will can create meta field to store data on database, this fields will receive different kinds of data, like dates or monetary values.

My initial idea to create this this fields is store in a database table (eg: meta_fields), the name, value and validations of this field.

After on the time of use it on app, I intend to extend the AR methods __get and __set to use the name field as a attribute.

Example:

If on my table meta_fields i have this values:

```<code>----------------------------------------------------
| id | name     | value      | validation          |
----------------------------------------------------
| 1  | money_en | $562,00    | some validation...  |
----------------------------------------------------
| 2  | date_crt | 2010-12-09 | some validation...  |
----------------------------------------------------
</code>```

I intend to use in my views and controllers like it:

```<code>$model->money_en //will return $562,00
</code>```

Now the questions are:

1 - How can I use this kind of fields to store values and recovery it?
2 - How can I user different validation kinds to this fields? Since I store the validations array as a serialized values on database?

Thanks.

答: Maybe you should look into an EAV implementation? Someone created an EAV Behavior for Yii in the YiiExt, here (I haven't used it). EAV is complicated and (often) a bit inefficient (lots of joins!), but it's the way to go if you want to have an arbitrary number and type of fields attached to a DB "row".</p>

Title: Yii model and custom fields

Body:
I'm creating a app where user will can create meta field to store data on database, this fields will receive different kinds of data, like dates or monetary values.

My initial idea to create this this fields is store in a database table (eg: meta_fields), the name, value and validations of this field.

After on the time of use it on app, I intend to extend the AR methods __get and __set to use the name field as a attribute.

Example:

If on my table meta_fields i have this values:

----------------------------------------------------
| id | name     | value      | validation          |
----------------------------------------------------
| 1  | money_en | $562,00    | some validation...  |
----------------------------------------------------
| 2  | date_crt | 2010-12-09 | some validation...  |
----------------------------------------------------

I intend to use in my views and controllers like it:

$model->money_en //will return $562,00

Now the questions are:

1 - How can I use this kind of fields to store values and recovery it?
2 - How can I user different validation kinds to this fields? Since I store the validations array as a serialized values on database?

Thanks.


问:
Classify image with pretrained caffemodel in pycaffe
I want to classify an image with a pretrained model. I have the caffemodel and prototxt files, but when I load the models in caffe for python with

```<code>net = caffe.Net('/home/me/data/f1.prototxt',
                '/home/me/data/f1.caffemodel',
                caffe.TEST)
</code>```

I am getting the error

```<code>Check failed: mdb_status == 0 (2 vs. 0) No such file or directory
</code>```

There is a similar question here but the example there is for training a model so it doesn't apply in my case. What am I missing here?

The filepaths and permissions are correct.

答: Scroll up through the log file; there should be an earlier message telling you exactly what file it couldn't open.  Check the path and permissions.  When I get this, it's usually because I invoked caffe from the wrong directory.

Body:
I want to classify an image with a pretrained model. I have the caffemodel and prototxt files, but when I load the models in caffe for python with

net = caffe.Net('/home/me/data/f1.prototxt',
                '/home/me/data/f1.caffemodel',
                caffe.TEST)

I am getting the error

Check failed: mdb_status == 0 (2 vs. 0) No such file or directory

There is a similar question here but the example there is for training a model so it doesn't apply in my case. What am I missing here?

The filepaths and permissions are correct.


问:
C switch case with function
can someone explain me this code?
I cant understand why printed value is 8 in this code

can someone explain it to me

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

int f(int i){
    switch (i){
        case 0 :
            return 0;
        case 1:

        case 2:
            return 1;
        default:

            return f(i-2)+f(i-1);
    }
}

void main(void) {

printf("%d", f(6));

}
</code>```

答:
This is a recursive function to implement the Fibonacci sequence

Lets consider a simpler scenario (in order to shorten response length) of if we were to call the function with argument of 4 : f(4)

Stepping through it we find:

Called f(4)

Hit default case statement to call f(2) + f(3)

The f(2) call will hit the case statement for 2 and return 1

The f(3) call will hit the default case statement and call f(1) + f(2)

Both f(1) and f(2) will hit their respective case statements and return 1

We now know the f(3) call returns f(1) + f(2) = 1 + 1 = 2

We now know the f(4) call returns f(2) + f(3) = 1 + 2 = 3

I would recommend the same process to see why a call of f(5) would return 5. And then using the fact that f(4) = 3 and f(5) = 5, you can understand why f(6) = f(4) + f(5) = 8.

Title: C switch case with function

Body:
can someone explain me this code?
I cant understand why printed value is 8 in this code

can someone explain it to me

#include <stdio.h>

int f(int i){
    switch (i){
        case 0 :
            return 0;
        case 1:

        case 2:
            return 1;
        default:

            return f(i-2)+f(i-1);
    }
}

void main(void) {

printf("%d", f(6));

}


问:
ImportError: No module named lxml.etree failed in Apache2 CGI
The error is only happened in web. If I run it in console, it is OK.I am working in ubuntu.

I have setup apache2 using CGI for handle python and tried to displayed the python version in the code and can prove web and console both running on same python version and user.

But as long as import lxml.etree, I got the error below.

```<code>Traceback (most recent call last):
  File "/usr/lib/cgi-bin/TestPy.py", line 3, in <module>
    import lxml.etree as ET
ImportError: No module named lxml.etree
</code>```

My CGI config is as below:
Filename: serve-cgi-bin.conf

```<code><IfDefine ENABLE_USR_LIB_CGI_BIN>
    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Require all granted

        #AddHandler cgi-script .py
        #Order allow,deny
        #Allow from all

    </Directory>
</IfDefine>
</code>```

My python code is as below:

```<code>#!/usr/bin/python

import lxml.etree as ET
import sys

print "Content-Type: text/plain\r\n\r\n"
print "Hello World!"

print "[" + sys.version + "]" + "  [" + sys.prefix + "]"
#xml_filename='/var/www/htmprint/Water.xml'
#xsl_filename='/var/www/htmprint/Water.xsl'
#dom = ET.parse(xml_filename)
#xslt = ET.parse(xsl_filename)
#transform = ET.XSLT(xslt)
#newdom = transform(dom)
#print(ET.tostring(newdom, pretty_print=True))
</code>```

I got the feeling the permission isn't quite right for the lxml.etree file but I cannot figure out this.

Thanks in advance if anyone can help.

Bin

答: Install the package to the global site-packages, not your .local which is your personal space.</p>

Body:
The error is only happened in web. If I run it in console, it is OK.I am working in ubuntu.

I have setup apache2 using CGI for handle python and tried to displayed the python version in the code and can prove web and console both running on same python version and user.

But as long as import lxml.etree, I got the error below.

Traceback (most recent call last):
  File "/usr/lib/cgi-bin/TestPy.py", line 3, in <module>
    import lxml.etree as ET
ImportError: No module named lxml.etree

My CGI config is as below:
Filename: serve-cgi-bin.conf

<IfDefine ENABLE_USR_LIB_CGI_BIN>
    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Require all granted

        #AddHandler cgi-script .py
        #Order allow,deny
        #Allow from all

    </Directory>
</IfDefine>

My python code is as below:

#!/usr/bin/python

import lxml.etree as ET
import sys

print "Content-Type: text/plain\r\n\r\n"
print "Hello World!"

print "[" + sys.version + "]" + "  [" + sys.prefix + "]"
#xml_filename='/var/www/htmprint/Water.xml'
#xsl_filename='/var/www/htmprint/Water.xsl'
#dom = ET.parse(xml_filename)
#xslt = ET.parse(xsl_filename)
#transform = ET.XSLT(xslt)
#newdom = transform(dom)
#print(ET.tostring(newdom, pretty_print=True))

I got the feeling the permission isn't quite right for the lxml.etree file but I cannot figure out this.

Thanks in advance if anyone can help.

Bin


Title: C switch case with function

Body:
Maybe you just need to step through the code in a debug run, but this is why you have f(6)=8

step1: f(6)
step2: f(6-2)              +f(6-1)
step3: f(4-2)+f(4-1)       +f(5-2)       +f(5-1)
step4: f(2)  +f(3-2)+f(3-1)+f(3-2)+f(3-1)+f(4-2)+f(4-1)
step5: 1     +1     +1     +1     +1     +1     +f(3-2)+f(3-1)
step6: 1     +1     +1     +1     +1     +1     +1     +1
final: 8


问:
Linking Types in Scala
I have a class of objects which either have one type of ID or another:

```<code>sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item {
  def id: ItemId
}

case class ItemWithNumericId(id: NumericId) extends Item
case class ItemWithStringId(id: StringId) extends Item
</code>```

I'd like to create an interface for some sort of service which retrieves items:

```<code>trait ItemService[IdType <: ItemId, ItemType <: Item] {
  def get(id: IdType): ItemType
}
</code>```

How do I link the ItemId type with the Item type to put a constraint on ItemServices to not allow something like:

```<code>class SillyItemService extends ItemService[NumericId, ItemWithStringId] {
  def get(id: NumericId): ItemWithStringId = ???
}
</code>```

I've realised I can add generic types to the Item class:

```<code>sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item[Id <: ItemId] {
  def id: Id
}

case class ItemWithNumericId(id: NumericId) extends Item[NumericId]
case class ItemWithStringId(id: StringId) extends Item[StringId]

trait ItemService[IdType <: ItemId, ItemType <: Item[IdType]] {
  def get(id: IdType): ItemType
}
</code>```

which is OK but It's super verbose. Ideally, the service would only have a single generic type.

Thanks very much for any answers/input.

答:
Something like this maybe?</p>

```<code> trait Item {
    type IdType
    def id: IdType
 }

 trait ItemService[I <: Item] {
   def get(id: I#IdType): Item
 }
</code>```

Title: Linking Types in Scala

Body:
I have a class of objects which either have one type of ID or another:

sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item {
  def id: ItemId
}

case class ItemWithNumericId(id: NumericId) extends Item
case class ItemWithStringId(id: StringId) extends Item

I'd like to create an interface for some sort of service which retrieves items:

trait ItemService[IdType <: ItemId, ItemType <: Item] {
  def get(id: IdType): ItemType
}

How do I link the ItemId type with the Item type to put a constraint on ItemServices to not allow something like:

class SillyItemService extends ItemService[NumericId, ItemWithStringId] {
  def get(id: NumericId): ItemWithStringId = ???
}

I've realised I can add generic types to the Item class:

sealed trait ItemId
case class NumericId(id: Int) extends ItemId
case class StringId(id: String) extends ItemId

sealed trait Item[Id <: ItemId] {
  def id: Id
}

case class ItemWithNumericId(id: NumericId) extends Item[NumericId]
case class ItemWithStringId(id: StringId) extends Item[StringId]

trait ItemService[IdType <: ItemId, ItemType <: Item[IdType]] {
  def get(id: IdType): ItemType
}

which is OK but It's super verbose. Ideally, the service would only have a single generic type.

Thanks very much for any answers/input.

Body:
Something like this maybe?

 trait Item {
    type IdType
    def id: IdType
 }

 trait ItemService[I <: Item] {
   def get(id: I#IdType): Item
 }


问:
c remove new line char help
Im fairly new to c sorry if this is a stupid question!

i have this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;
</code>```

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;
</code>```

there was no effect!

答:
Hint:
Remove the last character! (Hint to hint: you know the length)</p>

Title: c remove new line char help

Body:
Im fairly new to c sorry if this is a stupid question!

i have this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;

there was no effect!


问:
Select bigger articles among two wikipedias
Using "Quarry" from Wmflabs (https://quarry.wmflabs.org/).

As I understand this is MySQL.

How can I select all articles from german wiki, which are bigger by size, than articles in enwiki?

Here is the code, I use. I need the de_len, but I don't know how to get it.

```<code>USE enwiki_p;

SELECT
        page_title en_title,
        page_len en_len,
        ll.ll_title as de_title
FROM page
JOIN langlinks ll
    ON ll_from = page_id
WHERE page_namespace = 0
GROUP BY page_id
HAVING max(CASE ll_lang  WHEN 'de' THEN 1 ELSE 0 END) = 0
LIMIT 10
</code>```

答:
You need to work with minimum three tables from two databases to get properly page sizes of corresponing articles (pages) from two wikis, plus related interlanguage links for relationship, for a good comparison.
A solution would be this:</p>

```<code>SELECT
       enp.page_title as en_title,
       enp.page_len as en_len,
       dep.page_title as de_title,
       dep.page_len as de_len
FROM enwiki_p.page enp
JOIN enwiki_p.langlinks enll
  ON enll.ll_from = enp.page_id and ll_lang="de"
JOIN dewiki_p.page dep
  ON enll.ll_title = REPLACE(dep.page_title, '_', ' ')
WHERE enp.page_namespace = 0 and enp.page_is_redirect = 0
  AND dep.page_namespace = 0 and dep.page_is_redirect = 0
GROUP BY enp.page_id
HAVING dep.page_len > enp.page_len
ORDER BY dep.page_len DESC
LIMIT 100
</code>```

Body:
Using "Quarry" from Wmflabs (https://quarry.wmflabs.org/).

As I understand this is MySQL.

How can I select all articles from german wiki, which are bigger by size, than articles in enwiki?

Here is the code, I use. I need the de_len, but I don't know how to get it.

USE enwiki_p;

SELECT
        page_title en_title,
        page_len en_len,
        ll.ll_title as de_title
FROM page
JOIN langlinks ll
    ON ll_from = page_id
WHERE page_namespace = 0
GROUP BY page_id
HAVING max(CASE ll_lang  WHEN 'de' THEN 1 ELSE 0 END) = 0
LIMIT 10

Body:
You need to work with minimum three tables from two databases to get properly page sizes of corresponing articles (pages) from two wikis, plus related interlanguage links for relationship, for a good comparison.
A solution would be this:

SELECT
       enp.page_title as en_title,
       enp.page_len as en_len,
       dep.page_title as de_title,
       dep.page_len as de_len
FROM enwiki_p.page enp
JOIN enwiki_p.langlinks enll
  ON enll.ll_from = enp.page_id and ll_lang="de"
JOIN dewiki_p.page dep
  ON enll.ll_title = REPLACE(dep.page_title, '_', ' ')
WHERE enp.page_namespace = 0 and enp.page_is_redirect = 0
  AND dep.page_namespace = 0 and dep.page_is_redirect = 0
GROUP BY enp.page_id
HAVING dep.page_len > enp.page_len
ORDER BY dep.page_len DESC
LIMIT 100


问:
Why does recursion overwrite values in a list that is passed along?
This recusion is adapted from http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/ and does indeed print out all possible unique combination of arr with length r.

What I want from it is to save all possible combination in a list to further use this algorithm in another program. Why is the values overritten in combArray in the recustion and how do I solve this?

```<code>def combRecursive(arr, data, start, end, index, r, combArray):
    if index == r:
        combArray.append(data)
        return combArray

    i = start
    while True:
        if i > end or end - i + 1 < r - index:
            break
        data[index] = arr[i]
        combArray = combRecursive(arr, data, i + 1, end, index + 1, r, combArray)
        i += 1
    return combArray

def main():
    arr = [1, 2, 3, 4, 5]
    r = 3
    n = len(arr)
    data = [9999999, 9999999, 9999999]
    combArray = []

    combArray = combRecursive(arr, data, 0, n-1, 0, r, combArray)
    print("All possible unique combination is: ")
    for element in combArray:
        print(element)
</code>```

Result as of now:

```<code>[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
</code>```

What I want:

```<code>[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
</code>```

答: You initialize data, and from then on make changes to it & add it to combArray, which means you are always adding the same array to combArray, so all of its elements are the same.  If you want the elements to be distinct arrays, you need to make a new array for each you want to add to combArrays (by, for example, making a copy of data).

Body:
This recusion is adapted from http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/ and does indeed print out all possible unique combination of arr with length r.

What I want from it is to save all possible combination in a list to further use this algorithm in another program. Why is the values overritten in combArray in the recustion and how do I solve this?

def combRecursive(arr, data, start, end, index, r, combArray):
    if index == r:
        combArray.append(data)
        return combArray

    i = start
    while True:
        if i > end or end - i + 1 < r - index:
            break
        data[index] = arr[i]
        combArray = combRecursive(arr, data, i + 1, end, index + 1, r, combArray)
        i += 1
    return combArray

def main():
    arr = [1, 2, 3, 4, 5]
    r = 3
    n = len(arr)
    data = [9999999, 9999999, 9999999]
    combArray = []

    combArray = combRecursive(arr, data, 0, n-1, 0, r, combArray)
    print("All possible unique combination is: ")
    for element in combArray:
        print(element)

Result as of now:

[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]

What I want:

[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]