问:
Javascript Class: getter value when instantiating the class
I have a quick question - it was challenge in Hacker Rank - trying  to find an answer.

Question goes like this.

Console log should print the reverse order of numbers in the class.
Restrictions:
1. Class constructor should not be modified.
2. Console log statement should not be modified.

You can do anything else to make it working.

```<code>class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2
</code>```

Just curious to know how we can implement this?

答:
class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// jank
new HeyNumber().numbers.reverse().forEach((v, i, a) => {
  HeyNumber.prototype[i] = v
  HeyNumber.prototype.length = a.length
})

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2```

Body:
I have a quick question - it was challenge in Hacker Rank - trying  to find an answer.

Question goes like this.

Console log should print the reverse order of numbers in the class.
Restrictions:
1. Class constructor should not be modified.
2. Console log statement should not be modified.

You can do anything else to make it working.

class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2

Just curious to know how we can implement this?


来源: stackexchange

问:
Does the order of the comparison conditions matter when using OR operators in an IF function?
I'm trying to get a better understanding of the conditions within an IF statement. When I change the order of the conditions I receive a TypeError of undefined.

I receive a TypeError: Cannot read property 'length' of undefined when the order is changed to:

```<code>if (col === maze[row].length || row < 0 || col < 0 || row === maze.length) {
    return
}
</code>```

Does the order of the comparisons matter when using OR operators in an IF function? What is causing the TypeError when the order is written differently?

Working code base:

```<code>const maze = [
  [' ', ' ', ' ', '*', ' ', ' ', ' '],
  ['*', '*', ' ', '*', ' ', '*', ' '],
  [' ', ' ', ' ', ' ', ' ', ' ', ' '],
  [' ', '*', '*', '*', '*', '*', ' '],
  [' ', ' ', ' ', ' ', ' ', ' ', 'e'],
];

const solve = (maze, row = 0, col = 0, path = "") => {

  if (row < 0 || col < 0 || row === maze.length || col === maze[row].length) {
    return
  }

  // Base case
  if (maze[row][col] === "e") {
    return console.log(`Solved at (${row}, ${col})! Path to exit: ${path}`)

    // General case
  } else if (maze[row][col] === "*") {
    return
  }

  // Marker
  maze[row][col] = "*"

  // Right
  solve(maze, row, col + 1, path.concat("R"))

  // Down
  solve(maze, row + 1, col, path.concat("D"))

  // Left
  solve(maze, row, col - 1, path.concat("L"))

  // Up
  solve(maze, row - 1, col, path.concat("U"))

  // Remove marker
  maze[row][col] = " "
}

console.log(solve(maze));
</code>```

答:
Does the order of the comparisons matter when using OR operators in IF statements?

Yes, in addition to operator precedence, you also need to look at associativity and short-circuit evaluation. The || operator has left-to-right associativity, meaning that it will evaluate the expressions from left-to-right. Short-circuit evaluation means that further logical conditions are ignored once the result is already known.

What is causing the TypeError when the order is written differently?

Looking at your condition:

col === maze[row].length || row < 0 || col < 0 || row === maze.length
```

<p>Because the logical operations are evaluated from left-to-right, the first one to be evaluated is <code>col === maze[row].length</code>. When <code>row === maze.length</code>, then <code>col === maze[row].length</code> evaluates to <code>col === undefined.length</code>, which of course produces an error.</p>

<p>To fix this, you need to run this condition <em>after</em> first confirming that the index won't be out-of-bounds. A simple way to do this is:</p>

<pre class="lang-js prettyprint-override"><code>row < 0 || col < 0 || row === maze.length || col === maze[row].length
</code>```

Now, if any of the first three conditions is true, then JavaScript doesn't bother evaluating the rest, since it already knows that the result is true. Because of this, it doesn't crash anymore.

(Keep in mind that true || false === true, so as soon as you see true || then you don't even need to read the rest of the expression to know that the result will be true.)

Note that if you were using a language that doesn't use short-circuit evaluation, then you would instead have to use multiple if statements to run your conditions in the right order:

if (row < 0 || col < 0 || row === maze.length) {
    return
}

if (col === maze[row].length) {
    return
}
```

I often find myself starting out writing code like this while I think through the order in which the checks need to happen, and then afterwards I simplify it down into a single expression.

Hope that helps!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get a better understanding of the conditions within an IF statement. When I change the order of the conditions I receive a TypeError of undefined.

I receive a TypeError: Cannot read property 'length' of undefined when the order is changed to:

if (col === maze[row].length || row < 0 || col < 0 || row === maze.length) {
    return
}

Does the order of the comparisons matter when using OR operators in an IF function? What is causing the TypeError when the order is written differently?

Working code base:

const maze = [
  [' ', ' ', ' ', '*', ' ', ' ', ' '],
  ['*', '*', ' ', '*', ' ', '*', ' '],
  [' ', ' ', ' ', ' ', ' ', ' ', ' '],
  [' ', '*', '*', '*', '*', '*', ' '],
  [' ', ' ', ' ', ' ', ' ', ' ', 'e'],
];

const solve = (maze, row = 0, col = 0, path = "") => {

  if (row < 0 || col < 0 || row === maze.length || col === maze[row].length) {
    return
  }

  // Base case
  if (maze[row][col] === "e") {
    return console.log(`Solved at (${row}, ${col})! Path to exit: ${path}`)

    // General case
  } else if (maze[row][col] === "*") {
    return
  }

  // Marker
  maze[row][col] = "*"

  // Right
  solve(maze, row, col + 1, path.concat("R"))

  // Down
  solve(maze, row + 1, col, path.concat("D"))

  // Left
  solve(maze, row, col - 1, path.concat("L"))

  // Up
  solve(maze, row - 1, col, path.concat("U"))

  // Remove marker
  maze[row][col] = " "
}

console.log(solve(maze));

Body:
Does the order of the comparisons matter when using OR operators in IF statements?

Yes, in addition to operator precedence, you also need to look at associativity and short-circuit evaluation. The || operator has left-to-right associativity, meaning that it will evaluate the expressions from left-to-right. Short-circuit evaluation means that further logical conditions are ignored once the result is already known.

What is causing the TypeError when the order is written differently?

Looking at your condition:

col === maze[row].length || row < 0 || col < 0 || row === maze.length

Because the logical operations are evaluated from left-to-right, the first one to be evaluated is col === maze[row].length. When row === maze.length, then col === maze[row].length evaluates to col === undefined.length, which of course produces an error.

To fix this, you need to run this condition after first confirming that the index won't be out-of-bounds. A simple way to do this is:

row < 0 || col < 0 || row === maze.length || col === maze[row].length

Now, if any of the first three conditions is true, then JavaScript doesn't bother evaluating the rest, since it already knows that the result is true. Because of this, it doesn't crash anymore.

