问:
place a will-be sticky nav in html
My target is to show the banner picture first then the navigation menu, and while the  is scrolled to the top of the screen it sticks there on the top. Also, the site-logo, overlapping with the banner picture first, will appear on the nav bar when  is scrolled and sticks on top.

My question is where to place the nav section in html. Should it be moved to the header section? (In this case, what's the best way to originally position it in css for there is a picture element having several responsive img source tags?) Or should it just stays where it is now, and let the header section to be removed or to wrap the nav?

```<code><body>
  <header>

     .....
  </header>

  <div role="banner">
    <picture>
    </picture>
    <div role="site-logo"></div>
  </div>

  <nav role="navigation menu">
    <ul>
    </ul>
  </nav>
</body>
</code>```

答:
From here

CSS

```<code>.navbar-fixed {
  top: 0;
  z-index: 100;
  position: fixed;
  width: 100%;
}
</code>```

JQUERY

```<code>$(document).ready(function() {
  //change the integers below to match the height of your upper dive, which I called
  //banner.  Just add a 1 to the last number.  console.log($(window).scrollTop())
  //to figure out what the scroll position is when exactly you want to fix the nav
  //bar or div or whatever.  I stuck in the console.log for you.  Just remove when
  //you know the position.
  $(window).scroll(function () {

    console.log($(window).scrollTop());

    if ($(window).scrollTop() > 550) {
      $('nav').addClass('navbar-fixed');
    }

    if ($(window).scrollTop() < 551) {
      $('nav').removeClass('navbar-fixed');
    }
  });
});
</code>```

Title: place a will-be sticky nav in html

Body:
My target is to show the banner picture first then the navigation menu, and while the  is scrolled to the top of the screen it sticks there on the top. Also, the site-logo, overlapping with the banner picture first, will appear on the nav bar when  is scrolled and sticks on top.

My question is where to place the nav section in html. Should it be moved to the header section? (In this case, what's the best way to originally position it in css for there is a picture element having several responsive img source tags?) Or should it just stays where it is now, and let the header section to be removed or to wrap the nav?

     .....

    <picture>
    </picture>

Body:
From here

CSS

.navbar-fixed {
  top: 0;
  z-index: 100;
  position: fixed;
  width: 100%;
}

JQUERY

$(document).ready(function() {
  //change the integers below to match the height of your upper dive, which I called
  //banner.  Just add a 1 to the last number.  console.log($(window).scrollTop())
  //to figure out what the scroll position is when exactly you want to fix the nav
  //bar or div or whatever.  I stuck in the console.log for you.  Just remove when
  //you know the position.
  $(window).scroll(function () {

    console.log($(window).scrollTop());

    if ($(window).scrollTop() > 550) {
      $('nav').addClass('navbar-fixed');
    }

    if ($(window).scrollTop() < 551) {
      $('nav').removeClass('navbar-fixed');
    }
  });
});


来源: stackexchange

问:
Why does the following while loop work with an AND, as opposed to an OR
so I'm making a game and I just managed to fix the issue I was having by changing my OR to an AND and I'm not sure I understand why it works as opposed to the logical || I had there before.

```<code>    //while user doesn't press quit, hasn't crashed into a bomb or hasn't saved all bears the game continues
while (((!wantsToQuit(key)) && (hasLost == false)) && (bearsSaved !=3))
{
    if (isArrowKey(key))
    {
        updateGameData(grid, bears, bombs, detonator, exit, key, message, bearsSaved, bombsActive, moves, hasLost); //move bear in that direction
        updateGrid(grid, maze, bears, bombs, detonator, exit);  //update grid information
    }
    else if (toupper(key) == CHEAT) //pressing c enables cheat mode; disables bombs and sets the users moves to 500
    {
        cheatMode(message, moves, cheatActive, bombsActive);
    }
    else
        message = "INVALID KEY!";   //set 'Invalid key' message
    paintGame(grid, message, bearsSaved, moves); //display game info, modified grid & messages
    key = getKeyPress();            //display menu & read in next option
}
endProgram();                       //display final message
return(0);
</code>```

The basic idea is that the user has to save 3 bears by guiding them through a maze and avoiding bombs.

If they walk into a bomb, hasLost is set to true and thus endProgram is ran.

If they press Q, the while loop is no longer true and endProgram is ran.

However, if all bears are saved then the game also ends.

What I don't understand is why this while loop works whilst:

The player does not want to quit AND the player has not lost AND the player has not saved all 3 bears.

As opposed to:

The player does not want to quit AND the player has not lost OR the player has not saved all 3 bears.

To me the latter makes more sense logically speaking, since one would expect the game to continue running whilst they don't want to quit and haven't lost, or if they haven't saved all of the bears.

Thank you for clarification

答:
The player does not want to quit AND the player has not lost OR the player has not saved all 3 bears

In this scenario, your while-loop condition would look like:

```<code>while (((!wantsToQuit(key)) && (hasLost == false)) || (bearsSaved !=3))
</code>```

Let's assume that the player has not lost, and he does not want to quit the game. Now, if your player saves 3 bears, then the bearsSaved !=3 condition would be falsified. However, since you use the ||, even if the second statement is falsified, the game will continue, as the first statement is still true. This goes against your logic, because you want:

However, if all bears are saved then the game also ends.

With the || statement, you would have to falsify both conditions (I take the first 2 parenthesized conditions as one major one) in order for the loop to terminate.

That is why the logic you use right now makes sense; as soon as the user wins, the AND condition is falsified, and as soon as one AND condition is falsified, the loop terminates.

ContentLicense: CC BY-SA 3.0

Body:
so I'm making a game and I just managed to fix the issue I was having by changing my OR to an AND and I'm not sure I understand why it works as opposed to the logical || I had there before.

    //while user doesn't press quit, hasn't crashed into a bomb or hasn't saved all bears the game continues
while (((!wantsToQuit(key)) && (hasLost == false)) && (bearsSaved !=3))
{
    if (isArrowKey(key))
    {
        updateGameData(grid, bears, bombs, detonator, exit, key, message, bearsSaved, bombsActive, moves, hasLost); //move bear in that direction
        updateGrid(grid, maze, bears, bombs, detonator, exit);  //update grid information
    }
    else if (toupper(key) == CHEAT) //pressing c enables cheat mode; disables bombs and sets the users moves to 500
    {
        cheatMode(message, moves, cheatActive, bombsActive);
    }
    else
        message = "INVALID KEY!";   //set 'Invalid key' message
    paintGame(grid, message, bearsSaved, moves); //display game info, modified grid & messages
    key = getKeyPress();            //display menu & read in next option
}
endProgram();                       //display final message
return(0);

The basic idea is that the user has to save 3 bears by guiding them through a maze and avoiding bombs.

If they walk into a bomb, hasLost is set to true and thus endProgram is ran.

If they press Q, the while loop is no longer true and endProgram is ran.

However, if all bears are saved then the game also ends.

What I don't understand is why this while loop works whilst:

The player does not want to quit AND the player has not lost AND the player has not saved all 3 bears.

As opposed to:

The player does not want to quit AND the player has not lost OR the player has not saved all 3 bears.

To me the latter makes more sense logically speaking, since one would expect the game to continue running whilst they don't want to quit and haven't lost, or if they haven't saved all of the bears.

Thank you for clarification

Body:
The player does not want to quit AND the player has not lost OR the player has not saved all 3 bears

In this scenario, your while-loop condition would look like:

while (((!wantsToQuit(key)) && (hasLost == false)) || (bearsSaved !=3))

Let's assume that the player has not lost, and he does not want to quit the game. Now, if your player saves 3 bears, then the bearsSaved !=3 condition would be falsified. However, since you use the ||, even if the second statement is falsified, the game will continue, as the first statement is still true. This goes against your logic, because you want:

However, if all bears are saved then the game also ends.

With the || statement, you would have to falsify both conditions (I take the first 2 parenthesized conditions as one major one) in order for the loop to terminate.

That is why the logic you use right now makes sense; as soon as the user wins, the AND condition is falsified, and as soon as one AND condition is falsified, the loop terminates.


问:
Accessing files in directory outside of Anaconda
Newb here to python/anaconda.

I'm trying to run a python script (and it reads other files local to its directory) which doesn't belong to the same directory as the Anaconda directory where I'm executing the python command there.

So I am trying to run a python script (lets say it resides in path B directory) from the Anaconda python (say path A directory).  Within this script, there is a call to reading a local file so we have only the fileName.py and then the command prompt spits out this error:

```<code>C:\Users\usernameABC\Anaconda3>python C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py
Traceback (most recent call last):
  File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 165, in <module>
    main()
  File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 130, in main
    resp = ReadFemResp()
  File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 27, in ReadFemResp
    dct = thinkstats2.ReadStataDct(dct_file)
  File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\thinkstats2.py", line 2646, in ReadStataDct
    for line in open(dct_file, **options):
FileNotFoundError: [Errno 2] No such file or directory: '2002FemResp.dct'
</code>```

I basically just want to run the script, whether its in Anaconda or wherever is the easiest or most natural that most experienced coders would.  Please help!  Thanks in advance for feedback!

答:
You can change your current working directory using the

cd (change directory) command

You can also modify the script so that you can specify where the files are that you want to access. If you show us the script that you are running we may be able to help more.

Body:
Newb here to python/anaconda.

I'm trying to run a python script (and it reads other files local to its directory) which doesn't belong to the same directory as the Anaconda directory where I'm executing the python command there.

So I am trying to run a python script (lets say it resides in path B directory) from the Anaconda python (say path A directory).  Within this script, there is a call to reading a local file so we have only the fileName.py and then the command prompt spits out this error:

C:\Users\usernameABC\Anaconda3>python C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py
Traceback (most recent call last):
  File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 165, in <module>
    main()
  File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 130, in main
    resp = ReadFemResp()
  File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 27, in ReadFemResp
    dct = thinkstats2.ReadStataDct(dct_file)
  File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\thinkstats2.py", line 2646, in ReadStataDct
    for line in open(dct_file, **options):
FileNotFoundError: [Errno 2] No such file or directory: '2002FemResp.dct'

I basically just want to run the script, whether its in Anaconda or wherever is the easiest or most natural that most experienced coders would.  Please help!  Thanks in advance for feedback!


问:
Testing state in S#arp Architecture - Best practice
How do I test for state in a S#arp Architecture project?

For example, I have a custom RoleProvider. I want to test the method provider.AddUsersToRoles(string[], string[]).

So I start with:

```<code>// Arrange
const string ficticiousRole = "Management";
var userToExpect = UserInstanceFactory.CreateValidTransientUser();
var roleToExpect = RoleInstanceFactory.CreateValidTransientRole();

userRepository.Expect(r => r.GetByUsername(userToExpect.Username))
              .Return(userToExpect);
roleRepository.Expect(r => r.GetByName(ficticiousRole))
              .Return(roleToExpect);

var userNames = new List<string>();
var roleNames = new List<string>();
userNames.Add(userToExpect.Username);
roleNames.Add(ficticiousRole);
</code>```

Then I add the user to a role. Then I check if the user is in this role.

```<code>// Act
roleProvider.AddUsersToRoles(userNames.ToArray(), roleNames.ToArray());
var isNewUserInRole = roleProvider.IsUserInRole(userToExpect.Username, ficticiousRole);

// Assert
Assert.IsTrue(isNewUserInRole);
</code>```

The problem is that I'm using Rhino Mocks. I have limited knowledge of Rhino Mocks, but from what I understand (according to Ayende Rahien) you use Rhino Mocks to test for operations, not state.

So I guess an in-memory SqlLite db would be more suitable? What's the best way to do this in S#arp Arch?

答:
You can't do that with Rhino Mocks since that is simply a mocking framework that fakes things like database calls, etc. It sounds like you actually want to test persistence to the database which is basically database integration testing. In that case, you would most definitely want to use an in-memory database such as SqlLite (if possible!) as opposed to hitting a SQL Server instance.

What you want to do is at the beginning of each test or test class is tear down the database if it exists already, rebuild the database, populate the database with some seed data and then test your database interaction. This way, you can ensure you have a known database state before each test is run.

One thing I did on a project was grouped all of my read-only tests into one test class so that I only had to do the database rebuild step once for the class and moved all my delete, update and insert tests into other test classes that rebuilt the database before each and every test. Given enough tests, this can be quite time consuming and may want to be relegated to CI server.

ContentLicense: CC BY-SA 2.5

Body:
How do I test for state in a S#arp Architecture project?

For example, I have a custom RoleProvider. I want to test the method provider.AddUsersToRoles(string[], string[]).

So I start with:

// Arrange
const string ficticiousRole = "Management";
var userToExpect = UserInstanceFactory.CreateValidTransientUser();
var roleToExpect = RoleInstanceFactory.CreateValidTransientRole();

userRepository.Expect(r => r.GetByUsername(userToExpect.Username))
              .Return(userToExpect);
roleRepository.Expect(r => r.GetByName(ficticiousRole))
              .Return(roleToExpect);

var userNames = new List<string>();
var roleNames = new List<string>();
userNames.Add(userToExpect.Username);
roleNames.Add(ficticiousRole);

Then I add the user to a role. Then I check if the user is in this role.

// Act
roleProvider.AddUsersToRoles(userNames.ToArray(), roleNames.ToArray());
var isNewUserInRole = roleProvider.IsUserInRole(userToExpect.Username, ficticiousRole);

// Assert
Assert.IsTrue(isNewUserInRole);

The problem is that I'm using Rhino Mocks. I have limited knowledge of Rhino Mocks, but from what I understand (according to Ayende Rahien) you use Rhino Mocks to test for operations, not state.

So I guess an in-memory SqlLite db would be more suitable? What's the best way to do this in S#arp Arch?


问:
jQuery datetimepicker not initializing in ASP.NET
I am trying to initialize a datetimepicker but I am always getting an error:

```<code> $(...).timepicker not a function
</code>```

My code is as follow:

```<code> //REFERENCES:

 <link href="/CSS/jquery-ui-timepicker-addon.css" rel="stylesheet"  type="text/css" />
  <script type="text/javascript" src="/JS/jquery-ui-timepicker-addon.js"></script>
  <script type="text/javascript" src="/JS/jquery-1.10.2.js"></script>
  <script type="text/javascript" src="/JS/jquery-1.9.1.js"></script>
  <script type="text/javascript" src="/JS/jquery.min.js"></script>
  <script type="text/javascript" src="/JS/jquery-ui.js"></script>
  <script type="text/javascript" src="/JS/jquery-1.9.1.min.js"></script>

  //JAVASCRIPT

  <script type="text/javascript">
  $('"[id*=tb_input]"').timepicker();

  function tpicker() {
    $('"[id*=tb_input]"').timepicker();
  }
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(tpicker);
  </script>

  //HTML
  <asp:TextBox ID="tb_input" style="text-align:center" runat="server"
   CssClass="font2" Width="226px" onfocus="disableautocompletion(this.id);"
   Height="24px"></asp:TextBox>
</code>```

Any ideas? Thank you!

答:
Refference should be as
first load jquery core file , then load other files</p>

```<code><script type="text/javascript" src="/JS/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/JS/jquery-ui.js"></script>
<script type="text/javascript" src="/JS/jquery-ui-timepicker-addon.js"></script>
</code>```

Body:
I am trying to initialize a datetimepicker but I am always getting an error:

 $(...).timepicker not a function

My code is as follow:

 //REFERENCES:

 <link href="/CSS/jquery-ui-timepicker-addon.css" rel="stylesheet"  type="text/css" />

  //JAVASCRIPT

  //HTML
  <asp:TextBox ID="tb_input" style="text-align:center" runat="server"
   CssClass="font2" Width="226px" onfocus="disableautocompletion(this.id);"
   Height="24px"></asp:TextBox>

Any ideas? Thank you!

Body:
Refference should be as
first load jquery core file , then load other files

<script type="text/javascript" src="/JS/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/JS/jquery-ui.js"></script>
<script type="text/javascript" src="/JS/jquery-ui-timepicker-addon.js"></script>


问:
Turtles moving in a pattern (Netlogo)
Good afternoon, I'm trying to make my turtles to move between a set of 4 blue patches. I can make them get to those patches but after that they just stay there, and what I need is to them continuously move (in order) to the next blue patch to their right. I don't know how to do it.

This is the section of the code I'm talking about:

```<code>to move-turtles

    ask turtles
      [while [[pcolor] of patch-here != blue]
         [
           face min-one-of patches with [pcolor = blue ] [ distance myself ]
           forward 1
         ]
      ]
    tick
    end
</code>```

By advance, thank you!

答:
You're right- with a while loop your turtles will be stuck on the first blue patch they come to, since if they step onto a neighboring patch they will immediately want to move back to the closest blue patch (the one they just left). Additionally, everything that happens in the while loop occurs within a single tick- if you just want them to move to the nearest blue patch as part of your setup, just use move-to. If their movement to the nearest blue patch is important to you, it's probably better here to use an if statement rather than a while.

Additionally, you are describing two different "modes" of movement. First, you want the turtles to move to a circuit that you want them to follow. Then, if they are in that circuit, you want them to follow an ordered path where they target the next blue patch in the circuit and then move to that patch. Accordingly, it's probably easier to set up two separate procedures and call them at the appropriate time. It would probably also help if the turtles know where they are supposed to go next (a current target) and which movement mode they should be executing. So, you could set up turtles-own variables such as:

```<code>turtles-own [
  on-circuit?
  my-target
]
</code>```

Make sure you set those variables in your setup so that they are not the default "0" of undefined variables:

```<code>to setup
  ca
  reset-ticks
  ask (patch-set patch 5 5 patch 5 -5 patch -5 5 patch -5 -5 ) [
    set pcolor blue
  ]

  crt 1  [

    set on-circuit? false   ;;; so a starting turtle knows which movement procedure to use
    set my-target nobody
    setxy random 30 - 15 random 30 - 15
    pd
  ]

end
</code>```

Then, you can run your go procedure such that the turtles will try to get onto the circuit if their "on-circuit?" is false, and they will walk the circuit if their "on-circuit?" is true.

```<code>to go

  ask turtles [
    ifelse on-circuit? = false [  ;;; do this if turtle is not yet on the circuit
      get-to-circuit
    ]
    [  ;;;  do this if the turtle has been designated as on the circuit
      walk-circuit
    ]
  ]
  tick

end
</code>```

Now you make your get-to-circuit and walk-circuit procedures. I'll show you how I set up my get-to-circuit, but see if you can figure out the rest of the walk-circuit:

```<code>to get-to-circuit

  set my-target min-one-of other patches with [pcolor = blue ] [ distance myself ]
  face my-target
  fd 1
  if distance my-target < 1 [
    move-to my-target
    ;;; This lets the turtle know it can switch to "walk-circuit" on the next tick
    set on-circuit? true
    set heading one-of [ 0 90 180 270 ]
  ]
end

to walk-circuit
  if  my-target =  nobody [
    set my-target one-of ( other patches with [ pcolor = blue ] ) in-cone 10 180
  ]
?
?
? ...
</code>```

Title: Turtles moving in a pattern (Netlogo)

Body:
Good afternoon, I'm trying to make my turtles to move between a set of 4 blue patches. I can make them get to those patches but after that they just stay there, and what I need is to them continuously move (in order) to the next blue patch to their right. I don't know how to do it.

This is the section of the code I'm talking about:

to move-turtles

    ask turtles
      [while [[pcolor] of patch-here != blue]
         [
           face min-one-of patches with [pcolor = blue ] [ distance myself ]
           forward 1
         ]
      ]
    tick
    end

By advance, thank you!

Body:
You're right- with a while loop your turtles will be stuck on the first blue patch they come to, since if they step onto a neighboring patch they will immediately want to move back to the closest blue patch (the one they just left). Additionally, everything that happens in the while loop occurs within a single tick- if you just want them to move to the nearest blue patch as part of your setup, just use move-to. If their movement to the nearest blue patch is important to you, it's probably better here to use an if statement rather than a while.

Additionally, you are describing two different "modes" of movement. First, you want the turtles to move to a circuit that you want them to follow. Then, if they are in that circuit, you want them to follow an ordered path where they target the next blue patch in the circuit and then move to that patch. Accordingly, it's probably easier to set up two separate procedures and call them at the appropriate time. It would probably also help if the turtles know where they are supposed to go next (a current target) and which movement mode they should be executing. So, you could set up turtles-own variables such as:

turtles-own [
  on-circuit?
  my-target
]

Make sure you set those variables in your setup so that they are not the default "0" of undefined variables:

to setup
  ca
  reset-ticks
  ask (patch-set patch 5 5 patch 5 -5 patch -5 5 patch -5 -5 ) [
    set pcolor blue
  ]

  crt 1  [

    set on-circuit? false   ;;; so a starting turtle knows which movement procedure to use
    set my-target nobody
    setxy random 30 - 15 random 30 - 15
    pd
  ]

end

Then, you can run your go procedure such that the turtles will try to get onto the circuit if their "on-circuit?" is false, and they will walk the circuit if their "on-circuit?" is true.

to go

  ask turtles [
    ifelse on-circuit? = false [  ;;; do this if turtle is not yet on the circuit
      get-to-circuit
    ]
    [  ;;;  do this if the turtle has been designated as on the circuit
      walk-circuit
    ]
  ]
  tick

end

Now you make your get-to-circuit and walk-circuit procedures. I'll show you how I set up my get-to-circuit, but see if you can figure out the rest of the walk-circuit:

to get-to-circuit

  set my-target min-one-of other patches with [pcolor = blue ] [ distance myself ]
  face my-target
  fd 1
  if distance my-target < 1 [
    move-to my-target
    ;;; This lets the turtle know it can switch to "walk-circuit" on the next tick
    set on-circuit? true
    set heading one-of [ 0 90 180 270 ]
  ]
end

to walk-circuit
  if  my-target =  nobody [
    set my-target one-of ( other patches with [ pcolor = blue ] ) in-cone 10 180
  ]
?
?
? ...


问:
How can I splash before callback in AngularJS
This is my piece of code:

```<code>.factory('Latest', function(EBSheadless) {
  return {
    posts: function() {
      // Call the API, and define the specific endpoint
      return EBSheadlessDrupalAPI.loadEndpoint('views/news.json');
    },
    post: function(posts,id,callback){
      var findpost = {};
      for(var i=0;i<posts.length;i++) {
        findpost[posts[i].nid] = posts[i];
      }
      callback(findpost[id]);
    }
  };
})
</code>```

Its getting right result, e.g:

```<code>this-is-a-news
</code>```

But I need this links like this (I cannot edit backend):

```<code>/this-is-a-news
</code>```

So I have to add / in my callback. I tried many positions but its not working.
How can I solve it? Thanks!

答:
why don't you just concatenate string like this callback("/"+findpost[id]);.This will return /this-is-a-news.

```<code>post: function(posts,id,callback){
      var findpost = {};
      for(var i=0;i<posts.length;i++) {
        findpost[posts[i].nid] = posts[i];
      }
      callback("/"+findpost[id]);
}
</code>```

Body:
This is my piece of code:

.factory('Latest', function(EBSheadless) {
  return {
    posts: function() {
      // Call the API, and define the specific endpoint
      return EBSheadlessDrupalAPI.loadEndpoint('views/news.json');
    },
    post: function(posts,id,callback){
      var findpost = {};
      for(var i=0;i<posts.length;i++) {
        findpost[posts[i].nid] = posts[i];
      }
      callback(findpost[id]);
    }
  };
})

Its getting right result, e.g:

this-is-a-news

But I need this links like this (I cannot edit backend):

/this-is-a-news

So I have to add / in my callback. I tried many positions but its not working.
How can I solve it? Thanks!

Body:
why don't you just concatenate string like this callback("/"+findpost[id]);.This will return /this-is-a-news.

post: function(posts,id,callback){
      var findpost = {};
      for(var i=0;i<posts.length;i++) {
        findpost[posts[i].nid] = posts[i];
      }
      callback("/"+findpost[id]);
}


问:
R how to get the third and last row for each user
I have a table that has information about certain users. What I'm trying to do is extract the third and last row of each user...How would I do that? So for example:

```<code>User | num |

use1 | 3 |

use1 | 2 |

use1 | 5 |

use1 | 8 |

use1 | 6 |

use2 | 1 |

..
</code>```

So in this example, I'd want the row with num = 5 and num = 6 and this would continue for each different user in the table.

答:
We can use base R

```<code>i1 <- with(data, as.logical(ave(seq_along(User), User, FUN =
           function(x) seq_along(x) %in% c(3, length(x) & length(x) > 3))))
data[i1,]
</code>```

Body:
I have a table that has information about certain users. What I'm trying to do is extract the third and last row of each user...How would I do that? So for example:

User | num |

use1 | 3 |

use1 | 2 |

use1 | 5 |

use1 | 8 |

use1 | 6 |

use2 | 1 |

..

So in this example, I'd want the row with num = 5 and num = 6 and this would continue for each different user in the table.

Body:
We can use base R

i1 <- with(data, as.logical(ave(seq_along(User), User, FUN =
           function(x) seq_along(x) %in% c(3, length(x) & length(x) > 3))))
data[i1,]


问:
Google Scripts onEdit not recognising data being edited on a sheet during a sync from a mobile device
I have a Google sheet that is updated by a mobile app created on AppSheet.
I have a column of data that I need to keep a history of so wrote a script to copy the column to a fblank column in another sheet.

```<code>function readdailyChecks() {
    var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Todays Checks");
    var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("History");
    // Copy from 5th column, all rows for one column
    var valuesToCopy = sheetFrom.getRange("D2:D100").getValues()
    //Paste to another sheet from first cell onwards
    sheetTo.getRange(1,sheetTo.getLastColumn()+1,valuesToCopy.length,1).setValues(valuesToCopy);
}
</code>```

I then wrote another script to do this task when the sheet was edited thinking the sync would edit the sheet data.

```<code>function onEdit(e) {
    if(e);
   readdailyChecks(e)
}
</code>```

The idea being that the app would sync once the form was completed, update the sheet and trigger the onEdit code to do it's stuff.
The problem is that the sync changes the sheets data without editing it so the historical data is not created!

Is there an onSync code or a way that when the data changes the script can be triggered?

答:
I work at AppSheet. When updates are made to Google sheets via the Google Sheets backend API, they do not fire the onEdit trigger. I'm not sure why exactly this is, but it is a limitation imposed by Google. So that is what you are observing.

The AppSheet documentation suggests that you try a timed trigger instead, polling for changes. https://appsheethelp.zendesk.com/hc/en-us/articles/206483017-Google-Drive

Not the greatest, but it does work. Some AppSheet users have reported success with the onChange trigger instead of the onEdit trigger. To me, this defies logic based on the documented meaning on an onChange trigger, but it appears to work for these users, so worth a shot.

Body:
I have a Google sheet that is updated by a mobile app created on AppSheet.
I have a column of data that I need to keep a history of so wrote a script to copy the column to a fblank column in another sheet.

function readdailyChecks() {
    var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Todays Checks");
    var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("History");
    // Copy from 5th column, all rows for one column
    var valuesToCopy = sheetFrom.getRange("D2:D100").getValues()
    //Paste to another sheet from first cell onwards
    sheetTo.getRange(1,sheetTo.getLastColumn()+1,valuesToCopy.length,1).setValues(valuesToCopy);
}

I then wrote another script to do this task when the sheet was edited thinking the sync would edit the sheet data.

function onEdit(e) {
    if(e);
   readdailyChecks(e)
}

The idea being that the app would sync once the form was completed, update the sheet and trigger the onEdit code to do it's stuff.
The problem is that the sync changes the sheets data without editing it so the historical data is not created!

Is there an onSync code or a way that when the data changes the script can be triggered?


问:
May I know why this exception occuring while developing first spring program
```<code>Apr 03, 2017 3:53:58 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spconfig.xml]
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [spconfig.xml]; nested exception is java.io.FileNotFoundException: class path resource [spconfig.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:73)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:61)
at springcoreproject.Client.main(Client.java:9)
Caused by: java.io.FileNotFoundException: class path resource [spconfig.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:142)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
... 4 more
</code>```

答:
Add the spring core jar files to the classpath.

You can download the files at http://javatpoint.com/src/sp/spcorejars.zip

For more information on setting up first spring application see http://javatpoint.com/steps-to-create-spring-application


问:
Injecting Single Instance HttpClient with specific HttpMessageHandler
As part of an ASP.Net Core project that I am working on I have a requirement to communicate with a number of different Rest based API Endpoints from within my WebApi.  To achieve this I am using a number of service classes that each instantiate a static HttpClient.  Essentially I have a service class for each of the Rest based endpoints that the WebApi connects to.

An example of how the static HttpClient is instantiated in each of the service classes can be seen below.

```<code>private static HttpClient _client = new HttpClient()
{
    BaseAddress = new Uri("http://endpointurlexample"),
};
</code>```

Whilst the above is working well, it does not allow for effective unit testing of the service classes that are using HttpClient.  To enable me to carry out unit testing I have a fake HttpMessageHandler that I would like to use for the HttpClient in my unit tests, whilst the HttpClient is instantiated as above however I am unable to apply the fake HttpMessageHandler as part of my unit tests.

What is the best way for the HttpClient in the service classes to remain a single instance throughout the application (one instance per endpoint), but to allow a different HttpMessageHandler to be applied during the unit tests?

One approach I have thought of would be not to use a static field to hold the HttpClient in the service classes, rather to allow it to be injected via constructor injection using a singleton lifecycle, which would allow me to specify a HttpClient with the desired HttpMessageHandler during unit tests, the other option I thought of would be to use a HttpClient Factory Class that instantiated the HttpClients in static fields that could then be retrieved by injecting the HttpClient factory into the service classes, again allowing a different implementation with the relevant HttpMessageHandler to be returned in unit tests.  None of the above feel particularly clean however and it feels like there must be a better way?

Any questions, let me know.

答:
I might be late to the party, but I've created a Helper nuget package that allows you to test HttpClient endpoints in unit tests.

NuGet: install-package WorldDomination.HttpClient.Helpers

Repo: https://github.com/PureKrome/HttpClient.Helpers

The basic idea is that you create the fake response payload and pass that the a FakeHttpMessageHandler instance to your code, which includes that fake response payload. Then, when your code tries to actually HIT that URI endpoint, it doesn't ... and just returns the fake response instead. MAGIC!

and here's a really simple example:

```<code>[Fact]
public async Task GivenSomeValidHttpRequests_GetSomeDataAsync_ReturnsAFoo()
{
    // Arrange.

    // Fake response.
    const string responseData = "{ \"Id\":69, \"Name\":\"Jane\" }";
    var messageResponse = FakeHttpMessageHandler.GetStringHttpResponseMessage(responseData);

    // Prepare our 'options' with all of the above fake stuff.
    var options = new HttpMessageOptions
    {
        RequestUri = MyService.GetFooEndPoint,
        HttpResponseMessage = messageResponse
    };

    // 3. Use the fake response if that url is attempted.
    var messageHandler = new FakeHttpMessageHandler(options);

    var myService = new MyService(messageHandler);

    // Act.
    // NOTE: network traffic will not leave your computer because you've faked the response, above.
    var result = await myService.GetSomeFooDataAsync();

    // Assert.
    result.Id.ShouldBe(69); // Returned from GetSomeFooDataAsync.
    result.Baa.ShouldBeNull();
    options.NumberOfTimesCalled.ShouldBe(1);
}
</code>```

Body:
As part of an ASP.Net Core project that I am working on I have a requirement to communicate with a number of different Rest based API Endpoints from within my WebApi.  To achieve this I am using a number of service classes that each instantiate a static HttpClient.  Essentially I have a service class for each of the Rest based endpoints that the WebApi connects to.

An example of how the static HttpClient is instantiated in each of the service classes can be seen below.

private static HttpClient _client = new HttpClient()
{
    BaseAddress = new Uri("http://endpointurlexample"),
};

Whilst the above is working well, it does not allow for effective unit testing of the service classes that are using HttpClient.  To enable me to carry out unit testing I have a fake HttpMessageHandler that I would like to use for the HttpClient in my unit tests, whilst the HttpClient is instantiated as above however I am unable to apply the fake HttpMessageHandler as part of my unit tests.

What is the best way for the HttpClient in the service classes to remain a single instance throughout the application (one instance per endpoint), but to allow a different HttpMessageHandler to be applied during the unit tests?

One approach I have thought of would be not to use a static field to hold the HttpClient in the service classes, rather to allow it to be injected via constructor injection using a singleton lifecycle, which would allow me to specify a HttpClient with the desired HttpMessageHandler during unit tests, the other option I thought of would be to use a HttpClient Factory Class that instantiated the HttpClients in static fields that could then be retrieved by injecting the HttpClient factory into the service classes, again allowing a different implementation with the relevant HttpMessageHandler to be returned in unit tests.  None of the above feel particularly clean however and it feels like there must be a better way?

Any questions, let me know.

Body:
I might be late to the party, but I've created a Helper nuget package that allows you to test HttpClient endpoints in unit tests.

NuGet: install-package WorldDomination.HttpClient.Helpers

Repo: https://github.com/PureKrome/HttpClient.Helpers

The basic idea is that you create the fake response payload and pass that the a FakeHttpMessageHandler instance to your code, which includes that fake response payload. Then, when your code tries to actually HIT that URI endpoint, it doesn't ... and just returns the fake response instead. MAGIC!

and here's a really simple example:

[Fact]
public async Task GivenSomeValidHttpRequests_GetSomeDataAsync_ReturnsAFoo()
{
    // Arrange.

    // Fake response.
    const string responseData = "{ \"Id\":69, \"Name\":\"Jane\" }";
    var messageResponse = FakeHttpMessageHandler.GetStringHttpResponseMessage(responseData);

    // Prepare our 'options' with all of the above fake stuff.
    var options = new HttpMessageOptions
    {
        RequestUri = MyService.GetFooEndPoint,
        HttpResponseMessage = messageResponse
    };

    // 3. Use the fake response if that url is attempted.
    var messageHandler = new FakeHttpMessageHandler(options);

    var myService = new MyService(messageHandler);

    // Act.
    // NOTE: network traffic will not leave your computer because you've faked the response, above.
    var result = await myService.GetSomeFooDataAsync();

    // Assert.
    result.Id.ShouldBe(69); // Returned from GetSomeFooDataAsync.
    result.Baa.ShouldBeNull();
    options.NumberOfTimesCalled.ShouldBe(1);
}


问:
How does this CSS code to center an element work?
```<code>    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%)
</code>```

This is CSS code for centering a button in the viewport. Can somebody explain how this works? I found it somewhere online and it seems to work but I don't get the need for margin-right and transform. Naturally the code doesn't work without them but intuitively I feel the first three should be enough to center the element. I'm relatively new to CSS so I'd understand if this is considered a silly question :)

答: Take a look at this article: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/. Simply using the first three lines of css (position, top, and left) will center the top left corner of the object, which will make the whole object completely off-center. The negative translation moves the object up and to the right by half of its height and width, respectively, which makes the object centered. In fact, I don't think you even need the margin-right code, but I might be wrong.</p>

Body:
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%)

