text:
Q: Setting attribute to the option of DropDownChoice I have a DropDownChoice:
        DropDownChoice dateSpanChoice = new DropDownChoice("dateSpan", new PropertyModel(getModel(), "dateSpan"), dateSpans, new IChoiceRenderer() {

            private static final long serialVersionUID = 10105L;

            @Override
            public String getIdValue(Object object, int index) {
                return ((DateSpan) object).getId() + "";
            }

            @Override
            public Object getDisplayValue(Object object) {
                DateTime today = new DateTime();
                DateTime currentDate = new DateTime(today.getYear(), today.getMonthOfYear(), today.getDayOfMonth(), 0, 0, 0, 0);
                DateSpan dateSpan = (DateSpan) object;
                DateTime fromDate = dateSpan.getFromDate();
                DateTime toDate = dateSpan.getToDate();
                boolean currentDateIsEqualOrAfterFromDate = currentDate.isEqual(fromDate) | currentDate.isAfter(fromDate);
                boolean currentDateIsEqualOrBeforeToDate = currentDate.isEqual(toDate) | currentDate.isBefore(toDate);
                boolean currentDateBelongsToCurrentRange = currentDateIsEqualOrAfterFromDate & currentDateIsEqualOrBeforeToDate;
                if (currentDateBelongsToCurrentRange) {
                    return ((DateSpan) object).getDisplayValue() + " *";
                } else {
                    return ((DateSpan) object).getDisplayValue();
                }
            }
        }) {

            private static final long serialVersionUID = 10106L;

            protected CharSequence getDefaultChoice(final Object selected) {
                CharSequence charSequence = super.getDefaultChoice(selected);
                System.out.println("=============================================================");
                //System.out.println(charSequence);
                //THIS CHARSEQUENCE IS RENRING EMPTY STRING
                if(StringUtils.isBlank(charSequence.toString())) {
                    System.out.println("CHARSEQUENCE IS BLANK");
                } else {
                    System.out.println("CHARSEQUENCE IS NOT BLANK");
                }
                return charSequence;
            }
        };
        dateSpanChoice.setNullValid(false);

I am trying to add style="background-color: red" to the selected option. So I am overriding getDefaultChoice() but as you can see it is commented in code the CharSequence is empty.
Is there any way to set an attribute to a particular option of DropDownChoice?
Thanks and Regards.
Note: the DateTime is Joda time

A: You need Select/SelectOption instead of DropDownChoice for more complex uses of  element.

A: Have a look at the behavior package in Wicket.
 You can use the AttributeAppender-class for instance.


text:
Q: License Keygen in javascript So I saw another solution on here with a problem I was having. Though the problem isn't completely solved for me.
This is the code that I found on here.

function makeid(length) {
  var result = "";
  var characters = '0123456789';
  for (var i = 0; i < length; i++) {
    result += characters[Math.floor(Math.random() * characters.length)];
  }
  result = result.match(/\d{1,4}/g).join("-");
  return result;
}

console.log(makeid(16));

And this is the current code I have now.

function makeid(length) {
  var result = "";
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  for (var i = 0; i < length; i++) {
    result += characters[Math.floor(Math.random() * characters.length)];
  }
  result = result.match(/\d{1,4}/g).join("-");
  return result;
}

console.log(makeid(16));

The output is not want I want. I want the output to be in both Letters and Numbers and I'm not sure why it won't do both!

A: It's because your match() is only looking for digits ( \d ) and not any character ( . ):

function makeid(length) {
  var result = "";
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  for (var i = 0; i < length; i++) {
    result += characters[Math.floor(Math.random() * characters.length)];

  }
  result = result.match(/.{1,4}/g).join("-");
  return result;
}

console.log(makeid(15));

And you can get rid of slow match all together, by using % operator:

function makeid(length) {
  var result = "";
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  for (var i = 0; i < length; i++) {
    result += characters[Math.floor(Math.random() * characters.length)];
    if (i+1 < length && !((i+1) % 4))
      result += "-";
  }
  return result;
}

console.log(makeid(16));

redpajama_set_name: RedPajamaStackExchange


text: Q: Radial symmetry terminology A circle or a 2-D projection of a starfish is considered "radially" symmetric. I am wondering what is the terminology for radial symmetry such that the distance from the center of the 2-D shape and its boundary is the same everywhere as in the case of a circle, but not the starfish.


text:
Q: Hex char array 2 by 2 characters to uint8_t I'm making a program for a microcontroller (mbed LPC1768)  and having a few problems to decode serial input to uint8_t.
I get a char ackBuffer[20]; filled with input from an external device.
What we get is for example: F040A34B6785121\r
What I want to do is to get an uint8_t array where each number is symbolized by the hex value of 2 characters. The F is to show the message from the external device is started and the carriage return is the end of each message.
So what I want in the uint8_t array is:
0x04
0x0A
0x34
...

