问:
Because of the setInterval Javascript command, my photo won't slowly appear on my webpage
My webpage has a heading that starts out small.  But it grows in size as it approaches the screen.  Then it's supposed to float to the top of the screen.  While the heading approaches the top of the screen, a photo is supposed to fade into view.  There is also a caption that is supposed to fade into view.  But neither the photo or the caption will fade into view.  And I don't know why.

YouTube_Advanced_Heading.htm

```<code><!DOCTYPE html>
<html>
<head>
<title>Advanced Heading</title>
<link rel = "stylesheet" type = "text/css" href =
"YouTube_Advanced_Heading.css">
</link>
<script language = "JavaScript" src = "YouTube_Advanced_Heading.js">
</script>
</head>
<body id = "BColor" onload = "Setup()">
<h1 id = "My_Heading">The Winner Of The Video Response Wars Is:</h1>
<img id = "My_Image" src = "Bootsie.jpg">
</img>
<p id = "Winner_Text">Crazy Josh Cravy</p>
<input id = "Point_Values" type = "hidden">
</input>
<input id = "Raise_My_Text" type = "hidden">
</input>
<input id = "S_Collection" type = "hidden">
</input>
<input id = "F_Photo" type = "hidden">
</input>
<input id = "T_Height" type = "text">
</input>
</body>
</html>
</code>```

YouTube_Advance_Heading.css

```<code>#BColor {
background-color: yellow;}
#My_Heading {
position: absolute;
top: 300px;
left: 400px;
font-size: 32px;}
#My_Image {
position: absolute;
top: 200px;
left: 475px;
width: 400px;
height: 300px;}
#Winner_Text {
position: absolute;
top: 475px;
left: 525px;
font-weight: bold;
font-size: 30pt;}
</code>```

YouTube_Advance_Heading.js

```<code>My_Timer = setInterval(Display_Text, 100);

function Setup() {

   var User_Screen_Width
   var User_Screen_Height
   var Text_Width
   var Text_Height
   var Text_Array
   var Text_Array_Counter
   var Text
   var My_Timer
   var My_Timer_2
   var My_Timer_3
   var Point_Value
   var Screen_Position
   var Style_Collection
   var Fade_Number

   Text_Arrays = new Array(0, 27, 50, 75, 95, 122, 151, 174, 199, 217, 245,
   274,  292, 317, 341, 365, 390, 414, 439, 463, 487, 512, 536, 561, 585,
   609, 634, 658, 683, 707, 731, 756, 780, 805, 829, 853, 878, 902, 927,
   951, 975);
   document.getElementById("Point_Values").value = 0;
   document.getElementById("F_Photo").value = 0;
   document.getElementById("My_Image").style.opacity = 0.01
   document.getElementById("Winner_Text").style.opacity = 0.01

}

function Display_Text() {

     Point_Value = document.getElementById("Point_Values").value;

     if(Point_Value < 40) {

          Point_Value = parseInt(Point_Value);
          User_Screen_Width = screen.availWidth;
          Text_Array_Counter = Point_Value;
          Text_Width = Text_Arrays[Text_Array_Counter];
          Screen_Position = User_Screen_Width - Text_Width;
          Screen_Position = Screen_Position / 2;
          Style_Collection = "left: " + Screen_Position + "px; ";
          Style_Collection = Style_Collection + "font-size: " + Point_Value
          + "pt; ";
          document.getElementById("S_Collection").value = Style_Collection;
          document.getElementById("My_Heading").style.cssText =
          Style_Collection;
          Point_Value = Point_Value + 1;}

     if (Point_Value == 40) {

         document.getElementById("Raise_My_Text").value = 300;

         clearInterval(My_Timer);
         My_Timer_2 = setInterval(Raise_Text, 100);}

      else {

          document.getElementById("Point_Values").value = Point_Value;

      }

}

function Raise_Text() {

    Text_Height = document.getElementById("Raise_My_Text").value;

    if(Text_Height > 100) {

          Fade_Number = document.getElementById("F_Photo").value;
          Fade_Number = parseFloat(Fade_Number);
          Fade_Number = Fade_Number + .00017
          document.getElementById("T_Height").value = Fade_Number;
          document.getElementById("My_Image").style.opacity = Fade_Number;
          document.getElementById("Winner_Text").style.opacity =
          Fade_Number;

          if(Fade_Number < 1) {

               document.getElementById("F_Photo").value = Fade_Number;}

          Style_Collection = document.getElementById("S_Collection").value;
          document.getElementById("My_Heading").style.cssText =
          Style_Collection;
          Text_Height = document.getElementById("Raise_My_Text").value;
          Text_Height = Text_Height - 3;
          Style_Collection = Style_Collection + "top: " + Text_Height +
          "px;";
          document.getElementById("My_Heading").style.cssText =
          Style_Collection;
          document.getElementById("Raise_My_Text").value = Text_Height;}

}
</code>```

答:
The final opacity was way too low. So on line 79 of your js file, I removed a couple "0"s and it worked.</p>

```<code>Fade_Number = Fade_Number + .017
</code>```

Body:
My webpage has a heading that starts out small.  But it grows in size as it approaches the screen.  Then it's supposed to float to the top of the screen.  While the heading approaches the top of the screen, a photo is supposed to fade into view.  There is also a caption that is supposed to fade into view.  But neither the photo or the caption will fade into view.  And I don't know why.

YouTube_Advanced_Heading.htm

<!DOCTYPE html>

<title>Advanced Heading</title>
<link rel = "stylesheet" type = "text/css" href =
"YouTube_Advanced_Heading.css">
</link>

The Winner Of The Video Response Wars Is:

Crazy Josh Cravy

<input id = "Point_Values" type = "hidden">
</input>
<input id = "Raise_My_Text" type = "hidden">
</input>
<input id = "S_Collection" type = "hidden">
</input>
<input id = "F_Photo" type = "hidden">
</input>
<input id = "T_Height" type = "text">
</input>

YouTube_Advance_Heading.css

#BColor {
background-color: yellow;}
#My_Heading {
position: absolute;
top: 300px;
left: 400px;
font-size: 32px;}
#My_Image {
position: absolute;
top: 200px;
left: 475px;
width: 400px;
height: 300px;}
#Winner_Text {
position: absolute;
top: 475px;
left: 525px;
font-weight: bold;
font-size: 30pt;}

YouTube_Advance_Heading.js

My_Timer = setInterval(Display_Text, 100);

function Setup() {

   var User_Screen_Width
   var User_Screen_Height
   var Text_Width
   var Text_Height
   var Text_Array
   var Text_Array_Counter
   var Text
   var My_Timer
   var My_Timer_2
   var My_Timer_3
   var Point_Value
   var Screen_Position
   var Style_Collection
   var Fade_Number

   Text_Arrays = new Array(0, 27, 50, 75, 95, 122, 151, 174, 199, 217, 245,
   274,  292, 317, 341, 365, 390, 414, 439, 463, 487, 512, 536, 561, 585,
   609, 634, 658, 683, 707, 731, 756, 780, 805, 829, 853, 878, 902, 927,
   951, 975);
   document.getElementById("Point_Values").value = 0;
   document.getElementById("F_Photo").value = 0;
   document.getElementById("My_Image").style.opacity = 0.01
   document.getElementById("Winner_Text").style.opacity = 0.01

}

function Display_Text() {

     Point_Value = document.getElementById("Point_Values").value;

     if(Point_Value < 40) {

          Point_Value = parseInt(Point_Value);
          User_Screen_Width = screen.availWidth;
          Text_Array_Counter = Point_Value;
          Text_Width = Text_Arrays[Text_Array_Counter];
          Screen_Position = User_Screen_Width - Text_Width;
          Screen_Position = Screen_Position / 2;
          Style_Collection = "left: " + Screen_Position + "px; ";
          Style_Collection = Style_Collection + "font-size: " + Point_Value
          + "pt; ";
          document.getElementById("S_Collection").value = Style_Collection;
          document.getElementById("My_Heading").style.cssText =
          Style_Collection;
          Point_Value = Point_Value + 1;}

     if (Point_Value == 40) {

         document.getElementById("Raise_My_Text").value = 300;

         clearInterval(My_Timer);
         My_Timer_2 = setInterval(Raise_Text, 100);}

      else {

          document.getElementById("Point_Values").value = Point_Value;

      }

}

function Raise_Text() {

    Text_Height = document.getElementById("Raise_My_Text").value;

    if(Text_Height > 100) {

          Fade_Number = document.getElementById("F_Photo").value;
          Fade_Number = parseFloat(Fade_Number);
          Fade_Number = Fade_Number + .00017
          document.getElementById("T_Height").value = Fade_Number;
          document.getElementById("My_Image").style.opacity = Fade_Number;
          document.getElementById("Winner_Text").style.opacity =
          Fade_Number;

          if(Fade_Number < 1) {

               document.getElementById("F_Photo").value = Fade_Number;}

          Style_Collection = document.getElementById("S_Collection").value;
          document.getElementById("My_Heading").style.cssText =
          Style_Collection;
          Text_Height = document.getElementById("Raise_My_Text").value;
          Text_Height = Text_Height - 3;
          Style_Collection = Style_Collection + "top: " + Text_Height +
          "px;";
          document.getElementById("My_Heading").style.cssText =
          Style_Collection;
          document.getElementById("Raise_My_Text").value = Text_Height;}

}

Body:
The final opacity was way too low. So on line 79 of your js file, I removed a couple "0"s and it worked.

Fade_Number = Fade_Number + .017


来源: stackexchange

问:
Get whole dataset for each unique combination of two columns and their max and min values
I'm desperately searching a query which gives me all datasets to the following query:

```<code>SELECT col1, col2, MAX(col3), MIN(col4) FROM table1 GROUP BY col1, col2
</code>```

This returns a Table like the following

```<code>col 1  | col2   | max(col3) | min(col4)
------ | ------ | --------- | ------
10     | 0.5    | 20        | -5
10     | 0.9    | 30        | -2
</code>```

What I need is the dataset(the whole row) for each max and min and each entity. I could do this programatically with a query like