This is CSS code for centering a button in the viewport. Can somebody explain how this works? I found it somewhere online and it seems to work but I don't get the need for margin-right and transform. Naturally the code doesn't work without them but intuitively I feel the first three should be enough to center the element. I'm relatively new to CSS so I'd understand if this is considered a silly question :)


问:
How to find the average of unique rows in python
I want to find the average of unique values using data frames in python.
For example, I have a dataset as:

```<code> [c1]   [c2]
 foo    3.2
 bar    4.3
 foo    3.0
 foo    2.3
 bar    4.5
 foo    1.9
 bar    4.4
</code>```

I want the output as:

Count of foo = 4 and average of foo is 2.6 //(i.e., (3.2+3.0+2.3+1.9)/4))

count of bar = 3 and average of bar is 4.4 //(i.e., (4.3+4.5+4.4)/3))

答:
Assuming that you store your values in a list called data_averages:

```<code>import numpy as np # numpy module

# Your data_averages list that contains average

foo_list=[]
bar_list=[]

for i in range(len(data_averages)):
    if data_averages[i] == 'foo':
        foo_list.append(data_averages[i][1])
    else:
        bar_list.append(data_averages[i][1])

foo_avg = np.average(foo_list)
bar_list= np.average(bar_list)

print('Foo: ', foo_avg)
print('Bar: ', bar_avg)
</code>```