To make it even harder it can be the ackBuffer is a smaller size, so for example only F04004A\r (if this can be easy fixed then it's very nice, but I can work around this problem myself.
Thank you!

A: So I'm assuming that an ackMessage must start with 'F' and end with '\r'. And I'm even assuming that, since you work on a micro controller, anything that does more than required (eg. library functions) should be avoided. Given that you just have to iterate over the buffer:
uint8_t charToHex(unsigned char value)
{
  if (value >= '0' && value <= '9') return value - '0';
  else if (value >= 'A' && value <= 'F') return value - 'A' + 10;
  else if (value >= 'a' && value <= 'f') return value - 'a' + 10;
  assert(false);
}

#define BUFFER_SIZE (20)

int main(void)
{
  char ackBuffer[BUFFER_SIZE] = "F12345890AB\r";
  uint8_t result[(BUFFER_SIZE-2)/2]; // at most 9 bytes since it's 20 - 2 / 2

  char* ptr = ackBuffer;

  assert(*ptr == 'F');
  ++ptr;

  int count = 0;
  while(*ptr != '\r')
  {
    uint8_t value = charToHex(*ptr) << 4 | charToHex(*(ptr+1));
    result[count++] = value;
    ptr += 2;
  }

  int i;
  for (i = 0; i < count; ++i)
    printf("%x\n", result[i]);

  return 0;
}

Mind that you must have a charToHex consistent with the used encoding and probably you could need some more sanity checks around the code.


text:
Q: Call function from HTML table data tags following is my code:
def format_taxes(self):
    tax_list = self.data['tax_list']
    send_tax = ''

    for tax in tax_list:
        send_tax = send_tax + unicode('
'''
                                      '${label}	'''
                                      '${amount}	'''
                                      '
').format(**tax)

    return send_tax

def subtotals_as_table(self):
        return unicode(u'
'
                            '
'
                                'Subtotal	'
                                '${subtotal}	'
                            '
'
                            '''
                            **How do I call the format_taxes() function in here?**
                            '''
                            '
'
                                'Total	'
                                '${total}	'
                            '
'
                        '
'.format(**self.data))

Everything works great. It's just that I want to call format_taxes() function in the  tag data and I have no idea how to do that. Can anyone please help me out?

A: You can't call a function inside a format string, but it's not hard to do it the right way.  Most likely what you want is something like:
def subtotals_as_table(self):
    format_args = self.data.copy()
    format_args['taxes'] = self.format_taxes()
    return '
...
 ${taxes}
...
'.format(**format_args)

A: To call within the HTML use the following:
< input id="clickMe" type="button" value="clickme" onclick="doFunction();" / >


text:
Q: If statement in Django JSON method If I have a Building object with a ForeignKey Campus object, how would I modify the Building's JSON method so it doesn't look as ugly as this:
def json(self):
    if self.campus:
        return {
        'id_number': self.id,
        'campus': self.campus.json(),
        'common_name': self.common_name,
        #....all the other fields
        }

    else:
        return {
        'id_number': self.id,
        'common_name': self.common_name,
        #....all the other fields
        }

The code above works.  I was wondering if there was a way to format the if statement such that I could relocate it and not have to list out all the other fields for both if-branches.  Mainly because this would get even messier if I had another relational object that was null, blank=True.

A: I would try to avoid defining the other fields twice.
def json(self):
    out = {
    'id_number': self.id,
    'common_name': self.common_name,
    #....all the other fields
    }
    if self.campus:
        out['campus'] = self.campus.json()
    return out

Note that this method and your original method return a python dict, not a JSON encoded string.


text:
Q: Find the problem with this proof. The following attempts to prove that if $n^2$ is even, then $n$ is even.
Suppose $n^2$ is even. Then $n^2$ = 2$k$ for some integer $k$. Let $n$ = 2$m$ for some integer $m$. This shows that $n$ is even.
I believe the problem is the believing the let $n$ = 2$m$ step proves the statement. This seems to put a lot of weight on a mere assumption. For example, say I was trying to prove "If 3$n$ + 2 is odd, then $n$ is odd" by saying " let n = 2$k$ + 1 for some integer $k$. This shows $n$ is odd." I guess circular reasoning would be the best way to describe it, the argument beings what it wants to end with. It's along the same logical lines of saying "Marcus is tall, therefore Marcus is tall". Am I on point here guys?

A: I'm not sure exactly what you're trying to prove, but it looks like you're trying to show $$ n^2 \text{ is even} \implies n \text{ is even}$$
I think what is missing is since you're doing cases, you probably want to do a proof by contradiction for when n is odd. A better way (in my opinion) is a proof by contrapositive. Assume $ \exists q \in \mathbb{Z}. \; n = 2q+1,$ and show why $n^2$ cannot be even.
EDIT: Also you just assumed that $n$ is even, but there is no relation to $n^2$, so you can't prove anything.

A: The problem is that you make an assumption. If you say let $n=2m$ then of course $n$ is even. To put another way: you're assuming that what you want to prove is true. This way everyting can be true. The argument in the OP goes similar to this:

Suppose all dogs are the same colour. Let all dogs be  green. This shows all dogs are the same colour.

Wich is obviously wrong.
You can only assume something if it is without loss of generality, or if it is the opposite of what you want to prove (in wich case you are proving by contradiction). Neither applies to your case, since you assumption loses all generality and is exactly what you want to prove.


text:
Q: Cyclomatic Complexity of switch case statement I'm confusing about the CC of switch statement
If I have following code:
if (n >= 0) {
    switch(n) {
        case 0:
        case 1:
            printf("zero or one\n");
            break;
        case 2:
            printf("two\n");
            break;
        case 3:
        case 4:
            printf("three or four\n");
            break;
        }
    }
else {
    printf ("negative\n");
}

what is the CC?
I found a post said that it's 5, with this diagram

(the edges are 17, not 16, I think it's a typo)
It says that we only need to count case 0 and case 1 as one
But I think the diagram should be:

Edges: 17,
Nodes: 13,
17 - 13 + 2P = 6
I count every cases as 1
My OOSE professor said it's 6, but in different way
He said:
init     => 1
if       => 1
switch   => 1
case 0 1 => 1
case 2   => 1
case 3 4 => 1

so it should be 6
What's the correct answer?
I'm really confused, thanks.

edited:
Now I think it's 7. yes, 7
Because if n is more than 5, will just do nothing and exit the switch statement.
then we get this diagram:

now E = 18
18 - 13 + 2 = 7
am I correct..?
really, really, really confused...

A: Ok, I have found the answer.
from McCabe.com, page 26 and 27
The answer is 5, because the original version of CC by McCabe counts a fall-through case as 1.

A: Code metric tools I've worked with count each case as a separate branch, even if it's a fall through case.
But this is an arbitrary choice. Code metric tools tend to err on the side of caution by default. The way the switch statement will ultimately be evaluated is an internal implementation detail that will vary based on the type of input and number of cases (at least in C#).
The go-to answer for reducing cyclomatic complexity caused by switch statements is to convert the cases/outputs into a dictionary. In your example, it would be something like the code sample below. Be aware that this is only for readability/maintainability. If your switch statement is long enough the .Net compiler will automatically convert it to a dictionary for you, so there is no performance gain.
var outputs = new Dictionary<int, string>()
            {
                { 0, "zero or one\n" },
                { 1, "zero or one\n" },
                { 2, "two\n" },
                { 3, "three or four\n" },
                { 4, "three or four\n" }
            };

if (n >= 0)
{
    printf(outputs[n]);
}

A: The correct answer is 7.
Each case within the switch statement counts as 1, therefore 5 x 1 = 5.
The if counts as 1.
The else counts as 1.
So,
1 + (5 x 1) + 1 = 7.
If you would count this as a method's body the cc would be 8 as the method counts as a straight through path.
Please change your accepted answer to the correct one as 5 is an incorrect answer.


text:
Q: Multiple mutable borrows with Graph-like data structures I am trying to write a program that will find the longest path in the graph (i.e. the greatest depth) for a directed graph which is always a rooted or multi-rooted tree.
The specs of the assignment require I use DFS and memoization, but multiple mutable references occur when performing the DFS. Is there any other way to do this?
I thought about using HashMaps instead of internal Graph fields, but it would just produce the same error on mutability of the HashMap. I've found several other questions on the Rust user forum and here, but none of them gives the advise on how to resolve this. Am I supposed to use "unsafe" code or some other strategy?
use std::io;

struct Node {
    neighbours: Vec<usize>,
    depth: usize,
    visited: bool,
}

impl Node {
    fn new() -> Node { Node { neighbours: Vec::new(), depth: 0, visited: false } }
    fn add_neighbour(&mut self, node: usize) { self.neighbours.push(node); }
    fn neighbourhood_size(&self) -> usize { self.neighbours.len() }
}

struct Graph {
    nodes: Vec<Node>,
    depth: usize,
}

impl Graph {
    fn new() -> Graph { Graph { nodes: Vec::new(), depth: 0} }
    fn nodes_number(&self) -> usize { self.nodes.len()}
    fn add_node(&mut self) { self.nodes.push(Node::new()); }
    fn node(&mut self, i: usize) -> &mut Node { &mut self.nodes[i] }

    fn dfs(graph: &mut Graph, index: usize) {
        if !graph.node(index).visited {
            graph.node(index).visited = true;
        }
        match graph.node(index).neighbourhood_size() == 0 {
            true => { graph.node(index).depth = 1; },
            false => {
                for &i in graph.node(index).neighbours.iter() {
                    // multiple mutable references
                    Graph::dfs(graph, i);
                }
                graph.node(index).depth =
                    1 + graph.node(index).
                    neighbours.iter().
                    map(|&x| graph.node(x).depth).
                    max().unwrap();
            }
        }
        if graph.node(index).depth > graph.depth {
            graph.depth = graph.node(index).depth;
        }
    }
}

fn main() {
    let mut input_line = String::new();
    io::stdin().read_line(&mut input_line);
    let n = input_line.trim().parse::<usize>().unwrap();
    // to avoid counting from 0 or excessive use of (-1)
    let mut graph = Graph::new(); graph.add_node();
    for _ in 0 .. n {
        let mut input_line = String::new();
        io::stdin().read_line(&mut input_line);
        let separated = input_line.
            split(" ").
            collect::<Vec<_>>();
        let u = separated[0].trim().parse::<usize>().unwrap();
        let v = separated[1].trim().parse::<usize>().unwrap();
        if graph.nodes_number() <= u { graph.add_node(); }
        if graph.nodes_number() <= v { graph.add_node(); }
        graph.node(u).add_neighbour(v);
    }
    let n = graph.nodes_number();
    for i in 1 .. n {
        if !graph.node(i).visited { Graph::dfs(&mut graph, i); }
    }
    println!("{}", graph.depth);
}

A: Instead of taking a copy of the vector before iterating over it, you could also iterate over the indices:
for ni in 0..graph.node(index).neighbours.len() {
    let neighbour = graph.node(index).neighbours[ni];
    Graph::dfs(graph, neighbour);
}

The neighbours vector gets still borrowed for performing the iteration, but not for the whole course of the iteration:

*

*graph.node(index).neighbours.len(): once at the beginning of the iteration for getting the length

*let neighbour = graph.node(index).neighbours[ni];: in each iteration step for getting the neighbour at the current index

Like the copy approach, this solution is based on the constraint that the neighbours vector you are iterating over will not be changed by the call to dfs.
You can solve the remaining issues regarding multiple references in your code by providing immutable access to the graph nodes:
fn node_mut(&mut self, i: usize) -> &mut Node {
    &mut self.nodes[i]
}
fn node(&self, i: usize) -> &Node {
    &self.nodes[i]
}

Only make use of the mutable access via node_mut where necessary. For example when adding a neighbour: graph.node_mut(u).add_neighbour(v);

A: You are modifying your graph structure while iterating through a vector contained within it. The compiler has no way of verifying that you do not add or remove from the vector during the iteration, which would invalidate the iterator. This is the intuitive reason for the error.
The easiest way to avoid this is to take a copy of the vector before iterating over it, so the compiler can see that the iterator does not change. This is a little suboptimal but resolves the error for now. Another lifetime error is solved in a similar way (but without much cost) by copying the depth into a variable before doing a comparison.
use std::io;
use std::env;

struct Node {
    neighbours: Vec<usize>,
    depth: usize,
    visited: bool,
}

impl Node {
    fn new() -> Node {
        Node {
            neighbours: Vec::new(),
            depth: 0,
            visited: false,
        }
    }
    fn add_neighbour(&mut self, node: usize) {
        self.neighbours.push(node);
    }
    fn neighbourhood_size(&self) -> usize {
        self.neighbours.len()
    }
}

struct Graph {
    nodes: Vec<Node>,
    depth: usize,
}

impl Graph {
    fn new() -> Graph {
        Graph {
            nodes: Vec::new(),
            depth: 0,
        }
    }
    fn nodes_number(&self) -> usize {
        self.nodes.len()
    }
    fn add_node(&mut self) {
        self.nodes.push(Node::new());
    }
    fn node(&mut self, i: usize) -> &mut Node {
        &mut self.nodes[i]
    }

    fn dfs(graph: &mut Graph, index: usize) {
        if !graph.node(index).visited {
            graph.node(index).visited = true;
        }
        match graph.node(index).neighbourhood_size() == 0 {
            true => {
                graph.node(index).depth = 1;
            }
            false => {
                let neighbours = graph.node(index).neighbours.clone();
                for &i in neighbours.iter() {
                    // multiple mutable references
                    Graph::dfs(graph, i);
                }
                graph.node(index).depth = 1
                    + neighbours
                        .iter()
                        .map(|&x| graph.node(x).depth)
                        .max()
                        .unwrap();
            }
        }
        let depth = graph.node(index).depth;
        if depth > graph.depth {
            graph.depth = graph.node(index).depth;
        }
    }
}

fn main() {
    env::set_var("RUST_BACKTRACE", "1");
    let mut input_line = String::new();
    io::stdin().read_line(&mut input_line);
    let n = input_line.trim().parse::<usize>().unwrap();
    // to avoid counting from 0 or excessive use of (-1)
    let mut graph = Graph::new();
    graph.add_node();
    for _ in 0..n {
        let mut input_line = String::new();
        io::stdin().read_line(&mut input_line);
        let separated = input_line.split(" ").collect::<Vec<_>>();
        let u = separated[0].trim().parse::<usize>().unwrap();
        let v = separated[1].trim().parse::<usize>().unwrap();
        if graph.nodes_number() <= u {
            graph.add_node();
        }
        if graph.nodes_number() <= v {
            graph.add_node();
        }
        graph.node(u).add_neighbour(v);
    }
    let n = graph.nodes_number();
    for i in 1..n {
        if !graph.node(i).visited {
            Graph::dfs(&mut graph, i);
        }
    }
    println!("{}", graph.depth);
}

playground
If you were to modify your approach so that you did not mutate the structure during the search (i.e. you stored the visited data elsewhere), the code would work without this copy. This would also be more friendly to concurrent use.


text:
Q: Claims Based Forms Authentication Roles I'm trying to authenticate a user using forms authentication in MVC 4 (I'm using RavenDB so I can't use the standard membership providers).  Then later I'm using the User.IsInRole() method or AuthorizeAttribute to verify the user is in a staff role.
Here's where I set the ticket on successful authentication (at the moment in UserController.cs):
FormsAuthenticationTicket ticket =
    new FormsAuthenticationTicket(
        1,
        model.Email,
        DateTime.Now,
        DateTime.Now.AddDays(1),
        false,
        model.Email);

string hashedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie =
    new HttpCookie(
        FormsAuthentication.FormsCookieName,
        hashedTicket);

HttpContext.Response.Cookies.Add(cookie);

Here's where I check the ticket for each request (Global.asax):
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        var user = this.UserService.GetUserByEmail(authTicket.Name);

        var identity = new GenericIdentity(authTicket.Name, "Forms");

        var principal = new GenericPrincipal(identity, user.Roles);

        HttpContext.Current.User = principal;
    }
}

If I then put a debug point on one of my action methods (CalendarController.cs), I get isStaff equals false:
public ActionResult Index()
{
    var user = HttpContext.User;

    bool isStaff = user.IsInRole(Role.Staff);

    return View();
}

Just for completion (Roles.cs, just a temporary class to test things):
public static class Role
{
    public static string Staff
    {
        get { return "Staff"; }
    }

    public static string Manager
    {
        get { return "Manager"; }
    }
}

Can anyone help give me a point as to what I might be missing?  It looks as though the roles I set are disappearing by the time I get to the action method.

A: Since you are using Raven I am assuming you made your own custom MembershipProvider and RoleProvider; and modified the web.config to use them.  You should have an entry similar to this:
<membership defaultProvider="MyMembershipProvider">
  <providers>
    <add name="MyMembershipProvider" type="namespace.MyMembershipProvider, providerAssemblyName" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
  <providers>
    <add connectionStringName="DefaultConnection" applicationName="/" name="DefaultRoleProvider" type="namespace.MyRoleProvider, providerAssemblyName" />
  </providers>
</roleManager>

If you are using .NET Framework version 4.5 it uses claims-based security and you do not need to store the roles in the cookie. Instead roles are just another claim that is stored in the ClaimsPrincipal.  All principals now inherit from ClaimsPrincipal and it is stored for the users session in
System.Web.HttpContext.Current.User as ClaimsPrincipal

If your membership and role providers are setup correctly ASP.NET should use them to populate the roles in ClaimsPrincipal and then check the claims when you check IsInRole.
You can also retrieve roles from the ClaimsPrincipal for roles like this.
principal.FindAll(ClaimTypes.Role).Select(p => p.Value);

And you can add roles to a ClaimsPrincipal like this.
List<Claim> claims = new List<Claim>();
foreach (string role in roles)
   claims.Add(new Claim(ClaimTypes.Role, role));
ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Forms"));

Now you can just set your cookie after authentication like this.
FormsAuthentication.SetAuthCookie(username, false);

A: you are not creating the FormsAuthenticationTicket inserting roles info:
        var ticket = new FormsAuthenticationTicket(
                1, //ticket version
                userName,
                DateTime.Now,
                DateTime.Now.Add(timeout), //timeout
                true, //persistent cookies
                roles,// <---ROLES not model.Email
                FormsAuthentication.FormsCookiePath);

------EDIT-----
Forget what I said: i think you are calling IsInRole() too early or user.Roles has the wrong value (maybe spaces in strings: isinrole uses  StringComparison.OrdinalIgnoreCase) or you should use FormsIdentity instead of GenericIdentity.
What the debugger says?
For reference: http://pastebin.com/jkqqcg28
(this is the starting model I use for handling authentication)

A: Thanks guys for helping me with this, what I've come up with (included below) works great!  It auto-logs users straight in through the login screen if they have a valid ticket (cookie) and also handles Claims based roles using the ClaimsIdentity and ClaimsPrincipal objects, without putting the roles in the user's cookie.  It also handles authentication in the Global.asax.cs file without having to resort to putting in custom authorize attributes.
UserController.cs
public ActionResult Login()
{
    LoginViewModel model = new LoginViewModel();

    if ((HttpContext.User != null) &&
        (HttpContext.User.Identity.IsAuthenticated))
    {
        return RedirectToAction("Index", "Home");
    }

    return View(model);
}

[HttpPost]
public ActionResult Login(LoginViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    bool isAuthenticated = this.userService.IsPasswordValid(model.Email, model.Password);

    if (!isAuthenticated)
    {
        ModelState.AddModelError("AuthError", Resources.User.Login.AuthError);

        return View(model);
    }

    FormsAuthentication.SetAuthCookie(model.Email, model.RememberUser);

    return RedirectToAction("Index", "Home");
}

Global.asax.cs
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        var ticket = FormsAuthentication.Decrypt(authCookie.Value);

        FormsIdentity formsIdentity = new FormsIdentity(ticket);

        ClaimsIdentity claimsIdentity = new ClaimsIdentity(formsIdentity);

        var user = this.UserService.GetUserByEmail(ticket.Name);

        foreach (var role in user.Roles)
        {
            claimsIdentity.AddClaim(
                new Claim(ClaimTypes.Role, role));
        }

        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

        HttpContext.Current.User = claimsPrincipal;
    }
}


text:
Q: Access to a protected constructor in Java If I have a class A and its subclass B.
package washington;
public class A{
       protected A(){}
}

package washington;
public class B extends A{
      public B(){super();} // it works
      public static void main (String[] args){
      A b = new A(); // it does work.
       }
}

The class A has a protected constructor, but I cannot access the constructor in B. I think it is a rule, however, I cannot find a webpage describing this situation.. All that I saw mention protected can be accessed from subclass, same-package.... e.t.c.
package california;
public class A extends washington.A{
    public static void main (String[] args){
       new washington.A(); // it does not work.
    }
}

I wonder if this is because I use IntelliJ IDEA 2017.3.4.. compiler is javac 9.0.4

A: It seems that the problem is that you have your classes in different packages. Java doc says:

If the access is by a simple class instance creation expression new C(...), or a qualified class instance creation expression E.new C(...), where E is a Primary expression, or a method reference expression C :: new, where C is a ClassType, then the access is not permitted. A protected constructor can be accessed by a class instance creation expression (that does not declare an anonymous class) or a method reference expression only from within the package in which it is defined.

A: class A{
    protected A() {
        System.out.println("hello from A");
    }
}

class B extends A{
    public B() {
        super();
        System.out.println("hello from B");
    }

    public static void main (String[] args){
        A b1 = new B(); // you can either do this
        B b2 = new B(); // or this
    }
}

Try running the program and you will see the expected result printed on console.


text:
Q: Sharepoint public view not visible I created a public view over a list.
This list has about 52 views currently ( i know thats a lot ).
Its the heart of a ticketing system.
The problem when i use this list i dont see all public views when i want to set a view on pages where i include this list table. No errors gets reported
Is there something that i can do about this.
Or should i simply wait a day (perhaps something requires time to update)
Or is there a way to force something that needs to be updated.

A: Which version of SharePoint On-Premise are you using? There is a limit of 50 views within the List/LIbrary View Dropdown pre-SP2013. You can create more than 50, you will just need to know the URL of the view that is not visible within the list. If you are displaying the list as a web part/app within a web part page, only 50 views will display within the web part properties dropdown.

A: Go to List Settings > Per-Location View Settings, in case if your newly created view is hidden for that particular location you could just add it to the "Views available at this location section" and try.
OR
If you are using a list view web part on a page, go to edit the web part > under the web part settings > "List Views" Be sure to select the View that is required under the selected view section.

A: server reboot, solved it.
i don't think it should be solved like that, but apparently some things get triggered faster on restart.


text:
Q: S3 Static Webpage Access Denied Error for ACL policy I have a webpage hosted in S3 which is to be accessed only by specific users within the account. For testing purpose, I added below bucket policy which has my iam arn specified in the Principal but I'm getting access denied error when trying to access the page (which is in that bucket) via S3 url https://s3.amazonaws.com/..... despite being signed in.
Can you please let me know what i'm doing wrong here.
Bucket Policy:
{
"Version": "2012-10-17",
"Id": "Policy1484430450679",
"Statement": [
    {
        "Sid": "Stmt1484430445422",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::123:user/testuser"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::testbucket/*"
    }
]}

If I give Principal as '*', then the webpage is accessible via S3 url.


text:
Q: Gmail pop3 ssl can't fetch mail server Suddenly gmail can't fetch anymore mails from my mail server (postfix, dovecot), with the below message:
Unable to establish secure SSL connection to mail.domain.com
Server returned error: "SSL error: Certificate 1 of the best path has an error"

We didn't do any recent changes on our server, we are using tls v1.2, on all pop3, imap and smtp,
SMTP is still working okay on gmail,
Any other mail clients like Thunderbird, outlook, mail exchange ..etc are working fine with out server
Edit: I checked multiple pop3 ssl validation websites and command line like "openssl s_client", and our server passed all

A: It seems like since wednesday Google Mail Servers no longer accept intermediate certificates signed using the sha1 hash algorithm.
Running the command openssl s_client -connect server.example.com:995 -CAfile cacert.pem -showcerts revealed to me that the mail server was (and still is) providing the sha1 version of the intermediate certificate.
I don't know the name of Intermediate CA that is responsible in your case (It is the 1st one in your case, it was the 2nd in my case) but I'm sure you will find a reissued Intermediate CA Certificate on the CA website. Running openssl s_client … with the -showcerts parameter should show the -----BEGIN CERTIFICATE----- block under Certificate chain where the number is 1 (it begins counting with 0 so it would be the 2nd block). You can copy that BEGIN to END CERTIFICATE block into a .crt or .cer file and open it on Windows to see the details.
For that particular Intermediate CA in my case the Root CA already had re-issued a sha256 signed version of the same certificate 4 years ago but the server admin put the old sha-1 version into the chain. In my particular case I will just ignore it because I'm no longer actively using that mail account and the admins of that mail server don't seem to be experienced in the SSL/TLS context. (In 2016 it took them 2 months to realize what was wrong and how to fix it even though I had told them in detail, and then they still didn't manage to get it 100% right.)


text:
Q: Type Error: cannot read property ' map ' of undefined I am try to run an unit test for the following code
here is where the error is pointing to:
populateActionDropdown = (actionList) => {
    let actions = actionList.map(action => {
        if (action.Name != 'Sign Out') {
            let layout = ''
            if (action.Command.includes('Layout')) {
                if (/\(([^)]+)\)/.exec(action.Command)) {
                    layout = '/' + /\(([^)]+)\)/.exec(action.Command)[1].toLowerCase();
                }
            }

This is how I have been setting up most of my unit test. But I'm having problems calling props that contains map or sort next to it.
Example : this.props.something.map() or props.sort().
How could i mock actionList to make sure map gets called
Thanks
Unit test code below :
describe('ActionMenu ', () => {

    let tree;
    let baseProps;
    let mockaction = {
        actionId: "test",
        name: "test",
        map: "test",
    };
    let mocksetTarget;
    let mocksetAction;
    let mockmodule = {
        name: "test module name",
    };
    let mockactionMenuDropdownOpen;
    let mockactionMenuToggle;
    let mockactionList;

    beforeEach(() => {
        baseProps = {
            action: mockaction,
            setTarget: mocksetTarget,
            setAction: mocksetAction,
            module: mockmodule,
            actionMenuDropdownOpen: mockactionMenuDropdownOpen,
            actionMenuToggle: mockactionMenuToggle,
            actionList: mockactionList,
        }
    })

    it(' Should render with all of the props', () => {
        tree = renderer.create(<BrowserRouter><ActionMenuComponent {...baseProps}
        />
        </BrowserRouter>)
        let treeJson = tree.toJSON()
        expect(treeJson).toMatchSnapshot();
        tree.unmount()
    });
});

A:
But I'm having problems calling props that contains map or sort next
  to it. Example : this.props.something.map() or props.sort().

To make your test pass, assign the following value to your mockactionList:
let mockactionList = [
  {
    actionId: "test",
    Name: "test",
    Command: []
  },
  {
    actionId: "test2",
    Name: "test2",
    Command: []
  }
];


text:
Q: How to redirect URLs starting with a certain path via TYPO3's redirects module? I would like to redirect any URL that start with /oldpath/ and i assume that i will need regular expressions.
Examples:

*

*/oldpath/ should be redirected.

*/oldpath/something should be redirected.

*something/oldpath/ should not be redirected.

I have activated "regular expressions" and tried the following inputs in "Source Path":
/oldpath/

… does not work as I would like. Everything containing /oldpath/ will be redirected, even if it is not starting with /oldpath/.
^/oldpath/(.*)$

… does nothing.
What would be the correct regular expression?

A: You need to put the regular expression for redirects between #s. So yours should be #^/oldpath/(.*)$#, though #^/oldpath/# also works.


text:
Q: Reference value from state's input, using JSONPath syntax in combination with a hard-coded string Im creating a SSM document with a state machine, in the api parameter: Name.
I want to combine a value from the state's input (InstanceID) with the hard-coded text EC2-PROD-WEBSRV-CP_RAM_SWAP-Document.
Im wondering if something like "key2.$": "$.inputValue[+hardcodedstring]"  is possible.
So the final value will be i-013165f64447e25e0-EC2-PROD-WEBSRV-CP_RAM_SWAP-Document.
SSM CreateDocument schema:
{
   "Attachments": [
      {
         "Key": "string",
         "Name": "string",
         "Values": [ "string" ]
      }
   ],
   "Content": "string",
   "DisplayName": "string",
   "DocumentFormat": "string",
   "DocumentType": "string",
   "Name": "string",
   "Requires": [
      {
         "Name": "string",
         "Version": "string"
      }
   ],
   "Tags": [
      {
         "Key": "string",
         "Value": "string"
      }
   ],
   "TargetType": "string",
   "VersionName": "string"
}

I read the documentation but It seems it is possible just one or the other option.
https://aws.amazon.com/blogs/compute/using-jsonpath-effectively-in-aws-step-functions/

A: Use the States.Format intrinsic function to interpolate the value into a string:
"key2.$": "States.Format('{}-EC2-PROD-WEBSRV-CP_RAM_SWAP-Document', $.inputValue)"


text:
Q: webbrowser.document javascript vb6 I could do with help here...

TEKLİF TEMEL VERİLERİ

                      Değiştir

So in this case,  I want to click on "Değiştir" link which calls this code:
onclick="fuOnedit('coredata'); return false"

How can I do that ? I need to call javascript code. I tried this one but it didn't work:
WebBrowser1.Document.parentWindow ("fuOnedit('coredata'); return false")


text:
Q: C++ Checking input of cin for proper data Hello I am working on a program that is checking the users input and asking for the user to reinput if the data does not match the type the program is looking for (In this case I am looking for the double data type). Below is my current code.
#include <iostream>
using namespace std;

int main()
{
    //Declare Variables and define.
    double var1,
           var2,
           var3,
           var4,
           var5,
           sum,
           avg;

        cout << "Input Five Values to be averaged. Press Enter to Continue" << endl;

    do {
        cin.clear();
        cin.ignore();
        cout << "Input first value:" << endl;
        cin >> var1;

    } while(cin.fail());

    do {
        cin.clear();
        cin.ignore();
        cout << "Input second value:" << endl;
        cin >> var2;

    } while (cin.fail());

    do {
        cin.clear();
        cin.ignore();
        cout << "Input third value:" << endl;
        cin >> var3;

    } while (cin.fail());

    do {
        cin.clear();
        cin.ignore();
        cout << "Input Fouth value:" << endl;
        cin >> var4;

    } while (cin.fail());

    do {
        cin.clear();
        cin.ignore();
        cout << "Input fifth value:" << endl;
        cin >> var5;

    } while (cin.fail());

//Sum the values.
sum = var1 + var2 + var3 + var4 + var5;

//Calculate the Average of Sum.
avg = sum / 5;

// Display the results.
cout << "The average is: " << avg << endl;

system("pause");

return 0;
}

The problems come when I input "aa", "s2", of "2ss" it will not ask for the data again once, but for as many characters are in the cin, or in the case of "s2"/"22s" it will go to the next input request. Why is this happening and how can I correct the behavior?
Thank you in advance!

A: Instead of cin.ignore();, use:
cin.ignore(std::numberic_limits<std::streamsize>::max(), '\n');

This will ignore either 256 characters, or every character until a newline (whichever comes first). As of now, you only clear one character from the buffer, which--as you've found--isn't always enough.
Thank you to @Arnav and @Dietmar for the proper number of characters to ignore!

A: The other, better answers explained how to make it stop. This is why it's happening:
double d;
cin >> d;

will read as many "double-like" characters as possible and then stop. So, for example, if you entered "2ss" the extractor would consume the "2" and leave the get pointer at the first 's'. If you enter "aa" the extractor consumes nothing. What happens to the extra characters (as well as the newline) is up to you.
Since you didn't consume all the characters in the input buffer, when your loop cycled, one of the remaining characters was consumed by ignore() and you tried again, until they were all gone.
The actual requirement you were trying to implement was either that only a number could be entered on a line (in which case, the suggestion of getline / strod is appropriate), or that all extraneous characters on a line should be silently swallowed, in which case the more precise ignore() specification is correct.


text:
Q: Symbol not found _OBJC_IVAR_$_NSView._layer (in AppKit) only on 10.7, works fine on 10.8 and 10.9 My mac cocoa app works fine on 10.8 and 10.9 except on 10.7 (fresh install) with this error at start : Symbol not found: _OBJC_IVAR_$_NSView._layer
Process:         xxx [875]
Path:            /Users/USER/Desktop/xxx.app/Contents/MacOS/xxx
Identifier:      com.xxx.xxx
Version:         1.0 (1)
Code Type:       X86-64 (Native)
Parent Process:  launchd [127]

Date/Time:       2014-02-13 17:44:24.208 +0100
OS Version:      Mac OS X 10.7.5 (11G63)
Report Version:  9

Crashed Thread:  0

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000002, 0x0000000000000000

Application Specific Information:
dyld: launch, loading dependent libraries

Dyld Error Message:
  Symbol not found: _OBJC_IVAR_$_NSView._layer
  Referenced from: /Users/USER/Desktop/xxx.app/Contents/MacOS/xxx
  Expected in: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit
 in /Users/USER/Desktop/xxx.app/Contents/MacOS/xxx

(xxx = appname)
I checked on system disk, AppKit framework is fine in the forlder /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit
Weird, isn't it ?
Thank you for any help ...

A: I fixed the issue by remove this lines in all of my code :
//self.layer = _layer; //Not necessary at all
self.wantsLayer = YES; //Necessary since 10.8

Thank you so much for help!


text:
Q: Powershell passing XMLDocument through function calls I'm trying to pass a System.XML.XMLDocument object through function calls, however that object is changed to System.Object[] after function call.
More specifically, I have a function like this:
function GenerateXml()
{

    [System.XML.XMLDocument]$xmlDoc=New-Object System.XML.XMLDocument
    $declaration = $xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes")
    $xmlDoc.AppendChild($declaration)

    [System.XML.XMLElement]$root = $xmlDoc.CreateElement("dummy")
    $root.SetAttribute("Name", "dummy value")
    $xmlDoc.AppendChild($root)
    $xmlDoc
}

[System.XML.XMLDocument]$xmlDoc = GenerateXml

This will output an error like:
Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument".

So what is the best way of passing a XMLDocument through function calls?

A: Turns out Powershell will return all the output from a method to an array. To get the actual return value, you can either get the last member of the output array or just don't output anything else other than what you actually want.

A: Your follow up response "output a method to an array" is true, but avoidable. In your example you utilize the .AppendChild() method, which in itself can produce output and therefore a Return value as objects in an array. This scenario can be avoided as
$xmlDoc.AppendChild($root) | Out-Null


text:
Q: What happens if I romance Kaidan as a male Shepard in ME1 by editing save file and import the save file to ME2 and ME3? As said in the title, I want to romance Kaidan in the first game. Since it isn't possible in a normal play, I'm afraid the save file may get corrupted so I can't play my old Shepard if I import it into ME2 and ME3; or it can be imported but their relationship is gone. Maybe Bioware didn't prepare the lines for such scenario and they say something strange when they reunite. If any of these situations happen, I think I would consider delaying the romance until the third game.

A: Whenever a love interest related dialog comes up you will get the same dialog female/male Sheppard would get. This usually happens if you edit romances via save game editors that are gender exclusive like Kaidan who used to be exclusively for female player characters


text:
Q: What is a digital common? I am working with Benthowave BII-7186 Miniature Probe Hydrophone. In its datasheet I have come across the following information about wiring:

I am not sure what is Digital Common, and how different it is from Common?

A: You can look at this as well: https://www.benthowave.com/products/Specs/Hydrophone%20Wiring.pdf
Common is the GND for the power; You put your battery between +VDC pin and Common.
Digital Common is the GND for the digital inputs; You connect your digital outputs to A1 and A0 and the GND of the driver to Digital Common.
Output Signal Common is the GND for the output signal; You measure the output between the Output Signal pin and Output Signal Common.
I'm guessing the Common and Digital Common is connected directly inside the instrument. But, you can't use the Common as a connection for you digital interface because its a battery terminal to which the battery is connected to. Maybe the battery is even internally housed in the instrument, so you can't eve access that pin from the outside?


text:
Q: Why doesn't my Wordpress admin dashboard have a "Comments" menu item? I'm an administrator user on my site, and I can see the small "speech bubble" comments menu at the top admin bar, and I use it to moderate comments, but my sidebar does not show a "comments" menu.
I need to be able to see it to work with a the wpDiscuz plugin.
I've looked through functions.php and wp-admin/menu.php, and I can't find anything anomalous about them that would indicate they've been used to hide the comments menu.
I haven't seen anything similar to what is referenced here and here.
I'm stumped. Any advice?


text:
Q: CarouFredSel responsive height issue İ'm using caroufredsel plugin to instantiate a responsive carousel and i'm facing a problem. When i change window size by dragging the window everything works fine, but when i maximise window using maximise button, the height of the carousel doesn't adjust, leaving the gap below(except in Opera).
İt looks like the browsers don't fire the resize event properly.
İ've done a research, and found similar posts with advices, but nothing worked for me. This looks more like an issue of resize event not being handled properly when maximise button is clicked. Does anyone have any suggestions? Thanks in advance.
Here's the code:
$slider.carouFredSel({
    responsive: true,
    auto : false,
    height: 'variable',
    prev : "#carousel_nav_left",
    next : "#carousel_nav_right",
    circular  : true,
    infinite  : true,
    scroll: {
        items: 1,
        mousewheel: true,
        easing: "easeInOutQuint",
        duration: 700,
    },
    swipe: {
        onTouch: true,
        onMouse: true,
        easing: "easeInOutQuint",
        duration: 500
    },
    items: {
        width: 320,
        height: 'variable',
        visible: {
            min: 1,
            max: 3
        }
    },
});

Edit:
The fix offered in other posts was adding the following code during the initialization:
onCreate: function () {
    $(window).on('resize', function () { $slider.parent().add($slider).height($slider.children().first().height();
}).trigger('resize');

}

A: this is correct:
    onCreate: function () {
        $(window).on('resize', function () {
            $slider.parent().height($slider.children().first().height())
        })
    }


text:
Q: How to pass the value to URL from dropdown item? I am asking this question again....because I am not getting correct answer...
answers which I get is incorrect.
I am developing MVC application and I am using razor syntax. I am trying to get the selected item from dropdown list value and to pass it to the controller method.
but I am getting error.
$("#btnForword").click(function(){
    d =  document.getElementById("HODList").value;

    var url2 = "@Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = "idValue" , nHOD = "d" }))";
    url2 = url2.replace("idValue",'@Model.Id');
    url2 = url2.replace("d",'@d');

    $.ajax({
        url: url2, type: "POST", success: function (data) {
            $("#btnForword").css("display","none");

        }
    });
    return false;
});

I think error in this line...
   url2 = url2.replace("d",'@d');

Issue solved  Issue solved

The problem in variable 'D' yes in "D".
I checked using inspect element property of Google chrome, when I saw it in console window....
When I click on the button , I can see the string formed in below way
  http://localhost:54255/PaymentAdvice/SendPaymentAdviceForApproval?paymentAdviceId=304&nHO8=D

jquery-1.7.1.min.js:4

see the last character in the above link, it should not be come as a "=D" isnt it ?
I used the below code...and it works perfectly.
$("#btnForword").click(function(){

            var url2 = "@Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = "idValue" , nHOD = "HODId" }))";
            url2 = url2.replace("idValue",'@Model.Id');
            url2 = url2.replace("HODId",$('#HODList').val());

            $.ajax({
                url: url2, type: "POST", success: function (data) {
                    $("#btnForword").css("display","none");

                }
            });
            return false;
        });

Is this a bug in Jquery ?

A: Your variable d is not a server variable that can be called with "@" but a client variable set in javascript, so it should be user like :
$("#btnForword").click(function(){
    d =  document.getElementById("HODList").value;

    var url2 = "@Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = Model.Id , nHOD = "d" }))";
    url2 = url2.replace("d",d);

    $.ajax({
        url: url2, type: "POST", success: function (data) {
            $("#btnForword").css("display","none");

        }
    });
    return false;
});

(and the "@Model.Id" can be called directly in the Url.Action method).

A: Yes it is. The problem is that the js replace function replaces every "d" character contained in the url2 string with your @d variable!!!
You need to replace the "d" identifier with something that does not appear twice (or more) in the url string. Besides, I think is better if you create the url directly using javascript and not the Razor helper. You can do this in one line of code instead of three. Regards.


text:
Q: How to measure CPU cycles of a given process in C#? I have some different models that perform the same task, using different algorithms. I want to compare the performance of these models by measuring CPU cycles (I tried using System.Diagnostics.StopWatch to count Ticks, but the result is not accurate enough).
I have found a class that measures CPU cycles by using P/Invoke, as follows:
IModel model;
CodeTimer.Time(true, model.ToString(), totalTime, model.TimeStep);

The method above iterates by N times the method model.TimeStep. I noticed that the results of CodeTimer.Time vary greatly (by at least one order of magnitude, from 58 KCycles to 890 KCycles). Thus, correct me if I am wrong, but as CodeTimer class marks the cycles before and after the process, it can also count the cycles used by any other processes (even OS processes) occurring during the execution of model.TimeStep method (the method which I want to measure performance).
So two questions:

*

*Is my above supposition correct? If it is, then I need to come up with another solution to measure CPU cycles, which leads to my main question:

I then came up with the idea of iterating model.TimeStep() in a different System.Threading.Thread and measuring the cycles of the given thread using QueryProcessCycleTime. However as QueryProcessCycleTime receives as input a System.Threading.WaitHandle (or an IntPtr as well), I don't know how to tell this method that I want to measure the cycles of that specific Thread I just created. In another words, I don't know how to put together the thread which I create to iterate the model, the WaitHandle and the QueryProcessCycleTime, even though I have read some examples of using WaitHandle (I just can't mix everything together).

*How can I accomplish that?

It would be something like this:
class ModelSimulator
{
    public Model1 model1 { get; private set; } // implements IModel
    public Model2 model2 { get; private set; } // implements IModel

/* other methods */

    public void RunModel(object obj)
    {
        IModel model = (IModel)obj;
        Int32 t = model.maxTime;
        while (t-- > 0)
            model.TimeStep();
    }
}

And inside the main method, I do:
[DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern Boolean QueryProcessCycleTime(SafeWaitHandle processHandle, out UInt64 CycleTime);

static void Main(string[] args)
{
    ModelSimulator ms = new ModelSimulator();
    Thread thread = new Thread(ms.RunModel);
    thread.Start(ms.model1);
    // here I start the thread, but how can I use QueryProcessCycleTime to measure
    // the thread execution
}

PS: mine is not a duplicate of this question, because I need some more specific answer, which is not there... My question could be a complement to that question.

A: As suggested by @ShlomiBorovitz, one can use GetCurrentThread() in order to identify the Thread which is running the process. The possible solution is a very simple modification in the CodeTimer.cs. The modification needed may be found in the end of this answer. I added a class named PerformanceStatus to have the amount of Garbage Collection for levels 0, 1 and 2 as well in the result of the CodeTimer.Time() method used to measure performance. Thus, one can also know whether the Garbage Collector had collected anything during the process.
You then just need to use it like:
ModelSimulator nm = new ModelSimulator();
CodeTimer c = new CodeTimer(nm.RunModel, model); // model implements IModel
UInt64 time = c.Time().CPUCycles;
Console.WriteLine("{0:0.000e+000} KCy", (Double)time / 1000.0D);

Such that the class ModelSimulator is given in the question, bearing a method ModelSimulator.RunModel(IModel model) which receives an object of type IModel.
Here is the CodeTimer.cs needed to measure the performance
public sealed class CycleTime
{
    private Boolean m_trackingThreadTime;
    private SafeWaitHandle m_handle;
    private UInt64 m_startCycleTime;

    private CycleTime(Boolean trackingThreadTime, SafeWaitHandle handle)
    {
        m_trackingThreadTime = trackingThreadTime;
        m_handle = handle;
        m_startCycleTime = m_trackingThreadTime ? Thread() : Process(m_handle);
    }

    [CLSCompliant(false)]
    public UInt64 Elapsed()
    {
        UInt64 now = m_trackingThreadTime ? Thread(/*m_handle*/) : Process(m_handle);
        return now - m_startCycleTime;
    }

    public static CycleTime StartThread(SafeWaitHandle threadHandle)
    {
        return new CycleTime(true, threadHandle);
    }

    public static CycleTime StartProcess(SafeWaitHandle processHandle)
    {
        return new CycleTime(false, processHandle);
    }

    public static UInt64 Thread(IntPtr threadHandle)
    {
        UInt64 cycleTime;
        if (!QueryThreadCycleTime(threadHandle, out cycleTime))
            throw new Win32Exception();
        return cycleTime;
    }

    /// <summary>
    /// Retrieves the cycle time for the specified thread.
    /// </summary>
    /// <param name="threadHandle">Identifies the thread whose cycle time you'd like to obtain.</param>
    /// <returns>The thread's cycle time.</returns>
    [CLSCompliant(false)]
    public static UInt64 Thread(SafeWaitHandle threadHandle)
    {
        UInt64 cycleTime;
        if (!QueryThreadCycleTime(threadHandle, out cycleTime))
            throw new Win32Exception();
        return cycleTime;
    }

    [CLSCompliant(false)]
    public static UInt64 Thread()
    {
        UInt64 cycleTime;
        if (!QueryThreadCycleTime((IntPtr)(-2), out cycleTime))
            throw new Win32Exception();
        return cycleTime;
    }

    /// <summary>
    /// Retrieves the sum of the cycle time of all threads of the specified process.
    /// </summary>
    /// <param name="processHandle">Identifies the process whose threads' cycles times you'd like to obtain.</param>
    /// <returns>The process' cycle time.</returns>
    [CLSCompliant(false)]
    public static UInt64 Process(SafeWaitHandle processHandle)
    {
        UInt64 cycleTime;
        if (!QueryProcessCycleTime(processHandle, out cycleTime))
            throw new Win32Exception();
        return cycleTime;
    }

    /// <summary>
    /// Retrieves the cycle time for the idle thread of each processor in the system.
    /// </summary>
    /// <returns>The number of CPU clock cycles used by each idle thread.</returns>
    [CLSCompliant(false)]
    public static UInt64[] IdleProcessors()
    {
        Int32 byteCount = Environment.ProcessorCount;
        UInt64[] cycleTimes = new UInt64[byteCount];
        byteCount *= 8;   // Size of UInt64
        if (!QueryIdleProcessorCycleTime(ref byteCount, cycleTimes))
            throw new Win32Exception();
        return cycleTimes;
    }

    [DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern Boolean QueryThreadCycleTime(IntPtr threadHandle, out UInt64 CycleTime);

    [DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern Boolean QueryThreadCycleTime(SafeWaitHandle threadHandle, out UInt64 CycleTime);

    [DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern Boolean QueryProcessCycleTime(SafeWaitHandle processHandle, out UInt64 CycleTime);

    [DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern Boolean QueryIdleProcessorCycleTime(ref Int32 byteCount, UInt64[] CycleTimes);

    [DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
    public static extern IntPtr GetCurrentThread();
}

public sealed class CodeTimer //: IDisposable
{
    private Int32 m_collectionCount0;
    private Int32 m_collectionCount1;
    private Int32 m_collectionCount2;

    private Thread m_thread;
    private IModel m_model;
    private Action<IModel> m_performanceMethod;

    private UInt64 outThreadCycles;

    public CodeTimer(Action<IModel> perfMethod, IModel model)
    {
        PrepareForOperation();

        m_performanceMethod = perfMethod;
        m_model = model;
        m_thread = new Thread(PerformanceTest);
    }

    private void PerformanceTest()
    {
        PrepareForOperation();
        IntPtr p = CycleTime.GetCurrentThread();
        UInt64 t = CycleTime.Thread(p);
        m_performanceMethod(m_model);
        outThreadCycles = CycleTime.Thread(p) - t;
    }

    public PerformanceStatus Time()
    {
        m_thread.Start();
        m_thread.Join();
        return new PerformanceStatus(GC.CollectionCount(0) - m_collectionCount0, GC.CollectionCount(1) - m_collectionCount1, GC.CollectionCount(2) - m_collectionCount2, outThreadCycles);
    }

    private void PrepareForOperation()
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        m_collectionCount0 = GC.CollectionCount(0);
        m_collectionCount1 = GC.CollectionCount(1);
        m_collectionCount2 = GC.CollectionCount(2);
    }
}

public class PerformanceStatus
{
    public Int32 GCCount1;
    public Int32 GCCount2;
    public Int32 GCCount3;
    public UInt64 CPUCycles;
    public PerformanceStatus(Int32 gc1, Int32 gc2, Int32 gc3, UInt64 cpuCycles)
    {
        this.GCCount1 = gc1;
        this.GCCount2 = gc2;
        this.GCCount3 = gc3;
        this.CPUCycles = cpuCycles;
    }
}


text:
Q: FeathersJS with Firebase architecture I have an existing Firebase application (Which was built for quick prototyping and which is now grown big, I don't intend to move because existing dependencies and also because ease of use and authentication tied up) and I am trying to build a Rest API using FeatherJS.
It seems it is really easy to work with FeathersJS if you are using a standard database (MongoDB, etc).
How can I integrate Firebase with Feathers keeping the best practices in place (Service Architecture, AOP)? Can I override service in Feathers and map it to my Firebase Rest endpoint?
I created a custom service in Feathers and tried doing this :
  get(id, params) {
    return Promise.resolve(FirebaseRef.child(id).once('value'));
  }

I get the:
Converting circular structure to JSON error

Is what I am doing correct?

A: This worked :
return Promise.resolve(FirebaseRef.child('userId1').once('value').then(function (snap) {
          return snap.val();
        }));

I am still unsure if this is how I would best integrate Firebase with FeathersJs

A: The main architectural difference between Firebase and Feathers real-time is that Firebase uses key-value observation whereas Feathers uses real-time events you automatically get when following the REST architecture. The first step would be to wrap generic Firebase operations in its own custom service which could look like this (not tested):
class FirebaseService {
  constructor(name) {
    this.name = name;
  }

  ref(id) {
    return firebase.database().ref(`${this.name}/${id}`);
  }

  async get(id) {
    const ref = await this.ref(id).once('value');

    return ref.value;
  }

  async create(data) {
    const id = firebase.database().ref().child(`/${this.name}`).push().key;

    return this.update(id, data);
  }

  async update(id, data) {
    this.ref(id).set(data);

    return this.get(id);
  }

  async remove(id) {
    const deletedEntry = await this.get(id);

    this.ref(id).remove();

    return deletedEntry;
  }
}

This will already get you a Feathers Firebase integration that automatically sends real-time events as long as you use it through the Feathers API. If Firebase gets updated outside of the service and you want to notify clients, you can use the value listeners and call update and/or patch on the service on the server:
const id = <some user id>;
firebase.database().ref(`/users/${id}`).on('value', snapshot => {
  app.service('users').update(id, snapshot.value);
});


text:
Q: SMTP exception. asking for authentication? protected void Button1_Click(object sender, EventArgs e)
{
    MailMessage message = new MailMessage()
    {
        Subject = "Subject",
        Body = "Body"
    };
    message.To.Add(new MailAddress("demo@example.com", "Some name"));

    SmtpClient client = new SmtpClient();
    client.EnableSsl = true;
    client.Send(message);
}

config
<configuration>
  <system.net>
    <mailSettings>
      <smtp from="demo@example.com">
        <network host="****" defaultCredentials="false"  port="587" userName="****" password="****" />
      </smtp>
    </mailSettings>
  </system.net>
 <system.web>

Correction. it works now. Thanks Marek

A: Your problem might be with defaultCredentials set to true.  Try setting that to false and try again.  Also, why are you setting your credentials again in code?  Gmail also requires emails to be sent via SSL (if I remember correctly) on port 587.
Just today I implemented gmail smtp in my code.  My settings and code:
<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="MY_GMAIL_EMAIL">
        <network defaultCredentials="false" host="smtp.gmail.com" port="587" userName="MY_GMAIL_USERNAME" password="MY_GMAIL_PASSWORD" />
      </smtp>
    </mailSettings>
  </system.net>

MailMessage message = new MailMessage() {
                              Subject = "Subject",
                              Body = "Body"
                          };
message.To.Add(new MailAddress("someemail@domain.com", "Some name"));
SmtpClient smtpClient = new SmtpClient();
smtpClient.EnableSsl = true;
smtpClient.Send(message);


text:
Q: Приводит ли перекрестный вызов doGet() и doPost к deadlock? Во многих ресурсах можно найти вопрос для интервью о том как вызвать deadlock в сервлете, и везде говориться о том что нужно вызвать в теле doPost() метод doGet() и наоборот в  теле doGet() метод doPost() и вот один из них, вопрос №15.
Но возникает вопрос не фольклор ли это? Deadlock предполагает что потоки засыпают и ждут что у них будет вызван notify() или notifyAll(). Но при перекрестном вызове нет никаких wait() или notify(). Или есть?


text:
Q: passing array object to javascript function I am creating dynamic link where I am passing function with some values and array but when that function is called that array become string like "[object Object]". It don't remain as array
Javascript Code
var mdata = {};
            mdata.itemId = data.d.ID.toString();
            mdata.sucessMsg = "Gate Pass detail document is uploaded successfully.";
            mdata.errorMsg = "Gate Pass detail document uploading cancel";
            tdUplDoc.html("Upload Documents");

calling function
function openBasicDialog(tUrl, tTitle, tdata) {
    var options = {
        url: tUrl,
        title: tTitle,
        args: tdata,
        dialogReturnValueCallback: onPopUpCloseCallBackWithData
    };
    SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
    return false;
}

How I will keep my array as array not as string. Something I am doing wrong. Please somebody help me :(

A: Pass it as a JSON string,
"'..,'" + JSON.stringify(mdata) + "');\">Upload Documents");

And use it inside the function after parsing,
function openBasicDialog(tUrl, tTitle, tdata) {
    var options = {
        url: tUrl,
        title: tTitle,
        args: JSON.parse(tdata),  //parse it here
        dialogReturnValueCallback: onPopUpCloseCallBackWithData
    };

A: This won't work do the following
var a = document.createElement('a');
a.id = 'uplDoc';
a.href='#';
a.addEventListener('click', function(){
  openBasicDialog('UploadDocument.asp', 'Upload CivilID or Passport Copy', mdata);
}
tdUplDoc.appendChild(a);

A: You are getting [object Object] because you are doing a string concatenation and that is the string representation of this object:
"<a id='uplDoc' href='#' onclick=\"javascript:openBasicDialog('UploadDocument.aspx','Upload CivilID or Passport Copy','" + mdata + "');\"

What I would suggest is to add the element and write a click event listener on that element:
tdUplDoc.html("Upload Documents");

document.getElementById('uplDoc').addEventListener('click', function(){
   openBasicDialog('UploadDocument.asp', 'Upload CivilID or Passport Copy', mdata);
});


text:
Q: Need help in understanding MUX-NOT flip-flop I need help in doing practice problem:
A MUX-NOT flip-flop (MN flip-flop) behaves as follows. If M=1 the flip-flop complements the current state. If M=0, the next state of the flip-flop is equal to N. Derive the truth table and excitation table for an M-N flip-flop.
My book does not give any data about MN flip-flop and I did not find any adequate materials on that online. Can anyone help me to understand the question and the idea behind MN flip-flop?

A: Ignore what they are calling it and draw a truth table for what they describe. There appears three inputs: "the current state" which you can arbitrarily call Q(n), N, and M. There is one output which we can arbitrarily call Q(n+1). The names are not totally arbitrary, because Q(n+1) is by definition a one-time-step delayed version of Q(n) (i.e. Q(n) is the previous output).

  Inputs           Outputs
 Q(n)    M    N    Q(n+1)
  0      0    0      ?
  0      0    1      ?
  0      1    0      ?
  0      1    1      ?
  1      0    0      ?
  1      0    1      ?
  1      1    0      ?
  1      1    1      ?

You should be able to fill in the question marks from the narrative description trivially. This is a truth table.
I believe an excitation table is just a rephrasing of the truth table where the valid entries are include 0, 1, and Q(n) and it's complement /Q(n) (so there are only two "real" inputs). And removing "redundant" rows (i.e. if a variable is a don't-care under some conditions, then express that collapsed row with an "x" for that variable).

Inputs       Outputs
M    N       Q(n+1)
0    0       Q(n), /Q(n), 0, or 1?
0    1       Q(n), /Q(n), 0, or 1?
1    0       Q(n), /Q(n), 0, or 1?
1    1       Q(n), /Q(n), 0, or 1?

Can you reduce this further once you put answers in to the question marks?

A: By your description this is a T or Toggle Flip Flop.  When T = high, the Output toggles (changes state -> complements) when the T inout is low the state is held (Q_n+1 = Qn).

A: Here's the idea behind it; it's just a 2:1 MUX and a DFLOP.


text:
Q: What are ghost rows or columns in computation? I am newbie to MPI programming. While reading some information online, I am unable to understand about ghost rows/columns. Can somebody please explain to me what is it, how it is implemented and why do we use it?

A: Ghost regions are usually used with stencil applications. What that means is that the processes might be laid out like this (I'm going to answer this question in 2D, but you can extrapolate to however many dimensions is helpful for you):
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 | 8

Each process communicates directly with its neighbors (north, south, east, and west) to exchange data every iteration. Each process has some block of 2D data that is laid out like this:
1 5 9 3 7
2 3 4 8 0
2 5 7 3 9
9 3 8 1 4
8 3 7 3 2

The edges of that data are usually used as "ghost regions":
1   5 9 3   7
  ---------
2 | 3 4 8 | 0
2 | 5 7 3 | 9
9 | 3 8 1 | 4
  ---------
8   3 7 3   2

This means that this data is made available to the neighboring processes so they can use it in their own calculation, usually to calculate some sort of interactions between physical objects at the borders of a domain decomposition problem.
As for the implementation, that will depend on the data, but often it can be done using custom MPI datatypes. I won't provide code here since it's so specific to your application, but there are plenty of tutorials out there on the web where you can learn about how to use MPI datatypes.
Here's a tutorial I turned up with a quick Google search. It's not about MPI specifically, but it explains the basic concepts: http://www.hpjava.org/papers/HPJava/HPJava/node28.html


text:
Q: Node placements in tikz \documentclass[10pt,journal,compsoc]{IEEEtran}

\usepackage{tikz,pgfplots,pgfplotstable}

\usetikzlibrary{fit,matrix,positioning,decorations.pathreplacing,calc,shapes,arrows,shadows,patterns}

% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}
\newdimen\zerolinewidth

\begin{document}
\tikzstyle{redRectangle} = [
rectangle,
draw,
fill=red!20,
node distance=0.65 cm,
text width=7 em,
text centered,
rounded corners,
minimum height=4 em,
minimum width=3 cm,
thick
]

\tikzstyle{blueRectangle} = [
rectangle,
draw,
fill=blue!20,
node distance=1.5 cm,
text width=7 em,
text centered,
rounded corners,
minimum height=4 em,
minimum width=3 cm,
thick
]

\tikzstyle{yellowRectangle} = [
rectangle,
draw,
fill=yellow!20,
node distance=1.5 cm,
text width=7 em,
text centered,
rounded corners,
minimum height=4 em,
minimum width=3 cm,
thick
]

\tikzstyle{greenRectangle} = [
rectangle,
draw,
fill=green!20,
node distance=1.5 cm,
text width=7 em,
text centered,
rounded corners,
minimum height=4 em,
minimum width=3 cm,
thick
]

\tikzstyle{blueDiamond} = [
diamond,
draw,
fill=blue!20,
node distance=1.5 cm,
text width=7 em,
text badly centered,
inner sep=0pt,
thick
]

\tikzstyle{blueEllipse} = [
ellipse,
draw,
fill=blue!20,
node distance=1.5 cm,
text width=7 em,
thick
]

\tikzstyle{container} = [
rectangle,
draw,
inner sep=0.5 cm,
rounded corners
]

\tikzstyle{empty} = [
]

\tikzstyle{line} = [
draw,
-latex',
thick
]

\begin{tikzpicture}[auto]

\node [empty](origin){};
\node [redRectangle, right=of origin] (aa) {aa};
\node [redRectangle, left=of origin] (bb) {bb};
\node [redRectangle, below=of bb] (cc) {cc};
\node [redRectangle, below=of aa] (dd) {dd};
\path [line] (bb) -- (aa);
\path [line] (bb) -- (cc);
\path [line] (aa) -- (dd);

\node [redRectangle, right=of aa] (pp) {pp};
\node [redRectangle, right=of pp] (rr) {rr};
\node [redRectangle, below right=of pp] (qq) {qq};

\node [container, fit=(aa)(origin)(bb)(cc)(dd)](container1){};
\node [container, fit=(pp)(rr)(qq)](container2){};

\end{tikzpicture}

\end{document}

*

*Wants to increase distance between container1 and containder2 while keeping them next to each other horizontally.

*Wants to place node qq below and in the middle of pp and rr.

*Wants to place an another container above and in the middle of container1 and containder2.

*Wants to draw an another container around all the containers

Any help will be highly appreciable. I am using the given Reference code

A: Adaptations:

*

*I removed unused tikzlibrarys.

*Use tikzset instead of tikzstyle (see Should \tikzset or \tikzstyle be used to define TikZ styles?).

*I removed unused styles. (Note: you can define a basic style myrecangle and use it for redRectangle and so on, to avoid redundant code).

Short answers to questions:

*

*Use right=15mm of aa to increase the distance.

*To draw below in the middle use ($(pp)!.5!(rr) + (0,-2)$).

*Create node above and shift it (above=15mm of aa, xshift=20mm) or use notation above (at ($(aa)!.5!(pp) + (0,3)$)).

*Just draw container around all others.

Code:
\documentclass[10pt,journal,compsoc]{IEEEtran}

\usepackage{tikz}
\usetikzlibrary{fit,positioning,calc,arrows}

\tikzset{
    myRectangle/.style={
        rectangle,
        draw,
        node distance=0.65 cm,
        text width=7 em,
        text centered,
        rounded corners,
        minimum height=4 em,
        minimum width=3 cm,
        thick
    },
    redRectangle/.style={
        myRectangle,
        fill=red!20,
    },
    container/.style={
        rectangle,
        draw,
        inner sep=0.5 cm,
        rounded corners
    },
    line/.style={
        draw,
        -latex',
        thick
    }
}

\begin{document}

\begin{tikzpicture}[auto]
    \node [](origin){};
    \node [redRectangle, right=of origin] (aa) {aa};
    \node [redRectangle, left=of origin] (bb) {bb};
    \node [redRectangle, below=of bb] (cc) {cc};
    \node [redRectangle, below=of aa] (dd) {dd};
    \path [line] (bb) -- (aa);
    \path [line] (bb) -- (cc);
    \path [line] (aa) -- (dd);

    \node [redRectangle, right=15mm of aa] (pp) {pp}; % question 1
    \node [redRectangle, right=of pp] (rr) {rr};
    \node [redRectangle] (qq) at ($(pp)!.5!(rr) + (0,-2)$) {qq}; % question 2

    \node [container, fit=(aa)(origin)(bb)(cc)(dd)] (container1) {};
    \node [container, fit=(pp)(rr)(qq)] (container2) {};

    % question 3
    \node [redRectangle] (xx) at ($(aa)!.5!(pp) + (0,3)$) {xx};
    \node [container, fit=(xx)] (container3) {};

    % question 4
    \node [container, fit=(container1)(container2)(container3)] (containerAll) {};
\end{tikzpicture}

\end{document}

Result:


text:
Q: Advanced card payments SDK showing error during submission of form Error: "Hosted Fields payment is already in progress."
I have copied it from this PayPal documentation, and in the SDK URL pass a proper sandbox clientID.
if (paypal.HostedFields.isEligible()) {
       paypal.HostedFields.render({
         createOrder: function () {return "order-ID";}, // replace order-ID with the order ID
         styles: {
           'input': {
             'font-size': '17px',
             'font-family': 'helvetica, tahoma, calibri, sans-serif',
             'color': '#3a3a3a'
           },
           ':focus': {
             'color': 'black'
           }
         },
         fields: {
           number: {
             selector: '#card-number',
             placeholder: 'card number'
           },
           cvv: {
             selector: '#cvv',
             placeholder: 'card security number'
           },
           expirationDate: {
             selector: '#expiration-date',
             placeholder: 'mm/yy'
           }
         }
       }).then(function (hf) {
         $('#my-sample-form').submit(function (event) {
           event.preventDefault();
           hf.submit({
             // Cardholder Name
             cardholderName: document.getElementById('card-holder-name').value,
             // Billing Address
             billingAddress: {
               streetAddress: document.getElementById('card-billing-address-street').value,      // address_line_1 - street
               extendedAddress: document.getElementById('card-billing-address-unit').value,       // address_line_2 - unit
               region: document.getElementById('card-billing-address-state').value,           // admin_area_1 - state
               locality: document.getElementById('card-billing-address-city').value,          // admin_area_2 - town / city
               postalCode: document.getElementById('card-billing-address-zip').value,           // postal_code - postal_code
               countryCodeAlpha2: document.getElementById('card-billing-address-country').value   // country_code - country
             }
           });
         });
       });
     }

A: You need to replace "order-ID" with an actual PayPal Order ID created for this checkout.
There are several ways to obtain one. See https://developer.paypal.com/docs/business/checkout/server-side-api-calls/#server-side-api-calls for how to call the orders API from your server to 'Create Order' and 'Capture Order'. You should use these to create two routes on your server that return only JSON data (no HTML or text)
As for how to fetch and commit this from the JS UI, see  https://developer.paypal.com/demo/checkout/#/pattern/server for some demo code.

Alternatively, you could try doing an HTML/JS-only integration (no server) like https://developer.paypal.com/demo/checkout/#/pattern/client


text:
Q: How to combine passport-jwt with ACL(access control list) pattern I am using passport-jwt. And I'm trying to implement an acl pattern in my system . There are some different roles in my system. And I want to control their access to some resource.
I think the common way to do that in token based authentication is to write a middleware for express.js which will validate the token and add a 'role' field to 'req.user'. And then mount another middleware to every route which will specify which roles can access them.
  So my question is , How to combine this approach with passport-jwt .
plus:
  The common way of using passport-jwt strategy :
  app.get('/myapi', passport.authenticate('jwt', {session: false}),
    function(req, res, next){ ...})

The common way I think in token based authentication:
app.use(function(req, res, next){
  token = extractToken(req)
  jwt.verify(token, key, function(err, decoded) {
    if (err) {
      return res.send(err);
    } else {
      users.findOne({userId: decoded.userId}, function(err, user){
        if(!user) res.send('unknown')
        else{
          req.user = user //in which include a role field.
                      // for example: user.role = 'user' | 'manager'
        }
      })
    }
  });
})

and at every route:

function checkRole(roles){
  return function (req, res, next) {
    if (req.session.user && roles.includes(req.user.role)) {
        next();
    } else {
        res.send(403);
    }
  }
}

app.get('/myapi', checkRole(['user']), function(req, res){
  ....
})

A: I figure out myself.
I write a middleware to do those things together:
/*middleware/acl.js */

export function checkRoleWithPassport(roles, passport, strategy, opts){
  return function(req, res, next){
    passport.authenticate(strategy, opts, function(err, user, info){
      if(err) res.status(403).send('forbidden')
      else if(!user) res.status(403).send('forbidden')
      else{
        if(roles.length == 0)
          next()
        else if(roles.includes(user.role))
          next()
        else
          res.status(403).send('forbidden')
      }
    })(req, res, next)
  }
}

/* route/index.js */
app.get('/myapi', checkRoleWithPassport(['manager'], passport,
  'jwt', {session, false}), function(req, res){
   ...
})   // this should only allow the 'manager' to access /myapi


text:
Q: How to get the referrer url of post request in php? I'm developing a php website, where users are allowed to add products with descriptions, images etc. I am receiving the user input using POST method. But, if the users know the form input names and the form's action link, they can send constant requests using javascript and jam my database.
So, if I could somehow get the URL from where the POST request is coming, I could prevent that. I could only input the information into database if the POST request was from my site's url.
I know this attack may also be prevented using captcha, but I want an alternative, mainly because captchas are painful.
Any way I can do it without using captchas? Perhaps sessions?

A: You could use the header to allow only post coming from your url:
    header('Access-Control-Allow-Origin: http://yoururl.com');

Cheers

A: You could check against the:
$_SERVER['HTTP_REFERER']

Variable, but this can be falsified so be careful.
You'd be better off using some hidden inputs that are set to values which must be equal to the set fields for the insert to happen (the name for this technique escapes me at the moment).
i.e.
<input type="text" id="areyouhuman" name="areyouhuman" value="123456001" />

Hide it with CSS:
#areyouhuman{
     display:none;
}

Hope that helps a little?
P.S. I HATE Captcha's too!

A: Probably the best way to provide security to your Forms are by adding a CSRF Token to your form (http://en.wikipedia.org/wiki/Cross-site_request_forgery).
How it works is every time you render a form you generate a pseudo random code and store it in a session variable and also put the same code as a hidden input in your form.
So when the user posts the form you can validate to see if the csrf tokens are the same.
There is another thread about this so you can maybe take a look at that
(How to properly add CSRF token using PHP)


text:
Q: What should be the argument type when using "in-package"? I have defined a package: (defpackage my-package (:use cl) (:export my-function)). When using in-package for that package, what should be the type of the argument given to in-package?
The Common Lisp HyperSpec says:

in-package name => package
Arguments and Values:
name---a string designator; not evaluated.
package---the package named by name.

I have tried the following:

*

*(in-package my-package) — ✓

*(in-package :my-package) — ✓

*(in-package #:my-package) — ✓

*(in-package "MY-PACKAGE") — ✓

All of the above appear to be valid. What is the difference between the above? Which of the above should I use?
In addition, I noticed this:

*

*(in-package 'my-package) — ✗
Error in SBCL:
; compiling file "/path/to/my-program.lisp" (written 12 MAR 2021 01:23:45 AM):
; compiling (IN-PACKAGE (QUOTE MY-PACKAGE))
; file: /path/to/my-program.lisp
; in: IN-PACKAGE 'MY-PACKAGE
;     (IN-PACKAGE 'MY-PACKAGE)
;
; caught ERROR:
;   (during macroexpansion of (IN-PACKAGE 'MY-PACKAGE))
;   'MY-PACKAGE is not a string designator

Why is it correct to use a keyword or uninterned symbol, but not a symbol?

A: The argument to in-package should be a string designator, which is a character, symbol, or string.
In your examples:

*

*my-package is a symbol

*:my-package is a keyword (automatically interned and exported, as discussed in your previous question)

*#:my-package is an uninterned symbol

*"MY-PACKAGE" is a string
All of these are string designators, but the expression 'my-package is not a string designator (it is not a symbol); it is shorthand for the expression (quote my-package). The expression (quote my-package) does evaluate to a symbol, but.... Recall that the documentation for in-package (which is quoted above in the posted question) stipulates that its argument is not evaluated. This is because in-package is a macro. With all of the versions which worked, a symbol (or a string) was passed to the macro, but with 'my-package the unevaluated form (quote my-package) was passed. This explains the error message shown above:

; compiling (IN-PACKAGE (QUOTE MY-PACKAGE))
; file: /path/to/my-program.lisp
; in: IN-PACKAGE 'MY-PACKAGE
;     (IN-PACKAGE 'MY-PACKAGE)
;
; caught ERROR:
;   (during macroexpansion of (IN-PACKAGE 'MY-PACKAGE))
;   'MY-PACKAGE is not a string designator

Note that by default the Lisp reader will upcase symbol names, but strings are case sensitive and when used as string designators must be appropriately cased.


text:
Q: Differential equation with one univariate function and several variables I have a functional equation where I need to find one univariate function which satisfies conditions involving two variables, for example, find a function $f$ which satisfies, for all $x,y$:
$$
x (x+y) f'(x)(f(y)-f(x)) = (x-y)(f(x)-f^2(x))
$$
How are such equations called? I would like to find literature, but I don't even know where to begin, and what terms to use. This is not an ODE, but also not a PDE.

A: The direct answer to your question is (as stated in the comments) that the proper term is "functional differential equation".  However, I would caution you about making a full frontal assault on your problem via the methods associated with FDE's.  There are many problems which can be phrased as FDE's, but trying to solve them via general FDE techniques is often very ineffective.
A somewhat general "meta-technique" for solving hard problems involving derivatives$^1$ is to reduce the problem by

*

*Finding a necessary (but perhaps not sufficient) ODE that your solution must solve.

*Determining the solution space of the ODE.

*Looking within the solution space of the ODE for the solution to your original problem.

You can apply this technique to your example problem as follows: Set $y=x+\epsilon$ and take $\epsilon\rightarrow 0$ to find a related ODE $$2x^2 f'(x)^2 = f(x)^2-f(x)$$ which your unknown function $f$ must solve.  This ODE is separable and can be solved analytically!  It is first order, so there is a 1-parameter solution space.  Check through the solution space to determine which solutions satisfy the original equation involving $x$ and $y$, and then you're done.
So you can see how this line of reasoning can substantially constrain your possible solutions.  I would advise trying to make reductions like this before wandering through FDE land too much.

1. For example, the calculus of variations and the method of characteristics can be thought of this way.


text:
Q: SQLPLUS query output to *.csv format using java I'm trying to convert SQLPLUS query output to *.csv format by using java code. On executing this spooler.sql on sqlplus getting error as ERROR at line 1:
ORA-00923: FROM keyword not found where expected
Can someone help me getting this resolved... knowing the fact that error is in spooler.sql file. Thanks in advance!!!
Following is my spooler.sql file code
SET LINESIZE 30000
SET FEEDBACK OFF
SET SHOW OFF
SET TRIMSPOOL ON
SET HEADING OFF
SET FEED OFF
SET ECHO OFF
SPOOL D:\CVS_test.csv
select regexp_substr (col_code, '[^,]+', 1,1) as "col_code_1" || ',' || regexp_substr (col_code, '[^,]+', 1,2) as "col_code_2" || ',' || col_status
from temp_table left join TEMP_MSTR on temp_table.temp_org=TEMP_MSTR.mstr_org and temp_table.temp_acct = TEMP_MSTR.mstr_acct;
SPOOL OFF
EXIT

A: After removing alias code is working
select regexp_substr (col_code, '[^,]+', 1,1)|| ',' || regexp_substr (col_code, '[^,]+', 1,2) || ',' || col_status from temp_table left join TEMP_MSTR on temp_table.temp_org=TEMP_MSTR.mstr_org and temp_table.temp_acct = TEMP_MSTR.mstr_acct;


text:
Q: SWTableViewCell cell scrollViewDidScroll message sent to deallocated instance I used SWTableViewCell a third-party library to implement the swipe the UITableviewcell to open two buttons(save and delete) and click on those particular actions will occur.
See the screen shot i attached

When Swipe State is open and scroll the TableView then it crashes the app with message:
[SearchCell cell] scrollViewDidScroll message sent to deallocated instance
Help me how to solve this crash issue
thanks in advance,

A: Don't know if you fixed this already but set the delegate to nil when deallocating.

A: SWTableViewCell.m
Please change dealloc to this
- (void)dealloc
 {
    _cellScrollView.delegate = nil;
     [self removeOldTableViewPanObserver];
 }

Everything will be OK


text:
Q: How to calculate megabytes? I'm doing an exercise. But I'm confused on how to calculate the megabytes
A "genome" can be represented as a sequence of "bases", each of which can be encoded as a two-bit value. Assuming that a megabit is 1,000,000 bits, how many megabytes are required to encode a 16 million base genome?

A: The line about "a megabit is 1,000,000 bits" seems to suggest:

*

*8 bits in a byte

*1,000 bytes in a kilobyte

*1,000 kilobytes in a megabyte

Therefore:

*

*1,000,000 bytes in a megabyte; or

*8,000,000 bits in a megabyte

A: 16mln * 2 bit / MB = 32 MBit / MB = 32 MB / 8MB = 32 / 8 = 4

A: 1 byte = 8 bits. Today, at least.


text:
Q: Blazor -> Page Login -> cannot execute _httpContextAccessor.HttpContext.SignInAsync() I cannot create functionals for login user(cookie authentication) on Blazor(server side)
For simple example create some code:
@using Microsoft.AspNetCore.Http;
@using Microsoft.AspNetCore.Authentication;
@using Microsoft.AspNetCore.Authentication.Cookies;
@using System.Security.Claims;
@inject IHttpContextAccessor _httpContextAccessor
@inject NavigationManager UriHelper

<form class="form-group">
    <input class="form-control" @bind="Name" type="text" />
    <input class="form-control" @bind="Password" type="password" />
    <button type="button" @onclick="@(()=>SbmForm())" class="btn btn-light">Sbm</button>
</form>

@code{
    [Parameter]
    public string Name { get; set; }
    public string Password { get; set; }

    public async Task SbmForm()
    {
        if (!String.IsNullOrEmpty(Name))
        {
            var claims = new[] { new Claim(ClaimTypes.Name, Name),
                new Claim(ClaimTypes.Role, "Admin") };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            try
            {
                await _httpContextAccessor.HttpContext.SignInAsync(
                  CookieAuthenticationDefaults.AuthenticationScheme,
                  new ClaimsPrincipal(identity),
                  new AuthenticationProperties
                  {
                      IsPersistent = true
                  });
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
            UriHelper.NavigateTo("/counter");
        }
    }
}

I get exception "The response headers cannot be modified because the response has already started."  on code "await _httpContextAccessor.HttpContext.SignInAsync..." What I need to do?

A: EDIT: As Henk Holtermann suggested in the comments, the best way would be to look into the official Blazor Templates with authentication (Create New Project => Blazor App => Create => Change Authentication). If you for some reason must work with HttpContext, work with the example in the link I provided:
The HttpContext should not be used in a Blazor server-side application, as there is usually no HttpContext available in SignalR applications.
A possible workaround is to create Login/Logout razor pages. The razor pages can access the HttpContext, sign in and then redirect to your actual home page. You can find a detailed description here.


text:
Q: Windows 7 SP1 SMB (Port 135/445) enabled by default upon install? I'm curious as over several years ever since I started researching about computer security, SMB has been a place where remote code execution happens the most on the windows OS. Especially With the recent vulnerability MS17-010 Eternal blue. Therefore I am wondering if the Windows 7 SP1 installer has port 135 and port 445 opened by default?

A: They're closed on the default install of the original ISOs. It will open up as soon as you start sharing a printer or a folder.
But consider that there are a lot of custom Windows around, and I think it's possible that some customizer enables files and print sharing (to make a public shared folder on their default install, for instance).


text:
Q: How to configure keepalive for MSSQL client which uses SQL Server Driver I have a client application which uses SQL Server Driver to connect with a remote MSSQL Server. (Installed SQL Server 2012 in client and Server machines)
Once connection is established and if the connection is idle, i could see keepalive signals being sent by server, which is ACKed by client and sent from client, which is ACKed by server. (Using wireshark)
By default, a keepalive signal is sent every 30 seconds by server as well as client.
If i change the value of "Keep Alive" option in "SQL Server Network Configuration -> Protocols for MSSQLSERVER -> TCP/IP -> Properties" to "20000", server starts sending keepalive signals every 20 seconds.

Similar way, how do i configure the keepalive timeout value for client?
Where the default value is set?
I tried changing "Keep Alive" option in "SQL Native Client 11.0 Configuration -> Client Protocols -> TCP/IP -> Properties", but it didn't affect the client keepalive time.


text:
Q: can I create an array of items in lightning event if Yes, how do I get this array in JS controller? <aura:event type="COMPONENT" description="AddOrderEvent">
    <aura:attribute name="DishInOrder" type="DishInOrder__c[]"/>
</aura:event>

  var newDishInOrder = component.get('v.NewDishInOrder');
  newDishInOrder.Dish__c = dish;
  var orderEvent = component.getEvent("addOrder");
  var orders = orderEvent.getParams("DishesInOrder");
  orders.push(newDishInOrder);
  orderEvent.setParams({
        "DishesInOrder": orders
  });
  console.log(newDishInOrder.Dish__c);
  orderEvent.fire();

This code does not work.

A: Looking at your code sample, you are not setting the right event parameter.
Your attribute is named DishInOrder in the event markyp but you are setting DishesInOrder in your JavaScript code:
orderEvent.setParams({
    DishesInOrder: orders
});


text:
Q: Qt Crypto - How to validate RSA key? I'm trying to use the Qt Cryptographic Architecture to generate public/private key pairs for nodes, and want to have a protocol in which nodes confirm that a message came from a given source (public key) by issuing a challenge to ensure they are the owners of the corresponding private key. I'm a little stuck on the actual syntax for QCA though ...
This should get me a private key, from which I can also get the public key:
QCA::KeyGenerator generator;
QCA::PrivateKey privateKey = generator.createRSA(1024);

Does QCA already have some sort of challenge protocol built in? If so, how can I use it? If not, how can I apply some of the standard cryptographic challenge protocols using these keys?  I'm really just trying to demo a simple security concept - I'm not looking for anything complicated or even particularly robust.
Also, this is a side question, but since I don't need encryption, should I be opting for DSA as opposed to RSA?

A: There are more than one of doing that. But since all clients already have their asymmetric key pairs you may deploy two-way TLS in establishing connection.
In this scheme both client and server allow establishing connection only, if they trust certificates (public keys) of each other. This guarantees client authentication and non-repudiation.
From your side you will need to provision server certificate to all clients and all client certificates to the server. To avoid dealing with certificate authorities, certificates could be self-signed.
QCA has examples for TLS client and server.