SELECT * FROM table1 WHERE col1 = 10 AND (col2 = 0.5 OR col2 = 0.9) AND ((col3 = 20 OR col4 = -5) OR (col3 = 30 OR col4 = -2 ))
```

<p>which returns me 4 datasets,</p>

<p>but the Query gets more ugly with each added MAX or MIN or GROUP BY(this is what the users do with the program).</p>

<p>Let me try to explain it in one sentence: I'm searching a way of displaying the dataset to each max and min value(not col1,col2) of each unique combination of values of col1 and col2. </p>

<p>Is there a way, to do this in one query? </p>

<p>If you need further details don't fear to comment. </p>

<h2>Edit 1</h2>

<p><strong>Dataset</strong></p>

```id   | col 1  | col2   | col3   | col4
---- | ------ | ------ | ------ | ------
  0  |   10   |  0.5   |  20    |  0
  1  |   10   |  0.5   |  15    | -1
  2  |   10   |  0.5   |  17    | 12
  3  |   10   |  0.5   |  11    |  3
  4  |   10   |  0.5   |   5    | -5
  5  |   10   |  0.9   |  10    |  1
  6  |   10   |  0.9   |  22    | -1
  7  |   10   |  0.9   |  15    | -2
  8  |   10   |  0.9   |  30    |  3
```

<p><strong>Desired Output</strong></p>

```id   |  col 1  | col2   | col3   | col4
---- |  ------ | ------ | ------ | ------
  0  |   10    |  0.5   |  20    |  0
  4  |   10    |  0.5   |  5     | -5
  7  |   10    |  0.9   |  15    | -2
  8  |   10    |  0.9   |  30    |  3
```

答:
This should do it: </p>

```<code>SELECT A.* FROM

table1 A

INNER JOIN

(SELECT
col1,
col2,
MAX(col3) AS MAX_col3,
MIN(col4) AS MIN_col4
FROM table1
GROUP BY
col1,
col2) B

ON A.col1 = B.col1
AND A.col2 = B.col2
AND A.col3 = B.MAX_col3
AND A.col4 = B.MIN_col4
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm desperately searching a query which gives me all datasets to the following query:

SELECT col1, col2, MAX(col3), MIN(col4) FROM table1 GROUP BY col1, col2

This returns a Table like the following

col 1  | col2   | max(col3) | min(col4)
------ | ------ | --------- | ------
10     | 0.5    | 20        | -5
10     | 0.9    | 30        | -2

What I need is the dataset(the whole row) for each max and min and each entity. I could do this programatically with a query like

SELECT * FROM table1 WHERE col1 = 10 AND (col2 = 0.5 OR col2 = 0.9) AND ((col3 = 20 OR col4 = -5) OR (col3 = 30 OR col4 = -2 ))

which returns me 4 datasets,

but the Query gets more ugly with each added MAX or MIN or GROUP BY(this is what the users do with the program).

Let me try to explain it in one sentence: I'm searching a way of displaying the dataset to each max and min value(not col1,col2) of each unique combination of values of col1 and col2.

Is there a way, to do this in one query?

If you need further details don't fear to comment.

Edit 1

Dataset

id   | col 1  | col2   | col3   | col4
---- | ------ | ------ | ------ | ------
  0  |   10   |  0.5   |  20    |  0
  1  |   10   |  0.5   |  15    | -1
  2  |   10   |  0.5   |  17    | 12
  3  |   10   |  0.5   |  11    |  3
  4  |   10   |  0.5   |   5    | -5
  5  |   10   |  0.9   |  10    |  1
  6  |   10   |  0.9   |  22    | -1
  7  |   10   |  0.9   |  15    | -2
  8  |   10   |  0.9   |  30    |  3

Desired Output

id   |  col 1  | col2   | col3   | col4
---- |  ------ | ------ | ------ | ------
  0  |   10    |  0.5   |  20    |  0
  4  |   10    |  0.5   |  5     | -5
  7  |   10    |  0.9   |  15    | -2
  8  |   10    |  0.9   |  30    |  3

Body:
This should do it:

SELECT A.* FROM

table1 A

INNER JOIN

(SELECT
col1,
col2,
MAX(col3) AS MAX_col3,
MIN(col4) AS MIN_col4
FROM table1
GROUP BY
col1,
col2) B

ON A.col1 = B.col1
AND A.col2 = B.col2
AND A.col3 = B.MAX_col3
AND A.col4 = B.MIN_col4


问:
Passing 3D array as parameter into function in C++14 the right way
I need some help, I need to pass a rijndael round key into a function as a parameter. The round key is a 3D array which looks like this:

```<code>unsigned char rk[11][4][4];
</code>```

Now I need to input this into a function and make some binary operations to it (so the parameter should be editable). How do I do it the right way? The way I did it was to put it inside a struct and pass the struct to the function. But it is ugly. So now my code looks like this:

```<code>typedef struct{
  unsigned char rk[11][4][4];
}roundKey;

void addKey(roundKey* rk, ....)
{
  some_unsigned_char ^= rk->rk[foo][bar][i];
}
</code>```

It is ugly and I would like to do it the right way. How should I do it?

答:
Au contraire, I think you are doing it in one of the best possible ways, I'd just rearrange to make that a full-fledged class. That way we can easily pass it around, add some nice accessor methods to simplify the code, and otherwise do our best to abstract away the 3D nature of the array from most of the code.

```<code>class RoundKey {
 public:
  uint8_t rk[11][4][4];
  uint8_t& operator()(int x, int y, int z){
    return rk[x][y][z];
  }
};

void addKey(RoundKey &rk, ....){
  some_unsigned_char ^= rk(foo,bar,i);
}
</code>```

(Rearrange indices as appropriate.)

Given the simplicity of the class, the compiler's likely to compile it to something that is very similar, if not identical, to what passing the full 3D array around would have given.

Body:
I need some help, I need to pass a rijndael round key into a function as a parameter. The round key is a 3D array which looks like this:

unsigned char rk[11][4][4];

Now I need to input this into a function and make some binary operations to it (so the parameter should be editable). How do I do it the right way? The way I did it was to put it inside a struct and pass the struct to the function. But it is ugly. So now my code looks like this:

typedef struct{
  unsigned char rk[11][4][4];
}roundKey;

void addKey(roundKey* rk, ....)
{
  some_unsigned_char ^= rk->rk[foo][bar][i];
}

It is ugly and I would like to do it the right way. How should I do it?

Body:
Au contraire, I think you are doing it in one of the best possible ways, I'd just rearrange to make that a full-fledged class. That way we can easily pass it around, add some nice accessor methods to simplify the code, and otherwise do our best to abstract away the 3D nature of the array from most of the code.

class RoundKey {
 public:
  uint8_t rk[11][4][4];
  uint8_t& operator()(int x, int y, int z){
    return rk[x][y][z];
  }
};

void addKey(RoundKey &rk, ....){
  some_unsigned_char ^= rk(foo,bar,i);
}

(Rearrange indices as appropriate.)

Given the simplicity of the class, the compiler's likely to compile it to something that is very similar, if not identical, to what passing the full 3D array around would have given.


问:
Object Oriented questions in Javascript
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

```<code>function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

```<code>function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

```<code>var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());
</code>```

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

```<code>var user = new User("Bob", 44);
</code>```

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

答:
Every time a function() {} is evaluated, it creates a new function object.  Therefore, in #1 all of the User objects are sharing the same getName and getAge functions, but in #2 and #3, each object has its own copy of getName and getAge.  All of the different getName functions all behave exactly the same, so you can't see any difference in the output.

The {...} shorthand is a constructor.  When evaluated, it constructs a new "Object" with the given properties.  When you run "new User(...)", it constructs a new "User".  You happen to have created an Object with the same behavior as a User, but they are of different types.

Response to comment:

You can't, directly.  You could make a function that creates a new object as per #3.  For example:

```<code>function make_user(name, age) {
    return {
        name: name,
        age: age,
        getName: function() { return name; },
        getAge: function() { return age; },
    };
}

var user = make_user("Joe", "18");
</code>```

OwnerDisplayName: BrianH

ContentLicense: CC BY-SA 2.5

Title: Object Oriented questions in Javascript

Body:
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

var user = new User("Bob", 44);

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

LastEditorDisplayName: BrianH

Body:
Every time a function() {} is evaluated, it creates a new function object.  Therefore, in #1 all of the User objects are sharing the same getName and getAge functions, but in #2 and #3, each object has its own copy of getName and getAge.  All of the different getName functions all behave exactly the same, so you can't see any difference in the output.

The {...} shorthand is a constructor.  When evaluated, it constructs a new "Object" with the given properties.  When you run "new User(...)", it constructs a new "User".  You happen to have created an Object with the same behavior as a User, but they are of different types.

Response to comment:

You can't, directly.  You could make a function that creates a new object as per #3.  For example:

function make_user(name, age) {
    return {
        name: name,
        age: age,
        getName: function() { return name; },
        getAge: function() { return age; },
    };
}

var user = make_user("Joe", "18");

OwnerDisplayName: Glomek

LastEditorDisplayName: Glomek


问:
Rails: Customize Devise Confirmable module?
I have my Rails app setup with Devise, but it's still in the development stages. I also have a Thor task that creates the default Admin user.

Problem is Devise won't let that admin user login to the site until the account is confirmed. Is there any way I can disable the confirmable module for the creation of specific users, such as Admin?

My Thor task:

```<code>class Setup < Thor
  desc "create_admin [EMAIL] [PASSWORD]", "Creates the administrative user."
  def create_admin(email = "admin@bogus.com", password = "testpassword123")
    require File.expand_path('config/environment.rb') # load Rails environment
    admin = User.create(:email => email, :password => password, :password_confirmation => password)
    admin.assign_role :admin
    puts "Admin user (#{ email }) created."
  end
end
</code>```

答:
This should work

```<code>admin = User.create(:email => email, :password => password, :password_confirmation => password)
</code>```

So your confirmed_at is set, which is the field devise refers to when checking user confirmation.

EDIT

Forgive me if this seems like a hack but this seems to work for me. After executing the above line,

```<code>admin.update_attributes(:confirmed_at => Time.now)
</code>```

Body:
I have my Rails app setup with Devise, but it's still in the development stages. I also have a Thor task that creates the default Admin user.

Problem is Devise won't let that admin user login to the site until the account is confirmed. Is there any way I can disable the confirmable module for the creation of specific users, such as Admin?

My Thor task:

class Setup < Thor
  desc "create_admin [EMAIL] [PASSWORD]", "Creates the administrative user."
  def create_admin(email = "admin@bogus.com", password = "testpassword123")
    require File.expand_path('config/environment.rb') # load Rails environment
    admin = User.create(:email => email, :password => password, :password_confirmation => password)
    admin.assign_role :admin
    puts "Admin user (#{ email }) created."
  end
end

Body:
This should work

admin = User.create(:email => email, :password => password, :password_confirmation => password)

So your confirmed_at is set, which is the field devise refers to when checking user confirmation.

EDIT

Forgive me if this seems like a hack but this seems to work for me. After executing the above line,

admin.update_attributes(:confirmed_at => Time.now)


问:
How to Align Bootstrap thumbnails horizontally
I know this is a silly question but Can someone please tell me how can I arrange Bootstrap thumbnails horizontally?

Currently the thumbnails are placed vertically (one below the other).

This is my code snippet for the two thumbnails.

```<code><div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="photos/square.png" alt="...">
                <div class="caption">
                    <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
                    <p>...</p>
                    <p><a href="#" class="btn btn-primary btn-ok" role="button">Read More</a></p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="photos/square.png" alt="...">
                <div class="caption">
                    <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
                    <p>...</p>
                    <p><a href="#" class="btn btn-primary btn-ok" role="button">Read More</a></p>
                </div>
            </div>
        </div>
    </div>
</code>```

And here's s screenshot how it is placed.

答:
You created two 'rows'. Instead try this:

```<code><div class="row">
<div class="col-sm-6 col-md-4">
    <div class="thumbnail">
        <img alt="..." src="photos/square.png">
        <div class="caption">
            <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
            <p>...</p>
            <p><a class="btn btn-primary btn-ok" href="#" role="button">Read More</a></p>
        </div>
    </div>
    <div class="thumbnail">
        <img alt="..." src="photos/square.png">
        <div class="caption">
            <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
            <p>...</p>
            <p><a class="btn btn-primary btn-ok" href="#" role="button">Read More</a></p>
        </div>
    </div>
</div>
</code>```

Body:
I know this is a silly question but Can someone please tell me how can I arrange Bootstrap thumbnails horizontally?

Currently the thumbnails are placed vertically (one below the other).

This is my code snippet for the two thumbnails.

Software Name

...

Read More

Software Name

...

Read More

And here's s screenshot how it is placed.

Body:
You created two 'rows'. Instead try this:

<div class="row">
<div class="col-sm-6 col-md-4">
    <div class="thumbnail">
        <img alt="..." src="photos/square.png">
        <div class="caption">
            <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
            <p>...</p>
            <p><a class="btn btn-primary btn-ok" href="#" role="button">Read More</a></p>
        </div>
    </div>
    <div class="thumbnail">
        <img alt="..." src="photos/square.png">
        <div class="caption">
            <h3 style="font-size:16px;position:relative;left:35px;top:-27px;font-family:Myriad Pro;color:white;">Software Name</h3>
            <p>...</p>
            <p><a class="btn btn-primary btn-ok" href="#" role="button">Read More</a></p>
        </div>
    </div>
</div>


问:
Compiling Expression throws cannot be used for return type ArgumentException
I am trying to get more familiar with expression trees.

I have created a simple switch expression as follows:

```<code>var paramExp = Expression.Parameter(typeof(int));
Expression<Func<int>> defaultBodyExp = () => 4;
var switchBodyExp = Expression.Switch(paramExp, defaultBodyExp,
    Expression.SwitchCase(defaultBodyExp, Expression.Constant(1)));
var func = Expression.Lambda<Func<int, int>>(switchBodyExp, paramExp).Compile();
int result = func(6);
</code>```

But this raises the following exception when trying to call Compile:

Expression of type 'System.Func`1[System.Int32]' cannot be used for return type 'System.Int32'

I can get it working by doing the following:

```<code>var paramExp = Expression.Parameter(typeof(int));
//Expression<Func<int>> defaultBodyExp = () => 4;
var defaultBodyMethodInfo = typeof(Program).GetMethod("DefaultBody");
var switchBodyExp = Expression.Switch(paramExp, Expression.Call(defaultBodyMethodInfo),
    Expression.SwitchCase(Expression.Call(defaultBodyMethodInfo), Expression.Constant(1)));
var func = Expression.Lambda<Func<int, int>>(switchBodyExp, paramExp).Compile();
int result = func(6);

public static int DefaultBody()
{
    return 4;
}
</code>```

But I'm really not sure why my first example doesn't work and I'd love to know how to do that properly so I don't have to declare a method like in my second example. Do I need to be doing some sort of call invoke like in the second example?

I've had a look at some of the other similar answers on SO, but I'm new enough with Expression Trees this that I'm really not sure if they answer my problem or not.

答:
The lambda expression Expression<Func<int>> can only be used directly in a places that expect Func<int> (like Enumerable.Select) or  Expression<Func<int>> (like Queryable.Select, but you need to wrap it inside Expression.Quote).

In order to use it in a places which expect int like in your case, it needs to be converted to an expression that represents the result of the "execution" of the lambda expression. Let change the original code to

```<code>Expression<Func<int>> defaultBodyLambda = () => 4;
var defaultBodyExp = ???;
</code>```

and the question is what should ??? be.

One possible (and the general) solution is to use the Expression.Invoke method:

```<code>var defaultBodyExp = Expression.Invoke(defaultBodyLambda);
</code>```

Or, since this particular lambda expression has no parameters, we can simply use the LambdaExpression.Body property:

```<code>var defaultBodyExp = defaultBodyLambda.Body;
</code>```

Body:
I am trying to get more familiar with expression trees.

I have created a simple switch expression as follows:

var paramExp = Expression.Parameter(typeof(int));
Expression<Func<int>> defaultBodyExp = () => 4;
var switchBodyExp = Expression.Switch(paramExp, defaultBodyExp,
    Expression.SwitchCase(defaultBodyExp, Expression.Constant(1)));
var func = Expression.Lambda<Func<int, int>>(switchBodyExp, paramExp).Compile();
int result = func(6);

But this raises the following exception when trying to call Compile:

Expression of type 'System.Func`1[System.Int32]' cannot be used for return type 'System.Int32'

I can get it working by doing the following:

var paramExp = Expression.Parameter(typeof(int));
//Expression<Func<int>> defaultBodyExp = () => 4;
var defaultBodyMethodInfo = typeof(Program).GetMethod("DefaultBody");
var switchBodyExp = Expression.Switch(paramExp, Expression.Call(defaultBodyMethodInfo),
    Expression.SwitchCase(Expression.Call(defaultBodyMethodInfo), Expression.Constant(1)));
var func = Expression.Lambda<Func<int, int>>(switchBodyExp, paramExp).Compile();
int result = func(6);

public static int DefaultBody()
{
    return 4;
}

But I'm really not sure why my first example doesn't work and I'd love to know how to do that properly so I don't have to declare a method like in my second example. Do I need to be doing some sort of call invoke like in the second example?

I've had a look at some of the other similar answers on SO, but I'm new enough with Expression Trees this that I'm really not sure if they answer my problem or not.

Body:
The lambda expression Expression<Func<int>> can only be used directly in a places that expect Func<int> (like Enumerable.Select) or  Expression<Func<int>> (like Queryable.Select, but you need to wrap it inside Expression.Quote).

In order to use it in a places which expect int like in your case, it needs to be converted to an expression that represents the result of the "execution" of the lambda expression. Let change the original code to

Expression<Func<int>> defaultBodyLambda = () => 4;
var defaultBodyExp = ???;

and the question is what should ??? be.

One possible (and the general) solution is to use the Expression.Invoke method:

var defaultBodyExp = Expression.Invoke(defaultBodyLambda);

Or, since this particular lambda expression has no parameters, we can simply use the LambdaExpression.Body property:

var defaultBodyExp = defaultBodyLambda.Body;


问:
How to get references for ViewController
Community!

I have a question regarding References in Swift 3 and Xcode.
My Plan is this:

At the moment my App has 4 Controllers. A MapViewController, a PositionController, a MarkerController and a APIDataController. Those of course handle the respective Models. My problem now comes in, when I want the controllers to communicate. Look at this code (Please ignore that most functions aren't implemented here):

First my MarkerController:

```<code>import Foundation

protocol MarkerControllerDelegate: class{
    func willGetMarkerArray()
    func didGetMarkerArray(_ newMarkerArray: Marker)
}

class MarkerController: NSObject{

    var markerArray = [Marker]()
    weak var delegate: MarkerControllerDelegate?

    func createMarkerArray(){

    }

    func getMarkerArray() -> [Marker]{
        return markerArray
    }
}

extension MarkerController : APIDataControllerDelegate{
    func didRetriveAPIData(_ APIDataModelArray: APIDataModel) {
        createMarkerArray()
    }
}
</code>```

And now my APIDataController:

```<code>import Foundation

protocol APIDataControllerDelegate: class{
    func didRetriveAPIData(_ APIDataModelArray: [APIDataModel])
}

class APIDataController: NSObject {

    var APIDataModelArray = [APIDataModel]()
    weak var delegate: APIDataControllerDelegate?

    func retriveAPIData(){
        //get the data
        //.....
        //finished getting data
        delegate?.didRetriveAPIData(APIDataModelArray)
    }

    func getAPIDataModelArray() -> [APIDataModel] {
        return APIDataModelArray
    }
}
</code>```

And finally the beginning of my MapViewController:

```<code>import UIKit
import GoogleMaps
import GoogleMaps
import CoreLocation

class MapViewController: UIViewController{

    let positionController = PositionController()
    let apiDataController = APIDataController()
    let markerController = MarkerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        apiDataController.retriveAPIData()
        //blablabla
    }
    //blablablabla
}
</code>```

Now, this might be a lot of code at once, so let me explain you what is ought to happen:

At the beginning (or wherever in the code) MapViewController calls the retrieveAPIData method. Once the function is finished, APIDataController is planned to notify the MarkerController via the APIDataControllerDelegate-Protocol to start his work (run his createMarkerArray-Method).

Now, to do this, I have to declare a markerController-Instance as a Delegate to APIDataController. Now, since I have already created instances of all my controllers in mapViewController, I want to give those references to my other controllers where needed so that they all refer to the same Instances, kinda like a Singleton.

But, how do I create a Reference to my MapViewController IN my MapViewController, to pass it to my other Controllers so that they can from there go like:

```<code>let positionController = mapViewController.positionController?
</code>```

Nothing I tried seem to work. So any help would be appreciated.
Also if there are better ways to let my Controllers communicate I am open to here them, I am sure there is a better way to do it than I currently try to do.

答: Using Delegates for the communication between the controllers is the recommended way to do it. Setting the delegates depends on the way these controllers interact in your app. Often you will have a segue from one app to another, that is a good chance to set delegates. You can also do it in code that is putting together your views</p>

Body:
Community!

I have a question regarding References in Swift 3 and Xcode.
My Plan is this:

At the moment my App has 4 Controllers. A MapViewController, a PositionController, a MarkerController and a APIDataController. Those of course handle the respective Models. My problem now comes in, when I want the controllers to communicate. Look at this code (Please ignore that most functions aren't implemented here):

First my MarkerController:

import Foundation

protocol MarkerControllerDelegate: class{
    func willGetMarkerArray()
    func didGetMarkerArray(_ newMarkerArray: Marker)
}

class MarkerController: NSObject{

    var markerArray = [Marker]()
    weak var delegate: MarkerControllerDelegate?

    func createMarkerArray(){

    }

    func getMarkerArray() -> [Marker]{
        return markerArray
    }
}

extension MarkerController : APIDataControllerDelegate{
    func didRetriveAPIData(_ APIDataModelArray: APIDataModel) {
        createMarkerArray()
    }
}

And now my APIDataController:

import Foundation

protocol APIDataControllerDelegate: class{
    func didRetriveAPIData(_ APIDataModelArray: [APIDataModel])
}

class APIDataController: NSObject {

    var APIDataModelArray = [APIDataModel]()
    weak var delegate: APIDataControllerDelegate?

    func retriveAPIData(){
        //get the data
        //.....
        //finished getting data
        delegate?.didRetriveAPIData(APIDataModelArray)
    }

    func getAPIDataModelArray() -> [APIDataModel] {
        return APIDataModelArray
    }
}

And finally the beginning of my MapViewController:

import UIKit
import GoogleMaps
import GoogleMaps
import CoreLocation

class MapViewController: UIViewController{

    let positionController = PositionController()
    let apiDataController = APIDataController()
    let markerController = MarkerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        apiDataController.retriveAPIData()
        //blablabla
    }
    //blablablabla
}

Now, this might be a lot of code at once, so let me explain you what is ought to happen:

At the beginning (or wherever in the code) MapViewController calls the retrieveAPIData method. Once the function is finished, APIDataController is planned to notify the MarkerController via the APIDataControllerDelegate-Protocol to start his work (run his createMarkerArray-Method).

Now, to do this, I have to declare a markerController-Instance as a Delegate to APIDataController. Now, since I have already created instances of all my controllers in mapViewController, I want to give those references to my other controllers where needed so that they all refer to the same Instances, kinda like a Singleton.

But, how do I create a Reference to my MapViewController IN my MapViewController, to pass it to my other Controllers so that they can from there go like:

let positionController = mapViewController.positionController?

Nothing I tried seem to work. So any help would be appreciated.
Also if there are better ways to let my Controllers communicate I am open to here them, I am sure there is a better way to do it than I currently try to do.


问:
How to place div behind other div
I want to create a slideshow that consists in 5 images and I want to have a big one in the middle with 2 buttons and 4 behind them, in this way(the first one is 1, the second one is 2, the third one (the biggest) is 3 and so on...): http://imgur.com/P9EpTcq
(the dotted line is behind the solid line). I hope you understand what I'm saying.

Cosidering this simple HTML markup:

```<code><div class="slideshow">
    <img href="#" class="ssimg" id="1"/>
    <img href="#" class="ssimg" id="2"/>
    <div class="big-ssimg">
        <img href="#" class="ssimg" id="3"/>
        <div class="previous-bttn"></div>
        <div class="next-bttn"></div>
    </div>
    <img href="#" class="ssimg" id="4"/>
    <img href="#" class="ssimg" id="5"/>
</div>
</code>```

*I want the two divs inside .big-ssimg to be equal 1/4 of the parent each, the .previous-bttn to be the fist 1/4 of the .big-ssimg div, and the .next-bttn one to be the last 1/4 of the parent.

Considering this, how can I obtain it? I can handle js and other things, also I know how to use z-index, but not so much "position" and "display" css properties, I just need to know how to place them in that way:

img#1 and img#5 behind img#2 and img#4, img#2 and img#4 behind img#3

The next and previous buttons to be first and the last 1/4 of parent and to be over the image that represent 100% height and width of parent div.

答:
To stack them, you will set the position to either relative or absolute in order for z-index to work. Be sure to apply the positioning to all elements that you want to stack.

Typically I use Absolute position on all layers within a container div that is set to position:relative. This allows you to use the container to position the whole stack and the layer divs will be positioned relative to the container instead of the body.

```<code>.container{
    position:relative;
}

.layer1, .layer2 {
    position:absolute;
    top:0; //position the layers to the top left corner of the container
    left:0; //position the layers to the top left corner of the container

}

.layer1{
    z-index:100;
}

.layer2{
    z-index:200;
}

<div class="container">
   <div class="layer1"></div>
   <div class="layer2"></div>
</div>
</code>```

Title: How to place div behind other div

Body:
I want to create a slideshow that consists in 5 images and I want to have a big one in the middle with 2 buttons and 4 behind them, in this way(the first one is 1, the second one is 2, the third one (the biggest) is 3 and so on...): http://imgur.com/P9EpTcq
(the dotted line is behind the solid line). I hope you understand what I'm saying.

Cosidering this simple HTML markup:

*I want the two divs inside .big-ssimg to be equal 1/4 of the parent each, the .previous-bttn to be the fist 1/4 of the .big-ssimg div, and the .next-bttn one to be the last 1/4 of the parent.

Considering this, how can I obtain it? I can handle js and other things, also I know how to use z-index, but not so much "position" and "display" css properties, I just need to know how to place them in that way:

img#1 and img#5 behind img#2 and img#4, img#2 and img#4 behind img#3

The next and previous buttons to be first and the last 1/4 of parent and to be over the image that represent 100% height and width of parent div.

Body:
To stack them, you will set the position to either relative or absolute in order for z-index to work. Be sure to apply the positioning to all elements that you want to stack.

Typically I use Absolute position on all layers within a container div that is set to position:relative. This allows you to use the container to position the whole stack and the layer divs will be positioned relative to the container instead of the body.

.container{
    position:relative;
}

.layer1, .layer2 {
    position:absolute;
    top:0; //position the layers to the top left corner of the container
    left:0; //position the layers to the top left corner of the container

}

.layer1{
    z-index:100;
}

.layer2{
    z-index:200;
}

<div class="container">
   <div class="layer1"></div>
   <div class="layer2"></div>
</div>


问:
C bmp header contains wrong information
I am trying to get the height and width of a bmp picture, however the values i am getting are incorrect and are not the actual size of the picture.

Here is my code for doing so:

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

void main() {
FILE * Pic;
errno_t err;
int **PixelStrength;
int PictureWidth, PictureHeight;

err = fopen_s(&Pic, "d2.bmp", "r");
if (!err)
{

    fseek(Pic, 18, SEEK_SET);
    PictureWidth = fgetc(Pic);
    fseek(Pic, 22, SEEK_SET);
    PictureHeight = fgetc(Pic);
}

if (Pic)
{
    err = fclose(Pic);
}
}
</code>```

I should note that this has worked for a small picture however not for any larger one. The pictures that i have tried are 640 x 480 yet the values i receive are 128 x 224. Thank you for your help.

答:
fgetc() fetches a single byte from the file. The height and width values are stored as 32-bit little-endian. 640 is 0x280, and 480 is 0x1E0, so the values you are getting are 0x80 (128) and 0xE0 (224), just the low-order byte of the values.

Try something like

```<code>PictureWidth = fgetc(Pic);
PictureWidth += 256 * fgetc(Pic);
</code>```

(Yes, they really are 32-bit values, which is four bytes, but it's unlikely that you'll run into a 70000-pixel wide BPM anytime soon).

Title: C bmp header contains wrong information

Body:
I am trying to get the height and width of a bmp picture, however the values i am getting are incorrect and are not the actual size of the picture.

Here is my code for doing so:

#include <stdio.h>
#include <stdlib.h>

void main() {
FILE * Pic;
errno_t err;
int **PixelStrength;
int PictureWidth, PictureHeight;

err = fopen_s(&Pic, "d2.bmp", "r");
if (!err)
{

    fseek(Pic, 18, SEEK_SET);
    PictureWidth = fgetc(Pic);
    fseek(Pic, 22, SEEK_SET);
    PictureHeight = fgetc(Pic);
}

if (Pic)
{
    err = fclose(Pic);
}
}

I should note that this has worked for a small picture however not for any larger one. The pictures that i have tried are 640 x 480 yet the values i receive are 128 x 224. Thank you for your help.

Body:
fgetc() fetches a single byte from the file. The height and width values are stored as 32-bit little-endian. 640 is 0x280, and 480 is 0x1E0, so the values you are getting are 0x80 (128) and 0xE0 (224), just the low-order byte of the values.

Try something like

PictureWidth = fgetc(Pic);
PictureWidth += 256 * fgetc(Pic);

(Yes, they really are 32-bit values, which is four bytes, but it's unlikely that you'll run into a 70000-pixel wide BPM anytime soon).


问:
Orchard Custom Workflow Activity
I have built a custom module in Orchard that creates a new part, type and a custom activity but I'm struggling with the last part of what I need to do which is to create a copy of all the content items associated with a specific parent item.

For instance, when someone creates a "Trade Show" (new type from my module), various subpages can be created off of it (directions, vendor maps, etc.) since the client runs a single show at a time. What I need to do is, when they create a new Trade Show, I want to get the most recent prior show (which I'm doing via _contentManager.HqlQuery().ForType("TradeShow").ForVersion(VersionOptions.Latest).ForVersion(VersionOptions.Published).List().Last() (positive that's not the most efficient way, but it works and the record count would be ~10 after five years), then find all of those child pages that correlate to that old show and copy them into new Content Items. They have to be a copy because on occasion they may have to refer back to parts with the old shows, or it could change, etc. All the usual reasons.

How do I go about finding all of the content items that reference that prior show in an Activity? Here is my full class for the Activity:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using Orchard.Autoroute.Services;
using Orchard.ContentManagement;
using Orchard.Localization;
using Orchard.Projections.Models;
using Orchard.Projections.Services;
using Orchard.Workflows.Models;
using Orchard.Workflows.Services;
using Orchard.Workflows.Activities;

namespace Orchard.Web.Modules.TradeShows.Activities
{
public class TradeShowPublishedActivity : Task
{
    private readonly IContentManager _contentManager;
    private readonly IAutorouteService _autorouteService;
    private readonly IProjectionManager _projectionManager;

    public TradeShowPublishedActivity(IContentManager contentManager, IAutorouteService autorouteService, IProjectionManager projectionManager)
    {
        _contentManager = contentManager;
        _autorouteService = autorouteService;
        _projectionManager = projectionManager;

        T = NullLocalizer.Instance;
    }

    public Localizer T { get; set; }

    public override LocalizedString Category
    {
        get { return T("Flow"); }
    }

    public override LocalizedString Description
    {
        get { return T("Handles the automatic creation of content pages for the new show."); }
    }

    public override string Name
    {
        get { return "TradeShowPublished"; }
    }

    public override string Form
    {
        get { return null; }
    }

    public override IEnumerable<LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext, ActivityContext activityContext)
    {
        yield return T("Done");
    }

    public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
    {
        var priorShow = _contentManager.HqlQuery().ForType("TradeShow").ForVersion(VersionOptions.Latest).ForVersion(VersionOptions.Published).List().Last();
        var tradeShowPart = priorShow.Parts.Where(p => p.PartDefinition.Name == "TradeShowContentPart").Single();

        //new show alias
        //workflowContext.Content.ContentItem.As<Orchard.Autoroute.Models.AutoroutePart>().DisplayAlias

        yield return T("Done");
    }
}
</code>```

}