Basically, your script checks the first column of your list (data_averages).

Your list might look something like this for your code to work:

```<code># Make sure it is in following format: [string, float]
[['foo', 3.2],
['bar', 4.3],
['foo', 3.0]]
# And so on...
</code>```

I hope this helps! If ever there is a bug in the code, please comment below, I'll try my best to respond ASAP.

Body:
I want to find the average of unique values using data frames in python.
For example, I have a dataset as:

 [c1]   [c2]
 foo    3.2
 bar    4.3
 foo    3.0
 foo    2.3
 bar    4.5
 foo    1.9
 bar    4.4

I want the output as:

Count of foo = 4 and average of foo is 2.6 //(i.e., (3.2+3.0+2.3+1.9)/4))

count of bar = 3 and average of bar is 4.4 //(i.e., (4.3+4.5+4.4)/3))

Body:
Assuming that you store your values in a list called data_averages:

import numpy as np # numpy module

# Your data_averages list that contains average

foo_list=[]
bar_list=[]

for i in range(len(data_averages)):
    if data_averages[i] == 'foo':
        foo_list.append(data_averages[i][1])
    else:
        bar_list.append(data_averages[i][1])

foo_avg = np.average(foo_list)
bar_list= np.average(bar_list)

print('Foo: ', foo_avg)
print('Bar: ', bar_avg)