(Keep in mind that true || false === true, so as soon as you see true || then you don't even need to read the rest of the expression to know that the result will be true.)

Note that if you were using a language that doesn't use short-circuit evaluation, then you would instead have to use multiple if statements to run your conditions in the right order:

if (row < 0 || col < 0 || row === maze.length) {
    return
}

if (col === maze[row].length) {
    return
}

I often find myself starting out writing code like this while I think through the order in which the checks need to happen, and then afterwards I simplify it down into a single expression.

Hope that helps!


问:
How to convert JSON array to CSV using Node.js?
I want to convert json which has value array.
response.json

```<code>{
"rows": [
[
  "New Visitor",
  "(not set)",
  "(not set)",
  "0"
],
[
  "New Visitor",
  "(not set)",
  "(not set)",
  "mobile"
],
[
  "New Visitor",
  "(not set)",
  "(not set)",
  "mobile"
],
  [
    "New Visitor",
    "(not set)",
    "(not set)",
   "mobile",
  ]
 ]
}
</code>```

Now i want to convert this data into.
name.csv

```<code> "New Visitor","(not set)","(not set)","0"
 "New Visitor","(not set)","(not set)","mobile"
 "New Visitor","(not set)","(not set)","mobile"
 "New Visitor","(not set)","(not set)","mobile"
</code>```

Please give me suggetions using Node.js.

答:
I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, i think its the best module for this, works really well with objects, arrays, .. and its fast!

Install

```<code>npm i --save jsonexport
</code>```

Usage

```<code>const jsonexport = require('jsonexport');
const fs = require('fs');

jsonexport([{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "0"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile",
}], function(err, csv) {
  if (err) return console.error(err);
  fs.writeFile('output.csv', csv, function(err) {
    if (err) return console.error(err);
    console.log('output.csv saved');
  });
});
</code>```

https://github.com/kauegimenes/jsonexport

ContentLicense: CC BY-SA 3.0

Body:
I want to convert json which has value array.
response.json

{
"rows": [
[
  "New Visitor",
  "(not set)",
  "(not set)",
  "0"
],
[
  "New Visitor",
  "(not set)",
  "(not set)",
  "mobile"
],
[
  "New Visitor",
  "(not set)",
  "(not set)",
  "mobile"
],
  [
    "New Visitor",
    "(not set)",
    "(not set)",
   "mobile",
  ]
 ]
}

Now i want to convert this data into.
name.csv

 "New Visitor","(not set)","(not set)","0"
 "New Visitor","(not set)","(not set)","mobile"
 "New Visitor","(not set)","(not set)","mobile"
 "New Visitor","(not set)","(not set)","mobile"

Please give me suggetions using Node.js.

Body:
I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, i think its the best module for this, works really well with objects, arrays, .. and its fast!

Install

npm i --save jsonexport

Usage

const jsonexport = require('jsonexport');
const fs = require('fs');

jsonexport([{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "0"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile",
}], function(err, csv) {
  if (err) return console.error(err);
  fs.writeFile('output.csv', csv, function(err) {
    if (err) return console.error(err);
    console.log('output.csv saved');
  });
});

https://github.com/kauegimenes/jsonexport


问:
Apply function to tree structure in racket
I'm trying to apply a function to a tree in the form of a Map but not sure how to exactly go about it. Here's my attempt..

```<code>    (define-struct node (value left middle right)#:transparent)

(struct emptyNode () #:transparent) ; leaf node

(define T (node 1 (node 2 (node 5 (emptyNode) (emptyNode) (emptyNode)) (emptyNode) (emptyNode))
                            (node 3 (emptyNode) (node 6 (emptyNode) (node 8 (emptyNode) (emptyNode) (emptyNode)) (emptyNode)) (emptyNode))
                            (node 4 (emptyNode) (emptyNode) (node 7 (emptyNode) (emptyNode) (emptyNode)))))

;                   1
;                 / |  \
;               2   3   4
;              /    |     \
;             5     6      7
;                   |
;                   8

;f
;   a function, f, used in MaptoTree
(define (f b)
  (* b 2))

;MaptoTree
;    takes a function, f, and a tree structure, tree, as parameters.
;    it should then produce a new tree structure where f has been applied to each value in the original tree
(define (MaptoTree f T)
  (if (pair? T)
      ((map (lambda (x) (MaptoTree f x)) (rest T)))
      (f T)))
</code>```

edit: removed question about converting struct to list

答:
You must use the selectors for node, instead of pair?, rest, etc. We're using a struct to represent the tree, not a normal list.

After fixing that, we just have to traverse the tree applying the function on each value, building a new tree as we go - like this:

```<code>(define (MaptoTree f T)
  (if (emptyNode? T)
      (emptyNode)
      (node (f (node-value T))
            (MaptoTree f (node-left T))
            (MaptoTree f (node-middle T))
            (MaptoTree f (node-right T)))))
</code>```

Body:
I'm trying to apply a function to a tree in the form of a Map but not sure how to exactly go about it. Here's my attempt..

    (define-struct node (value left middle right)#:transparent)

(struct emptyNode () #:transparent) ; leaf node

(define T (node 1 (node 2 (node 5 (emptyNode) (emptyNode) (emptyNode)) (emptyNode) (emptyNode))
                            (node 3 (emptyNode) (node 6 (emptyNode) (node 8 (emptyNode) (emptyNode) (emptyNode)) (emptyNode)) (emptyNode))
                            (node 4 (emptyNode) (emptyNode) (node 7 (emptyNode) (emptyNode) (emptyNode)))))

;                   1
;                 / |  \
;               2   3   4
;              /    |     \
;             5     6      7
;                   |
;                   8

;f
;   a function, f, used in MaptoTree
(define (f b)
  (* b 2))

;MaptoTree
;    takes a function, f, and a tree structure, tree, as parameters.
;    it should then produce a new tree structure where f has been applied to each value in the original tree
(define (MaptoTree f T)
  (if (pair? T)
      ((map (lambda (x) (MaptoTree f x)) (rest T)))
      (f T)))

edit: removed question about converting struct to list

Body:
You must use the selectors for node, instead of pair?, rest, etc. We're using a struct to represent the tree, not a normal list.

After fixing that, we just have to traverse the tree applying the function on each value, building a new tree as we go - like this:

(define (MaptoTree f T)
  (if (emptyNode? T)
      (emptyNode)
      (node (f (node-value T))
            (MaptoTree f (node-left T))
            (MaptoTree f (node-middle T))
            (MaptoTree f (node-right T)))))


问:
Submit form after unbinding
```<code>$("#qwerq").submit(function (e){
    e.preventDefault();
    var check=0;

    if($("#firstName").val() == "") {
        check=1;
    }

    if(check!=1){
        $("#qwerq").unbind("submit") ;
        $("#qwerq").submit();
        //$("#qwerq").trigger('submit', [true]);
    }
});
</code>```

When the form is having id="qwerq" is as per needs and the submit gets unbinded, the form does not submit on its own.

I have tried using .submit() and .trigger("submit").  I have to manually click on submit again.

What should I add so that I don't have to click again?

答:
Instead of unbinding the events, why won't you just prevent submitting only on error?

if(check === 1) return false;
```

return false in jQuery's event handler means preventDefault and stopPropagation.

Title: Submit form after unbinding

Body:
$("#qwerq").submit(function (e){
    e.preventDefault();
    var check=0;

    if($("#firstName").val() == "") {
        check=1;
    }

    if(check!=1){
        $("#qwerq").unbind("submit") ;
        $("#qwerq").submit();
        //$("#qwerq").trigger('submit', [true]);
    }
});

When the form is having id="qwerq" is as per needs and the submit gets unbinded, the form does not submit on its own.

I have tried using .submit() and .trigger("submit").  I have to manually click on submit again.

What should I add so that I don't have to click again?

Body:
Instead of unbinding the events, why won't you just prevent submitting only on error?

if(check === 1) return false;

return false in jQuery's event handler means preventDefault and stopPropagation.


答:
You need to keep two things in mind.

Javascript evaluation is from left to right.

The OR || operator is short circuiting. Which means the first time it encounters a true expression it "short-circuits" i.e. bypasses all other expressions and just returns a true. This is basic boolean algebra.

In regards to your doubt about the TypeError: Cannot read property 'length' of undefined, either of maze[row] or maze is undefined. On running your snippet it turns out to be that maze[row] is the culprit here. This might be because since you do a row-1, in your code row might become negative causing maze[row] to be undefined.

If you turn the order to

```<code>if (row < 0 || col < 0 || col === maze[row].length || row === maze.length) {
    return
  }
</code>```

whenever row < 0 i.e negative the OR operation short circuits all the other expressions. Hence maze[row].length is never evaluated and no undefined behaviour is encountered.

Title: Does the order of the comparison conditions matter when using OR operators in an IF function?

Body:
You need to keep two things in mind.

Javascript evaluation is from left to right.

The OR || operator is short circuiting. Which means the first time it encounters a true expression it "short-circuits" i.e. bypasses all other expressions and just returns a true. This is basic boolean algebra.

In regards to your doubt about the TypeError: Cannot read property 'length' of undefined, either of maze[row] or maze is undefined. On running your snippet it turns out to be that maze[row] is the culprit here. This might be because since you do a row-1, in your code row might become negative causing maze[row] to be undefined.

If you turn the order to

if (row < 0 || col < 0 || col === maze[row].length || row === maze.length) {
    return
  }

whenever row < 0 i.e negative the OR operation short circuits all the other expressions. Hence maze[row].length is never evaluated and no undefined behaviour is encountered.


问:
Getting AttributeError: __enter__ when using Microphone from Speech Recognizer
The code is below. As I researched the documention Speech_Recognision must be installed if we use Microphone. So I installed it but still i have this error.

```<code>def recordAudio():

r = sr.Recognizer()

with sr.Microphone as source:
    print('I am listening to you sir.')
    audio = r.listen(source)
    data = ''

try:
    data = r.recognize_google(audio)
    print('You said: ' + data)
except sr.UnknownValueError:
    print('Voice cannot be recognized.')
except sr.RequestError as e:
    print('Req results:' + e)

return data
</code>```

line 54, in recordAudio
    with sr.Microphone as source:
AttributeError: __enter__

答:
An AttributeError: __enter__ means you are attempting to enter a context manager block with an object which does not support the context manager protocol; it does not have a __enter__ method.

Specifically, you are attempting to open the sr.Microphone class in you with statement. As per the documentation, you need to provide an instance sr.Microphone() to the context manager instead.

```<code>with sr.Microphone() as source:
    ...
</code>```

Body:
The code is below. As I researched the documention Speech_Recognision must be installed if we use Microphone. So I installed it but still i have this error.

def recordAudio():

r = sr.Recognizer()

with sr.Microphone as source:
    print('I am listening to you sir.')
    audio = r.listen(source)
    data = ''

try:
    data = r.recognize_google(audio)
    print('You said: ' + data)
except sr.UnknownValueError:
    print('Voice cannot be recognized.')
except sr.RequestError as e:
    print('Req results:' + e)

return data

line 54, in recordAudio
    with sr.Microphone as source:
AttributeError: __enter__

Body:
An AttributeError: __enter__ means you are attempting to enter a context manager block with an object which does not support the context manager protocol; it does not have a __enter__ method.

Specifically, you are attempting to open the sr.Microphone class in you with statement. As per the documentation, you need to provide an instance sr.Microphone() to the context manager instead.

with sr.Microphone() as source:
    ...


问:
Navigation Properties on Join Tables in Entity Framework
So I have a table in my SQL database:

```CompanyRelationships
--------------------
ID
CompanyID
RelatedCompanyID
PermissionGroupID
```

Which defines when a company allows access to it's records to another company.  The "CompanyID" is the company that is granting access, the "RelatedCompanyID" is the company that is getting the access.

Yes, two records could exist for the same two companies (each granting access to the other)

The problem is when I generate the entity model from the db (In Visual Studio 2010), the navigation properties I get are not exactly helpful as to which is which.  I get:

```Company
Company1
UserGroup```

UserGroup is of course obvious, but I would like to know which company reference is which, as that is kind of important.  I'm sure I could test it and find out, but then I would have to retest to be sure every time I regenerated from the database.  Is there a way to force the naming of the navigation property to be that of the FK field and not the entity it is linked to?

答:
You Could always Click on the Navigational Property on the Entity in the Model Browser, and look up the Properties Window. The Window Shows the Association Name (created when adding Table relationships in database). Once you identify the Relation, you could always rename the Navigational Property Name to a name of your choice.

Example, Clicking "Company1" Navigational property in the Entity Diagram would show you a relationship name as "Company_Id_to_Related_Company_Id" (or whatever the name is). Once you know what it means, you can rename the Navigational Property to a meaningful name such as "MasterCompany".

Body:
So I have a table in my SQL database:

CompanyRelationships
--------------------
ID
CompanyID
RelatedCompanyID
PermissionGroupID

Which defines when a company allows access to it's records to another company.  The "CompanyID" is the company that is granting access, the "RelatedCompanyID" is the company that is getting the access.

Yes, two records could exist for the same two companies (each granting access to the other)

The problem is when I generate the entity model from the db (In Visual Studio 2010), the navigation properties I get are not exactly helpful as to which is which.  I get:

Company
Company1
UserGroup

UserGroup is of course obvious, but I would like to know which company reference is which, as that is kind of important.  I'm sure I could test it and find out, but then I would have to retest to be sure every time I regenerated from the database.  Is there a way to force the naming of the navigation property to be that of the FK field and not the entity it is linked to?


问:
How do I index through a dictionary within a dictionary?
I have a dictionary within a dictionary with this default structure:

```<code>meta_data.setdefault(date_str, {'games': 0, 'wins': 0})
</code>```

After indexing through a spreadsheet to calculate the totals per date I get a dictionary with key,values like so:

```<code>'04/01/2020': {'games': 7, 'wins': 2.0}
</code>```

I want to calculate the win ratio, and so I (think I) need to index through each date.  The calculation needs to access both key,values from the sub-dictionary.  I know this is super basic....thanks for the help.

答:
You can do something like dictionary_name["key1"]["key2"] to access any value from the dictionary.

For example: dictionary_name['04/01/2020']['games']

If you want to do this as a loop:

for key in dictionary_name:
    value = dictionary_name[key]
```

<p>If you want to do a loop over a multidimensional dictionary:</p>

<pre class="lang-py prettyprint-override"><code>for key1 in dictionary_name:
    for key2 in dictionary_name[key1]:
        value = dictionary_name[key2]
</code>```

Coming to your specific example, I think this is what you are trying to do:

games = 0
wins = 0
for date in dictionary_name:
    games += dictionary_name[date]['games']
    wins += dictionary_name[date]['wins']
win_ratio = wins / games
win_percentage = win_ratio * 100
# from here, you can do your calculations as needed
```

I hope this helps! Comment if you have any questions.

Body:
I have a dictionary within a dictionary with this default structure:

meta_data.setdefault(date_str, {'games': 0, 'wins': 0})

After indexing through a spreadsheet to calculate the totals per date I get a dictionary with key,values like so:

'04/01/2020': {'games': 7, 'wins': 2.0}

I want to calculate the win ratio, and so I (think I) need to index through each date.  The calculation needs to access both key,values from the sub-dictionary.  I know this is super basic....thanks for the help.

Body:
You can do something like dictionary_name["key1"]["key2"] to access any value from the dictionary.

For example: dictionary_name['04/01/2020']['games']

If you want to do this as a loop:

for key in dictionary_name:
    value = dictionary_name[key]

If you want to do a loop over a multidimensional dictionary:

for key1 in dictionary_name:
    for key2 in dictionary_name[key1]:
        value = dictionary_name[key2]

Coming to your specific example, I think this is what you are trying to do:

games = 0
wins = 0
for date in dictionary_name:
    games += dictionary_name[date]['games']
    wins += dictionary_name[date]['wins']
win_ratio = wins / games
win_percentage = win_ratio * 100
# from here, you can do your calculations as needed

I hope this helps! Comment if you have any questions.


问:
Ruby on rails rails-devise-roles example app
I found this example Ruby on rails app showcasing devise gem and it's use with roles.

In the readme they mention that:

an ordinary user can’t change their role

an ordinary user can see (and edit) their own user profile

However, looking at the users controller

class UsersController < ApplicationController
  before_action :authenticate_user!
  before_action :admin_only, :except => :show

  def show
    @user = User.find(params[:id])
    unless current_user.admin?
      unless @user == current_user
        redirect_to root_path, :alert => "Access denied."
      end
    end
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(secure_params)
      redirect_to users_path, :notice => "User updated."
    else
      redirect_to users_path, :alert => "Unable to update user."
    end
  end

  def admin_only
    unless current_user.admin?
      redirect_to root_path, :alert => "Access denied."
    end
  end

  def secure_params
    params.require(:user).permit(:role)
  end

end
```

We can see that all actions are allowed only for admin users, except show, where the current signed in user is being tested if he is the @user we are trying to fetch/show. That makes sense for this part of the readme "an ordinary user can see their own user profile".

What I don't get is, the readme says user can also edit their own profile, but the update action is only allowed to be executed by admin user (and event then, the admin is able to only change user's role? permit(:role)).

答:
I suggest following a more up-to-date guide on this sort of thing:
https://altalogy.com/blog/rails-6-user-accounts-with-3-types-of-roles/

The repo you linked was last updated 4 years ago. I attempted to pull down the repo and test it locally for these points you raised and I ran into way too many issues trying to do so. Look elsewhere for guidance on this.

Edit: I did take a look through the code though and I'm not entirely sure how this app does what the README says it does.

Body:
I found this example Ruby on rails app showcasing devise gem and it's use with roles.

In the readme they mention that:

an ordinary user can’t change their role

an ordinary user can see (and edit) their own user profile

However, looking at the users controller

class UsersController < ApplicationController
  before_action :authenticate_user!
  before_action :admin_only, :except => :show

  def show
    @user = User.find(params[:id])
    unless current_user.admin?
      unless @user == current_user
        redirect_to root_path, :alert => "Access denied."
      end
    end
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(secure_params)
      redirect_to users_path, :notice => "User updated."
    else
      redirect_to users_path, :alert => "Unable to update user."
    end
  end

  def admin_only
    unless current_user.admin?
      redirect_to root_path, :alert => "Access denied."
    end
  end

  def secure_params
    params.require(:user).permit(:role)
  end

end

We can see that all actions are allowed only for admin users, except show, where the current signed in user is being tested if he is the @user we are trying to fetch/show. That makes sense for this part of the readme "an ordinary user can see their own user profile".

What I don't get is, the readme says user can also edit their own profile, but the update action is only allowed to be executed by admin user (and event then, the admin is able to only change user's role? permit(:role)).


问:
How to pass js argument into css style
I'm creating a web service with Angular and Spring Boot and I'm using cdkDrag to place some images around the workspace. I want to keep the images on the same places after refreshing browser. After every drag and drop, I'm saving every image coordinates in the database. When I refresh the browser, I have previous coordinates storaged in Router class:

```<code>export class Router implements Node {

  id: string;

  x: number;
  y: number;

  constructor() {
  }
}
</code>```

Some html:

```<code>  <mat-sidenav-content>
    <a *ngFor="let router of routers">
      <img id="node" src="assets/images/router.png" cdkDrag (click)="updateParameters($event, router)">
    </a>
  </mat-sidenav-content>'
</code>```

And here, I want to set margin-left as router.x + "px" and margin-top as router.y. Is it possible? I tried style="margin-left: {{router.x}}px" but it does not work.

答:
You need to use ngStyle.

An attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional . suffix (such as 'top.px', 'font-style.em'). The value is an expression to be evaluated. The resulting non-null value, expressed in the given unit, is assigned to the given style property. If the result of evaluation is null, the corresponding style is removed.

```<code><some-element [ngStyle]="{'margin-left': router.x + 'px'}">...</some-element>
</code>```

Title: How to pass js argument into css style

Body:
I'm creating a web service with Angular and Spring Boot and I'm using cdkDrag to place some images around the workspace. I want to keep the images on the same places after refreshing browser. After every drag and drop, I'm saving every image coordinates in the database. When I refresh the browser, I have previous coordinates storaged in Router class:

export class Router implements Node {

  id: string;

  x: number;
  y: number;

  constructor() {
  }
}

Some html:

  <mat-sidenav-content>

  </mat-sidenav-content>'

And here, I want to set margin-left as router.x + "px" and margin-top as router.y. Is it possible? I tried style="margin-left: {{router.x}}px" but it does not work.

Body:
You need to use ngStyle.

An attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional . suffix (such as 'top.px', 'font-style.em'). The value is an expression to be evaluated. The resulting non-null value, expressed in the given unit, is assigned to the given style property. If the result of evaluation is null, the corresponding style is removed.

<some-element [ngStyle]="{'margin-left': router.x + 'px'}">...</some-element>


问:
Mockito Unit Tests stubbing a method throws NullPointerException
I am writing some unit tests for the run() method in the below class

```<code>public class TopicProcessor implements Runnable {

     private final KafkaConfig config;
     private final String inTopic;
     private final String outTopic;
     private final String inBroker;
     private final String outBroker;
     private KafkaConsumer<Long, byte[]> kafkaConsumer;
     private KafkaProducer<Long, byte[]> kafkaProducer;

     public void setKafkaConsumer(KafkaConsumer<Long, byte[]> kafkaConsumer) {
         this.kafkaConsumer = kafkaConsumer;
     }

     public void setKafkaProducer(KafkaProducer<Long, byte[]> kafkaProducer) {
         this.kafkaProducer = kafkaProducer;
     }

     public TopicProcessor(String topicKey, KafkaConfig config) {
         this.config = config;
         Map<String, Map<String, String>> mapping = this.config.getMapping(topicKey);
         this.inTopic = mapping.get("in").get("topic");
         this.outTopic = mapping.get("out").get("topic");
         this.inBroker = mapping.get("in").get("broker");
         this.outBroker = mapping.get("out").get("broker");
     }

     @Override
     public void run() {
         long now;
         getKafkaConsumer().subscribe(Collections.singletonList(this.inTopic));
         while (true) {
             ConsumerRecords<Long, byte[]> records = getKafkaConsumer().poll(Duration.ofMillis(100));
             meterInfo("consumer.received." + this.inTopic, records.count());
             for (ConsumerRecord<Long, byte[]> record : records) {
                 now = currentTimeMillis();
                 histogram("consumer.latency." + this.inTopic, now - record.timestamp());
                 getKafkaProducer().send(new ProducerRecord<>(this.outTopic, record.key(), record.value()));
                 meterInfo("publisher.sent." + this.outTopic);
             }
         }
     }
</code>```

Basically, In the run() method, I am subscribed to a topic, polled all records using KafkaConsumer.poll() method and for each record, I am sending the record using KafkaProducer.send() method.

I have to write unit tests for below scenario : -

Test that KafkaConsumer.poll() method called one time

Test that KafkaProducer.send() method called one time

Below is my Test method: -

```<code>@Test
public void test(){
    //Mocks
    KafkaConsumer<Long, byte[]> consumerMock = mock(KafkaConsumer.class);
    KafkaProducer<Long, byte[]> producerMock = mock(KafkaProducer.class);

    //test data
    Map<TopicPartition, List<ConsumerRecord<Long, byte[]>>> records = new LinkedHashMap<>();
records.put(new TopicPartition("topic", 0), new ArrayList<>());
    ConsumerRecords<Long, byte[]> consumerRecords = new ConsumerRecords<>(records);

    ProducerRecord<Long, byte[]> producer_record = new ProducerRecord<Long, byte[]>("topic", 1, 0L, 1L, new byte[]{'a'});

    //object creation to call the method
    KafkaConfig kafkaConfig = new KafkaConfig(yamlConfig);
    TopicProcessor topicProcessor = new TopicProcessor("pacing_record", kafkaConfig);

    //stubbing Kafka methods - poll and send
    when(consumerMock.poll(Duration.ofMillis(anyInt()))).thenReturn(consumerRecords);
    doReturn("sent").when(producerMock.send(producer_record, null));

    //Injecting mocks thorugh setter method
    topicProcessor.setKafkaConsumer(consumerMock);
    topicProcessor.setKafkaProducer(producerMock);

    //calling a class method run() from above class to verify that kafka methods are called
    topicProcessor.run();

    verify(consumerMock, times(1)).poll(Duration.ofMillis(anyInt()));

}
</code>```

Below line in the above test method throws NullPointerException

```<code>    when(kafkaConsumerMock.poll(Duration.ofMillis(anyInt()))).thenReturn(consumerRecords);
</code>```

Anyone know how to correctly stub the method and verify it is called or not?

答:
```<code>when(kafkaConsumerMock.poll(Duration.ofMillis(anyInt())))
</code>```

This is an incorrect usage of Mockito. The any* methods should only be used as the direct parameters to the mocked method.

I think what you're trying to say here is "for any duration, I don't care how long it is". If so, you can express that as:

```<code>when(kafkaConsumerMock.poll(any(Duration.class))
</code>```

or

```<code>when(kafkaConsumerMock.poll(any())
</code>```

if there is no ambiguous overload.

Similarly, to verify:

```<code>verify(kafkaConsumerMock, times(1)).poll(any(Duration.class))
</code>```

Body:
I am writing some unit tests for the run() method in the below class

public class TopicProcessor implements Runnable {

     private final KafkaConfig config;
     private final String inTopic;
     private final String outTopic;
     private final String inBroker;
     private final String outBroker;
     private KafkaConsumer<Long, byte[]> kafkaConsumer;
     private KafkaProducer<Long, byte[]> kafkaProducer;

     public void setKafkaConsumer(KafkaConsumer<Long, byte[]> kafkaConsumer) {
         this.kafkaConsumer = kafkaConsumer;
     }

     public void setKafkaProducer(KafkaProducer<Long, byte[]> kafkaProducer) {
         this.kafkaProducer = kafkaProducer;
     }

     public TopicProcessor(String topicKey, KafkaConfig config) {
         this.config = config;
         Map<String, Map<String, String>> mapping = this.config.getMapping(topicKey);
         this.inTopic = mapping.get("in").get("topic");
         this.outTopic = mapping.get("out").get("topic");
         this.inBroker = mapping.get("in").get("broker");
         this.outBroker = mapping.get("out").get("broker");
     }

     @Override
     public void run() {
         long now;
         getKafkaConsumer().subscribe(Collections.singletonList(this.inTopic));
         while (true) {
             ConsumerRecords<Long, byte[]> records = getKafkaConsumer().poll(Duration.ofMillis(100));
             meterInfo("consumer.received." + this.inTopic, records.count());
             for (ConsumerRecord<Long, byte[]> record : records) {
                 now = currentTimeMillis();
                 histogram("consumer.latency." + this.inTopic, now - record.timestamp());
                 getKafkaProducer().send(new ProducerRecord<>(this.outTopic, record.key(), record.value()));
                 meterInfo("publisher.sent." + this.outTopic);
             }
         }
     }

Basically, In the run() method, I am subscribed to a topic, polled all records using KafkaConsumer.poll() method and for each record, I am sending the record using KafkaProducer.send() method.

I have to write unit tests for below scenario : -

Test that KafkaConsumer.poll() method called one time

Test that KafkaProducer.send() method called one time

Below is my Test method: -

@Test
public void test(){
    //Mocks
    KafkaConsumer<Long, byte[]> consumerMock = mock(KafkaConsumer.class);
    KafkaProducer<Long, byte[]> producerMock = mock(KafkaProducer.class);

    //test data
    Map<TopicPartition, List<ConsumerRecord<Long, byte[]>>> records = new LinkedHashMap<>();
records.put(new TopicPartition("topic", 0), new ArrayList<>());
    ConsumerRecords<Long, byte[]> consumerRecords = new ConsumerRecords<>(records);

    ProducerRecord<Long, byte[]> producer_record = new ProducerRecord<Long, byte[]>("topic", 1, 0L, 1L, new byte[]{'a'});

    //object creation to call the method
    KafkaConfig kafkaConfig = new KafkaConfig(yamlConfig);
    TopicProcessor topicProcessor = new TopicProcessor("pacing_record", kafkaConfig);

    //stubbing Kafka methods - poll and send
    when(consumerMock.poll(Duration.ofMillis(anyInt()))).thenReturn(consumerRecords);
    doReturn("sent").when(producerMock.send(producer_record, null));

    //Injecting mocks thorugh setter method
    topicProcessor.setKafkaConsumer(consumerMock);
    topicProcessor.setKafkaProducer(producerMock);

    //calling a class method run() from above class to verify that kafka methods are called
    topicProcessor.run();

    verify(consumerMock, times(1)).poll(Duration.ofMillis(anyInt()));

}

Below line in the above test method throws NullPointerException

    when(kafkaConsumerMock.poll(Duration.ofMillis(anyInt()))).thenReturn(consumerRecords);

Anyone know how to correctly stub the method and verify it is called or not?

Body:
when(kafkaConsumerMock.poll(Duration.ofMillis(anyInt())))

This is an incorrect usage of Mockito. The any* methods should only be used as the direct parameters to the mocked method.

I think what you're trying to say here is "for any duration, I don't care how long it is". If so, you can express that as:

when(kafkaConsumerMock.poll(any(Duration.class))

or

when(kafkaConsumerMock.poll(any())

if there is no ambiguous overload.

Similarly, to verify:

verify(kafkaConsumerMock, times(1)).poll(any(Duration.class))


问:
how to change the format of the columns of csv exported- laravel excel
I exported a csv file with laravel-excel 3.1 and when reviewing the values are enclosed in quotes, so they are exported as strings, but I need it to be in type number

Exported csv file:

```<code>"ano_plantacion","zona","sitio","manejo","sup_ha","codigo","rpend"
"2018","87","3","10","30.69","2042201801",""
"2017","87","3","10","14.86","2042201701",""
</code>```

What I want or should be:

```<code>ano_plantacion,zona,sitio,manejo,sup_ha,codigo,rpend
2018,87,3,10,30.69,2042201801,
2017,87,3,10,14.86,2042201701,
</code>```

Class SuperImport:

```<code><?php

namespace App\Exports;

use App\Super;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

class SuperExport implements FromCollection,WithHeadings, WithColumnFormatting
{
    use Exportable;

    protected $superficie;

    public function __construct($superficie = null)
    {
        $this->superficie = $superficie;
    }
    public function headings(): array
    {
        return [
            'ano_plantacion',
            'zona',
            'sitio',
            'manejo',
            'sup_ha',
            'codigo',
            'rpend',

        ];
    }

    public function columnFormats(): array
    {
        return [
            'A' => NumberFormat::FORMAT_GENERAL,
            'B' => NumberFormat::FORMAT_GENERAL,
            'C' => NumberFormat::FORMAT_GENERAL,
            'D' => NumberFormat::FORMAT_GENERAL,
            'E' => NumberFormat::FORMAT_GENERAL,
            'F' => NumberFormat::FORMAT_GENERAL,
            'G' => NumberFormat::FORMAT_GENERAL,
        ];
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return $this->superficie ?: Super::all();
    }
}
</code>```

Controller:

```<code>$super = Super::select('ano_plantacion','zona','sitio', 'manejo','sup_ha','codigo','rpend')->get();
Excel::store( new SuperExport($super), 'export/Super.csv' );
</code>```

It is assumed that with the columnFormats() method it is possible to change the format, but I don't see in the documentation what format is available, and when executing the code the problem continues.

Help pls :(

答:
I found another solution, instead of using laravel excel, I tried another library: https://github.com/rap2hpoutre/fast-excel

So was my controller:

```<code>  (new FastExcel(Super::all()))->export(storage_path('app/export/SuperFast.csv'), function ($super) {
      return [
          'ano_plantacion' => $super->ano_plantacion,
          'zona' => $super->zona,
          'sitio' => $super->sitio,
          'manejo' => $super->manejo,
          'sup_ha' => $super->sup_ha,
          'codigo' => $super->codigo,
          'repend' => $super->repend,
      ];
  });
</code>```

This is how my csv was: http://prntscr.com/squjh5

Body:
I exported a csv file with laravel-excel 3.1 and when reviewing the values are enclosed in quotes, so they are exported as strings, but I need it to be in type number

Exported csv file:

"ano_plantacion","zona","sitio","manejo","sup_ha","codigo","rpend"
"2018","87","3","10","30.69","2042201801",""
"2017","87","3","10","14.86","2042201701",""

What I want or should be:

ano_plantacion,zona,sitio,manejo,sup_ha,codigo,rpend
2018,87,3,10,30.69,2042201801,
2017,87,3,10,14.86,2042201701,

Class SuperImport:

<?php

namespace App\Exports;

use App\Super;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

class SuperExport implements FromCollection,WithHeadings, WithColumnFormatting
{
    use Exportable;

    protected $superficie;

    public function __construct($superficie = null)
    {
        $this->superficie = $superficie;
    }
    public function headings(): array
    {
        return [
            'ano_plantacion',
            'zona',
            'sitio',
            'manejo',
            'sup_ha',
            'codigo',
            'rpend',

        ];
    }

    public function columnFormats(): array
    {
        return [
            'A' => NumberFormat::FORMAT_GENERAL,
            'B' => NumberFormat::FORMAT_GENERAL,
            'C' => NumberFormat::FORMAT_GENERAL,
            'D' => NumberFormat::FORMAT_GENERAL,
            'E' => NumberFormat::FORMAT_GENERAL,
            'F' => NumberFormat::FORMAT_GENERAL,
            'G' => NumberFormat::FORMAT_GENERAL,
        ];
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return $this->superficie ?: Super::all();
    }
}

Controller:

$super = Super::select('ano_plantacion','zona','sitio', 'manejo','sup_ha','codigo','rpend')->get();
Excel::store( new SuperExport($super), 'export/Super.csv' );

It is assumed that with the columnFormats() method it is possible to change the format, but I don't see in the documentation what format is available, and when executing the code the problem continues.

Help pls :(

Body:
I found another solution, instead of using laravel excel, I tried another library: https://github.com/rap2hpoutre/fast-excel

So was my controller:

  (new FastExcel(Super::all()))->export(storage_path('app/export/SuperFast.csv'), function ($super) {
      return [
          'ano_plantacion' => $super->ano_plantacion,
          'zona' => $super->zona,
          'sitio' => $super->sitio,
          'manejo' => $super->manejo,
          'sup_ha' => $super->sup_ha,
          'codigo' => $super->codigo,
          'repend' => $super->repend,
      ];
  });

This is how my csv was: http://prntscr.com/squjh5


问:
App is crashing on only iOS 13 in the background mode
The app is crashing only on iOS 13 and when I saw the detailed report, Reports are mentioning the app was in the background when it was crashed. No reference of the line of code mentioned in the crash logs where I can find the line which is causing the crash. Please suggest if anyone else also face such type of problem ever.

Crashed: com.apple.main-thread

EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000f5e5f9c3c

```<code>Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x1aed79d10 objc_opt_respondsToSelector + 20
1  Foundation                     0x1af423588 _NSDescriptionWithStringProxyFunc + 56
2  CoreFoundation                 0x1aefdc534 __CFStringAppendFormatCore + 7960
3  CoreFoundation                 0x1aefddb10 _CFStringCreateWithFormatAndArgumentsAux2 + 152
4  Foundation                     0x1af2f63c4 +[NSString stringWithFormat:] + 72
5  UIKitCore                      0x1b30d95d8 -[_UIBackgroundTaskInfo description] + 144
6  UIKitCore                      0x1b30e302c _fireBackgroundExpirationHandlers + 1068
7  UIKitCore                      0x1b30e2b2c -[UIApplication workspaceNoteAssertionExpirationImminent:] + 136
8  FrontBoardServices             0x1b41adc50 __45-[FBSUIApplicationWorkspaceShim setDelegate:]_block_invoke_3 + 48
9  libdispatch.dylib              0x1aed01524 _dispatch_client_callout + 16
10 libdispatch.dylib              0x1aecaa434 _dispatch_block_invoke_direct$VARIANT$mp + 224
11 FrontBoardServices             0x1b41fe440 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 40
12 FrontBoardServices             0x1b41fe10c -[FBSSerialQueue _queue_performNextIfPossible] + 404
13 FrontBoardServices             0x1b41fe634 -[FBSSerialQueue _performNextFromRunLoopSource] + 28
14 CoreFoundation                 0x1aefb9b64 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
15 CoreFoundation                 0x1aefb9abc __CFRunLoopDoSource0 + 80
16 CoreFoundation                 0x1aefb9244 __CFRunLoopDoSources0 + 184
17 CoreFoundation                 0x1aefb4274 __CFRunLoopRun + 788
18 CoreFoundation                 0x1aefb3c34 CFRunLoopRunSpecific + 424
19 GraphicsServices               0x1b90fd38c GSEventRunModal + 160
20 UIKitCore                      0x1b30e622c UIApplicationMain + 1932
21 MagicBox Learning              0x104644058 main + 14 (main.m:14)
22 libdyld.dylib                  0x1aee3b800 start + 4

</code>```

This is what I am doing in beginBackgroundTask(expirationHandler:). Please correct what wrong I am doing here.

```<code>
- (void)applicationDidEnterBackground:(UIApplication *)application {

    self.isAppLaunched      =   NO;

    _bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you
        // stopped or ending the task outright.

        [self cancelAllProductDownloadsInProgress];

        dispatch_async(_MAGICBOX.databaseQueue, ^{
            [application endBackgroundTask:self.bgTask];
            self.bgTask = UIBackgroundTaskInvalid;
        });
    }];

    //Dismiss keyboard
    [self.window endEditing:YES];
}

</code>```

答: The key line is workspaceNoteAssertionExpirationImminent. You are asking for a background task (probably with beginBackgroundTask(expirationHandler:)), and when it expires you are failing to do the correct cleanup. Therefore your app is punished by being killed dead.

Body:
The app is crashing only on iOS 13 and when I saw the detailed report, Reports are mentioning the app was in the background when it was crashed. No reference of the line of code mentioned in the crash logs where I can find the line which is causing the crash. Please suggest if anyone else also face such type of problem ever.

Crashed: com.apple.main-thread

EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000f5e5f9c3c

Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x1aed79d10 objc_opt_respondsToSelector + 20
1  Foundation                     0x1af423588 _NSDescriptionWithStringProxyFunc + 56
2  CoreFoundation                 0x1aefdc534 __CFStringAppendFormatCore + 7960
3  CoreFoundation                 0x1aefddb10 _CFStringCreateWithFormatAndArgumentsAux2 + 152
4  Foundation                     0x1af2f63c4 +[NSString stringWithFormat:] + 72
5  UIKitCore                      0x1b30d95d8 -[_UIBackgroundTaskInfo description] + 144
6  UIKitCore                      0x1b30e302c _fireBackgroundExpirationHandlers + 1068
7  UIKitCore                      0x1b30e2b2c -[UIApplication workspaceNoteAssertionExpirationImminent:] + 136
8  FrontBoardServices             0x1b41adc50 __45-[FBSUIApplicationWorkspaceShim setDelegate:]_block_invoke_3 + 48
9  libdispatch.dylib              0x1aed01524 _dispatch_client_callout + 16
10 libdispatch.dylib              0x1aecaa434 _dispatch_block_invoke_direct$VARIANT$mp + 224
11 FrontBoardServices             0x1b41fe440 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 40
12 FrontBoardServices             0x1b41fe10c -[FBSSerialQueue _queue_performNextIfPossible] + 404
13 FrontBoardServices             0x1b41fe634 -[FBSSerialQueue _performNextFromRunLoopSource] + 28
14 CoreFoundation                 0x1aefb9b64 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
15 CoreFoundation                 0x1aefb9abc __CFRunLoopDoSource0 + 80
16 CoreFoundation                 0x1aefb9244 __CFRunLoopDoSources0 + 184
17 CoreFoundation                 0x1aefb4274 __CFRunLoopRun + 788
18 CoreFoundation                 0x1aefb3c34 CFRunLoopRunSpecific + 424
19 GraphicsServices               0x1b90fd38c GSEventRunModal + 160
20 UIKitCore                      0x1b30e622c UIApplicationMain + 1932
21 MagicBox Learning              0x104644058 main + 14 (main.m:14)
22 libdyld.dylib                  0x1aee3b800 start + 4

This is what I am doing in beginBackgroundTask(expirationHandler:). Please correct what wrong I am doing here.

- (void)applicationDidEnterBackground:(UIApplication *)application {

    self.isAppLaunched      =   NO;

    _bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you
        // stopped or ending the task outright.

        [self cancelAllProductDownloadsInProgress];

        dispatch_async(_MAGICBOX.databaseQueue, ^{
            [application endBackgroundTask:self.bgTask];
            self.bgTask = UIBackgroundTaskInvalid;
        });
    }];

    //Dismiss keyboard
    [self.window endEditing:YES];
}


问:
img "glued" to the division on hover. How to make it appear elsewhere while maintaining the relation
I'm awfully new to the whole game and approach problems pretty much everyday. Most of the time I solve them with google, learning a lot, but this time I can't find anything.

So, I've got this lovely header that moves to the right and makes some space for another element. I'd like this element (the bonobo head) to appear when I hover over the header.

So, I set the display of the image to none, and block on header:hover, but the image seems glued to the header.

I would like it to appear next to it, in any given location. What do ?

.header {
  position: relative;
  display: block;
  left: 0%;
  padding: 15px;
  background-color: #54e954;
  text-align: center;
  width: 100%;
  height: auto;
  transition: 2s;
  border-radius: 8px;
}

.header:hover {
  left: 15%;
  background-color: #d0f307;
}

.photo {
  position: relative;
  display: none;
}

.header:hover .photo {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <h1 class="h1header">Lorem Ipsum</h1>
  <div>
    <img src="https://upload.wikimedia.org/wikipedia/commons/4/4b/Bonobo-Head.jpg" class="photo">
  </div>
</div></code>```

答:
Is that what you want it to look like ? If you want this, I did it using the display flex structure.

.header {
  position: relative;
  display: flex;  /* added */
  justify-content: center;
  align-items: center;
  left: 0%;
  padding: 15px;
  background-color: #54e954;
  text-align: center;
  width: 100%;
  height: auto;
  transition: 2s;
  border-radius: 8px;
}

.header:hover {
  left: 15%;
  background-color: #d0f307;
}

.photo {
  position: relative;
  display: none;
}

.header:hover .photo {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <h1 class="h1header">Lorem Ipsum</h1>
  <div class="img-container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/4/4b/Bonobo-Head.jpg" class="photo">
  </div>
</div></code>```

Updated : With Javascript, you can better control hover and hoverout operations. Here's an example I've prepared for you. By the way, I had to get the img tag out of the header tag. You can see the additions I've made.

let header = document.querySelector(".header");
let imageContainer = document.querySelector(".img-container");
header.onmouseover = function() {
  imageContainer.classList.add("showImage");
}
header.onmouseout = function() {
  imageContainer.classList.remove("showImage");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.header {
  position: relative;
  display: flex;
  /* added */
  justify-content: center;
  align-items: center;
  left: 0%;
  padding: 15px;
  background-color: #54e954;
  text-align: center;
  width: 100%;
  height: 80px;
  transition: 1s;
  border-radius: 8px;
}

.header:hover {
  transform: translateX(15%);
  /* added*/
  background-color: #d0f307;
}

.img-container {
  position: relative;
  display: none;
}

.img-container.showImage {
  position: relative;
  display: block;
}

.container {
  display: flex;
  justify-content: space-between;
}</code>```

Lorem Ipsum

```

Body:
I'm awfully new to the whole game and approach problems pretty much everyday. Most of the time I solve them with google, learning a lot, but this time I can't find anything.

So, I've got this lovely header that moves to the right and makes some space for another element. I'd like this element (the bonobo head) to appear when I hover over the header.

So, I set the display of the image to none, and block on header:hover, but the image seems glued to the header.

I would like it to appear next to it, in any given location. What do ?

.header {
  position: relative;
  display: block;
  left: 0%;
  padding: 15px;
  background-color: #54e954;
  text-align: center;
  width: 100%;
  height: auto;
  transition: 2s;
  border-radius: 8px;
}

.header:hover {
  left: 15%;
  background-color: #d0f307;
}

.photo {
  position: relative;
  display: none;
}

.header:hover .photo {
  display: block;
}

Lorem Ipsum

Body:
Is that what you want it to look like ? If you want this, I did it using the display flex structure.

.header {
  position: relative;
  display: flex;  /* added */
  justify-content: center;
  align-items: center;
  left: 0%;
  padding: 15px;
  background-color: #54e954;
  text-align: center;
  width: 100%;
  height: auto;
  transition: 2s;
  border-radius: 8px;
}

.header:hover {
  left: 15%;
  background-color: #d0f307;
}

.photo {
  position: relative;
  display: none;
}

.header:hover .photo {
  display: block;
}

<div class="header">
  <h1 class="h1header">Lorem Ipsum</h1>
  <div class="img-container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/4/4b/Bonobo-Head.jpg" class="photo">
  </div>
</div>

Updated : With Javascript, you can better control hover and hoverout operations. Here's an example I've prepared for you. By the way, I had to get the img tag out of the header tag. You can see the additions I've made.

let header = document.querySelector(".header");
let imageContainer = document.querySelector(".img-container");
header.onmouseover = function() {
  imageContainer.classList.add("showImage");
}
header.onmouseout = function() {
  imageContainer.classList.remove("showImage");
}

.header {
  position: relative;
  display: flex;
  /* added */
  justify-content: center;
  align-items: center;
  left: 0%;
  padding: 15px;
  background-color: #54e954;
  text-align: center;
  width: 100%;
  height: 80px;
  transition: 1s;
  border-radius: 8px;
}

.header:hover {
  transform: translateX(15%);
  /* added*/
  background-color: #d0f307;
}

.img-container {
  position: relative;
  display: none;
}

.img-container.showImage {
  position: relative;
  display: block;
}

.container {
  display: flex;
  justify-content: space-between;
}

<div class="container">
  <div class="img-container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/4/4b/Bonobo-Head.jpg" class="photo">
  </div>
  <div class="header">
    <h1 class="h1header">Lorem Ipsum</h1>
  </div>
</div>


问:
Cannot Reverse the list for newly added (Firebase Realtime Database)
I am displaying latest added posts, and for that to achieve, I am using the following code:-

```<code>Query ref = FirebaseDatabase.getInstance().getReference()
                .child("Rules")
                .child(category)
                .orderByKey()
                .startAt("25")///This is the child name i am getting by some other method
                .endAt("30")///This is the child name i am getting by some other method
                .limitToLast(6);

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange( DataSnapshot dataSnapshot) {

                if(dataSnapshot.exists()){
                    Log.d(TAG, "onDataChange: "+ dataSnapshot.getChildrenCount());
                    sortsearch.setVisibility(View.VISIBLE);
                    linearLayout.setVisibility(View.GONE);
                    list = new ArrayList<>();

                    for (DataSnapshot ds : dataSnapshot.getChildren()){
                        list.add(ds.getValue(Deal.class));

                    }

                    try
                    {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Collections.reverse(list);///Using to Reverse the list
                                try
                                {
                                    Handler handler = new Handler();
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            adapterClass.notifyDataSetChanged();
                                            adapterClass =new AdapterClass(list);
                                            recyclerView.setAdapter(adapterClass);
                                            recyclerView.setLayoutManager(linearLayoutManager);
                                        }
                                    }, 1000);
                                }
                                catch (Exception e){

                                    e.printStackTrace();
                                }
                            }
                        }, 1000);
                    }
                    catch (Exception e){

                        e.printStackTrace();
                    }

                }
                else{

                    nodata.setVisibility(View.VISIBLE);
                    sortsearch.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.GONE);
                    TextView failedform = findViewById(R.id.failedform);
                    failedform.setVisibility(View.VISIBLE);
                    searchbynamesearchview.setVisibility(View.GONE);
                }

            }

            @Override
            public void onCancelled( DatabaseError databaseError) {
                Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
</code>```

In the above code i am using Collections.reverse method to reverse the list, but when i add 6 more posts, it is not getting reversed with the same method. Below is the method i am using to load more 6 posts recently posted:-

```<code>Query ref = FirebaseDatabase.getInstance().getReference()
                .child("Childname")
                .child(category)
                .orderByKey()
                .endAt("24")///This is the child name i am getting by some other method
                .startAt("19");///This is the child name i am getting by some other method

        ref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                final Deal post = dataSnapshot.getValue(Deal.class);
                Collections.reverse(list);

                list.add(post);

                recyclerView.setAdapter(adapterClass);
                adapterClass.notifyDataSetChanged();

                recyclerView.setLayoutManager(linearLayoutManager);
                nextpage.setVisibility(View.GONE);
                loaderloadmore.setVisibility(View.GONE);

            }
            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }
            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
            }
            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d(TAG, "onCancelled: There is an error");
            }
        });