My Migrations.cs file sets up the part that is used for child pages to reference the parent show like this:

```<code>ContentDefinitionManager.AlterPartDefinition("AssociatedTradeShowPart", builder => builder.WithField("Trade Show", cfg => cfg.OfType("ContentPickerField")
                                                                                .WithDisplayName("Trade Show")
                                                                                .WithSetting("ContentPickerFieldSettings.Attachable", "true")
                                                                                .WithSetting("ContentPickerFieldSettings.Description", "Select the trade show this item is for.")
                                                                                .WithSetting("ContentPickerFieldSettings.Required", "true")
                                                                                .WithSetting("ContentPickerFieldSettings.DisplayedContentTypes", "TradeShow")
                                                                                .WithSetting("ContentPickerFieldSettings.Multiple", "false")
                                                                                .WithSetting("ContentPickerFieldSettings.ShowContentTab", "true")));
</code>```

Then, my child pages (only one for now, but plenty more coming) are created like this:

```<code>ContentDefinitionManager.AlterTypeDefinition("ShowDirections", cfg => cfg.DisplayedAs("Show Directions")
                                                                                .WithPart("AutoroutePart", builder => builder.WithSetting("AutorouteSettings.AllowCustomPattern", "true")
                                                                                .WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false")
                                                                                .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'international-trade-show'}]")
                                                                                .WithSetting("AutorouteSettings.DefaultPatternIndex", "0"))
                                                                                .WithPart("CommonPart", builder => builder.WithSetting("DateEditorSettings.ShowDateEditor", "false"))
                                                                                .WithPart("PublishLaterPart")
                                                                                .WithPart("TitlePart")
                                                                                .WithPart("AssociatedTradeShowPart") /* allows linking to parent show */
                                                                                .WithPart("ContainablePart", builder => builder.WithSetting("ContainablePartSettings.ShowContainerPicker", "true"))
                                                                                .WithPart("BodyPart"));
</code>```

答:
So you have the Trade Show content item, the next step will be to find all parts with a ContentPickerField, then filter that list down to those where the field contains your show's ID. </p>

```<code>        var items = _contentManager.Query().List().ToList() // Select all content items
            .Select(p => (p.Parts
                // Select all parts on content items
            .Where(f => f.Fields.Where(d =>
                d.FieldDefinition.Name == typeof(ContentPickerField).Name &&
                // See if any of the fields are ContentPickerFields
                (d as ContentPickerField).Ids.ToList().Contains(priorShow.Id)).Any())));
                   // That field contains the Id of the show
</code>```

<p>This could get expensive depending on how many content items are in your database. </p>

Title: Orchard Custom Workflow Activity

Body:
I have built a custom module in Orchard that creates a new part, type and a custom activity but I'm struggling with the last part of what I need to do which is to create a copy of all the content items associated with a specific parent item.

For instance, when someone creates a "Trade Show" (new type from my module), various subpages can be created off of it (directions, vendor maps, etc.) since the client runs a single show at a time. What I need to do is, when they create a new Trade Show, I want to get the most recent prior show (which I'm doing via _contentManager.HqlQuery().ForType("TradeShow").ForVersion(VersionOptions.Latest).ForVersion(VersionOptions.Published).List().Last() (positive that's not the most efficient way, but it works and the record count would be ~10 after five years), then find all of those child pages that correlate to that old show and copy them into new Content Items. They have to be a copy because on occasion they may have to refer back to parts with the old shows, or it could change, etc. All the usual reasons.

How do I go about finding all of the content items that reference that prior show in an Activity? Here is my full class for the Activity:

using System;
using System.Collections.Generic;
using System.Linq;
using Orchard.Autoroute.Services;
using Orchard.ContentManagement;
using Orchard.Localization;
using Orchard.Projections.Models;
using Orchard.Projections.Services;
using Orchard.Workflows.Models;
using Orchard.Workflows.Services;
using Orchard.Workflows.Activities;

namespace Orchard.Web.Modules.TradeShows.Activities
{
public class TradeShowPublishedActivity : Task
{
    private readonly IContentManager _contentManager;
    private readonly IAutorouteService _autorouteService;
    private readonly IProjectionManager _projectionManager;

    public TradeShowPublishedActivity(IContentManager contentManager, IAutorouteService autorouteService, IProjectionManager projectionManager)
    {
        _contentManager = contentManager;
        _autorouteService = autorouteService;
        _projectionManager = projectionManager;

        T = NullLocalizer.Instance;
    }

    public Localizer T { get; set; }

    public override LocalizedString Category
    {
        get { return T("Flow"); }
    }

    public override LocalizedString Description
    {
        get { return T("Handles the automatic creation of content pages for the new show."); }
    }

    public override string Name
    {
        get { return "TradeShowPublished"; }
    }

    public override string Form
    {
        get { return null; }
    }

    public override IEnumerable<LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext, ActivityContext activityContext)
    {
        yield return T("Done");
    }

    public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
    {
        var priorShow = _contentManager.HqlQuery().ForType("TradeShow").ForVersion(VersionOptions.Latest).ForVersion(VersionOptions.Published).List().Last();
        var tradeShowPart = priorShow.Parts.Where(p => p.PartDefinition.Name == "TradeShowContentPart").Single();

        //new show alias
        //workflowContext.Content.ContentItem.As<Orchard.Autoroute.Models.AutoroutePart>().DisplayAlias

        yield return T("Done");
    }
}

}

My Migrations.cs file sets up the part that is used for child pages to reference the parent show like this:

ContentDefinitionManager.AlterPartDefinition("AssociatedTradeShowPart", builder => builder.WithField("Trade Show", cfg => cfg.OfType("ContentPickerField")
                                                                                .WithDisplayName("Trade Show")
                                                                                .WithSetting("ContentPickerFieldSettings.Attachable", "true")
                                                                                .WithSetting("ContentPickerFieldSettings.Description", "Select the trade show this item is for.")
                                                                                .WithSetting("ContentPickerFieldSettings.Required", "true")
                                                                                .WithSetting("ContentPickerFieldSettings.DisplayedContentTypes", "TradeShow")
                                                                                .WithSetting("ContentPickerFieldSettings.Multiple", "false")
                                                                                .WithSetting("ContentPickerFieldSettings.ShowContentTab", "true")));

Then, my child pages (only one for now, but plenty more coming) are created like this:

ContentDefinitionManager.AlterTypeDefinition("ShowDirections", cfg => cfg.DisplayedAs("Show Directions")
                                                                                .WithPart("AutoroutePart", builder => builder.WithSetting("AutorouteSettings.AllowCustomPattern", "true")
                                                                                .WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false")
                                                                                .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'international-trade-show'}]")
                                                                                .WithSetting("AutorouteSettings.DefaultPatternIndex", "0"))
                                                                                .WithPart("CommonPart", builder => builder.WithSetting("DateEditorSettings.ShowDateEditor", "false"))
                                                                                .WithPart("PublishLaterPart")
                                                                                .WithPart("TitlePart")
                                                                                .WithPart("AssociatedTradeShowPart") /* allows linking to parent show */
                                                                                .WithPart("ContainablePart", builder => builder.WithSetting("ContainablePartSettings.ShowContainerPicker", "true"))
                                                                                .WithPart("BodyPart"));

Body:
So you have the Trade Show content item, the next step will be to find all parts with a ContentPickerField, then filter that list down to those where the field contains your show's ID.

        var items = _contentManager.Query().List().ToList() // Select all content items
            .Select(p => (p.Parts
                // Select all parts on content items
            .Where(f => f.Fields.Where(d =>
                d.FieldDefinition.Name == typeof(ContentPickerField).Name &&
                // See if any of the fields are ContentPickerFields
                (d as ContentPickerField).Ids.ToList().Contains(priorShow.Id)).Any())));
                   // That field contains the Id of the show

This could get expensive depending on how many content items are in your database.


问:
CSS, Images, JS not loading in IIS
My all applications were working fine but suddenly all sites under IIS are not loading css, images, scripts. It redirect to login page.

If i login it works fine. e.g. mysite.com/Account/LogOn?ReturnUrl=%2fpublic%2fimages%2ficons%2f41.png

On my local machine it works fine without login.

答:
If you tried all the above solutions and still have problems, consider using the method ResolveClientUrl() of ASP.NET .