Basically, your script checks the first column of your list (data_averages).

Your list might look something like this for your code to work:

# Make sure it is in following format: [string, float]
[['foo', 3.2],
['bar', 4.3],
['foo', 3.0]]
# And so on...

I hope this helps! If ever there is a bug in the code, please comment below, I'll try my best to respond ASAP.


问:
Select hardcoded values in Informix DB
I need to select hardcoded values in one column, so I will be able to join them with table in Informix DB. So I try in different variations to do something like this:

```<code>select a from ( values (1), (2), (3) ) ;
</code>```

And I expect to get results:

```<code>1
2
3
</code>```

I think in other DB this or some other variations that I tried would return the values. However, in Informix it does not work.

Could anyone suggest the solution working in Informix please?

答:
Informix requires an actual query statement.  I think this will work:</p>

```<code>select a
from (select 1 as a from systables where tabid = 1 union all
      select 2 as a from systables where tabid = 1 union all
      select 3 as a from systables where tabid = 1
     ) t;
</code>```

Title: Select hardcoded values in Informix DB

Body:
I need to select hardcoded values in one column, so I will be able to join them with table in Informix DB. So I try in different variations to do something like this:

select a from ( values (1), (2), (3) ) ;

And I expect to get results:

1
2
3

I think in other DB this or some other variations that I tried would return the values. However, in Informix it does not work.