</code>```

I also used the below method to reverse my list, they are working, but upon loading more posts they are getting added at top of the list, i want to add the results of loadmore at the bottom:-

```<code>LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
</code>```

答:
From what I see you're making it way more difficult than needed.

```<code>ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange( DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            sortsearch.setVisibility(View.VISIBLE);
            linearLayout.setVisibility(View.GONE);
            list = new ArrayList<>();

            for (DataSnapshot ds : dataSnapshot.getChildren()){
                list.add(0, ds.getValue(Deal.class));
            }

            adapterClass =new AdapterClass(list);
            recyclerView.setAdapter(adapterClass);
            recyclerView.setLayoutManager(linearLayoutManager);
        }
        else{

            nodata.setVisibility(View.VISIBLE);
            sortsearch.setVisibility(View.GONE);
            linearLayout.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
            TextView failedform = findViewById(R.id.failedform);
            failedform.setVisibility(View.VISIBLE);
            searchbynamesearchview.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCancelled( DatabaseError databaseError) {
        Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});
</code>```

By using list.add(0, ds.getValue(Deal.class)) you add each subsequent item to the start of the list, effectively reversing the item order.

If you want to add more nodes to the end of the list in reverse order, it's easiest to do it as a two-step process:

Get the items into a new list in the reversed order with the approach outlined above.

Append the items from this list to the original list as they are.

Something like:

```<code>Query query = FirebaseDatabase.getInstance().getReference()
            .child("Rules")
            .child(category)
            .orderByKey()
            .startAt("25")
            .endAt("30")
            .limitToLast(6);