A script for Example :

Instead of using

```<code><script src="~/dist/js/app.min.js" ></script>
</code>```

Use the method

```<code><script src="<%= ResolveClientUrl("~/dist/js/app.min.js") %>" ></script>
</code>```

This was my solution that worked for a friend I was helping!

Title: CSS, Images, JS not loading in IIS

Body:
If you tried all the above solutions and still have problems, consider using the method ResolveClientUrl() of ASP.NET .

A script for Example :

Instead of using

<script src="~/dist/js/app.min.js" ></script>

Use the method

<script src="<%= ResolveClientUrl("~/dist/js/app.min.js") %>" ></script>

This was my solution that worked for a friend I was helping!


问:
Generate HMAC-SHA256 hash with BouncyCastle
I need to generate a HMAC-SHA256 hash in a PCL (developing for Xamarin Forms) which doesn't support the .NET built-in HMAC/cryptography classes, so I'm working with BouncyCastle to implement my cryptography classes.

I need to generate a HMAC-SHA256 hash, but I haven't been able to find any example on Google, nor does BouncyCastle seem to have any documentation for this. Can anyone help me out?

答:
```<code>private static void CreateToken(string message, string key)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[]keyByte = encoding.GetBytes(key);

        HMACSHA256 hmacsha = new HMACSHA256(keyByte);
        byte[]messageBytes = encoding.GetBytes(message);

        byte[]hashmessage = hmacsha.ComputeHash(messageBytes);
        Console.WriteLine(ByteToString(hashmessage));
    }
    public static string ByteToString(byte[]buff) {
        string sbinary = "";

        for (int i = 0; i < buff.Length; i++) {
            sbinary += buff[i].ToString("X2"); // hex format
        }
        return (sbinary);
    }
</code>```

Above code saved my time while working for HMAC-SHA256, I hope this may help someone and here is the reference in detail http://billatnapier.com/security01.aspx

Body:
private static void CreateToken(string message, string key)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[]keyByte = encoding.GetBytes(key);

        HMACSHA256 hmacsha = new HMACSHA256(keyByte);
        byte[]messageBytes = encoding.GetBytes(message);

        byte[]hashmessage = hmacsha.ComputeHash(messageBytes);
        Console.WriteLine(ByteToString(hashmessage));
    }
    public static string ByteToString(byte[]buff) {
        string sbinary = "";

        for (int i = 0; i < buff.Length; i++) {
            sbinary += buff[i].ToString("X2"); // hex format
        }
        return (sbinary);
    }

Above code saved my time while working for HMAC-SHA256, I hope this may help someone and here is the reference in detail http://billatnapier.com/security01.aspx


问:
What are the proper use-cases for the PostgreSQL Array Datatype?
It seems to me that the functionality of the PostgreSQL array datatype overlaps a lot with the standard one-to-many and many-to-many relationships.

For example, a table called users could have an array field called "favorite_colors", or there could be a separate table called "favorite_colors" and a join table between "users" and "favorite_colors".

In what cases is the array datatype OK to use instead of a full-blown join?

答:
One incredibly handy use case is tagging:</p>

```<code>CREATE TABLE posts (
    title TEXT,
    tags TEXT[]
);

-- Select all posts with tag 'kitty'
SELECT * FROM posts WHERE tags @> '{kitty}';
</code>```

Body:
One incredibly handy use case is tagging:

CREATE TABLE posts (
    title TEXT,
    tags TEXT[]
);

-- Select all posts with tag 'kitty'
SELECT * FROM posts WHERE tags @> '{kitty}';


问:
Is it possible to Push (using API) and Pull (using indexer) data into the same Index with Azure Search?
I have an index in Azure Search lets says called Hotels.

I have a hotels table in Azure SQL that has the same schema that is a copy of the hotels index found in Azure Search.

I push from my back-end to Azure SQL table and Azure Search at create/update/delete.

In a scenario my data was pushed to Azure SQL but failed to be pushed to Azure Search is it possible to have my Azure SQL Hotels table be an indexer, such that the indexer could sync data to my Azure Search index (hotels) that failed to be pushed from my backend?

答:
Yes, you can both mix push and pull as well as have multiple pull indexers targeting the same index. We see this done often when part of the data is in one data source and part in another, where the index is the point where they converge, coordinated by their key.

The pattern you're describing is not as common, but generally speaking it should work. You'd have to account for cases where your write conflicts with an indexer write, and make sure the writes you do as they happen ultimately win. Also if you go down this path make sure to configure a change detection (and deletion detection if you delete rows) policy so we index from SQL incrementally and don't ready everything on every run.

An alternative approach if you're worried about missing writes is to push all your writes into a queue, and then pull from the queue and into Azure Search. That way you have a single stream of writes instead of two.


问:
Source files listed in Linux executable
Running strings on an ELF 64-bit LSB executable built with gcc 4.9.2 for GNU/Linux 2.6.32 on Linux Mint, I saw

some/path/sourcefile1.cpp

some/path/sourcefile2.cpp

etc

I do not want the source paths and file names in the resulting executable. I tried to remove them using strip --strip-all binaryName but still the paths and filenames persist.

This was built with CMake. I gave CMake a -s flag to pass on to the compiler, but it appeared to have no effect on the outcome. I do not believe the binary was built with debug symbols. I told CMake to make a release build.

Regardless of how it was built, I expected that strip should be able to remove the paths and file names of the source code.

How do I remove this information from the resulting binary? I do not care about the size of the executable.

Update:

Here is what I still see with strings:

```<code>/home/kmort/longPathHere/filename1.cpp -auxbase-strip CMakeFiles/filename2.dir/__/__/__/__/__/longPathHere/filename1.cpp.o
/home/kmort/longPathHere/filename2.cpp -auxbase-strip CMakeFiles/filename2.dir/__/__/__/__/__/longPathHere/filename2.cpp.o
etc
</code>```

There were __FILE__ references. I have removed those.

After I have stripped the binary, objdump --syms results in "no symbols".

I am using -DNDEBUG. All -g entries have been removed, so I'm not compiling for debug.

readelf only shows one thing I don't want in there, and it's the Library rpath, which I think I can remove no problem.

Though I see the path and file names of the source files, there is a .o at the end, which makes me think it's coming from the linker.

The -auxbase-strip makes me think -fno-compare-debug should help, but it does not.

Prior to building, I delete the build folder and run cmake .. --DCMAKE_BUILD_TYPE=Release, which should give me a clean release build.

This is baffling to me.

答:
Your source code almost certainly invokes the __FILE__ macro for
diagnostic/debugging purposes. These invocations expand to source file paths that
cannot be stripped because they are static program data.

You say you are making a Release build. You should be able
to define preprocessor macros for your release build that eliminate all
debugging code from compilation. Either you have not done so or
the conditional-compilation directives in your source code are faulty and fail to
eliminate some invocations of __FILE__ even in a release build.

The likeliest scenario is that you have calls to the assert() macro
in your source code which are not nullified in your release build
because you have failed to define the preprocessor macro NDEBUG.
Unless assert() is nullified, it invokes __FILE__ - and assert()
will not be nullified if you do not define NDEBUG.

If indeed all of the non-strippable paths in your release executable
are due to non-nullified assert()s then you can get rid of them
by adding -DNDEBUG to the preprocessor flags of your release build.

Title: Source files listed in Linux executable

Body:
Running strings on an ELF 64-bit LSB executable built with gcc 4.9.2 for GNU/Linux 2.6.32 on Linux Mint, I saw

some/path/sourcefile1.cpp

some/path/sourcefile2.cpp

etc

I do not want the source paths and file names in the resulting executable. I tried to remove them using strip --strip-all binaryName but still the paths and filenames persist.

This was built with CMake. I gave CMake a -s flag to pass on to the compiler, but it appeared to have no effect on the outcome. I do not believe the binary was built with debug symbols. I told CMake to make a release build.

Regardless of how it was built, I expected that strip should be able to remove the paths and file names of the source code.

How do I remove this information from the resulting binary? I do not care about the size of the executable.

Update:

Here is what I still see with strings:

/home/kmort/longPathHere/filename1.cpp -auxbase-strip CMakeFiles/filename2.dir/__/__/__/__/__/longPathHere/filename1.cpp.o
/home/kmort/longPathHere/filename2.cpp -auxbase-strip CMakeFiles/filename2.dir/__/__/__/__/__/longPathHere/filename2.cpp.o
etc

There were __FILE__ references. I have removed those.

After I have stripped the binary, objdump --syms results in "no symbols".

I am using -DNDEBUG. All -g entries have been removed, so I'm not compiling for debug.

readelf only shows one thing I don't want in there, and it's the Library rpath, which I think I can remove no problem.

Though I see the path and file names of the source files, there is a .o at the end, which makes me think it's coming from the linker.

The -auxbase-strip makes me think -fno-compare-debug should help, but it does not.

Prior to building, I delete the build folder and run cmake .. --DCMAKE_BUILD_TYPE=Release, which should give me a clean release build.

This is baffling to me.


问:
Issue with Fluent nhibernate and the type Decimal
I am encoutering an issue with the decimal type and fluent nhibernate.

Here is my problem:

I have a class with a property:

```<code>public virtual decimal? Amount { get; set; }
</code>```

In my mapping I have :

```<code>Map(x => x.Amount, "SOMETHING").Length(8).Precision(19).Scale(4).CustomSqlType("money");
</code>```

The Nhibernate mapping I get is:

```<code><property name="Amount" type="System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
  <column name="SOMETHING" length="8" sql-type="money" precision="19" scale="4" />
</property>
</code>```

And what I get when I try to update this value with a sql server 2000 is:

```<code>Disallowed implicit conversion from data type varchar to data type money, table 'ANYTABLE, column '...'. Use the CONVERT function to run this query.
</code>```

I am using MsSqlConfiguration.MsSql2000 to configure fluent hibernate and version 1.1.0.0 of fluent nhibernate.

Thanks for your help!

答: May be the length attribute is disturbing it. Take it away. Only strings have lengths.</p>

Body:
I am encoutering an issue with the decimal type and fluent nhibernate.

Here is my problem:

I have a class with a property:

public virtual decimal? Amount { get; set; }

In my mapping I have :