Could anyone suggest the solution working in Informix please?

Body:
Informix requires an actual query statement.  I think this will work:

select a
from (select 1 as a from systables where tabid = 1 union all
      select 2 as a from systables where tabid = 1 union all
      select 3 as a from systables where tabid = 1
     ) t;


问:
Why is it "impossible" to implement garbage collection in C because of weak typing?
I was told by a rather smart person that you cannot implement garbage collection in C because of it's weakly typed. The basic idea seems to be that C gives you too much freedom. He mentioned casting pointers without type checking...

I don't really grok the idea. Can someone give me an explanation and possibly a code sample of why this wouldn't work.

NOTE: Obviously C is about speed and why would you want to add garbage collection? I'm just curious really.

答: The problem is that there's no way for the runtime to know for certain if any piece of memory is referenced or not. Even if you wrap all memory allocation in code that registers the usage, you can still obtain pointers to used memory via regular pointer manipulation (or by mistake). Casts only make the problem harder for the runtime. So if the runtime frees a piece of memory, it will mess things up for any pointers still pointing to that area of memory. Obviously the situation only gets worse when you consider that garbage collection has to work for multi-threaded applications as well. </p>

OwnerDisplayName: Tim Merrifield

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: Brian Rasmussen

LastEditorDisplayName: Brian Rasmussen


问:
java item listener
i need help regarding the save menu item i have in my menu bar. i have set the code to

```<code>private void smActionPerformed(java.awt.event.ActionEvent evt) {

}
</code>```

but i am unsure what needs to go inbetween the brackets? The gui is a form where poeple fill in there medical record e.g combo box "mr/mrs" textfield "medical problems" etc and when they click file save i would like the user to get a save box (like save as box in word) and the information to be saved in a txt file.

P.S. would it be possible to have the "file type" set to save as a txt file as default.

答:
Use JFileChooser#showSaveDialog() to ask the enduser to select a File.

```<code>JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
    File file = fileChooser.getSelectedFile();
    // ...
} else {
    // User pressed cancel.
}
</code>```

Title: java item listener

Body:
i need help regarding the save menu item i have in my menu bar. i have set the code to

private void smActionPerformed(java.awt.event.ActionEvent evt) {

}

but i am unsure what needs to go inbetween the brackets? The gui is a form where poeple fill in there medical record e.g combo box "mr/mrs" textfield "medical problems" etc and when they click file save i would like the user to get a save box (like save as box in word) and the information to be saved in a txt file.

P.S. would it be possible to have the "file type" set to save as a txt file as default.

Body:
Use JFileChooser#showSaveDialog() to ask the enduser to select a File.

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
    File file = fileChooser.getSelectedFile();
    // ...
} else {
    // User pressed cancel.
}


问:
C# MVC - Access Items in a List that is in a Model
I have a Blog that is populating from a BlogResponseModel, and the related comments for each Blog entry are held in a List.  It looks like this:

```<code>public class BlogResponseModel
{
    public int Id { get; set; }
    public DateTime SubmissionDate { get; set; }
    public string Title { get; set; }
    public string ImageID { get; set; }
    public string ImageAttribution { get; set; }
    public string Body { get; set; }
    public List<BlogCommentModel> CommentList { get; set; }
}
</code>```

The comments are collected and each comment is related to the Id element above. The BlogCommentModel looks like this:

```<code>public class BlogCommentModel
{
    public int CommentId { get; set; }
    public int CommentCount { get; set; }
    public DateTime CommentDate { get; set; }
    public string Commenter { get; set; }
    public string CommenterEmail { get; set; }
    public string Comment { get; set; }
    public int BlogParentId { get; set; }
}
</code>```

In my view, I am using a foreach to format and display each Blog entry, and this is working very well.  Where I have hit the wall is figuring out how to embed the related comments at the foot of each Blog post.

Here is the current attempt in the View that has me stumped. I do a foreach to render the Blog post...

```<code>   @foreach (var response in Model)
   {
        // enter all the Blog specifics here...
</code>```

At this point, the Blog entry is rendered, and we are ready to add the Comments:

```<code><div class="message row">
    <div>
        <H5>Comments</H5>
    </div>
    @foreach (var comment in ?? WHAT ?? (how do I access BlogResponseModel)
    {
        <div class="replies span12">
            <div class="reply">
                <div class="created pull-right">
                    @comment.CommentDate
                </div>
                <div class="created">
                    @comment.Commenter
                </div>
                <div>
                    @comment.Comment
                </div>
            </div>
        </div>
    }
</div>
</code>```

How do I populate the Comments from List CommentList that is in the BlogResponseModel?

Thanks in advance for your advice.  I'm new to MVC and still wrapping my mind around the architecture.

答:
You can add

```<code>public virtual ICollection<BlogCommentModel> CommentList { get; set; }
</code>```

instead of

```<code>public List<BlogCommentModel> CommentList { get; set; }
</code>```

Then in the View

```<code>@foreach (var item in Model)
{
    @Html.DisplayFor(modelItem => item.Title)

    @foreach (var myBlogCommentModel in @item.BlogCommentModel)
    {
        @myBlogCommentModel.Commenter
        @myBlogCommentModel.CommenterEmail
    }
}
</code>```

I hope this will help.

Body:
I have a Blog that is populating from a BlogResponseModel, and the related comments for each Blog entry are held in a List.  It looks like this:

public class BlogResponseModel
{
    public int Id { get; set; }
    public DateTime SubmissionDate { get; set; }
    public string Title { get; set; }
    public string ImageID { get; set; }
    public string ImageAttribution { get; set; }
    public string Body { get; set; }
    public List<BlogCommentModel> CommentList { get; set; }
}

The comments are collected and each comment is related to the Id element above. The BlogCommentModel looks like this:

public class BlogCommentModel
{
    public int CommentId { get; set; }
    public int CommentCount { get; set; }
    public DateTime CommentDate { get; set; }
    public string Commenter { get; set; }
    public string CommenterEmail { get; set; }
    public string Comment { get; set; }
    public int BlogParentId { get; set; }
}

In my view, I am using a foreach to format and display each Blog entry, and this is working very well.  Where I have hit the wall is figuring out how to embed the related comments at the foot of each Blog post.