query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange( DataSnapshot dataSnapshot) {
        List newList = new LinkedList();
        for (DataSnapshot ds : dataSnapshot.getChildren()){
            newList.add(0, ds.getValue(Deal.class));
        }
        list.addAll(newList);
        adapterClass.notifyDataSetChanged(); // tell the adapter to repaint
    }

    @Override
    public void onCancelled( DatabaseError databaseError) {
        Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});
</code>```

Body:
I am displaying latest added posts, and for that to achieve, I am using the following code:-

Query ref = FirebaseDatabase.getInstance().getReference()
                .child("Rules")
                .child(category)
                .orderByKey()
                .startAt("25")///This is the child name i am getting by some other method
                .endAt("30")///This is the child name i am getting by some other method
                .limitToLast(6);

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange( DataSnapshot dataSnapshot) {

                if(dataSnapshot.exists()){
                    Log.d(TAG, "onDataChange: "+ dataSnapshot.getChildrenCount());
                    sortsearch.setVisibility(View.VISIBLE);
                    linearLayout.setVisibility(View.GONE);
                    list = new ArrayList<>();

                    for (DataSnapshot ds : dataSnapshot.getChildren()){
                        list.add(ds.getValue(Deal.class));

                    }

                    try
                    {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Collections.reverse(list);///Using to Reverse the list
                                try
                                {
                                    Handler handler = new Handler();
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            adapterClass.notifyDataSetChanged();
                                            adapterClass =new AdapterClass(list);
                                            recyclerView.setAdapter(adapterClass);
                                            recyclerView.setLayoutManager(linearLayoutManager);
                                        }
                                    }, 1000);
                                }
                                catch (Exception e){

                                    e.printStackTrace();
                                }
                            }
                        }, 1000);
                    }
                    catch (Exception e){

                        e.printStackTrace();
                    }

                }
                else{

                    nodata.setVisibility(View.VISIBLE);
                    sortsearch.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.GONE);
                    TextView failedform = findViewById(R.id.failedform);
                    failedform.setVisibility(View.VISIBLE);
                    searchbynamesearchview.setVisibility(View.GONE);
                }

            }

            @Override
            public void onCancelled( DatabaseError databaseError) {
                Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

In the above code i am using Collections.reverse method to reverse the list, but when i add 6 more posts, it is not getting reversed with the same method. Below is the method i am using to load more 6 posts recently posted:-

Query ref = FirebaseDatabase.getInstance().getReference()
                .child("Childname")
                .child(category)
                .orderByKey()
                .endAt("24")///This is the child name i am getting by some other method
                .startAt("19");///This is the child name i am getting by some other method

        ref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                final Deal post = dataSnapshot.getValue(Deal.class);
                Collections.reverse(list);

                list.add(post);

                recyclerView.setAdapter(adapterClass);
                adapterClass.notifyDataSetChanged();

                recyclerView.setLayoutManager(linearLayoutManager);
                nextpage.setVisibility(View.GONE);
                loaderloadmore.setVisibility(View.GONE);

            }
            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }
            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
            }
            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d(TAG, "onCancelled: There is an error");
            }
        });

I also used the below method to reverse my list, they are working, but upon loading more posts they are getting added at top of the list, i want to add the results of loadmore at the bottom:-

LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);

Body:
From what I see you're making it way more difficult than needed.

ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange( DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            sortsearch.setVisibility(View.VISIBLE);
            linearLayout.setVisibility(View.GONE);
            list = new ArrayList<>();

            for (DataSnapshot ds : dataSnapshot.getChildren()){
                list.add(0, ds.getValue(Deal.class));
            }

            adapterClass =new AdapterClass(list);
            recyclerView.setAdapter(adapterClass);
            recyclerView.setLayoutManager(linearLayoutManager);
        }
        else{

            nodata.setVisibility(View.VISIBLE);
            sortsearch.setVisibility(View.GONE);
            linearLayout.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
            TextView failedform = findViewById(R.id.failedform);
            failedform.setVisibility(View.VISIBLE);
            searchbynamesearchview.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCancelled( DatabaseError databaseError) {
        Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

By using list.add(0, ds.getValue(Deal.class)) you add each subsequent item to the start of the list, effectively reversing the item order.

If you want to add more nodes to the end of the list in reverse order, it's easiest to do it as a two-step process:

Get the items into a new list in the reversed order with the approach outlined above.

Append the items from this list to the original list as they are.

Something like:

Query query = FirebaseDatabase.getInstance().getReference()
            .child("Rules")
            .child(category)
            .orderByKey()
            .startAt("25")
            .endAt("30")
            .limitToLast(6);

query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange( DataSnapshot dataSnapshot) {
        List newList = new LinkedList();
        for (DataSnapshot ds : dataSnapshot.getChildren()){
            newList.add(0, ds.getValue(Deal.class));
        }
        list.addAll(newList);
        adapterClass.notifyDataSetChanged(); // tell the adapter to repaint
    }

    @Override
    public void onCancelled( DatabaseError databaseError) {
        Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});


问:
How to add a datasource with encrypted password in WildFly Swarm with .war packaging?
I am using the below configuration to add data source to my WAR in a WildFly swarm:

```<code>  swarm:
    datasources:
       data-sources:
         MyDS:
           driver-name: oracle
           connection-url: <my-connection-string>
           user-name: <my-user-name>
           password: <my-password-in-clear-text>