Map(x => x.Amount, "SOMETHING").Length(8).Precision(19).Scale(4).CustomSqlType("money");

The Nhibernate mapping I get is:

<property name="Amount" type="System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
  <column name="SOMETHING" length="8" sql-type="money" precision="19" scale="4" />
</property>

And what I get when I try to update this value with a sql server 2000 is:

Disallowed implicit conversion from data type varchar to data type money, table 'ANYTABLE, column '...'. Use the CONVERT function to run this query.

I am using MsSqlConfiguration.MsSql2000 to configure fluent hibernate and version 1.1.0.0 of fluent nhibernate.

Thanks for your help!


答:
Remove the second row and add some CSS to give the thumbnails a fixed width and inline flow.

EDIT: Added some CSS to achieve the background colors without an image.

.thumbnail {
    border:1px black solid;
    width:180px;
    display:inline-block;
    background-color:white;
    height:300px;
  }
  .green-space {
    margin:3px;
    height:150px;
    background-color:#3ECE30;
  }
  .green-space .empty-space {
    height:120px;
  }
  .green-space h3 {
    font-size:16px;
    font-family:Myriad Pro;
    color:white;
    background-color:#1F641A;
    text-align:center;
    height:22px;
    line-height:22px;
  }
  .caption {
    position:relative;
    height:calc(100% - 150px);
    text-align:center;
  }
  .caption .btn{
    position:absolute;
    bottom:10px;
    left:50%;
    margin-left: -45px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail" style="display:inline-block">
                <div class="green-space">
                  <div class="empty-space">
                  </div>
                  <h3>Software Name</h3>
                </div>
                <div class="caption">
                    <p>...</p>
                    Read More
                </div>
            </div>
            <div class="thumbnail" style="display:inline-block">
                <div class="green-space">
                  <div class="empty-space">
                  </div>
                  <h3>Software Name</h3>
                </div>
                <div class="caption">
                    <p>...</p>
                    Read More
                </div>
            </div>
        </div>
    </div></code>```

Title: How to Align Bootstrap thumbnails horizontally

Body:
Remove the second row and add some CSS to give the thumbnails a fixed width and inline flow.

EDIT: Added some CSS to achieve the background colors without an image.

.thumbnail {
    border:1px black solid;
    width:180px;
    display:inline-block;
    background-color:white;
    height:300px;
  }
  .green-space {
    margin:3px;
    height:150px;
    background-color:#3ECE30;
  }
  .green-space .empty-space {
    height:120px;
  }
  .green-space h3 {
    font-size:16px;
    font-family:Myriad Pro;
    color:white;
    background-color:#1F641A;
    text-align:center;
    height:22px;
    line-height:22px;
  }
  .caption {
    position:relative;
    height:calc(100% - 150px);
    text-align:center;
  }
  .caption .btn{
    position:absolute;
    bottom:10px;
    left:50%;
    margin-left: -45px;
  }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail" style="display:inline-block">
                <div class="green-space">
                  <div class="empty-space">
                  </div>
                  <h3>Software Name</h3>
                </div>
                <div class="caption">
                    <p>...</p>
                    <a href="#" class="btn btn-default btn-ok" role="button">Read More</a>
                </div>
            </div>
            <div class="thumbnail" style="display:inline-block">
                <div class="green-space">
                  <div class="empty-space">
                  </div>
                  <h3>Software Name</h3>
                </div>
                <div class="caption">
                    <p>...</p>
                    <a href="#" class="btn btn-default btn-ok" role="button">Read More</a>
                </div>
            </div>
        </div>
    </div>


问:
modifing in a pre-save hook not persisted
I have a model that I modify using the pre-save hook in the schema. When saved, mongoose returns the modified data, __v is updated and everything looks dandy. But when I retrieve the model, my model isn't changed at all...

This is a slimmed down version of my sourcecode:

```<code>var schema = new Schema({
  name: {
    type: String,
    required: true,
  },
  version: {
    type: Number,
    required: false,
  },
  versions: {
    type: Object,
    required: false,
  },
  elements: {
    type: Array,
    required: false,
  },
})
  .pre('save', function(next) {
    version = Object
      .keys(this.versions)
      .map(function(key) { return parseInt(key); })
      .sort(function(a, b) { return a - b; })
      .reverse()[0] + 1;
    if (isNaN(version)) {
      version = 1;
    }

    this.versions[version] = {
      createdAt: new Date(),
      elements: this.elements.slice(),
    };
    this.elements = null;
  })
</code>```

I do this because I need to keep all changes in a specific version, so that people can load in specific versions of the data, but the client should not know about these, and simply get a version-number and the correct elements.

Could you point me in the correct direction with my issue, or show me what I'm doing wrong. Any help is greatly appreciated.

答:
You need to call the 'next' function at the end of your callback when done:</p>

```<code>next();
</code>```

Body:
I have a model that I modify using the pre-save hook in the schema. When saved, mongoose returns the modified data, __v is updated and everything looks dandy. But when I retrieve the model, my model isn't changed at all...

This is a slimmed down version of my sourcecode:

var schema = new Schema({
  name: {
    type: String,
    required: true,
  },
  version: {
    type: Number,
    required: false,
  },
  versions: {
    type: Object,
    required: false,
  },
  elements: {
    type: Array,
    required: false,
  },
})
  .pre('save', function(next) {
    version = Object
      .keys(this.versions)
      .map(function(key) { return parseInt(key); })
      .sort(function(a, b) { return a - b; })
      .reverse()[0] + 1;
    if (isNaN(version)) {
      version = 1;
    }

    this.versions[version] = {
      createdAt: new Date(),
      elements: this.elements.slice(),
    };
    this.elements = null;
  })

I do this because I need to keep all changes in a specific version, so that people can load in specific versions of the data, but the client should not know about these, and simply get a version-number and the correct elements.

Could you point me in the correct direction with my issue, or show me what I'm doing wrong. Any help is greatly appreciated.

Body:
You need to call the 'next' function at the end of your callback when done:

next();


问:
Microsoft Graph: how to get all groups reusing the token generated through ADAL
I'm trying to use Microsoft Graph and I'm a little bit lost here. I'm using ADAL to authenticate my app (app id + secret) through the AuthenticationContext.AcquireTokenAsync method. The code looks like this:

```<code>AuthenticationContext AuthContext = new AuthenticationContext(Authority);
ClientCredential ClientCredential = new ClientCredential(ClientId, AppKey);
var result = await AuthContext.AcquireTokenAsync(
                                        "https://graph.windows.net",
                                        ClientCredential);
</code>```

Now, if I reuse the token with the Azure Graph, I can recover all the groups by using this code:

```<code>var url = $"https://graph.windows.net/myorganization/groups?api-version=1.6";
 var client = new HttpClient();
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", resultAccessToken);
  var response = await client.GetAsync(url);
  if (response.Content != null) {
       Console.WriteLine(await response.Content.ReadAsStringAsync());
  }
</code>```

According to the docs, I should use the newer Microsoft Graph API, but I'm having some issues when I try to use the following code:

```<code>var authenticationProvider = new DelegateAuthenticationProvider(
      req.Headers.Authorization = new AuthenticationHeaderValue("bearer",
                                           resultAccessToken.AccessToken);
      return Task.CompletedTask;
});
var graph = new GraphServiceClient(authenticationProvider);
var groups = await graph.Groups
                    .Request()
                    .GetAsync();
</code>```

Whenever I run this, I end up getting the following exception:

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken
Message: Access token validation failure.

It's obvious that I'm missing something here, but what? (btw, I've managed to get everything working with the MSAL libraries, but in this case, I really need to have my component integrated with others that use ADAL),

Thanks.

Luis

答:
The AAD Graph and the Microsoft Graph have different physical endpoints.

To call the AAD Graph, you need a token with the Audience Claim https://graph.windows.net

To call the Microsoft Graph, you need a token with the Audience Claim https://graph.microsoft.com

This means you need to do 2 things:

Make sure your application is configured to the Microsoft Graph. (This means you need to update your application's configuration to call other resources)

Update your code to request a token for the right resource.

I hope this helps!

Body:
I'm trying to use Microsoft Graph and I'm a little bit lost here. I'm using ADAL to authenticate my app (app id + secret) through the AuthenticationContext.AcquireTokenAsync method. The code looks like this:

AuthenticationContext AuthContext = new AuthenticationContext(Authority);
ClientCredential ClientCredential = new ClientCredential(ClientId, AppKey);
var result = await AuthContext.AcquireTokenAsync(
                                        "https://graph.windows.net",
                                        ClientCredential);

Now, if I reuse the token with the Azure Graph, I can recover all the groups by using this code:

var url = $"https://graph.windows.net/myorganization/groups?api-version=1.6";
 var client = new HttpClient();
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", resultAccessToken);
  var response = await client.GetAsync(url);
  if (response.Content != null) {
       Console.WriteLine(await response.Content.ReadAsStringAsync());
  }

According to the docs, I should use the newer Microsoft Graph API, but I'm having some issues when I try to use the following code:

var authenticationProvider = new DelegateAuthenticationProvider(
      req.Headers.Authorization = new AuthenticationHeaderValue("bearer",
                                           resultAccessToken.AccessToken);
      return Task.CompletedTask;
});
var graph = new GraphServiceClient(authenticationProvider);
var groups = await graph.Groups
                    .Request()
                    .GetAsync();

Whenever I run this, I end up getting the following exception:

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken
Message: Access token validation failure.

It's obvious that I'm missing something here, but what? (btw, I've managed to get everything working with the MSAL libraries, but in this case, I really need to have my component integrated with others that use ADAL),

Thanks.

Luis


问:
Reading words from file with fscanf
I have a file .txt with the following encoding:

```<code>Alpha-Beta-Gamma-Delta-Epsilon
Zeta-Eta-Theta-Iota-Kappa-Lamda-Mi
Ni-Ksi-Pi-Ro-Sigma
</code>```

I want to read those words and store them in an array.
I read those words with fscanf(fp, "%[^-]", word)

But when I put fscanf inside a while, it keeps reading the same word. If I put it inside the while statement it doesn't repeat.

The point is to read every word separately from Alpha to Sigma

I provide you a minimal-verifiable code with the problem:

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

int main(){
    FILE *fp;
    char *word = (char*)malloc(40);
    int count = 0;
    char* Words[30]; //max 30
    fp = fopen("MyWords.txt","r"); //read only
    int r = 1;
    while(1){
        if(fscanf(fp, "%[^-]", word) == EOF) break;
        printf("%s",word);
    }
    fclose(fp);
    return 0;
}
</code>```