Here is the current attempt in the View that has me stumped. I do a foreach to render the Blog post...

   @foreach (var response in Model)
   {
        // enter all the Blog specifics here...

At this point, the Blog entry is rendered, and we are ready to add the Comments:

Comments

    @foreach (var comment in ?? WHAT ?? (how do I access BlogResponseModel)
    {

                    @comment.CommentDate

                    @comment.Commenter

                    @comment.Comment

    }

How do I populate the Comments from List CommentList that is in the BlogResponseModel?

Thanks in advance for your advice.  I'm new to MVC and still wrapping my mind around the architecture.

Body:
You can add

public virtual ICollection<BlogCommentModel> CommentList { get; set; }

instead of

public List<BlogCommentModel> CommentList { get; set; }

Then in the View

@foreach (var item in Model)
{
    @Html.DisplayFor(modelItem => item.Title)

    @foreach (var myBlogCommentModel in @item.BlogCommentModel)
    {
        @myBlogCommentModel.Commenter
        @myBlogCommentModel.CommenterEmail
    }
}

I hope this will help.


问:
Why isn’t this newtype being given the right Read instance?
I created a newtype alias of the IP type from Data.IP:

```<code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module IPAddress (IPAddress) where

import Data.IP (IP)
import Database.PostgreSQL.Simple.ToField

newtype IPAddress = IPAddress IP
    deriving (Read, Show)

instance ToField IPAddress where
    toField ip = toField $ show ip
</code>```

(I wanted to make it an instance of ToField without creating an orphan instance.)

The new type doesn’t seem to support Read in the way it should, though. In this GHCi transcript, you can see that the given string can be interpreted as an IP but not as an IPAddress:

```<code>*Main IPAddress> :m + Data.IP
*Main IPAddress Data.IP> read "1.2.3.4" :: IP
1.2.3.4
*Main IPAddress Data.IP> read "1.2.3.4" :: IPAddress
IPAddress *** Exception: Prelude.read: no parse
</code>```

The behavior is the same regardless of whether I have GeneralizedNewtypeDeriving on. Why is the Read instance for IPAddress not identical to the one for IP?

答:
GHC has three mechanisms for deriving typeclass instances:

The normal deriving mechanism outlined in the Haskell standard, which can derive instances for a small, predefined set of classes (Eq, Ord, Enum, Bounded, Read, and Show).

The set of classes that can be derived can be extended using the DeriveFunctor, DeriveFoldable, DeriveTraversable, and DeriveLift extensions, which are treated the same way as the classes listed in the standard when enabled.

GeneralizedNewtypeDeriving, which can derive instances that defer to instances on the wrapped type.

DeriveAnyClass, which turns derived classes into empty instance declarations.

There’s a problem here. It is extremely easy to construct a scenario where more than one of the above mechanisms can be used to derive an instance, and the instances can be quite different! In your example, both ordinary deriving and newtype deriving could apply. If you also enabled DeriveAnyClass, it could apply, too.

To disambiguate, GHC uses hardcoded rules you cannot change, which it tries from top to bottom:

If the class can be derived using the ordinary deriving mechanism, use that.

If DeriveAnyClass is enabled, use that.

If GeneralizedNewtypeDeriving is enabled and the declared datatype is a newtype, use that.

Note that this means turning on DeriveAnyClass and GeneralizedNewtypeDeriving at the same time is effectively worthless. If anything, the bottom two rules should be swapped, but they can’t really be changed now.

In your case, since Read is a class for which an instance can be derived via the ordinary deriving mechanism, GHC uses that one instead of using newtype deriving, and you get the behavior you see. This is consistent with the way Show works, too—deriving Show will produce an instance that includes IPAddress in the output—so Read should follow the same format to satisfy the one law Read has.

It would be nice if there were some mechanism to instruct GHC to use a particular deriving mechanism, but there currently isn’t. In this case, you’ll have to write the instance by hand. Fortunately, it isn’t too hard.

Body:
I created a newtype alias of the IP type from Data.IP:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module IPAddress (IPAddress) where

import Data.IP (IP)
import Database.PostgreSQL.Simple.ToField

newtype IPAddress = IPAddress IP
    deriving (Read, Show)

instance ToField IPAddress where
    toField ip = toField $ show ip

(I wanted to make it an instance of ToField without creating an orphan instance.)

The new type doesn’t seem to support Read in the way it should, though. In this GHCi transcript, you can see that the given string can be interpreted as an IP but not as an IPAddress:

*Main IPAddress> :m + Data.IP
*Main IPAddress Data.IP> read "1.2.3.4" :: IP
1.2.3.4
*Main IPAddress Data.IP> read "1.2.3.4" :: IPAddress
IPAddress *** Exception: Prelude.read: no parse

The behavior is the same regardless of whether I have GeneralizedNewtypeDeriving on. Why is the Read instance for IPAddress not identical to the one for IP?


问:
acquireToken callback never called
I've made some progress after my initial post on integrating adal.js with Vue.js. I'm successfully logging in, and the properties I'd expect to be set are being set in localStorage.

However, calls to acquireToken never call the the callback I'm passing. The code looks like this:

```<code>let url = 'https://api.webserver.com/api/endpoint';

authContext.acquireToken(url, (err, token) => {
  console.log(`acquiring token for ${url}`);
  console.log(err, token);
});
</code>```

Looking at the source for adal.js, the method signature for acquireToken is as follows:

```<code>AuthenticationContext.prototype.acquireToken(resource, callback)
</code>```

The callback isn't called. Is the url value I'm passing what the method is expecting? I'm unclear about this.

Your help is appreciated. Thanks in advance!

答:
According to your init post, you have completed the Azure AD application's configuration, you can try to replace the url to the client_id, under acquireToken() function.

According to the source code of adal for js, the acquireToken() calls getCachedToken() at L515.

And the function getCachedToken() will get the token in browser's session via var token = this._getItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource); You can check all the AD info in DEV TOOL of browser after you successfully login. We can find that the resource here is in the client_id format.

Title: acquireToken callback never called

Body:
I've made some progress after my initial post on integrating adal.js with Vue.js. I'm successfully logging in, and the properties I'd expect to be set are being set in localStorage.

However, calls to acquireToken never call the the callback I'm passing. The code looks like this:

let url = 'https://api.webserver.com/api/endpoint';

authContext.acquireToken(url, (err, token) => {
  console.log(`acquiring token for ${url}`);
  console.log(err, token);
});

Looking at the source for adal.js, the method signature for acquireToken is as follows:

AuthenticationContext.prototype.acquireToken(resource, callback)

The callback isn't called. Is the url value I'm passing what the method is expecting? I'm unclear about this.

Your help is appreciated. Thanks in advance!


问:
How to make an array of UIImageViews at class level in Swift?
When I try to make an array with UIImageView s declared as @IBAction I receive the "Cannot use instance member within property initializer, property initializers run before self is available" compiler error. How do I workaround this?

答:
As the error explains, you can't use instance members when you initialize the property outside of a method at the class level. Leave your array initializer at the class level and add your properties to it within a method.</p>

```<code>var imageViews = [UIImageView]()

override func viewDidLoad(){
    imageViews = [pos_1,pos2]

    //or
    imageViews.append(pos_1)
    imageViews.append(pos_2)
 }
</code>```

Body:
As the error explains, you can't use instance members when you initialize the property outside of a method at the class level. Leave your array initializer at the class level and add your properties to it within a method.

var imageViews = [UIImageView]()

override func viewDidLoad(){
    imageViews = [pos_1,pos2]

    //or
    imageViews.append(pos_1)
    imageViews.append(pos_2)
 }


问:
Laravel index policy
I using Laravel 5.4 and I am trying to write a policy for my index view. I am trying to use a Method Without a Model, I am receiving the following error:

HttpException in Handler.php line 133:

This action is unauthorized.

Here is my Controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\County;
use Session;
use App\Http\Controllers\Controller;

class CountyController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $counties = County::orderBy('id', 'desc')->paginate(5);
        $this->authorize('index');

        return view('county.index', array(
                'counties' => $counties
            ));
    }
</code>```

Here is my AuthServicePovider:

```<code><?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Role;
use App\County;

use App\Policies\CountyPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        County::class => CountyPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::define('is-Admin', function ($user) {
            if($user->roles()->where('name','Admin')->first()){
                return true;
            }
            return false;
        });
    }
}
</code>```

Here is my Policy:

```<code><?php

namespace App\Policies;

use App\User;
use App\Role;
use App\County;
use Illuminate\Auth\Access\HandlesAuthorization;

class CountyPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the county.
     *
     * @param  \App\User  $user
     * @param  \App\County  $county
     * @return mixed
     */
    public function index(User $user)
    {
        $userRoles = $user->getRoleNames();
        $acceptedRoles = ['Sudo','Admin'];
        $testArr = array_intersect($acceptedRoles, $userRoles);

        dd($testArr);

        if(!empty($testArr)){
            return true;
        }
        return false;
        //
    }

    /**
     * Determine whether the user can view the county.
     *
     * @param  \App\User  $user
     * @param  \App\County  $county
     * @return mixed
     */
    public function view(User $user, County $county)
    {
        $userRoles = $user->getRoleNames();
        $acceptedRoles = ['Sudo','Admin','Client'];
        $testArr = array_intersect($acceptedRoles, $userRoles);

        if(!empty($testArr)){
            return true;
        }
        return false;
        //
    }

    /**
     * Determine whether the user can create counties.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        //
    }

    /**
     * Determine whether the user can update the county.
     *
     * @param  \App\User  $user
     * @param  \App\County  $county
     * @return mixed
     */
    public function update(User $user, County $county)
    {
        //
    }

    /**
     * Determine whether the user can delete the county.
     *
     * @param  \App\User  $user
     * @param  \App\County  $county
     * @return mixed
     */
    public function delete(User $user, County $county)
    {
        //
    }
}
</code>```

I never get to dd($testArr) in the index policy. Also the view policy is working perfectly.

How do I write a policy for my index view?

答:
keeping everything the same but changing:

```<code>$this->authorize('index');
</code>```

to

```<code>$this->authorize('index', County::class);
</code>```

fixed the problem. Apparently the model class needs to be passed on actions that don't require a model. This is only described under the middleware section of Laravel's docs, not the controller helpers... A little confusing.

Title: Laravel index policy

Body:
I using Laravel 5.4 and I am trying to write a policy for my index view. I am trying to use a Method Without a Model, I am receiving the following error:

HttpException in Handler.php line 133:

This action is unauthorized.

Here is my Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\County;
use Session;
use App\Http\Controllers\Controller;

class CountyController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $counties = County::orderBy('id', 'desc')->paginate(5);
        $this->authorize('index');

        return view('county.index', array(
                'counties' => $counties
            ));
    }

Here is my AuthServicePovider:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Role;
use App\County;

use App\Policies\CountyPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        County::class => CountyPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::define('is-Admin', function ($user) {
            if($user->roles()->where('name','Admin')->first()){
                return true;
            }
            return false;
        });
    }
}

Here is my Policy:

<?php

namespace App\Policies;

use App\User;
use App\Role;
use App\County;
use Illuminate\Auth\Access\HandlesAuthorization;

class CountyPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the county.
     *
     * @param  \App\User  $user
     * @param  \App\County  $county
     * @return mixed
     */
    public function index(User $user)
    {
        $userRoles = $user->getRoleNames();
        $acceptedRoles = ['Sudo','Admin'];
        $testArr = array_intersect($acceptedRoles, $userRoles);

        dd($testArr);

        if(!empty($testArr)){
            return true;
        }
        return false;
        //
    }

    /**
     * Determine whether the user can view the county.
     *
     * @param  \App\User  $user
     * @param  \App\County  $county
     * @return mixed
     */
    public function view(User $user, County $county)
    {
        $userRoles = $user->getRoleNames();
        $acceptedRoles = ['Sudo','Admin','Client'];
        $testArr = array_intersect($acceptedRoles, $userRoles);

        if(!empty($testArr)){
            return true;
        }
        return false;
        //
    }

    /**
     * Determine whether the user can create counties.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        //
    }

    /**
     * Determine whether the user can update the county.
     *
     * @param  \App\User  $user
     * @param  \App\County  $county
     * @return mixed
     */
    public function update(User $user, County $county)
    {
        //
    }

    /**
     * Determine whether the user can delete the county.
     *
     * @param  \App\User  $user
     * @param  \App\County  $county
     * @return mixed
     */
    public function delete(User $user, County $county)
    {
        //
    }
}

I never get to dd($testArr) in the index policy. Also the view policy is working perfectly.

How do I write a policy for my index view?

Body:
keeping everything the same but changing:

$this->authorize('index');

to

$this->authorize('index', County::class);

fixed the problem. Apparently the model class needs to be passed on actions that don't require a model. This is only described under the middleware section of Laravel's docs, not the controller helpers... A little confusing.


问:
PHP ONE Script to handle ALL requests
I just started with PHP development and I've been looking at my company's web server files. The previous programmers have put a single endpoint to handle all requests. For example,

```<code>www.example.com/webservice.php
</code>```

Using this endpoint, the client will send a myriad of query parameters with an "action" parameter that is mandatory. "action"'s value dictates the function that will be called.

So, webservice.php is a large file with an extremely long if...else statement, which checks $_GET["action"] and calls the respective function in another file (functions.php) together with the related parameters.

My concerns regarding this design is:-

The performance issue

With almost ~100 else if checks for "action", surely it is not efficient coding right?

The RESTfulness of the design

Having some knowledge regarding the RESTful philosophy, my approach would be to separate it into components such as

```<code>www.example.com/module/submodule/action.php
</code>```

答:
Most large PHP applications and MVC frameworks use URL rewriting so even though the URL looks like www.example.com/user/get/5 it really is all starting at some index.php file and perhaps invoking some routes.php file when then dispatches the appropriate controller.

It sounds like you are dealing with a legacy application however and yes 100 if else cases is not ideal, but the issue is not having a single entry point, but rather the quality of code that resides in that file.

Title: PHP ONE Script to handle ALL requests

Body:
I just started with PHP development and I've been looking at my company's web server files. The previous programmers have put a single endpoint to handle all requests. For example,

www.example.com/webservice.php

Using this endpoint, the client will send a myriad of query parameters with an "action" parameter that is mandatory. "action"'s value dictates the function that will be called.

So, webservice.php is a large file with an extremely long if...else statement, which checks $_GET["action"] and calls the respective function in another file (functions.php) together with the related parameters.

My concerns regarding this design is:-

The performance issue

With almost ~100 else if checks for "action", surely it is not efficient coding right?

The RESTfulness of the design

Having some knowledge regarding the RESTful philosophy, my approach would be to separate it into components such as

www.example.com/module/submodule/action.php


问:
How to convert office file to image
I am searching from last two days but did not find any thing.

My requirement is to create a document viewer in my web application (C#.Net) and I don't want to use any third party tool for this. Can I convert the files in image or PDF or in any common formate which can be easly render on web page. I also can not use Introp object.

Any help will be highly appreciated

答:
You can use tools like smallpdf or OfficeToPDF to do that. Just integrate them into your application.

Small PDF(https://smallpdf.com/library-detail)

officetopdf (https://officetopdf.codeplex.com/)

Title: How to convert office file to image


问:
Enabling UART on Beaglebone Black
I'm having trouble getting UART enabled. I've gone through many different directions on how to enable and troubleshoot from updating the uEnv.txt file to updating the kernel. I've come to conclude that it may be an issue with using a different kernel than the instructions, but I'm not sure?
I don't know very much about the Beaglebone and I'm still learning. Whenever I try to test UART by using Python and typing the following:

import Adafruit_BBIO.UART as UART

UART.setup("UART1")

I get the error: File "stdin", line 1, in module

RuntimeError: Unable to export UART channel.

I'm also starting to worry that I simply don't have capemgr. When I run the command :

ls sys/devices

I don't have capemgr listed.

I'm using the latest Debian Image : Jessie Debian 8.3 (2016-01-24)

the Kernel version I'm running is 4.1.17-ti-rt-r46.

and my DTC version is 1.4.1-g1e75ebc9

I would really appreciate any help. I've been wrestling with this issue for a few days now. Thank you!

答:
Apparently the powers that be like to change files to keep us on our toes.

TamusJRoyce left a comment here: http://www.thing-printer.com/cape-manager-is-back-baby/ that helped me:

/media/BEAGLEBONE/env.txt and /boot/uBoot/uEnv.txt has moved to /etc/default/capemgr (file which may not exist). It also has a new syntax. Add "CAPE=BB-SPI-01,BB-UART1,BB-UART2,BB-UART4" to get main ports working. Then reboot.

To enable UART1 and UART2 on Beaglebone Black Running Debian 8

Step 1: sudo nano /etc/default/capemgr

Step 2: Change #CAPE= to: CAPE=BB-UART1,BB-UART2

Step 3: reboot

Step 4: ls /dev/ttyO*

result: /dev/ttyO0  /dev/ttyO1  /dev/ttyO2

Title: Enabling UART on Beaglebone Black


问:
C2084 - function already has a body
I'm running into an error "C2084 - function 'void Pet::display(void)' already has a body". Error occurs on Dog.cpp file. Slightly confused about the issue. Any help would be appreciated.

Pet.h

```<code>#ifndef _PET_H_
#define _PET_H_