</code>```

How can this be changed so that the password is encrypted and not in clear text?

答:
For thorntail.

```<code>thorntail:
  datasources:
    data-sources:
      myDS:
        use-java-context: true
        statistics-enabled: true
        driver-name: mysql
        connection-url: ${db.url}
        security-domain: mydbSecure
        jndi-name: java:/myDS
        check-valid-connection-sql: select 1
        valid-connection-checker-class-name: org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker
        validate-on-match: false
        background-validation: true
        background-validation-millis: 10000
        use-fast-fail: true
        min-pool-size: 5
        max-pool-size: 10
        prefill: true
        flush-strategy: FailingConnectionOnly
        exception-sorter-class-name: org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter
  security:
    security-domains:
      mydbSecure:
        classic-authentication:
          login-modules:
            default:
              module-options:
                username: ${ds.uname}
                password: ${ds.pass}
              flag: required
              code: org.picketbox.datasource.security.SecureIdentityLoginModule
        cache-type: default

</code>```

This is how you would encode the password

```<code>public class EncodePassword {
    public static void main(String[] args) throws Exception
    {
        String password = "password";
        String encode = encode(password);
        System.out.println("Encoded password: "+encode);
    }
    private static String encode(String secret) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException
    {
        byte[] kbytes = "jaas is the way".getBytes();
        SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encoding = cipher.doFinal(secret.getBytes());
        BigInteger n = new BigInteger(encoding);
        return n.toString(16);
    }
}
</code>```

The below is how you would decode the password.

```<code>public class DecodePassword {
    public static void main(String[] args) throws Exception {
        String value = "5dfc52b51bd35553df8592078de921bc";
        try {
            System.out.println(decode(value));
        } catch (Exception io) {
            io.printStackTrace();
        }
    }

    public static char[] decode(String secret)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] kbytes = "jaas is the way".getBytes();
        SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
        BigInteger n = new BigInteger(secret, 16);
        byte[] encoding = n.toByteArray();
        //SECURITY-344: fix leading zeros
        if (encoding.length % 8 != 0) {
            int length = encoding.length;
            int newLength = ((length / 8) + 1) * 8;
            int pad = newLength - length; //number of leading zeros
            byte[] old = encoding;
            encoding = new byte[newLength];
            for (int i = old.length - 1; i >= 0; i--) {
                encoding[i + pad] = old[i];
            }
            //SECURITY-563: handle negative numbers
            if (n.signum() == -1) {
                for (int i = 0; i < newLength - length; i++) {
                    encoding[i] = (byte) -1;
                }
            }
        }
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decode = cipher.doFinal(encoding);
        return new String(decode).toCharArray();

    }
}
</code>```

for more information regarding picketBox.

https://source.jboss.org/browse/PicketBox/trunk/security-jboss-sx/jbosssx/src/main/java/org/picketbox/datasource/security/SecureIdentityLoginModule.java?r=276

Body:
I am using the below configuration to add data source to my WAR in a WildFly swarm:

  swarm:
    datasources:
       data-sources:
         MyDS:
           driver-name: oracle
           connection-url: <my-connection-string>
           user-name: <my-user-name>
           password: <my-password-in-clear-text>

How can this be changed so that the password is encrypted and not in clear text?

Body:
For thorntail.

thorntail:
  datasources:
    data-sources:
      myDS:
        use-java-context: true
        statistics-enabled: true
        driver-name: mysql
        connection-url: ${db.url}
        security-domain: mydbSecure
        jndi-name: java:/myDS
        check-valid-connection-sql: select 1
        valid-connection-checker-class-name: org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker
        validate-on-match: false
        background-validation: true
        background-validation-millis: 10000
        use-fast-fail: true
        min-pool-size: 5
        max-pool-size: 10
        prefill: true
        flush-strategy: FailingConnectionOnly
        exception-sorter-class-name: org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter
  security:
    security-domains:
      mydbSecure:
        classic-authentication:
          login-modules:
            default:
              module-options:
                username: ${ds.uname}
                password: ${ds.pass}
              flag: required
              code: org.picketbox.datasource.security.SecureIdentityLoginModule
        cache-type: default

This is how you would encode the password

public class EncodePassword {
    public static void main(String[] args) throws Exception
    {
        String password = "password";
        String encode = encode(password);
        System.out.println("Encoded password: "+encode);
    }
    private static String encode(String secret) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException
    {
        byte[] kbytes = "jaas is the way".getBytes();
        SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encoding = cipher.doFinal(secret.getBytes());
        BigInteger n = new BigInteger(encoding);
        return n.toString(16);
    }
}

The below is how you would decode the password.

public class DecodePassword {
    public static void main(String[] args) throws Exception {
        String value = "5dfc52b51bd35553df8592078de921bc";
        try {
            System.out.println(decode(value));
        } catch (Exception io) {
            io.printStackTrace();
        }
    }

    public static char[] decode(String secret)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] kbytes = "jaas is the way".getBytes();
        SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
        BigInteger n = new BigInteger(secret, 16);
        byte[] encoding = n.toByteArray();
        //SECURITY-344: fix leading zeros
        if (encoding.length % 8 != 0) {
            int length = encoding.length;
            int newLength = ((length / 8) + 1) * 8;
            int pad = newLength - length; //number of leading zeros
            byte[] old = encoding;
            encoding = new byte[newLength];
            for (int i = old.length - 1; i >= 0; i--) {
                encoding[i + pad] = old[i];
            }
            //SECURITY-563: handle negative numbers
            if (n.signum() == -1) {
                for (int i = 0; i < newLength - length; i++) {
                    encoding[i] = (byte) -1;
                }
            }
        }
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decode = cipher.doFinal(encoding);
        return new String(decode).toCharArray();

    }
}

for more information regarding picketBox.

https://source.jboss.org/browse/PicketBox/trunk/security-jboss-sx/jbosssx/src/main/java/org/picketbox/datasource/security/SecureIdentityLoginModule.java?r=276


问:
unable to enable button on row selection
The idea is to enable button on selection of a row. But when i selecting any row the button is not getting enabled.

Please find  code snippet and screenshot [error_1] as attached

```<code>     onInit: function () {
        var oViewModel,
            iOriginalBusyDelay,
            oTable = this.byId("table");

        // Put down worklist table's original value for busy indicator delay,
        // so it can be restored later on. Busy handling on the table is
        // taken care of by the table itself.
        iOriginalBusyDelay = oTable.getBusyIndicatorDelay();
        // keeps the search state
        this._aTableSearchState = [];

        this.oSemanticPage = this.byId("page");
        this.oEditAction = this.byId("editAction");
        oTable.attachSelectionChange(this.onTableSelection, this);
    },

    /* =========================================================== */
    /* event handlers                                              */
    /* =========================================================== */
    onTableSelection: function () {
        var oTable = this.getView().byId("table");
        var aSelectedItems = oTable.getSelectedItems();

        if (aSelectedItems.length > 0) {
            this.byId("test").setEnabled(true);
        }
</code>```

答:
It is not advisable to get the Button and manipulate its enable/disable property. Try to use a model and change the model property accordingly. This is how MVC works.

    selectionChange: function() {
      oModel.setProperty("/btnEnabled", this.getSelectedItems().length > 0);
    }
```

demo: https://jsbin.com/rexeyaf/edit?js,output

Body:
The idea is to enable button on selection of a row. But when i selecting any row the button is not getting enabled.

Please find  code snippet and screenshot [error_1] as attached

     onInit: function () {
        var oViewModel,
            iOriginalBusyDelay,
            oTable = this.byId("table");

        // Put down worklist table's original value for busy indicator delay,
        // so it can be restored later on. Busy handling on the table is
        // taken care of by the table itself.
        iOriginalBusyDelay = oTable.getBusyIndicatorDelay();
        // keeps the search state
        this._aTableSearchState = [];

        this.oSemanticPage = this.byId("page");
        this.oEditAction = this.byId("editAction");
        oTable.attachSelectionChange(this.onTableSelection, this);
    },

    /* =========================================================== */
    /* event handlers                                              */
    /* =========================================================== */
    onTableSelection: function () {
        var oTable = this.getView().byId("table");
        var aSelectedItems = oTable.getSelectedItems();

        if (aSelectedItems.length > 0) {
            this.byId("test").setEnabled(true);
        }

Body:
It is not advisable to get the Button and manipulate its enable/disable property. Try to use a model and change the model property accordingly. This is how MVC works.

    selectionChange: function() {
      oModel.setProperty("/btnEnabled", this.getSelectedItems().length > 0);
    }

demo: https://jsbin.com/rexeyaf/edit?js,output


问:
Error function is not defined in class in iphone
I have interface like below.

```<code>@interface HistoryShow : UIViewController {
}

-(IBAction) listTableViewController:(id) sender;

@end
</code>```

and my implementation is here

```<code>-(IBAction) listTableViewController:(id) sender {

    NSLog(@"Loaded");
    NSLog(@"FFFFFFFFFFF");
}
</code>```

and i have connected this function to File's Manager but i am seeing a warning on Inspector screen is function "listTableViewController" is no longer defined in "HistoryShow". It seems to defined perfectly. What is wrong with me ?
thanks

答: Did you try performing a clean and build.</p>

Body:
I have interface like below.

@interface HistoryShow : UIViewController {
}

-(IBAction) listTableViewController:(id) sender;

@end

and my implementation is here

-(IBAction) listTableViewController:(id) sender {

    NSLog(@"Loaded");
    NSLog(@"FFFFFFFFFFF");
}

and i have connected this function to File's Manager but i am seeing a warning on Inspector screen is function "listTableViewController" is no longer defined in "HistoryShow". It seems to defined perfectly. What is wrong with me ?
thanks


问:
How can I set up Soot when using it as a library?
I want to use Soot library to build an SSA from *.java file. But all the examples I found use Soot as standalone tool, not library. Can anyone give me example hot to do it in program?

For a start I am just trying to load my class from the source file and print it (TestClass.class is in the directory A/home/abdullin/workspace/test):

```<code>import soot.G
import soot.Scene
import soot.options.Options

fun main(args: Array<String>) {
    G.reset();
    Options.v().set_whole_program(true)
    Scene.v().loadBasicClasses()

    Scene.v().sootClassPath = "${Scene.v().defaultClassPath()}:/home/abdullin/workspace/test"

    val sc = Scene.v().getSootClass("TestClass")
    Scene.v().loadNecessaryClasses()
    sc.setApplicationClass()

    println(sc.name)
    sc.methods.forEach {
        println(it)
    }
}
</code>```

But when I run this, I get runtime exception Aborting: can't find classfile TestClass. If I change Scene.v().getSootClass("TestClass") to Scene.v().loadClassAndSupport("TestClass") as they do in some of their tutorials, soot finds my class, but it is not complete. It prints me signatures of class methods, but can't find their bodies, activeBody field is null.

```<code>TestClass
<TestClass: void <init>()>
<TestClass: void main(java.lang.String[])>
<TestClass: void f1()>
</code>```

答:
You can read this post (https://o2lab.github.io/710/p/a1.html). But if you try to analyze a jar file, you should unzip it and get a set of class files. Then you should add your classes directory into the soot_class_path.

Demo:

```<code>public static void main(String[] args) {
    //spotbugs -- testing
    String classesDir = "D:\\wkspace\\seed8\\dir\\spotbugs";
    String mainClass = "edu.umd.cs.findbugs.LaunchAppropriateUI";

    //set classpath
    String jreDir = System.getProperty("java.home") + "\\lib\\jce.jar";
    String jceDir = System.getProperty("java.home") + "\\lib\\rt.jar";
    String path = jreDir + File.pathSeparator + jceDir + File.pathSeparator + classesDir;
    Scene.v().setSootClassPath(path);

    //add an intra-procedural analysis phase to Soot
    TestCallGraphSootJar_3 analysis = new TestCallGraphSootJar_3();
    PackManager.v().getPack("wjtp").add(new Transform("wjtp.TestSootCallGraph", analysis));

    excludeJDKLibrary();

    Options.v().set_process_dir(Arrays.asList(classesDir));
    Options.v().set_whole_program(true);
    //Options.v().set_app(true);

    SootClass appClass = Scene.v().loadClassAndSupport(mainClass);
    Scene.v().setMainClass(appClass);
    Scene.v().loadNecessaryClasses();

    //enableCHACallGraph();
    enableSparkCallGraph();

    PackManager.v().runPacks();
}
</code>```

If you replace

```<code>SootClass appclass = Scene.v().loadClassAndSupport(mainclass);
Scene.v().setMainClass(appclass);
Scene.v().loadNecessaryClasses();
</code>```

by

```<code>Scene.v().loadNecessaryClasses();
SootClass appclass = Scene.v().getSootClass(mainclass);
Scene.v().setMainClass(appclass);
</code>```

, the program also works.

Body:
I want to use Soot library to build an SSA from *.java file. But all the examples I found use Soot as standalone tool, not library. Can anyone give me example hot to do it in program?

For a start I am just trying to load my class from the source file and print it (TestClass.class is in the directory A/home/abdullin/workspace/test):

import soot.G
import soot.Scene
import soot.options.Options

fun main(args: Array<String>) {
    G.reset();
    Options.v().set_whole_program(true)
    Scene.v().loadBasicClasses()

    Scene.v().sootClassPath = "${Scene.v().defaultClassPath()}:/home/abdullin/workspace/test"

    val sc = Scene.v().getSootClass("TestClass")
    Scene.v().loadNecessaryClasses()
    sc.setApplicationClass()

    println(sc.name)
    sc.methods.forEach {
        println(it)
    }
}

But when I run this, I get runtime exception Aborting: can't find classfile TestClass. If I change Scene.v().getSootClass("TestClass") to Scene.v().loadClassAndSupport("TestClass") as they do in some of their tutorials, soot finds my class, but it is not complete. It prints me signatures of class methods, but can't find their bodies, activeBody field is null.

TestClass
<TestClass: void <init>()>
<TestClass: void main(java.lang.String[])>
<TestClass: void f1()>

Body:
You can read this post (https://o2lab.github.io/710/p/a1.html). But if you try to analyze a jar file, you should unzip it and get a set of class files. Then you should add your classes directory into the soot_class_path.

Demo:

public static void main(String[] args) {
    //spotbugs -- testing
    String classesDir = "D:\\wkspace\\seed8\\dir\\spotbugs";
    String mainClass = "edu.umd.cs.findbugs.LaunchAppropriateUI";

    //set classpath
    String jreDir = System.getProperty("java.home") + "\\lib\\jce.jar";
    String jceDir = System.getProperty("java.home") + "\\lib\\rt.jar";
    String path = jreDir + File.pathSeparator + jceDir + File.pathSeparator + classesDir;
    Scene.v().setSootClassPath(path);

    //add an intra-procedural analysis phase to Soot
    TestCallGraphSootJar_3 analysis = new TestCallGraphSootJar_3();
    PackManager.v().getPack("wjtp").add(new Transform("wjtp.TestSootCallGraph", analysis));

    excludeJDKLibrary();

    Options.v().set_process_dir(Arrays.asList(classesDir));
    Options.v().set_whole_program(true);
    //Options.v().set_app(true);

    SootClass appClass = Scene.v().loadClassAndSupport(mainClass);
    Scene.v().setMainClass(appClass);
    Scene.v().loadNecessaryClasses();

    //enableCHACallGraph();
    enableSparkCallGraph();

    PackManager.v().runPacks();
}

If you replace

SootClass appclass = Scene.v().loadClassAndSupport(mainclass);
Scene.v().setMainClass(appclass);
Scene.v().loadNecessaryClasses();

by

Scene.v().loadNecessaryClasses();
SootClass appclass = Scene.v().getSootClass(mainclass);
Scene.v().setMainClass(appclass);

, the program also works.


问:
Why is my Angular application not finding the embedded component?
This is the embedded component, HomeTabComponent.

```<code>@Component({
  selector: 'app-home-tab',
  templateUrl: './home-tab.component.html',
  styleUrls: ['./home-tab.component.scss']
})
export class HomeTabComponent implements OnInit {}
</code>```

The embedded component, HomeTabComponent, is declared in home.module.ts:

```<code>import { HomeTabComponent } from "./home-tab/home-tab.component";

@NgModule({
  declarations: [HomeComponent, HomeTabComponent],
  exports: [HomeTabComponent],
  imports: [CommonModule, HomeRoutingModule],
})
export class HomeModule {}
</code>```

It is then embedded in home.component.html:

```<code><section id="product-carousel">
    <app-home-tab></app-home-tab>
</section>
</code>```

But I get the following error:

```<code>compiler.js:2175 Uncaught Error: Template parse errors:
'app-home-tab' is not a known element:
1. If 'app-home-tab' is an Angular component, then verify that it is part of this module.
2. If 'app-home-tab' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas'
of this component to suppress this message. ("
</section>
    <section id="product-carousel">
        [ERROR ->]<app-home-tab></app-home-tab>
        <!-- <div class="row">
</code>```

HomeRoutingModule:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class HomeRoutingModule { }
</code>```

答:
Not sure if you have done it, but you should add your HomeModule inside the imports of your parent NgModule, for example, if you are using it on the app module then:

```<code>import { HomeModule } from './home/home.module';

@NgModule({
  imports:      [ BrowserModule, FormsModule, HomeModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

Example url: https://stackblitz.com/edit/angular-ivy-76w6xq?file=src%2Fapp%2Fapp.component.html

Body:
This is the embedded component, HomeTabComponent.

@Component({
  selector: 'app-home-tab',
  templateUrl: './home-tab.component.html',
  styleUrls: ['./home-tab.component.scss']
})
export class HomeTabComponent implements OnInit {}

The embedded component, HomeTabComponent, is declared in home.module.ts:

import { HomeTabComponent } from "./home-tab/home-tab.component";

@NgModule({
  declarations: [HomeComponent, HomeTabComponent],
  exports: [HomeTabComponent],
  imports: [CommonModule, HomeRoutingModule],
})
export class HomeModule {}

It is then embedded in home.component.html:

    <app-home-tab></app-home-tab>

But I get the following error:

compiler.js:2175 Uncaught Error: Template parse errors:
'app-home-tab' is not a known element:
1. If 'app-home-tab' is an Angular component, then verify that it is part of this module.
2. If 'app-home-tab' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas'
of this component to suppress this message. ("

        [ERROR ->]<app-home-tab></app-home-tab>

Body:
Not sure if you have done it, but you should add your HomeModule inside the imports of your parent NgModule, for example, if you are using it on the app module then:

import { HomeModule } from './home/home.module';

@NgModule({
  imports:      [ BrowserModule, FormsModule, HomeModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Example url: https://stackblitz.com/edit/angular-ivy-76w6xq?file=src%2Fapp%2Fapp.component.html