Note: I don't want to modify the file. Also how should I handle with the \n characheter

答:
The above answer works just fine, If you don't want regex complications in your code even though it's simple, use strtok after reading the whole string out. Then add it onto the array.

```<code>while(1){
    if(fscanf(fp, "%s", word) == EOF) break;
    printf("%s\n",word);
    const char s[2] = "-";
    char *token;
    token = strtok(word, s);
    while( token != NULL )
    {
        printf("%s\n", token );
        token = strtok(NULL, s);
    }
}
</code>```

Which gives the output

```<code>Alpha-Beta-Gamma-Delta-Epsilon

Alpha
Beta
Gamma
Delta
Epsilon

Zeta-Eta-Theta-Iota-Kappa-Lamda-Mi

Zeta
Eta
Theta
Iota
Kappa
Lamda
Mi

Ni-Ksi-Pi-Ro-Sigma

Ni
Ksi
Pi
Ro
Sigma
</code>```

Cheers!

Title: Reading words from file with fscanf

Body:
I have a file .txt with the following encoding:

Alpha-Beta-Gamma-Delta-Epsilon
Zeta-Eta-Theta-Iota-Kappa-Lamda-Mi
Ni-Ksi-Pi-Ro-Sigma

I want to read those words and store them in an array.
I read those words with fscanf(fp, "%[^-]", word)

But when I put fscanf inside a while, it keeps reading the same word. If I put it inside the while statement it doesn't repeat.

The point is to read every word separately from Alpha to Sigma

I provide you a minimal-verifiable code with the problem:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    FILE *fp;
    char *word = (char*)malloc(40);
    int count = 0;
    char* Words[30]; //max 30
    fp = fopen("MyWords.txt","r"); //read only
    int r = 1;
    while(1){
        if(fscanf(fp, "%[^-]", word) == EOF) break;
        printf("%s",word);
    }
    fclose(fp);
    return 0;
}

Note: I don't want to modify the file. Also how should I handle with the \n characheter

Body:
The above answer works just fine, If you don't want regex complications in your code even though it's simple, use strtok after reading the whole string out. Then add it onto the array.

while(1){
    if(fscanf(fp, "%s", word) == EOF) break;
    printf("%s\n",word);
    const char s[2] = "-";
    char *token;
    token = strtok(word, s);
    while( token != NULL )
    {
        printf("%s\n", token );
        token = strtok(NULL, s);
    }
}

Which gives the output

Alpha-Beta-Gamma-Delta-Epsilon

Alpha
Beta
Gamma
Delta
Epsilon

Zeta-Eta-Theta-Iota-Kappa-Lamda-Mi

Zeta
Eta
Theta
Iota
Kappa
Lamda
Mi

Ni-Ksi-Pi-Ro-Sigma

Ni
Ksi
Pi
Ro
Sigma

Cheers!


问:
Populate Custom Category Taxonomy with Data in WP Plugin
I'm writing a wordpress plugin that allows people in the admin to hide/show content specific to US states. I have a custom category taxonomy called States, and it lists all of the states. Admins can check which states they want the post to appear in. Pages and posts will not show up in the loop if the user's state doesn't match up with the posts' selected states.

Now, my question is, how do I populate the plugin with all of the states' data upon install (or remove it upon uninstall)?

答:
This should work. You'll need to add the rest of the states, and make sure that your taxonomy is actually called "States", but other than that it should be fine:</p>

```<code><?php

$foo_states = array(
    'Alabama',
    'Alaska',
    'Arizona',
    'Arkansas'
);

function foo_install() {
    global $foo_states;

    foreach ( (array) $foo_states as $state ) {
        wp_insert_term($state, 'States');
    }
}
register_activation_hook(__FILE__, 'foo_install')

function foo_uninstall() {
    global $foo_states;

    foreach ( (array) $foo_states as $state ) {
        wp_delete_term(get_term_by('name', $state, 'States')->term_id, 'States');
    }
}
register_deactivation_hook(__FILE__, 'foo_uninstall');

?>
</code>```

Body:
This should work. You'll need to add the rest of the states, and make sure that your taxonomy is actually called "States", but other than that it should be fine:

<?php

$foo_states = array(
    'Alabama',
    'Alaska',
    'Arizona',
    'Arkansas'
);

function foo_install() {
    global $foo_states;

    foreach ( (array) $foo_states as $state ) {
        wp_insert_term($state, 'States');
    }
}
register_activation_hook(__FILE__, 'foo_install')

function foo_uninstall() {
    global $foo_states;

    foreach ( (array) $foo_states as $state ) {
        wp_delete_term(get_term_by('name', $state, 'States')->term_id, 'States');
    }
}
register_deactivation_hook(__FILE__, 'foo_uninstall');

?>


问:
Violation nonlinear constraints fmincon interior-point Matlab
I am trying to impose two nonlinear constraints with fmincon (interior-point) in Matlab:

```<code>sqrt(w*S*w') <= sigmaTgt/sqrt(260)
sqrt(w*S*w') >= sigmaTgt/sqrt(260)-0.02/sqrt(260)
</code>```

I tried the following:

```<code>function [c,ceq] = in_nonlconstr(w, S)

    c(1) = sqrt(w*S*w') - tgtVolAnn/sqrt(260);
    c(2) = - sqrt(w*S*w') + ( tgtVolAnn/sqrt(260) - 0.02/sqrt(260) );
    ceq = [];

end
</code>```

but after the optimization I keep getting that sqrt(w*S*w') satisfies c(1) but not c(2), despite an exitflag of 1 and the solver having converged.

Am I writing it correctly or is there smth wrong with my solver?

Message from output.message:

Local minimum found that satisfies the constraints.

Optimization completed because the objective function is
  non-decreasing in  feasible directions, to within the default value of
  the optimality tolerance, and constraints are satisfied to within the
  default value of the constraint tolerance.

Stopping criteria details:

Optimization completed: The relative first-order optimality measure,
  9.821943e-07, is less than options.OptimalityTolerance = 1.000000e-06, and the relative maximum constraint violation, 0.000000e+00, is less
  than options.ConstraintTolerance = 1.000000e-06.

Optimization Metric                                            Options
  relative first-order optimality =   9.82e-07       OptimalityTolerance
  =   1e-06 (default) relative max(constraint violation) =   0.00e+00    ConstraintTolerance =   1e-06 (default)

答:
Give this a shot:

```<code>options = optimset('OptimalityTolerance', 1e-20, 'ConstraintTolerance', 1e-20);
% this may need to be instead started with the function name, depends on your MATLAB version
options = optimset('fmincon','OptimalityTolerance', 1e-20, 'ConstraintTolerance', 1e-20);
fmincon(....., options) % i.e. what you already are passing to fmincon but adding additional tolerances
</code>```

Let me know if that solves your problem.  If not my variable names are probably wrong, I'd need you to run options=optimset('fmincon') and post the variable names inside options to set the tolerances.  The other option you have is to change your algorithm - MATHWORKS says sqp is usually better than the method you're using:

```<code>options = optimset('fmincon','Algorithm','sqp','TolConSQP',1e-20) % other choices are 'active-set' or 'trust-region-reflective' and don't have the `TolConSQP` tolerance parameter, which you may not need at all anyhow
</code>```

You of course can use a lower tolerance if it works for your application - it seems 1e-20 is the largest for any of the algorithms.
See here for documentation: http://www.mathworks.com/help/optim/ug/fmincon.html#inputarg_options

Body:
I am trying to impose two nonlinear constraints with fmincon (interior-point) in Matlab:

sqrt(w*S*w') <= sigmaTgt/sqrt(260)
sqrt(w*S*w') >= sigmaTgt/sqrt(260)-0.02/sqrt(260)

I tried the following:

function [c,ceq] = in_nonlconstr(w, S)

    c(1) = sqrt(w*S*w') - tgtVolAnn/sqrt(260);
    c(2) = - sqrt(w*S*w') + ( tgtVolAnn/sqrt(260) - 0.02/sqrt(260) );
    ceq = [];

end

but after the optimization I keep getting that sqrt(w*S*w') satisfies c(1) but not c(2), despite an exitflag of 1 and the solver having converged.

Am I writing it correctly or is there smth wrong with my solver?

Message from output.message:

Local minimum found that satisfies the constraints.

Optimization completed because the objective function is
  non-decreasing in  feasible directions, to within the default value of
  the optimality tolerance, and constraints are satisfied to within the
  default value of the constraint tolerance.

Stopping criteria details:

Optimization completed: The relative first-order optimality measure,
  9.821943e-07, is less than options.OptimalityTolerance = 1.000000e-06, and the relative maximum constraint violation, 0.000000e+00, is less
  than options.ConstraintTolerance = 1.000000e-06.

Optimization Metric                                            Options
  relative first-order optimality =   9.82e-07       OptimalityTolerance
  =   1e-06 (default) relative max(constraint violation) =   0.00e+00    ConstraintTolerance =   1e-06 (default)

Body:
Give this a shot:

options = optimset('OptimalityTolerance', 1e-20, 'ConstraintTolerance', 1e-20);
% this may need to be instead started with the function name, depends on your MATLAB version
options = optimset('fmincon','OptimalityTolerance', 1e-20, 'ConstraintTolerance', 1e-20);
fmincon(....., options) % i.e. what you already are passing to fmincon but adding additional tolerances

Let me know if that solves your problem.  If not my variable names are probably wrong, I'd need you to run options=optimset('fmincon') and post the variable names inside options to set the tolerances.  The other option you have is to change your algorithm - MATHWORKS says sqp is usually better than the method you're using:

options = optimset('fmincon','Algorithm','sqp','TolConSQP',1e-20) % other choices are 'active-set' or 'trust-region-reflective' and don't have the `TolConSQP` tolerance parameter, which you may not need at all anyhow

You of course can use a lower tolerance if it works for your application - it seems 1e-20 is the largest for any of the algorithms.
See here for documentation: http://www.mathworks.com/help/optim/ug/fmincon.html#inputarg_options