#include <string>
using namespace std;

enum Type { dog = 0, cat };

class Pet {
private:
    string name, breed; // private local variables
    Type type;

public:
    Pet(string pet_name, string pet_breed, Type pet_type); // constructor

    // accessor methods
    string getName();
    string getBreed();
    Type getType();

    virtual void display() {};
};

#endif // _PET_H_
</code>```

Dog.h

```<code>#ifndef _DOG_H_
#define _DOG_H_

#include "Pet.h"
#include <string>

using namespace std;

class Dog : public Pet {
public:
    Dog(string pet_name, string pet_breed, Type pet_type) : Pet(pet_name, pet_breed, pet_type) {
    } // constructor

    virtual void display() = 0;

};

#endif
</code>```

Dog.cpp

```<code>#include "Dog.h"
#include "Pet.h"
#include <iostream>

void Pet::display() {
    cout << "Name: " << name << endl;
    cout << "Breed: " << breed << endl;
    cout << "Type: Dog" << endl;
}
</code>```

答:
You are declaring the method display pure virtual in the class Dog which is derived from another class Pet. But the Pet class already has a concrete method called display. That' why you get this error.

Declare display as pure virtual in the Pet class and then give a concrete implementation in its child class Dog.

Title: C2084 - function already has a body

Body:
I'm running into an error "C2084 - function 'void Pet::display(void)' already has a body". Error occurs on Dog.cpp file. Slightly confused about the issue. Any help would be appreciated.

Pet.h

#ifndef _PET_H_
#define _PET_H_

#include <string>
using namespace std;

enum Type { dog = 0, cat };

class Pet {
private:
    string name, breed; // private local variables
    Type type;

public:
    Pet(string pet_name, string pet_breed, Type pet_type); // constructor

    // accessor methods
    string getName();
    string getBreed();
    Type getType();

    virtual void display() {};
};

#endif // _PET_H_

Dog.h

#ifndef _DOG_H_
#define _DOG_H_

#include "Pet.h"
#include <string>

using namespace std;

class Dog : public Pet {
public:
    Dog(string pet_name, string pet_breed, Type pet_type) : Pet(pet_name, pet_breed, pet_type) {
    } // constructor

    virtual void display() = 0;

};

#endif

Dog.cpp

#include "Dog.h"
#include "Pet.h"
#include <iostream>

void Pet::display() {
    cout << "Name: " << name << endl;
    cout << "Breed: " << breed << endl;
    cout << "Type: Dog" << endl;
}


问:
Is it possible to write dynamic queries for views?
Is it allowed to write queries with dynamic source table? the system that I am developing creates a backup of the current database per week. so the most active database would be mainDB, the previous week backup would be named as mainDb20170327, and the week before that would be mainDb20170320

I need to create a dynamic view that is hosted in each of these database instances. so mainDb has a view named view_mainDb, and mainDb20170320 has a view named view_mainDb20170320.

In the sql query of the view, how can I make the source db instance dynamic?

I tried to user adding the text and concatenating but it doesn't seem to be possible. Or I'm missing something.

答:
The definition of a view must be fixed. You can't make any part of it dynamic.

You'll have to write a stored procedure to do what you want to do, or else do it in application code.


问:
log4j not writing into file but its writing into console
i am aritinga small application in Linux based system where i am using slf4j libraries for logger

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

i could see the logs are visible in console but not appending to log files.

```<code><appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
    <param name="threshold" value="INFO" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%d{ABSOLUTE}][%-5p][%-10t]%m%n" />
    </layout>
</appender>

<!-- EXAMPLE logging setup NOTES: 1. files are written to "./logs/<filename>".
    You must setup the environment so that ./logs is a symlink to the correct
    location according to the EXAMPLE log standard. For example, "/opt/logs/".
    If that's not possible, change the File setting in each appender appropriately. -->

<appender name="EXAMPLE_AUDIT" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="INFO" />
    <param name="File" value="./logs/audit.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="20" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_AUDIT" />
    </layout>
</appender>

<appender name="EXAMPLE_METRIC" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="DEBUG" />
    <param name="File" value="./logs/metric.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="10" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_METRIC" />
    </layout>
</appender>

<appender name="EXAMPLE_ERROR" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="ERROR" />    <!-- only WARN and ERROR are allowed in this log -->
    <param name="File" value="./logs/error.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="10" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_ERROR" />
    </layout>
</appender>

<appender name="EXAMPLE_DEBUG" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="DEBUG" />
    <param name="File" value="./logs/debug.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="20" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_DEBUG" />
    </layout>
</appender>

<logger name="com.rsg.EXAMPLE.audit" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_AUDIT" />
</logger>

<logger name="com.rsg.EXAMPLE.metrics" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_METRIC" />
</logger>

<logger name="com.rsg.EXAMPLE.error" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.debug" additivity="false">
    <level value="info" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_DEBUG" />
</logger>

<root>
    <level value="DEBUG" />
    <appender-ref ref="EXAMPLE_DEBUG" />
    <appender-ref ref="CONSOLE" />

</root>

<logger name="org.openEXAMPLE.agcp.commonFunction.input"
    additivity="false">
    <level value="INFO" />
    <appender-ref ref="CONSOLE" />
</logger>

<logger name="org.openEXAMPLE.agcp.commonFunction.output"
    additivity="false">
    <level value="INFO" />
    <appender-ref ref="CONSOLE" />

</logger>

<logger name="org.openEXAMPLE.agcp.commonFunction.error"
    additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<!-- The EXAMPLE logging standard has four specific classes of logging that
    are unrelated to subsystem logger names. If you want them activated, uncomment
    this block. -->
<logger name="com.rsg.EXAMPLE.audit" additivity="false">
    <level value="info" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_AUDIT" />
</logger>

<logger name="com.rsg.EXAMPLE.metrics" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_METRIC" />
</logger>

<logger name="com.rsg.EXAMPLE.error" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.debug" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_DEBUG" />
</logger>

<logger name="com.rsg.ova.apiClient.http.HttpClient" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
    <appender-ref ref="CONSOLE" />
</logger>

<logger name="com.rsg.ova.roman.client.impl.romanSimplerBatchPublisher"
    additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
    <appender-ref ref="CONSOLE" />
</logger>
</code>```

答:
The configuration shown in the question is in the log4j 1.2 format.

The format for log4j2.xml is different. It is plugin based so you don't need to specify the class name of the appenders any more.

Please see the Log4j2 manual. It has many examples configurations.

Body:
i am aritinga small application in Linux based system where i am using slf4j libraries for logger

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

i could see the logs are visible in console but not appending to log files.

<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
    <param name="threshold" value="INFO" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%d{ABSOLUTE}][%-5p][%-10t]%m%n" />
    </layout>
</appender>

<appender name="EXAMPLE_AUDIT" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="INFO" />
    <param name="File" value="./logs/audit.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="20" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_AUDIT" />
    </layout>
</appender>

<appender name="EXAMPLE_METRIC" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="DEBUG" />
    <param name="File" value="./logs/metric.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="10" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_METRIC" />
    </layout>
</appender>

<appender name="EXAMPLE_ERROR" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="ERROR" />
    <param name="File" value="./logs/error.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="10" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_ERROR" />
    </layout>
</appender>

<appender name="EXAMPLE_DEBUG" class="org.apache.log4j.RollingFileAppender">
    <param name="threshold" value="DEBUG" />
    <param name="File" value="./logs/debug.log" />
    <param name="MaxFileSize" value="128MB" />
    <param name="MaxBackupIndex" value="20" />
    <layout class="com.rsg.ova.logging.log4j.EXAMPLELayout">
        <param name="ConversionPattern" value="EXAMPLE_DEBUG" />
    </layout>
</appender>

<logger name="com.rsg.EXAMPLE.audit" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_AUDIT" />
</logger>

<logger name="com.rsg.EXAMPLE.metrics" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_METRIC" />
</logger>

<logger name="com.rsg.EXAMPLE.error" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.debug" additivity="false">
    <level value="info" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_DEBUG" />
</logger>

<root>
    <level value="DEBUG" />
    <appender-ref ref="EXAMPLE_DEBUG" />
    <appender-ref ref="CONSOLE" />

</root>

<logger name="org.openEXAMPLE.agcp.commonFunction.input"
    additivity="false">
    <level value="INFO" />
    <appender-ref ref="CONSOLE" />
</logger>

<logger name="org.openEXAMPLE.agcp.commonFunction.output"
    additivity="false">
    <level value="INFO" />
    <appender-ref ref="CONSOLE" />

</logger>

<logger name="org.openEXAMPLE.agcp.commonFunction.error"
    additivity="false">
    <level value="DEBUG" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.audit" additivity="false">
    <level value="info" />
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="EXAMPLE_AUDIT" />
</logger>

<logger name="com.rsg.EXAMPLE.metrics" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_METRIC" />
</logger>

<logger name="com.rsg.EXAMPLE.error" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
</logger>

<logger name="com.rsg.EXAMPLE.debug" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_DEBUG" />
</logger>

<logger name="com.rsg.ova.apiClient.http.HttpClient" additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
    <appender-ref ref="CONSOLE" />
</logger>

<logger name="com.rsg.ova.roman.client.impl.romanSimplerBatchPublisher"
    additivity="false">
    <level value="info" />
    <appender-ref ref="EXAMPLE_ERROR" />
    <appender-ref ref="CONSOLE" />
</logger>


问:
Firebase Insert data with 2 key attributes
Im new to the Firebase concept but what I am trying to do is add a new Firebase element into my "Groups" category where the tree structure is as such:

```<code>Groups:
---- GroupID (provided by firebase)
    ---- GroupPW (provided by user that create new group)
        ---- GroupName (provided by user that create new group)
        ---- etc....
</code>```

I have the following in the ViewController, under the CreateGroup IBAction button:

```<code>    let group = Group(groupName: self.name.text!, groupPW: self.password.text!)

    let ref = FIRDatabase.database().reference()
    let key = ref.child("Groups").childByAutoId().key

    taskFirebasePath.setValue(group.toDictionary())
</code>```

I am not really sure what to do now?

答:
I'm not sure what taskFirebasePath is. But if you wanna insert data to group, I think should change it to.

```<code>let group = Group(groupName: self.name.text!, groupPW: self.password.text!)

let ref = FIRDatabase.database().reference()
let childRef= ref.child("Groups").childByAutoId().child(self.password.text!)

childRef.setValue(group.toDictionary())
</code>```

Body:
Im new to the Firebase concept but what I am trying to do is add a new Firebase element into my "Groups" category where the tree structure is as such:

Groups:
---- GroupID (provided by firebase)
    ---- GroupPW (provided by user that create new group)
        ---- GroupName (provided by user that create new group)
        ---- etc....

I have the following in the ViewController, under the CreateGroup IBAction button:

    let group = Group(groupName: self.name.text!, groupPW: self.password.text!)

    let ref = FIRDatabase.database().reference()
    let key = ref.child("Groups").childByAutoId().key

    taskFirebasePath.setValue(group.toDictionary())

I am not really sure what to do now?

Body:
I'm not sure what taskFirebasePath is. But if you wanna insert data to group, I think should change it to.

let group = Group(groupName: self.name.text!, groupPW: self.password.text!)

let ref = FIRDatabase.database().reference()
let childRef= ref.child("Groups").childByAutoId().child(self.password.text!)

childRef.setValue(group.toDictionary())


问:
Comparison between Mockito vs JMockit - why is Mockito voted better than JMockit?
I'm investigating which mocking framework to use for my project and have narrowed it down to JMockit and Mockito.

I notice that Mockito was voted "the best mock framework for Java" on Stackoverflow.

In comparing features on JMockit's "Mocking Tool Comparision Matrix"  it appears that JMockit has multiple different features.

Does anyone have any specific information (not opinions) on what Mockito can do which can't be achieved with JMockit and vice versa?

答: For easy testing of our legacy codebase (with lots of static method calls, etc.), JMockit has been invaluable.  [Shameless plug for an article on my blog]</p>


问:
Use ffmpeg to Convert Video to Gif android studio
I am currently making a simple Androidapp that converts a video from the SD card into a gif.

I learnt ffmpeg is the most efficient method to handle the conversion. But I have no idea how to add ffmeg to my android studio project.

答:
In your app's build.gradle add

```<code>compile 'com.writingminds:FFmpegAndroid:0.3.2'
</code>```

After that add a button for selecting the path of video and in the onClick method of the button create a intent that will help the user to select video from his phone

```<code> Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_CONTACT_REQUEST);
</code>```

Now retreive the above result using the below method

```<code>    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();

            // OI FILE Manager
            String filemanagerstring = selectedImageUri.getPath();

            // MEDIA GALLERY

            String selectedImagePath =getPath(selectedImageUri);
            if (selectedImagePath != null) {
                String[] cmd = {"-i"
                        , selectedImagePath
                        , "Image.gif"};
                conversion(cmd);

            }
        }
    }
}
</code>```

define getPath method to get the path of selected video

```<code> public String getPath(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
        // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}
</code>```

then Create a method to convert the video into gif

```<code> public static void conversion(String[] cmd) {
    FFmpeg ffmpeg = FFmpeg.getInstance(this);

    try {

        // to execute "ffmpeg -version" command you just need to pass "-version"
        ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
            }

            @Override
            public void onProgress(String message) {
            }

            @Override
            public void onFailure(String message) {
            }

            @Override
            public void onSuccess(String message) {
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // Handle if FFmpeg is already running
        e.printStackTrace();
    }
}
</code>```

you can refer to https://github.com/WritingMinds/ffmpeg-android-java

Body:
In your app's build.gradle add

compile 'com.writingminds:FFmpegAndroid:0.3.2'

After that add a button for selecting the path of video and in the onClick method of the button create a intent that will help the user to select video from his phone

 Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_CONTACT_REQUEST);

Now retreive the above result using the below method

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();

            // OI FILE Manager
            String filemanagerstring = selectedImageUri.getPath();

            // MEDIA GALLERY

            String selectedImagePath =getPath(selectedImageUri);
            if (selectedImagePath != null) {
                String[] cmd = {"-i"
                        , selectedImagePath
                        , "Image.gif"};
                conversion(cmd);

            }
        }
    }
}

define getPath method to get the path of selected video

 public String getPath(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
        // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}

then Create a method to convert the video into gif

 public static void conversion(String[] cmd) {
    FFmpeg ffmpeg = FFmpeg.getInstance(this);

    try {

        // to execute "ffmpeg -version" command you just need to pass "-version"
        ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
            }

            @Override
            public void onProgress(String message) {
            }

            @Override
            public void onFailure(String message) {
            }

            @Override
            public void onSuccess(String message) {
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // Handle if FFmpeg is already running
        e.printStackTrace();
    }
}

you can refer to https://github.com/WritingMinds/ffmpeg-android-java


问:
Form validation regular expressions using javascript
Hello How can i add regular expressions in to my form validation i have done really basic form validation below and would just like to add regular expressions to increae security any ideas?? Noob at js</p>

```<code>    <head>
    <script>
    function validateForm() {
    var x = document.forms["login"]["username"].value;
    if (x == "") {
    alert("Name must be filled out");
    return false;
    }
    var x = document.forms["login"]["password"].value;
    if (x == "") {
    alert("Password must be filled out");
    return false;
    }
    }
    </script>
    </head>
</code>```

答:
```<code>  function validateForm() {
    var x = document.forms["login"]["username"].value;
    if (!/^\w+$/.test(x)) {
    alert("Name must be filled out");
    return false;
    }
    var x = document.forms["login"]["password"].value;
    if (!/^\w+$/.test(x)) {
    alert("Password must be filled out");
    return false;
    }
  }
</code>```