问:
How to print out original padded hash from signature using openssl
I want to learn about different padding and identifier or format when signing a file. So i want to know what happens when using openssl

For example:
openssl dgst -sha256 -sign xiaomi_rootca.key -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:-1 -out sig.bin 1.txt

Surely it will generate a sig.bin. However i want to know what openssl did to hash.bin before it is converted to sig.bin

So let's split this process into steps:

openssl dgst -binary -sha256 -out hash.bin 1.txt

padding it

maybe add some identifier like rfc3447.txt page 12 says? and generate a final file final_hash.bin

raw sign. openssl rsautl -sign -inkey private.key -in fianl_hash.bin -out sig.bin

Well, i want to know what happened exactly during step 2 and 3. So is there any command to reverse step 4?

Before i can use openssl rsautl -verify, however it doesn't support pss pading.

答:
I don't think you can split it up like you have.

When you are doing a digest only command you use the EVP_DigestInit API.  When you use the -sign option it uses the EVP_DigestSignInit API.

So I think it's a little bit more involved than what you have broken down.  To really tell the difference now, you would have to start to look into the engine code, specifically the private key type implementation (e.g. RSA, EC, etc).

Looking at the RSA PSS engine implementation, it looks like the padding is implemented in-line with the signing operation itself.

e.g. in the pkey_rsa_sign function you see code like:

```<code>} else if (rctx->pad_mode == RSA_PKCS1_PSS_PADDING) {
    if (!setup_tbuf(rctx, ctx))
        return -1;
    if (!RSA_padding_add_PKCS1_PSS_mgf1(rsa,
                                        rctx->tbuf, tbs,
                                        rctx->md, rctx->mgf1md,
                                        rctx->saltlen))
        return -1;
</code>```

If you want to verify a digest it seems like you really want to use the EVP_DigestVerifyInit API (as this is what the dgst command is using) as I'm not sure you are going to get anywhere going down the path you want to go down in your question.

Body:
I don't think you can split it up like you have.

When you are doing a digest only command you use the EVP_DigestInit API.  When you use the -sign option it uses the EVP_DigestSignInit API.

So I think it's a little bit more involved than what you have broken down.  To really tell the difference now, you would have to start to look into the engine code, specifically the private key type implementation (e.g. RSA, EC, etc).

Looking at the RSA PSS engine implementation, it looks like the padding is implemented in-line with the signing operation itself.

e.g. in the pkey_rsa_sign function you see code like:

} else if (rctx->pad_mode == RSA_PKCS1_PSS_PADDING) {
    if (!setup_tbuf(rctx, ctx))
        return -1;
    if (!RSA_padding_add_PKCS1_PSS_mgf1(rsa,
                                        rctx->tbuf, tbs,
                                        rctx->md, rctx->mgf1md,
                                        rctx->saltlen))
        return -1;

If you want to verify a digest it seems like you really want to use the EVP_DigestVerifyInit API (as this is what the dgst command is using) as I'm not sure you are going to get anywhere going down the path you want to go down in your question.


来源: stackexchange

问:
Directory disappears from azure cloud shell (home)

Scenario

I had a working directory (repo) on azure cloudshell (cloud shell on azure portal) at home which i don't see now.
It disappeared couple of days as well but appeared again automatically after couple of hours.

Now again it has disappeared. Not sure how to get it back.

I could find below on microsoft pages which says $Home gets persisted so my directory should have been persisted.

System state and persistence
The machine that provides your Cloud Shell session is temporary, and it is recycled after your session is inactive for 20 minutes. Cloud Shell requires an Azure file share to be mounted. As a result, your subscription must be able to set up storage resources to access Cloud Shell. Other considerations include:

With mounted storage, only modifications within the clouddrive directory are persisted. In Bash, your $HOME directory is also persisted.
Azure file shares can be mounted only from within your assigned region.
In Bash, run env to find your region set as ACC_LOCATION.
Azure Files supports only locally redundant storage and geo-redundant storage accounts.

Anyone knows what I am doing wrong ?

I could clone the my repo from azure devOps but I dont want to. This would be my last option.

答:
I restarted the cloud shell and my repo appeared again.
It would be still good to know why it disappeared :)</p>

ContentLicense: CC BY-SA 4.0


问:
How to export all routes in Express?
I have an NodeJS Express app that is getting really big in just one file (app.js).

I want to export all my routes into a single, external file, say ./lib/routes.js. How to do that?

How to export the following bit of code and require it correctly in main app.js?

```<code>app.get('/logout', function(req, res) {
    res.render('logout', {
        username: req.session.username
    });
});

app.get('/dashboard', function(req, res) {
    res.render('dashboard', {
        username: req.session.username
    });
});

app.get('/login', function(req, res) {
    res.render('login', {
        badLogin: false,
        loginError: false
    });
});
</code>```

答:
using glob you can export all routes on directory for example '/routes':

npm i --save glob

```<code>
    // *** /routes/index.js file ***

    const express = require('express')
    const Router = express.Router
    const router = Router()
    const glob = require('glob')

    /**
     * options ignore files inside routes folder
     */
    const options = {
        ignore: [`${__dirname}/_helpers.js`, `${__dirname}/index.js`]
    }

    /**
     * read all files on current directory and export routes as lowercase of the filename
     * example 'routes/Products.js' route will be access by '/products'
     */
    const routes =
        glob.sync(__dirname + '/*.js', options)
            .map(filename => {
                const arr = filename.split('/')
                let name = arr.pop();
                name = name.replace('.js', '')
                return {
                    path: `/${name.toLowerCase()}`,
                    router: require(`${filename.replace('.js', '')}`)
                }
            })
            .filter(obj => Object.getPrototypeOf(obj.router) == Router)
            .forEach(obj => router.use(obj.path, obj.router))

    module.exports = router;
</code>```

then

on app.js

```<code>// app.js file

const express = require('express')
const routes = require('./routes')

const app = express()

app.use('/api', routes)

</code>```

ContentLicense: CC BY-SA 3.0

Title: How to export all routes in Express?

Body:
I have an NodeJS Express app that is getting really big in just one file (app.js).

I want to export all my routes into a single, external file, say ./lib/routes.js. How to do that?

How to export the following bit of code and require it correctly in main app.js?

app.get('/logout', function(req, res) {
    res.render('logout', {
        username: req.session.username
    });
});

app.get('/dashboard', function(req, res) {
    res.render('dashboard', {
        username: req.session.username
    });
});

app.get('/login', function(req, res) {
    res.render('login', {
        badLogin: false,
        loginError: false
    });
});

Body:
using glob you can export all routes on directory for example '/routes':

npm i --save glob

    // *** /routes/index.js file ***

    const express = require('express')
    const Router = express.Router
    const router = Router()
    const glob = require('glob')

    /**
     * options ignore files inside routes folder
     */
    const options = {
        ignore: [`${__dirname}/_helpers.js`, `${__dirname}/index.js`]
    }

    /**
     * read all files on current directory and export routes as lowercase of the filename
     * example 'routes/Products.js' route will be access by '/products'
     */
    const routes =
        glob.sync(__dirname + '/*.js', options)
            .map(filename => {
                const arr = filename.split('/')
                let name = arr.pop();
                name = name.replace('.js', '')
                return {
                    path: `/${name.toLowerCase()}`,
                    router: require(`${filename.replace('.js', '')}`)
                }
            })
            .filter(obj => Object.getPrototypeOf(obj.router) == Router)
            .forEach(obj => router.use(obj.path, obj.router))

    module.exports = router;

then

on app.js

// app.js file

const express = require('express')
const routes = require('./routes')

const app = express()

app.use('/api', routes)


问:
'ts-node' is not recognized as an internal or external command, operable program or batch file
I'm getting error in my Vs Code terminal and command prompt that 'ts-node' is not recognized as an internal or external command, operable program or batch file. while i'm trying the start command in the terminal npm run dev and i have added my package.json file also.

```<code>{
"name": "tsnode",
"version": "1.0.0",
"description": "ts-node experiment.",
"scripts": {
    "dev": "nodemon --exec 'ts-node --cache-directory .tscache' ./server.ts",
    "start": "ts-node --fast ./server.ts"
},
"author": "Mugesh",
"license": "ISC",
"dependencies": {
    "@types/body-parser": "^1.16.3",
    "@types/chalk": "^0.4.31",
    "@types/express": "^4.0.35",
    "@types/node": "^7.0.18",
    "body-parser": "^1.17.1",
    "chalk": "^1.1.3",
    "express": "^4.15.2",
    "nodemon": "^1.11.0",
    "ts-node": "^3.0.4",
    "typescript": "^2.3.4"
}
</code>```

}

答:
I had a similar problem while using nodemon:

I had nodemon installed globally, AND ts-node only installed locally.

Solution:

I installed ts-node globally (still keeping the local dependency).

Body:
I'm getting error in my Vs Code terminal and command prompt that 'ts-node' is not recognized as an internal or external command, operable program or batch file. while i'm trying the start command in the terminal npm run dev and i have added my package.json file also.

{
"name": "tsnode",
"version": "1.0.0",
"description": "ts-node experiment.",
"scripts": {
    "dev": "nodemon --exec 'ts-node --cache-directory .tscache' ./server.ts",
    "start": "ts-node --fast ./server.ts"
},
"author": "Mugesh",
"license": "ISC",
"dependencies": {
    "@types/body-parser": "^1.16.3",
    "@types/chalk": "^0.4.31",
    "@types/express": "^4.0.35",
    "@types/node": "^7.0.18",
    "body-parser": "^1.17.1",
    "chalk": "^1.1.3",
    "express": "^4.15.2",
    "nodemon": "^1.11.0",
    "ts-node": "^3.0.4",
    "typescript": "^2.3.4"
}

}


问:
Rock Paper Scissors score keeps resetting
I'm making a rock, paper, scissors game with a pointing system and it seems to always give me a value of zero every time the scores are revealed. Help is appreciated.-------------------------------------------------------------------------------------------------------------------------------------------------------------</p>

```<code>def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    scoreplayer = 0

    scorecpu = 0

    if player.lower() == cpu:
        print("This is a tie, no one scores a point")
        play()

    elif player.lower() == "rock":
        if cpu == "paper":
            print("Paper beats Rock, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "scissors":
            print("Rock beats Scissors, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "paper":
        if cpu == "scissors":
            print("Scissors beats Paper, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "rock":
            print("Paper Beats Rock, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player == "scissors":
        if cpu == "rock":
            print("Rock beats Scissors, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "paper":
            print("Scissors beats Paper, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "e":
        print("")
        print("You have " + str(scoreplayer) + " points")
        print("")
        print("CPU has " + str(scorecpu) + " points")
        sys.exit()

    else:
        play()
</code>```

答:
because you're setting your variables in your function it will by definition be reset each time it runs. like @Carcigenicate said you could pass them as arguments to it or
use a while loop but you might also want to look into the global statement.</p>

Body:
I'm making a rock, paper, scissors game with a pointing system and it seems to always give me a value of zero every time the scores are revealed. Help is appreciated.-------------------------------------------------------------------------------------------------------------------------------------------------------------

def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    scoreplayer = 0

    scorecpu = 0

    if player.lower() == cpu:
        print("This is a tie, no one scores a point")
        play()

    elif player.lower() == "rock":
        if cpu == "paper":
            print("Paper beats Rock, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "scissors":
            print("Rock beats Scissors, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "paper":
        if cpu == "scissors":
            print("Scissors beats Paper, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "rock":
            print("Paper Beats Rock, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player == "scissors":
        if cpu == "rock":
            print("Rock beats Scissors, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "paper":
            print("Scissors beats Paper, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "e":
        print("")
        print("You have " + str(scoreplayer) + " points")
        print("")
        print("CPU has " + str(scorecpu) + " points")
        sys.exit()

    else:
        play()


问:
Why does adding a margin to my div push its content (columns) off the page?
Adding a margin to the  div pushes the right column off the edge of the screen to the right.

I have tried adding margins to both  and , altering  widths and even removing a width property from the  CSS altogether.

With no margin at all, the 3 columns fit the width of the screen perfectly with a default tiny margin showing the background colour of my page. Adding ANY margin to  messes the whole thing up.

```<code><HTML>
<main>
    <section>
    Some text 1
    </section>

    <section>
    Some text 2
    </section>

    <section>
    Some text 3
    </section>
</main>

CSS

<<<<<<<SOME MEDIA QUERIES TO MAKE IT ADAPTABLE FOR MOBILE>>>>>>>

@media (min-width: 620px) {
main {
    column-count: 2;
}
section {
    break-inside: avoid;
}
}

@media (min-width: 960px) {
    main {
        column-count: 3;
    }
}

<<<<<<<<<<<<NORMAL CSS>>>>>>>>>>>>>>

main {
    width: 100%;
    margin-right: 5%;  <<<<<PROBLEM AREA
    margin-left: 5%;
}

section {
    height: 25%;
    margin-bottom: 5%;
    padding: 20px;
    display: inline-block;
}
</code>```

I would like a 5% margin on the left and right of the  div with no margin between the  divs.

答:
Explanation of the different parts:

Content - The content of the box, where text and images appear

Padding - Clears an area around the content. The padding is transparent

Border - A border that goes around the padding and content

Margin - Clears an area outside the border. The margin is transparent

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

div {
  background-color: lightgrey;
  width: 300px;
  border: 15px solid green;
  padding: 50px;
  margin: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>This text is the content of the box. We have added a 50px padding, 20px margin and a 15px green border.
Total width here becomes:

300px (width)
+ 100px (left + right padding)
+ 30px (left + right border)
+ 40px (left + right margin)
= 470px
</div></code>```

Body:
Adding a margin to the  div pushes the right column off the edge of the screen to the right.

I have tried adding margins to both  and , altering  widths and even removing a width property from the  CSS altogether.

With no margin at all, the 3 columns fit the width of the screen perfectly with a default tiny margin showing the background colour of my page. Adding ANY margin to  messes the whole thing up.

    Some text 1

    Some text 2

    Some text 3

CSS

<<<<<<<SOME MEDIA QUERIES TO MAKE IT ADAPTABLE FOR MOBILE>>>>>>>

@media (min-width: 620px) {
main {
    column-count: 2;
}
section {
    break-inside: avoid;
}
}

@media (min-width: 960px) {
    main {
        column-count: 3;
    }
}

<<<<<<<<<<<<NORMAL CSS>>>>>>>>>>>>>>

main {
    width: 100%;
    margin-right: 5%;  <<<<<PROBLEM AREA
    margin-left: 5%;
}

section {
    height: 25%;
    margin-bottom: 5%;
    padding: 20px;
    display: inline-block;
}

I would like a 5% margin on the left and right of the  div with no margin between the  divs.

Body:
Explanation of the different parts:

Content - The content of the box, where text and images appear

Padding - Clears an area around the content. The padding is transparent

Border - A border that goes around the padding and content

Margin - Clears an area outside the border. The margin is transparent

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

div {
  background-color: lightgrey;
  width: 300px;
  border: 15px solid green;
  padding: 50px;
  margin: 20px;
}

<div>This text is the content of the box. We have added a 50px padding, 20px margin and a 15px green border.
Total width here becomes:

300px (width)
+ 100px (left + right padding)
+ 30px (left + right border)
+ 40px (left + right margin)
= 470px
</div>


问:
How to fix 'unable to import gurobipy', undefined variable 'model', and undefined variable 'GRB' in VSCode & Python?
I am trying to write an optimization code for the seating layout of a Boeing 777x using Gurobi in python, and am encountering error messages with my code. Specifically, pylint errors with importing gurobipy (pylint(import-error)), undefined variable 'Model' (pylint(undefined-variable)), and undefined variable 'GRB' (pylint(undefined-variable)).

I am rather new to coding and am unsure if gurobipy or pylint is possibly downloaded into the wrong place and cannot be accessed by VSCode. I have gurobi.lic, gurobi.log, the pylint folder, and my code (BoeingOptimization.py) all saved into the same folder on my desktop. Those same files (folder in the case of pylint) are also somewhere else in the user files too. I think there may be some sort of path issue because I believe everything is downloaded, but possibly in the wrong locations?

```<code># !/usr/bin/python
from gurobipy import *

# Create the model to be used in the terminal
m = Model("777x Optimization")

# Name and Create the variables
x1 = m.addVar(name="First-Class Seat Pitch [in]")
x2 = m.addVar(name="First-Class Seat Width [in]")
x3 = m.addVar(name="First-Class Seat Thickness [in]")
x4 = m.addVar(name="Premium-Economy Seat Pitch [in]")
x5 = m.addVar(name="Premium-Economy Seat Width [in]")
x6 = m.addVar(name="Premium-Economy Seat Thickness [in]")
x7 = m.addVar(name="Number of First-Class Rows")
x8 = m.addVar(name="Number of Premium-Economy Rows")
x9 = m.addVar(name="Number of First-Class Seats Per Row")
x10 = m.addVar(name="Number of Premium-Economy Seats per Row")

# Set objective: f(x1,x2,x3,x4,x5,x6,x7,x8)
obj = x7*x9*(x1+x2+x3) + x8*x10*(x4+x5+x6)
m.setObjective(obj, GRB.MINIMIZE)

# Add constraints
m.addConstr((x7*x1*x2)+(x4*x5*x8) <= 342625, "Area Constraint")
m.addConstr(1512*x8 + 5410*x7 >= 202182, "Ticket Revenue             Constraint")
m.addConstr(0.25*x5 + 0.35*x6 +0.4*x4 >= 18.6975, "Premium-Economy    Comfort Level Constraint")
m.addConstr(0.25*x2 + 0.35*x3 +0.4*x1 >= 29.16, "First-Class Economy Comfort Constraint")
m.addConstr(x8 - 1.4*x7 >= 0 , "Ratio of First Class to Economy Class Seats Constraint")
m.addConstr(x1 >= 57, "Minimum First-Class Pitch Constraint")
m.addConstr(x2 >= 25, "Minimum First-Class Width Constraint")
m.addConstr(x3 >= 3, "Minimum First-Class Thickness Constraint")
m.addConstr(x4 >= 36, "Minimum Premium-Economy Pitch Constraint")
m.addConstr(x5 >= 18.5, "Minimum Premium-Economy Width Constraint")
m.addConstr(x6 >= 1.5, "Minimum Premium-Economy Thickness Constraint")
m.addConstr(x9*x2 <= 233.04, "Seats Per Aisle Constraint First-Class")
m.addConstr(x10*x5 <= 233.04, "Seats Per Aisle Constraint Premium-Economy")
m.optimize()

for v in m.getVars():
    print('%s %g' % (v.varName, v.x))

print('Obj: %g' % obj.getValue())
</code>```

答: You'll need to select the correct Python interpreter to be used by VSCode (selectable from the bottom left corner of VSCode - check that it is the same version and directory that you expect).</p>

Body:
I am trying to write an optimization code for the seating layout of a Boeing 777x using Gurobi in python, and am encountering error messages with my code. Specifically, pylint errors with importing gurobipy (pylint(import-error)), undefined variable 'Model' (pylint(undefined-variable)), and undefined variable 'GRB' (pylint(undefined-variable)).

I am rather new to coding and am unsure if gurobipy or pylint is possibly downloaded into the wrong place and cannot be accessed by VSCode. I have gurobi.lic, gurobi.log, the pylint folder, and my code (BoeingOptimization.py) all saved into the same folder on my desktop. Those same files (folder in the case of pylint) are also somewhere else in the user files too. I think there may be some sort of path issue because I believe everything is downloaded, but possibly in the wrong locations?

# !/usr/bin/python
from gurobipy import *

# Create the model to be used in the terminal
m = Model("777x Optimization")

# Name and Create the variables
x1 = m.addVar(name="First-Class Seat Pitch [in]")
x2 = m.addVar(name="First-Class Seat Width [in]")
x3 = m.addVar(name="First-Class Seat Thickness [in]")
x4 = m.addVar(name="Premium-Economy Seat Pitch [in]")
x5 = m.addVar(name="Premium-Economy Seat Width [in]")
x6 = m.addVar(name="Premium-Economy Seat Thickness [in]")
x7 = m.addVar(name="Number of First-Class Rows")
x8 = m.addVar(name="Number of Premium-Economy Rows")
x9 = m.addVar(name="Number of First-Class Seats Per Row")
x10 = m.addVar(name="Number of Premium-Economy Seats per Row")

# Set objective: f(x1,x2,x3,x4,x5,x6,x7,x8)
obj = x7*x9*(x1+x2+x3) + x8*x10*(x4+x5+x6)
m.setObjective(obj, GRB.MINIMIZE)

# Add constraints
m.addConstr((x7*x1*x2)+(x4*x5*x8) <= 342625, "Area Constraint")
m.addConstr(1512*x8 + 5410*x7 >= 202182, "Ticket Revenue             Constraint")
m.addConstr(0.25*x5 + 0.35*x6 +0.4*x4 >= 18.6975, "Premium-Economy    Comfort Level Constraint")
m.addConstr(0.25*x2 + 0.35*x3 +0.4*x1 >= 29.16, "First-Class Economy Comfort Constraint")
m.addConstr(x8 - 1.4*x7 >= 0 , "Ratio of First Class to Economy Class Seats Constraint")
m.addConstr(x1 >= 57, "Minimum First-Class Pitch Constraint")
m.addConstr(x2 >= 25, "Minimum First-Class Width Constraint")
m.addConstr(x3 >= 3, "Minimum First-Class Thickness Constraint")
m.addConstr(x4 >= 36, "Minimum Premium-Economy Pitch Constraint")
m.addConstr(x5 >= 18.5, "Minimum Premium-Economy Width Constraint")
m.addConstr(x6 >= 1.5, "Minimum Premium-Economy Thickness Constraint")
m.addConstr(x9*x2 <= 233.04, "Seats Per Aisle Constraint First-Class")
m.addConstr(x10*x5 <= 233.04, "Seats Per Aisle Constraint Premium-Economy")
m.optimize()

for v in m.getVars():
    print('%s %g' % (v.varName, v.x))

print('Obj: %g' % obj.getValue())


问:
Devexpress Xtragrid how to add Combobox editor to column
I want to place a combobox inside one column of a Xtragrid. I can bind the combobox to array  values but how do you bind the combobox to the column? </p>

答:
This is a simple example of how to add a ComboBox to GridColumn.</p>

```<code>Dim xSunday As New DevExpress.XtraEditors.Repository.RepositoryItemComboBox
Me.GridView1.Columns("Sunday").ColumnEdit = xSunday
xSunday.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor
xSunday.Items.Clear()
xSunday.Items.Add("Full")
xSunday.Items.Add("Half")
xSunday.Items.Add("Off")
</code>```

OwnerDisplayName: Learner

LastEditorDisplayName: Jon B

Body:
This is a simple example of how to add a ComboBox to GridColumn.

Dim xSunday As New DevExpress.XtraEditors.Repository.RepositoryItemComboBox
Me.GridView1.Columns("Sunday").ColumnEdit = xSunday
xSunday.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor
xSunday.Items.Clear()
xSunday.Items.Add("Full")
xSunday.Items.Add("Half")
xSunday.Items.Add("Off")


问:
JDBC connection pooling library which can handle connections that go idle often nicely?
Let’s say there is this code which lives in a server side backend:

```<code>class Foo {
    void doSomething() {
        try (Connection c = dataSource.getConnection()) {
            executeSQL(c);
            externalApiCall(); // this can be slow
            executeSQL(c);
        }
    }
}
</code>```

The problem here is that externalApiCall() can be very slow, and it keeps a lot of database connections open (even though it’s not used) and it can lead to running out of the maximum number of the connections. It will be harmful to other parts of my app which don’t depend on any external API, and I want to avoid this.

The code above is simplified and in reality I use something like a ServletFilter which puts Connection into ThreadLocal when it receives a http request, so it’s difficult to change the overall mechanism which opens a Connection at the beginning of business logic.

So my question is: isn’t there any nice connection pooling library, a wrapper or something that can handle such a situation nicely? For example, something which opens a real database connection only when a Statement object is created and close the connection afterwards automatically when the Statement is closed. Currently I use Tomcat DBCP.

答:
Use cp3 connection pooling.

The property max_idle_time may satisfy your requirements here.

maxIdleTime

Default: 0

Seconds a Connection can remain pooled but unused before being discarded. Zero means idle connections never expire.

For more info, refer
https://www.mchange.com/projects/c3p0/

Body:
Let’s say there is this code which lives in a server side backend:

class Foo {
    void doSomething() {
        try (Connection c = dataSource.getConnection()) {
            executeSQL(c);
            externalApiCall(); // this can be slow
            executeSQL(c);
        }
    }
}

The problem here is that externalApiCall() can be very slow, and it keeps a lot of database connections open (even though it’s not used) and it can lead to running out of the maximum number of the connections. It will be harmful to other parts of my app which don’t depend on any external API, and I want to avoid this.

The code above is simplified and in reality I use something like a ServletFilter which puts Connection into ThreadLocal when it receives a http request, so it’s difficult to change the overall mechanism which opens a Connection at the beginning of business logic.

So my question is: isn’t there any nice connection pooling library, a wrapper or something that can handle such a situation nicely? For example, something which opens a real database connection only when a Statement object is created and close the connection afterwards automatically when the Statement is closed. Currently I use Tomcat DBCP.


问:
How to convert interger to time while the interger is actually time data but no separation
I have data that contains time data but in integer type and have no separation between the integer.
my data like = [91310, 101012, ...]  in fact it's suppose to be ["9:13:10", "10:10:12"]

how to convert that into time format

Body:
Format the number with 5 (or 6) leading zeros and then take 2 character slices from the string:

[":".join(f"{n:05}."[-c:2-c] for c in [7,5,3]) for n in data]

# ['0:00:00', '0:00:05', '0:00:15', '0:02:35', '0:23:59', '1:35:46', '11:25:32']

If you're using this for a duration and you want to allow hours to go beyond 24 or even negative time:

data = [112532,3333759,-120503,-1234]

[":".join(f"{n:0{5+(n<0)}}."[-s:-e] for s,e in [(0,5),(5,3),(3,1)]) for n in data]

# ['11:25:32', '333:37:59', '-12:05:03', '-0:12:34']


问:
How To write an SQL query to return all "historical records" for TODAY'S DATE (month and day) for EVERY YEAR in the DB?
I've been using Visual Studio, C#, and SQL Server for 8 months now and have created a very functional personal project as I've been learning.  But, there one bit of functionality I want in my program that I cannot get to work--automatically, that is.

If I type THIS into the button click event, run the program, and click the History button, it works perfectly.  All seven columns of information go to the datagridview perfectly.

```<code>SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM AllConcertList WHERE Date LIKE '%%%%-05-27' ORDER BY DATE DESC; ", conn);
</code>```

However, what is not awesome is that I want to write the query so that I can push a button ("History") that will return information from MAY 27 (or whatever today's date actually is) of EVERY YEAR, and I just can't figure out how to do it.  It is a "Happened On This Day In History" list.

Obviously, I need to keep SELECT * FROM AllConcertList WHERE Date...  Somehow I need to include GETDATE() otherwise how would the program know  to start with 05-27?  But then I feel I need to include DATEFROMPARTS because I only really want Month and Day to be static to whatever the actual date (today) is.  It must be a subquery in there somehow.

答:
You can dynamically get today's month and date, then build your query string. </p>

```<code>DateTime today = DateTime.Today;
String sql = String.Format("SELECT * FROM AllConcertList WHERE Date LIKE '%%%%-{0}' ORDER BY DATE DESC;", today.ToString("MM-dd"));
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
</code>```

<p>And to show best practice, the same query, but parameterized. </p>

```<code>DateTime today = DateTime.Today;
SqlCommand cmd =  new SqlCommand("SELECT * FROM AllConcertList WHERE Date LIKE @monthDate ORDER BY DATE DESC;", conn);
cmd.Parameters.AddWithValue("@monthDate", "%%%%-" + today.ToString("MM-dd"));
</code>```

Body:
I've been using Visual Studio, C#, and SQL Server for 8 months now and have created a very functional personal project as I've been learning.  But, there one bit of functionality I want in my program that I cannot get to work--automatically, that is.

If I type THIS into the button click event, run the program, and click the History button, it works perfectly.  All seven columns of information go to the datagridview perfectly.

SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM AllConcertList WHERE Date LIKE '%%%%-05-27' ORDER BY DATE DESC; ", conn);

However, what is not awesome is that I want to write the query so that I can push a button ("History") that will return information from MAY 27 (or whatever today's date actually is) of EVERY YEAR, and I just can't figure out how to do it.  It is a "Happened On This Day In History" list.

Obviously, I need to keep SELECT * FROM AllConcertList WHERE Date...  Somehow I need to include GETDATE() otherwise how would the program know  to start with 05-27?  But then I feel I need to include DATEFROMPARTS because I only really want Month and Day to be static to whatever the actual date (today) is.  It must be a subquery in there somehow.

Body:
You can dynamically get today's month and date, then build your query string.

DateTime today = DateTime.Today;
String sql = String.Format("SELECT * FROM AllConcertList WHERE Date LIKE '%%%%-{0}' ORDER BY DATE DESC;", today.ToString("MM-dd"));
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);

And to show best practice, the same query, but parameterized.

DateTime today = DateTime.Today;
SqlCommand cmd =  new SqlCommand("SELECT * FROM AllConcertList WHERE Date LIKE @monthDate ORDER BY DATE DESC;", conn);
cmd.Parameters.AddWithValue("@monthDate", "%%%%-" + today.ToString("MM-dd"));


问:
Android studio error "cannot resolve method"
I am facing a problem in the Java code of my application

```<code>        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s)
        {
            Message message = dataSnapshot.getValue(Message.class);
            message.setKey(dataSnapshot.getKey());
            messages.add(message);
            displayMessages(messages);
        }
</code>```

Error thrown :  "cannot resolve method"

答:
I think you are missing some things try the following code:</p>

```<code>ref.addChildEventListener(new ChildEventListener() {
  @Override
  public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
    Post newPost = dataSnapshot.getValue(Post.class);
    System.out.println("Author: " + newPost.author);
    System.out.println("Title: " + newPost.title);
    System.out.println("Previous Post ID: " + prevChildKey);
  }

  @Override
  public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}

  @Override
  public void onChildRemoved(DataSnapshot dataSnapshot) {}

  @Override
  public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}

  @Override
  public void onCancelled(DatabaseError databaseError) {}
});
</code>```

Body:
I am facing a problem in the Java code of my application

        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s)
        {
            Message message = dataSnapshot.getValue(Message.class);
            message.setKey(dataSnapshot.getKey());
            messages.add(message);
            displayMessages(messages);
        }

Error thrown :  "cannot resolve method"

Body:
I think you are missing some things try the following code:

ref.addChildEventListener(new ChildEventListener() {
  @Override
  public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
    Post newPost = dataSnapshot.getValue(Post.class);
    System.out.println("Author: " + newPost.author);
    System.out.println("Title: " + newPost.title);
    System.out.println("Previous Post ID: " + prevChildKey);
  }

  @Override
  public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}

  @Override
  public void onChildRemoved(DataSnapshot dataSnapshot) {}

  @Override
  public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}

  @Override
  public void onCancelled(DatabaseError databaseError) {}
});


问:
How to suppress output when running npm scripts
I have decided to experiment with npm scripts as a build tool and so far I like it.  One issue I'd like to solve is when running a script to run jshint when something doesn't pass linting I get a ton of "npm ERR!" lines.  I would like to suppress these as the output from the linter is more meaningful.

Is there a good way to set this globally and is there a way to set it for each script run?

答:
```<code>npm install --quiet --no-progress
</code>```

Will keep warnings and errors, and suppress the ADHD progress bar on terminals that support it.

Body:
npm install --quiet --no-progress

Will keep warnings and errors, and suppress the ADHD progress bar on terminals that support it.


问:
Laravel - Setting null to model columns has no effect
I'm trying to set a null value on a Model column but it gets ignored and it doesn't update.

```<code>if($rol_colegio)
    $update_pl['rol_colegio'] = $rol_colegio; //$rol_colegio may be null

$usuario->update($update_pl);
</code>```

The data does get updated successfully when I try to use non-null data, but if the variable is null this entry doesn't get updated.

What would be the cause of this?

答:
$rol_colegion = null doesn't match condition if($rol_colegio).

Just remove if($rol_colegio).

Body:
I'm trying to set a null value on a Model column but it gets ignored and it doesn't update.

if($rol_colegio)
    $update_pl['rol_colegio'] = $rol_colegio; //$rol_colegio may be null

$usuario->update($update_pl);

The data does get updated successfully when I try to use non-null data, but if the variable is null this entry doesn't get updated.

What would be the cause of this?


问:
How to Inject Services into Directive Link Functions

AngularJS Repeated Directive Instances - How to keep link functions DRY to avoid duplication on multiple instances of directive?

Pretty much the title says it all but in summary I want to move the link functions below to a common place so that on multiple instantiations of the directive I do not have the same set of link function present for each directive but rather have the set of link function in a common place?

How do I make this work?

Directive

```<code>angular.module('Risk').directive('webixUi', WebixElement);

function WebixElement(){
      return {
            restrict: 'A',
            scope: {
                elem: '@'
            },
            controller: function($scope, CommonService){
                $scope.getTextValue = function(obj, model, type, field){
                     CommonService.getTextValue(obj, model, type, field);
                }
            },
            link: function (scope, element, attrs) {

                function clearLevel(){
                    leveldiv = document.querySelector("div[name='level']");
                    leveldiv.innerHTML = '';
                    leveldiv.setAttribute('class', '');
                }

                function assignRiskLevel(obj){
                    l = scope.$parent.risk.likelihood;
                    t = scope.$parent.risk.technical;
                    s = scope.$parent.risk.schedule;
                    c = scope.$parent.risk.cost;

                    if (validLevel(obj) && riskNotEmpty(l,t,s,c))
                    {
                        if (riskIsValid(l,t,s,c))
                        {
                            l = Number(l);
                            tech = Number(t);
                            schd = Number(s);
                            cost = Number(c);
                            c = Math.max(tech,schd,cost);
                            displayLevel(scope.$parent.riskMatrix[l][c],l,c);
                            clearDot();
                            drawDot(l,c);
                        }
                    }
                    else
                    {
                        clearLevel();
                        clearDot();
                    }
                }

                function isLevelField(id){
                        return (id == 'likelihood' || id == 'technical' || id == 'schedule' || id == 'cost');
                }

                function clearValidation(id){
                    (document.querySelector('#'+id+ ' > div.webix_control')).classList.remove("webix_invalid");
                }

                function makeInvalid(id){
                    (document.querySelector('#'+id+' > div.webix_control')).classList.add("webix_invalid");
                }

                function validLevel(obj){
                    return obj.getValue().charCodeAt(0) - '0'.charCodeAt(0) >= 1
                        && obj.getValue().charCodeAt(0) - '0'.charCodeAt(0) <= 5;
                }

                function riskIsValid(l,t,s,c){
                    var lvl = [l,t,s,c];
                    valid = true;
                    for (var idx = 0; idx < lvl.length; idx++)
                        if ((lvl[idx].charCodeAt(0) - '0'.charCodeAt(0) < 1) || (lvl[idx].charCodeAt(0) - '0'.charCodeAt(0) > 5))
                            valid = false;
                    return valid;
                }

                function riskNotEmpty(l, t, s, c){
                    if (l != '' && t != '' && s != '' && c != '')
                        return true;
                    return false;
                }

                function clearDot(){
                    levelDiv = document.querySelector("div.level");
                    if (levelDiv)
                        levelDiv.parentNode.removeChild(levelDiv);
                }

                function fieldEmpty(elem){
                    return elem.getValue() == '' || elem.getValue().trim() == '';
                }

                function formValid(){
                    for (var idx = 0; idx < scope.$parent.fields.length; idx++){
                        field = scope.$parent.fields[idx];
                        if (isLevelField(field) && !validLevel(scope.$parent.risk[field]))
                            return false;
                        else if (scope.$parent.risk[field] == '')
                            return false;
                    }

                    return true;
                }

                function validate(elem, id){
                   if (isLevelField(id) && (!validLevel(elem) || fieldEmpty(elem))){
                        makeInvalid(id);
                        clearDot();
                   }
                   else if (typeof elem !== 'undefined' && (elem.getValue() == 0 || fieldEmpty(elem)))
                        makeInvalid(id);

                   if (formValid())
                      enableElement("#submit");
                   else
                      disableElement("#submit");
                }

                function enableElement(id){
                    (document.querySelector(id)).removeAttribute('disabled');
                }

                function disableElement(id){
                    (document.querySelector(id)).setAttribute('disabled', 'disabled');
                }

                function validCharacter(c){
                    return (c >= 32 && c <= 126);
                }

                function clearTextValue(code, obj, field){
                    if (!validCharacter(code) || obj.getValue().trim() == '')
                    {
                        scope.$parent.risk[field] = '';
                        return;
                    }
                }

                function handleKeyPress(obj, code, attr){
                     getTextValueAndValidate(code, obj, attr);
                     validate(obj, attr);
                }

                function updateAndValidate(code, obj, attr){
                    clearTextValue(code, obj, attr);
                    validate(obj, attr);
                }

                function getTextValueAndValidate(code, obj, field){
                    clearTextValue(code, obj, field);
                    clearValidation(field);
                    scope.getTextValue(obj, scope.$parent, 'risk', field);
                    validate(obj, field);
                }

                function drawDot(l, c){
                    document.querySelector("td[name='risk["+l+"]["+c+"]']").innerHTML
                    = "<div class='level' style='width:15px; height:15px; background-color: black'/>";
                }

                function displayLevel(level, l, c){
                   leveldiv =  document.querySelector("div[name='level']");
                   if (level >= scope.$parent.risklevels.riskhigh)
                   {
                       leveldiv.innerHTML = 'H ' + l + '-' + c;
                       leveldiv.setAttribute('class', 'high');
                   }
                   else if (level < scope.$parent.risklevels.riskhigh  && level >= scope.$parent.risklevels.riskmedium)
                   {
                        leveldiv.innerHTML = 'M ' + l + '-' + c;
                        leveldiv.setAttribute('class', 'med');
                   }
                   else if (level < scope.$parent.risklevels.riskmedium)
                   {
                        leveldiv.innerHTML = 'L ' + l + '-' + c;
                        leveldiv.setAttribute('class', 'low');
                   }
                }

                function getConfig(attr, type, width, height, maxlength)
                {
                    var view;
                    if (type == "level")
                        view = "text";
                    else
                        view = type;

                    var config =
                    {
                        view: view,
                        value: scope.$parent.risk[attr],
                        on: {
                            "onTimedKeyPress": function(code){
                                var obj = this.eventSource || this;
                                handleKeyPress(obj, code, attr);
                                if (type == "level")
                                    assignRiskLevel(obj);
                            },
                            "onBlur": function(code){
                                var obj = this.eventSource || this;
                                updateAndValidate(code, obj, attr);
                            }
                        },
                        responsive: true,
                        width: width,
                        height: height
                    };
                    if (maxlength)
                        config.attributes = {maxlength : maxlength};
                    return config;
                };

                scope.$parent[attrs.webixUi] = getConfig(attrs.webixUi, attrs.type, attrs.width, attrs.height, attrs.hasOwnProperty('maxlength')? attrs.maxlength: null);
            }
      }
}
</code>```

Repeated webix-ui directives on two different values

```<code><div ng-if="$root.initDone">
    <div webix-ui="risktitle" width="500" height="30" type="text"
         id="risktitle" name="risktitle" />
    </div>

<div ng-if="$root.initDone">
    <div webix-ui="riskstatement" width="500" height="97" type="textarea"
         id="riskstatement" name="riskstatement" />
    </div>
</code>```

答:
Services can be injected into the directive construction function:

```<code>angular.module('Risk').directive('webixUi', WebixElement);

̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶W̶e̶b̶i̶x̶E̶l̶e̶m̶e̶n̶t̶(̶)̶{̶ ̶
function WebixElement(DOMops){
      return {
            restrict: 'A',
            scope: {
                elem: '@'
            },
            controller: function($scope, CommonService){
                $scope.getTextValue = function(obj, model, type, field){
                     CommonService.getTextValue(obj, model, type, field);
                }
            },
            link: function (scope, element, attrs) {

                var clearLevel = DOMops.clearLevel;

                /**
                function clearLevel(){
                    leveldiv = document.querySelector("div[name='level']");
                    leveldiv.innerHTML = '';
                    leveldiv.setAttribute('class', '');
                }
                **/
</code>```

Move the common functions to that service.

Body:
AngularJS Repeated Directive Instances - How to keep link functions DRY to avoid duplication on multiple instances of directive?

Pretty much the title says it all but in summary I want to move the link functions below to a common place so that on multiple instantiations of the directive I do not have the same set of link function present for each directive but rather have the set of link function in a common place?

How do I make this work?

Directive

angular.module('Risk').directive('webixUi', WebixElement);

function WebixElement(){
      return {
            restrict: 'A',
            scope: {
                elem: '@'
            },
            controller: function($scope, CommonService){
                $scope.getTextValue = function(obj, model, type, field){
                     CommonService.getTextValue(obj, model, type, field);
                }
            },
            link: function (scope, element, attrs) {

                function clearLevel(){
                    leveldiv = document.querySelector("div[name='level']");
                    leveldiv.innerHTML = '';
                    leveldiv.setAttribute('class', '');
                }

                function assignRiskLevel(obj){
                    l = scope.$parent.risk.likelihood;
                    t = scope.$parent.risk.technical;
                    s = scope.$parent.risk.schedule;
                    c = scope.$parent.risk.cost;

                    if (validLevel(obj) && riskNotEmpty(l,t,s,c))
                    {
                        if (riskIsValid(l,t,s,c))
                        {
                            l = Number(l);
                            tech = Number(t);
                            schd = Number(s);
                            cost = Number(c);
                            c = Math.max(tech,schd,cost);
                            displayLevel(scope.$parent.riskMatrix[l][c],l,c);
                            clearDot();
                            drawDot(l,c);
                        }
                    }
                    else
                    {
                        clearLevel();
                        clearDot();
                    }
                }

                function isLevelField(id){
                        return (id == 'likelihood' || id == 'technical' || id == 'schedule' || id == 'cost');
                }

                function clearValidation(id){
                    (document.querySelector('#'+id+ ' > div.webix_control')).classList.remove("webix_invalid");
                }

                function makeInvalid(id){
                    (document.querySelector('#'+id+' > div.webix_control')).classList.add("webix_invalid");
                }

                function validLevel(obj){
                    return obj.getValue().charCodeAt(0) - '0'.charCodeAt(0) >= 1
                        && obj.getValue().charCodeAt(0) - '0'.charCodeAt(0) <= 5;
                }

                function riskIsValid(l,t,s,c){
                    var lvl = [l,t,s,c];
                    valid = true;
                    for (var idx = 0; idx < lvl.length; idx++)
                        if ((lvl[idx].charCodeAt(0) - '0'.charCodeAt(0) < 1) || (lvl[idx].charCodeAt(0) - '0'.charCodeAt(0) > 5))
                            valid = false;
                    return valid;
                }

                function riskNotEmpty(l, t, s, c){
                    if (l != '' && t != '' && s != '' && c != '')
                        return true;
                    return false;
                }

                function clearDot(){
                    levelDiv = document.querySelector("div.level");
                    if (levelDiv)
                        levelDiv.parentNode.removeChild(levelDiv);
                }

                function fieldEmpty(elem){
                    return elem.getValue() == '' || elem.getValue().trim() == '';
                }

                function formValid(){
                    for (var idx = 0; idx < scope.$parent.fields.length; idx++){
                        field = scope.$parent.fields[idx];
                        if (isLevelField(field) && !validLevel(scope.$parent.risk[field]))
                            return false;
                        else if (scope.$parent.risk[field] == '')
                            return false;
                    }

                    return true;
                }

                function validate(elem, id){
                   if (isLevelField(id) && (!validLevel(elem) || fieldEmpty(elem))){
                        makeInvalid(id);
                        clearDot();
                   }
                   else if (typeof elem !== 'undefined' && (elem.getValue() == 0 || fieldEmpty(elem)))
                        makeInvalid(id);

                   if (formValid())
                      enableElement("#submit");
                   else
                      disableElement("#submit");
                }

                function enableElement(id){
                    (document.querySelector(id)).removeAttribute('disabled');
                }

                function disableElement(id){
                    (document.querySelector(id)).setAttribute('disabled', 'disabled');
                }

                function validCharacter(c){
                    return (c >= 32 && c <= 126);
                }

                function clearTextValue(code, obj, field){
                    if (!validCharacter(code) || obj.getValue().trim() == '')
                    {
                        scope.$parent.risk[field] = '';
                        return;
                    }
                }

                function handleKeyPress(obj, code, attr){
                     getTextValueAndValidate(code, obj, attr);
                     validate(obj, attr);
                }

                function updateAndValidate(code, obj, attr){
                    clearTextValue(code, obj, attr);
                    validate(obj, attr);
                }

                function getTextValueAndValidate(code, obj, field){
                    clearTextValue(code, obj, field);
                    clearValidation(field);
                    scope.getTextValue(obj, scope.$parent, 'risk', field);
                    validate(obj, field);
                }

                function drawDot(l, c){
                    document.querySelector("td[name='risk["+l+"]["+c+"]']").innerHTML
                    = "
";
                }

                function displayLevel(level, l, c){
                   leveldiv =  document.querySelector("div[name='level']");
                   if (level >= scope.$parent.risklevels.riskhigh)
                   {
                       leveldiv.innerHTML = 'H ' + l + '-' + c;
                       leveldiv.setAttribute('class', 'high');
                   }
                   else if (level < scope.$parent.risklevels.riskhigh  && level >= scope.$parent.risklevels.riskmedium)
                   {
                        leveldiv.innerHTML = 'M ' + l + '-' + c;
                        leveldiv.setAttribute('class', 'med');
                   }
                   else if (level < scope.$parent.risklevels.riskmedium)
                   {
                        leveldiv.innerHTML = 'L ' + l + '-' + c;
                        leveldiv.setAttribute('class', 'low');
                   }
                }

                function getConfig(attr, type, width, height, maxlength)
                {
                    var view;
                    if (type == "level")
                        view = "text";
                    else
                        view = type;

                    var config =
                    {
                        view: view,
                        value: scope.$parent.risk[attr],
                        on: {
                            "onTimedKeyPress": function(code){
                                var obj = this.eventSource || this;
                                handleKeyPress(obj, code, attr);
                                if (type == "level")
                                    assignRiskLevel(obj);
                            },
                            "onBlur": function(code){
                                var obj = this.eventSource || this;
                                updateAndValidate(code, obj, attr);
                            }
                        },
                        responsive: true,
                        width: width,
                        height: height
                    };
                    if (maxlength)
                        config.attributes = {maxlength : maxlength};
                    return config;
                };

                scope.$parent[attrs.webixUi] = getConfig(attrs.webixUi, attrs.type, attrs.width, attrs.height, attrs.hasOwnProperty('maxlength')? attrs.maxlength: null);
            }
      }
}

Repeated webix-ui directives on two different values

Body:
Services can be injected into the directive construction function:

angular.module('Risk').directive('webixUi', WebixElement);

̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶W̶e̶b̶i̶x̶E̶l̶e̶m̶e̶n̶t̶(̶)̶{̶ ̶
function WebixElement(DOMops){
      return {
            restrict: 'A',
            scope: {
                elem: '@'
            },
            controller: function($scope, CommonService){
                $scope.getTextValue = function(obj, model, type, field){
                     CommonService.getTextValue(obj, model, type, field);
                }
            },
            link: function (scope, element, attrs) {

                var clearLevel = DOMops.clearLevel;

                /**
                function clearLevel(){
                    leveldiv = document.querySelector("div[name='level']");
                    leveldiv.innerHTML = '';
                    leveldiv.setAttribute('class', '');
                }
                **/

Move the common functions to that service.


问:
Animate change to title text in Navigation Controller
I am attempting to animate the change to the title of a detail UITableViewController that is embedded in a UINavigationController.

These two Q&A on stack overflow seem most relevant...

Animate nav bar title text change OP by Jordan H;

Transition Navigation Bar Title, OP by Jacob

I've attempted a number of code variants, mostly following Ashley Mills answer and others based on his answer, but essentially I cannot seem to make the animation work!

Note writing in Swift 5 using Xcode 10.2.

I'm using a Master-Detail UITableViewController setup to manage a list and the details of the items in that list.

I'm using Large Titles...

```<code>navigationController?.navigationBar.prefersLargeTitles = true
</code>```

...and a search controller...

```<code>navigationItem.searchController = <<mySearchController>>
navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true
</code>```

...all set in the viewDidLoad() method for the Master View Controller.

Here's what I've done.

In my project:

import QuartzCore framework, per the comment by Jack Bellis "you'll need to add the QuartzCore framework via [project]>[target]>Build Phases>Link Binaries>QuartzCore.framework.";

In the Master View Controller:

import QuartzCore;

In the Detail View Controller:

In the viewDidAppear(_ animated: Bool) method, write the CATransition code similar to the answers to the OP noted above (which changes the Large Title, but without animation).

```<code>override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    let animationTransition = CATransition()

    animationTransition.duration = 2.0

    animationTransition.type = CATransitionType.push
    animationTransition.subtype = CATransitionSubtype.fromTop

    navigationController!.navigationBar.layer.add(animationTransition, forKey: "pushText")

    navigationItem.title = <<NEW TITLE TEXT>>
}
</code>```

In the viewDidAppear(_ animated: Bool) method, write alternatives to the CATransition code suggested in the answers to the OP noted above (which only adds a separate title into the centre of the navigation bar and does not change the Large Title).

```<code>override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    let animationTransition = CATransition()

    animationTransition.duration = 2.0

    animationTransition.type = CATransitionType.fade

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
    label.text = <<NEW TITLE TEXT>>
    navigationItem.titleView = label

    navigationItem.titleView!.layer.add(animationTransition, forKey: "fadeText")
}
</code>```

I've also tried including CAMediaTimingFunction...

```<code>    animationTransition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
</code>```

I've also tried calling setNeedsLayout and setNeedsDisplay...

```<code>    navigationItem.titleView?.setNeedsLayout()
    navigationController?.navigationBar.setNeedsDisplay()
</code>```

For clarity:

the title text does change, but without animation;

the code is written in the viewDidAppear(_ animated:) method, because I want the user to see the transition;

the duration is long (2 seconds) for testing - I may reduce this if/when the animation is working;

Using the Inspectors in the storyboard, I've read through all the UITableView/Controller and UINavigationController settings to see whether I may have missed something.

Any suggestions?

答:
So I've worked it out.

I had to find the specific layer within the UINavigationBar's subviews that contained the title text, then animate that layer. The results are exactly what I wanted.

Here's my answer (Swift 5 iOS 12)...

```<code>override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    if (newTitle ?? "").isEmpty == false { // only proceed with a valid value for newTitle.

        // CATransition code
        let titleAnimation = CATransition()
        titleAnimation.duration = 0.5
        titleAnimation.type = CATransitionType.push
        titleAnimation.subtype = CATransitionSubtype.fromRight
        titleAnimation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)

        // this is a detail view controller, so we must grab the reference
        // to the parent view controller's navigation controller
        // then cycle through until we find the title labels.
        if let subviews = parent?.navigationController?.navigationBar.subviews {

            for navigationItem in subviews {

                for itemSubView in navigationItem.subviews {

                    if let largeLabel = itemSubView as? UILabel {

                        largeLabel.layer.add(titleAnimation, forKey: "changeTitle")
                    }
                }
            }
        }
        // finally set the title
        navigationItem.title = newTitle
   }
</code>```

Note: there is no need to import QuartzCore.

...and here's the process I went through to identify what I had to change...

This SO Q&A How to set multi line Large title in navigation bar? ( New feature of iOS 11)
 helped me identify the process detailed below, so thanks in particular to the original post and the answer by @Krunal .

Using the same code to cycle through the UINavigationBar's subviews (as above), I used a print to terminal to identify the various UINavigationItems and their subviews.

```<code>        counter = 0

        if let subviews = parent?.navigationController?.navigationBar.subviews {

            for navigationItem in subviews {

                print("____\(navigationItem)")

                for itemSubView in navigationItem.subviews {

                    counter += 1

                    print("_______\(itemSubView)")
                }
            }
        }
        print("COUNTER: \(counter)")
</code>```

this code yielded the following prints in terminal (for iPhone 8 Plus running iOS 12.2 in simulator)...

```<code> ____<_UIBarBackground: 0x7f922740c000; frame = (0 -20; 414 116); userInteractionEnabled = NO; layer = <CALayer: 0x6000026ce1c0>>
 _______<UIImageView: 0x7f922740c9c0; frame = (0 116; 414 0.333333); userInteractionEnabled = NO; layer = <CALayer: 0x6000026ce7c0>>
 _______<UIVisualEffectView: 0x7f922740cbf0; frame = (0 0; 414 116); layer = <CALayer: 0x6000026ce880>>
 ____<_UINavigationBarLargeTitleView: 0x7f922740f390; frame = (0 44; 414 52); clipsToBounds = YES; layer = <CALayer: 0x6000026cd840>>
 _______<UILabel: 0x7f9227499fe0; frame = (20.1667 3.66667; 206.333 40.6667); text = 'Event Details'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6000005bf250>>
 ____<_UINavigationBarContentView: 0x7f922740d660; frame = (0 0; 414 44); clipsToBounds = YES; layer = <CALayer: 0x6000026cea00>>
 _______<_UIButtonBarStackView: 0x7f92274984a0; frame = (302 0; 100 44); layer = <CALayer: 0x60000261cc60>>
 _______<_UIButtonBarButton: 0x7f922749a5c0; frame = (0 0; 82.3333 44); layer = <CALayer: 0x60000261ee60>>
 _______<UILabel: 0x7f922749a2d0; frame = (155 11.6667; 104.333 20.3333); text = 'Event Details'; alpha = 0; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6000005bfc50>>
 ____<_UINavigationBarModernPromptView: 0x7f9227602db0; frame = (0 0; 0 50); alpha = 0; hidden = YES; layer = <CALayer: 0x6000026e4600>>
 COUNTER: 2
</code>```

I've actually applied the animation twice - to the UILabel layer within _UINavigationBarLargeTitleView and the UILabel layer within _UINavigationBarContentView. This does not seem to matter however because, when the large title first appears, the label within content view (which I assume is for the "old style" title in the navigation bar when the large title is scrolled off screen) is hidden on viewDidAppear.

Incidentally, if you drop in the following two lines, you'll also have multi-line large titles:

```<code> largeLabel.numberOfLines = 0
 largeLabel.lineBreakMode = .byWordWrapping
</code>```

BUT, I've not yet figured out how to animate the increase in size of the large title frame, so a change to two or more lines is immediate and IMHO ruins the animation of the title change.

Not yet tested on device, but does seem to work OK for both iPhone and iPad sims.

If you find any bugs, let me know and I'll update my answer.

Body:
I am attempting to animate the change to the title of a detail UITableViewController that is embedded in a UINavigationController.

These two Q&A on stack overflow seem most relevant...

Animate nav bar title text change OP by Jordan H;

Transition Navigation Bar Title, OP by Jacob

I've attempted a number of code variants, mostly following Ashley Mills answer and others based on his answer, but essentially I cannot seem to make the animation work!

Note writing in Swift 5 using Xcode 10.2.

I'm using a Master-Detail UITableViewController setup to manage a list and the details of the items in that list.

I'm using Large Titles...

navigationController?.navigationBar.prefersLargeTitles = true

...and a search controller...

navigationItem.searchController = <<mySearchController>>
navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true

...all set in the viewDidLoad() method for the Master View Controller.

Here's what I've done.

In my project:

import QuartzCore framework, per the comment by Jack Bellis "you'll need to add the QuartzCore framework via [project]>[target]>Build Phases>Link Binaries>QuartzCore.framework.";

In the Master View Controller:

import QuartzCore;

In the Detail View Controller:

In the viewDidAppear(_ animated: Bool) method, write the CATransition code similar to the answers to the OP noted above (which changes the Large Title, but without animation).

override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    let animationTransition = CATransition()

    animationTransition.duration = 2.0

    animationTransition.type = CATransitionType.push
    animationTransition.subtype = CATransitionSubtype.fromTop

    navigationController!.navigationBar.layer.add(animationTransition, forKey: "pushText")

    navigationItem.title = <<NEW TITLE TEXT>>
}

In the viewDidAppear(_ animated: Bool) method, write alternatives to the CATransition code suggested in the answers to the OP noted above (which only adds a separate title into the centre of the navigation bar and does not change the Large Title).

override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    let animationTransition = CATransition()

    animationTransition.duration = 2.0

    animationTransition.type = CATransitionType.fade

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
    label.text = <<NEW TITLE TEXT>>
    navigationItem.titleView = label

    navigationItem.titleView!.layer.add(animationTransition, forKey: "fadeText")
}

I've also tried including CAMediaTimingFunction...

    animationTransition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)

I've also tried calling setNeedsLayout and setNeedsDisplay...

    navigationItem.titleView?.setNeedsLayout()
    navigationController?.navigationBar.setNeedsDisplay()

For clarity:

the title text does change, but without animation;

the code is written in the viewDidAppear(_ animated:) method, because I want the user to see the transition;

the duration is long (2 seconds) for testing - I may reduce this if/when the animation is working;

Using the Inspectors in the storyboard, I've read through all the UITableView/Controller and UINavigationController settings to see whether I may have missed something.

Any suggestions?

Body:
So I've worked it out.

I had to find the specific layer within the UINavigationBar's subviews that contained the title text, then animate that layer. The results are exactly what I wanted.

Here's my answer (Swift 5 iOS 12)...

override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    if (newTitle ?? "").isEmpty == false { // only proceed with a valid value for newTitle.

        // CATransition code
        let titleAnimation = CATransition()
        titleAnimation.duration = 0.5
        titleAnimation.type = CATransitionType.push
        titleAnimation.subtype = CATransitionSubtype.fromRight
        titleAnimation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)

        // this is a detail view controller, so we must grab the reference
        // to the parent view controller's navigation controller
        // then cycle through until we find the title labels.
        if let subviews = parent?.navigationController?.navigationBar.subviews {

            for navigationItem in subviews {

                for itemSubView in navigationItem.subviews {

                    if let largeLabel = itemSubView as? UILabel {

                        largeLabel.layer.add(titleAnimation, forKey: "changeTitle")
                    }
                }
            }
        }
        // finally set the title
        navigationItem.title = newTitle
   }

Note: there is no need to import QuartzCore.

...and here's the process I went through to identify what I had to change...

This SO Q&A How to set multi line Large title in navigation bar? ( New feature of iOS 11)
 helped me identify the process detailed below, so thanks in particular to the original post and the answer by @Krunal .

Using the same code to cycle through the UINavigationBar's subviews (as above), I used a print to terminal to identify the various UINavigationItems and their subviews.

        counter = 0

        if let subviews = parent?.navigationController?.navigationBar.subviews {

            for navigationItem in subviews {

                print("____\(navigationItem)")

                for itemSubView in navigationItem.subviews {

                    counter += 1

                    print("_______\(itemSubView)")
                }
            }
        }
        print("COUNTER: \(counter)")

this code yielded the following prints in terminal (for iPhone 8 Plus running iOS 12.2 in simulator)...

 ____<_UIBarBackground: 0x7f922740c000; frame = (0 -20; 414 116); userInteractionEnabled = NO; layer = <CALayer: 0x6000026ce1c0>>
 _______<UIImageView: 0x7f922740c9c0; frame = (0 116; 414 0.333333); userInteractionEnabled = NO; layer = <CALayer: 0x6000026ce7c0>>
 _______<UIVisualEffectView: 0x7f922740cbf0; frame = (0 0; 414 116); layer = <CALayer: 0x6000026ce880>>
 ____<_UINavigationBarLargeTitleView: 0x7f922740f390; frame = (0 44; 414 52); clipsToBounds = YES; layer = <CALayer: 0x6000026cd840>>
 _______<UILabel: 0x7f9227499fe0; frame = (20.1667 3.66667; 206.333 40.6667); text = 'Event Details'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6000005bf250>>
 ____<_UINavigationBarContentView: 0x7f922740d660; frame = (0 0; 414 44); clipsToBounds = YES; layer = <CALayer: 0x6000026cea00>>
 _______<_UIButtonBarStackView: 0x7f92274984a0; frame = (302 0; 100 44); layer = <CALayer: 0x60000261cc60>>
 _______<_UIButtonBarButton: 0x7f922749a5c0; frame = (0 0; 82.3333 44); layer = <CALayer: 0x60000261ee60>>
 _______<UILabel: 0x7f922749a2d0; frame = (155 11.6667; 104.333 20.3333); text = 'Event Details'; alpha = 0; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6000005bfc50>>
 ____<_UINavigationBarModernPromptView: 0x7f9227602db0; frame = (0 0; 0 50); alpha = 0; hidden = YES; layer = <CALayer: 0x6000026e4600>>
 COUNTER: 2

I've actually applied the animation twice - to the UILabel layer within _UINavigationBarLargeTitleView and the UILabel layer within _UINavigationBarContentView. This does not seem to matter however because, when the large title first appears, the label within content view (which I assume is for the "old style" title in the navigation bar when the large title is scrolled off screen) is hidden on viewDidAppear.

Incidentally, if you drop in the following two lines, you'll also have multi-line large titles:

 largeLabel.numberOfLines = 0
 largeLabel.lineBreakMode = .byWordWrapping

BUT, I've not yet figured out how to animate the increase in size of the large title frame, so a change to two or more lines is immediate and IMHO ruins the animation of the title change.

Not yet tested on device, but does seem to work OK for both iPhone and iPad sims.

If you find any bugs, let me know and I'll update my answer.


问:
React-native command not found in Terminal
I keep encountering the "command not found" error when trying to create a new react native project. I've looked through past questions on this topic and they all say to change the PATH, which doesn't seem to work for me.

I tried installing and uninstalling react-native-cli. I've checked and changed the PATH. Nothing works.

```<code>Davids-MBP-2:~ David$ brew -v
Homebrew >=1.7.1 (shallow or no git repository)
Homebrew/homebrew-core (no git repository)
Davids-MBP-2:~ David$ watchman -v
4.9.0
Davids-MBP-2:~ David$ node -v
v11.13.0
Davids-MBP-2:~ David$ npm install -g react-native-cli
/Users/David/.npm-global/bin/react-native -> /Users/David/.npm-global/lib/node_modules/react-native-cli/index.js
+ react-native-cli@2.0.1
updated 1 package in 1.392s
Davids-MBP-2:~ David$ react-native init hello
-bash: react-native: command not found
Davids-MBP-2:~ David$
</code>```

I installed node, homebrew, watchman, and finally react-native. The first three work, but react doesn't.

答:
You first to make you sure that /usr/local/share/npm/bin is in your PATH to use binaries installed with npm.

Add  following are to your ~/.bashrc:

```<code>export PATH="/usr/local/share/npm/bin:$PATH"
</code>```

you also sure about that path you install npm pakage.if that can not fullfill your requirement npm from bin then you must uninstall and after fully uninstall you install it again it may be work.It work in my case

Body:
I keep encountering the "command not found" error when trying to create a new react native project. I've looked through past questions on this topic and they all say to change the PATH, which doesn't seem to work for me.

I tried installing and uninstalling react-native-cli. I've checked and changed the PATH. Nothing works.

Davids-MBP-2:~ David$ brew -v
Homebrew >=1.7.1 (shallow or no git repository)
Homebrew/homebrew-core (no git repository)
Davids-MBP-2:~ David$ watchman -v
4.9.0
Davids-MBP-2:~ David$ node -v
v11.13.0
Davids-MBP-2:~ David$ npm install -g react-native-cli
/Users/David/.npm-global/bin/react-native -> /Users/David/.npm-global/lib/node_modules/react-native-cli/index.js
+ react-native-cli@2.0.1
updated 1 package in 1.392s
Davids-MBP-2:~ David$ react-native init hello
-bash: react-native: command not found
Davids-MBP-2:~ David$

I installed node, homebrew, watchman, and finally react-native. The first three work, but react doesn't.

Body:
You first to make you sure that /usr/local/share/npm/bin is in your PATH to use binaries installed with npm.

Add  following are to your ~/.bashrc:

export PATH="/usr/local/share/npm/bin:$PATH"

you also sure about that path you install npm pakage.if that can not fullfill your requirement npm from bin then you must uninstall and after fully uninstall you install it again it may be work.It work in my case


问:
jsonwebtoken: expiresIn does not expires?
I am trying to set the token to be expired in one hour following the example from the guide:

```<code>jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 })
</code>```

But the toke never expires in a few hours later:

```<code>curl -XGET -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTU4OTAzMDI3LCJleHAiOjE1NTg5MDY2Mjd9.8uHKDM4Hgy08kw_0CLib2QnzqudeC_RsIlh8e9uURT0' 'http://localhost:3000/api/users'
</code>```

Have I missing something?

How do I set it to expire in 1 or 5 minutes?

The code for verifying the token:

```<code>import jwt from 'jsonwebtoken'
import config from '../config'

export default async (ctx, next) => {
  try {
    await next()

    if(ctx.req.hasOwnProperty('headers') && ctx.req.headers.hasOwnProperty('authorization')) {
      ctx.req.user = jwt.verify(ctx.req.headers['authorization'], config.JWT_SECRET, function (err, payload) {
        console.log(payload)
      })
    } else {
      // If there is no autorization header, return 401 status code.
      ctx.throw(401, 'Protected resource, use Authorization header to get access')
    }
  } catch (err) {
    ctx.status = err.status || 500

    ctx.type = 'json'
    ctx.body = {
      status: ctx.status,
      message: err.message
    }

    ctx.app.emit('error', err, ctx)
  }
}
</code>```

答:
The jwt.verify function in the question code sample is using a callback function to return it's asynchronous result.

Koa is promise based and won't pick up this callback result or catch any errors being raised (including a TokenExpiredError). The verify err is completely ignored at the moment.

jwt.verify can be converted into a promise, or if you don't supply the callback argument the function will return synchronously. The try/catch will then work as expected.

```<code>import util from 'util'
import jwt from 'jsonwebtoken'
import config from '../config'

export const verifyPromise = util.promisify(jwt.verify)

export default async function verifyToken(ctx, next){

  if(!ctx.req.hasOwnProperty('headers') || !ctx.req.headers.hasOwnProperty('authorization')) {
    return ctx.throw(401, 'Protected resource, use Authorization header to get access')
  }

  try {
    let payload = await verifyPromise(ctx.req.headers['authorization'], config.JWT_SECRET, {})
    console.log(payload)
  }
  catch (err) {
    if (err.name === 'TokenExpiredError'){
      return ctx.throw(401, 'Protected resource, token expired')
    }

    console.error(err)
    return ctx.throw(500, 'Protected resource, token error')

  }

  await next()

}
</code>```

The jwt.sign function takes a number as seconds or a string description of time from zeit/ms

```<code>{ expiresIn: 1 * 60 }
{ expiresIn: '1m' }
</code>```

Body:
I am trying to set the token to be expired in one hour following the example from the guide:

jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 })

But the toke never expires in a few hours later:

curl -XGET -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTU4OTAzMDI3LCJleHAiOjE1NTg5MDY2Mjd9.8uHKDM4Hgy08kw_0CLib2QnzqudeC_RsIlh8e9uURT0' 'http://localhost:3000/api/users'

Have I missing something?

How do I set it to expire in 1 or 5 minutes?

The code for verifying the token:

import jwt from 'jsonwebtoken'
import config from '../config'

export default async (ctx, next) => {
  try {
    await next()

    if(ctx.req.hasOwnProperty('headers') && ctx.req.headers.hasOwnProperty('authorization')) {
      ctx.req.user = jwt.verify(ctx.req.headers['authorization'], config.JWT_SECRET, function (err, payload) {
        console.log(payload)
      })
    } else {
      // If there is no autorization header, return 401 status code.
      ctx.throw(401, 'Protected resource, use Authorization header to get access')
    }
  } catch (err) {
    ctx.status = err.status || 500

    ctx.type = 'json'
    ctx.body = {
      status: ctx.status,
      message: err.message
    }

    ctx.app.emit('error', err, ctx)
  }
}

Body:
The jwt.verify function in the question code sample is using a callback function to return it's asynchronous result.

Koa is promise based and won't pick up this callback result or catch any errors being raised (including a TokenExpiredError). The verify err is completely ignored at the moment.

jwt.verify can be converted into a promise, or if you don't supply the callback argument the function will return synchronously. The try/catch will then work as expected.

import util from 'util'
import jwt from 'jsonwebtoken'
import config from '../config'

export const verifyPromise = util.promisify(jwt.verify)

export default async function verifyToken(ctx, next){

  if(!ctx.req.hasOwnProperty('headers') || !ctx.req.headers.hasOwnProperty('authorization')) {
    return ctx.throw(401, 'Protected resource, use Authorization header to get access')
  }

  try {
    let payload = await verifyPromise(ctx.req.headers['authorization'], config.JWT_SECRET, {})
    console.log(payload)
  }
  catch (err) {
    if (err.name === 'TokenExpiredError'){
      return ctx.throw(401, 'Protected resource, token expired')
    }

    console.error(err)
    return ctx.throw(500, 'Protected resource, token error')

  }

  await next()

}

The jwt.sign function takes a number as seconds or a string description of time from zeit/ms

{ expiresIn: 1 * 60 }
{ expiresIn: '1m' }


问:
Converting Negative Number in String Format to Numeric when Sign as at the end
I have certain numbers within a column of my dataframe that have negative numbers in a string format like this: "500.00-" I need to convert every negative number within the column to numeric format. I'm sure there's an easy way to do this, but I have struggled finding one specific to pandas dataframe. Any help would be greatly appreciated.   </p>

<p>I have tried the basic to_numeric function as shown below, but it doesn't read it in correctly. Also, only some of the numbers within the column are negative, therefore I can't simply remove all the negative signs and multiply the column by 1. </p>

```<code>Q1['Credit'] = pd.to_numeric(Q1['Credit'])
</code>```

答:
Sample data:

```<code>df:
      num
0   50.00
1  60.00-
2  70.00+
3  -80.00
</code>```

Using series str accessor to check last digit. If it is '-' or '+', swap it to front. Use df.mask to apply it only to rows having -/+ as suffix. Finally, astype column to float

```<code>df.num.mask(df.num.str[-1].isin(['-','+']), df.num.str[-1].str.cat(df.num.str[:-1])).astype('float')

Out[1941]:
0    50.0
1   -60.0
2    70.0
3   -80.0
Name: num, dtype: float64
</code>```

Body:
I have certain numbers within a column of my dataframe that have negative numbers in a string format like this: "500.00-" I need to convert every negative number within the column to numeric format. I'm sure there's an easy way to do this, but I have struggled finding one specific to pandas dataframe. Any help would be greatly appreciated.

I have tried the basic to_numeric function as shown below, but it doesn't read it in correctly. Also, only some of the numbers within the column are negative, therefore I can't simply remove all the negative signs and multiply the column by 1.

Q1['Credit'] = pd.to_numeric(Q1['Credit'])

Body:
Sample data:

df:
      num
0   50.00
1  60.00-
2  70.00+
3  -80.00

Using series str accessor to check last digit. If it is '-' or '+', swap it to front. Use df.mask to apply it only to rows having -/+ as suffix. Finally, astype column to float

df.num.mask(df.num.str[-1].isin(['-','+']), df.num.str[-1].str.cat(df.num.str[:-1])).astype('float')

Out[1941]:
0    50.0
1   -60.0
2    70.0
3   -80.0
Name: num, dtype: float64


问:
How to "Unlock Jenkins"?
I am installing Jenkins 2 on windows,after installing,a page is opened,URL is:

http://localhost:8080/login?from=%2F

content of the page is like this:

Question:

How to "Unlock Jenkins"?

PS:I have looked for the answer in documentation and google.

答:
Yet another way to bypass the unlock screen is to copy the UpgradeWizard state to the InstallUtil last execution version, add an install.runSetupWizard file with the contents 'false', and update the config.xml installStateName from NEW to RUNNING.

```<code>docker exec -it jenkins bash
sed -i s/NEW/RUNNING/ /var/jenkins_home/config.xml
echo 'false' > /var/jenkins_home/jenkins.install.runSetupWizard
cp /var/jenkins_home/jenkins.install.UpgradeWizard.state /var/jenkins_home/jenkins.install.InstallUtil.lastExecVersion
exit
docker restart jenkins
</code>```

For reference, this is the command I use to run jenkins:

```<code>docker run --rm --name jenkins --network host -u root -d -v jenkins:/var/jenkins_home -v /var/run/docker.sock:/var/run/docker.sock jenkinsci/blueocean:1.16.0
</code>```

You will also want to update the config with the Root URL:

```<code>echo "<?xml version='1.1' encoding='UTF-8'?><jenkins.model.JenkinsLocationConfiguration><jenkinsUrl>http://<IP>:8080/</jenkinsUrl></jenkins.model.JenkinsLocationConfiguration>" > jenkins.model.JenkinsLocationConfiguration.xml
exit
docker restart jenkins
</code>```

Title: How to "Unlock Jenkins"?

Body:
Yet another way to bypass the unlock screen is to copy the UpgradeWizard state to the InstallUtil last execution version, add an install.runSetupWizard file with the contents 'false', and update the config.xml installStateName from NEW to RUNNING.

docker exec -it jenkins bash
sed -i s/NEW/RUNNING/ /var/jenkins_home/config.xml
echo 'false' > /var/jenkins_home/jenkins.install.runSetupWizard
cp /var/jenkins_home/jenkins.install.UpgradeWizard.state /var/jenkins_home/jenkins.install.InstallUtil.lastExecVersion
exit
docker restart jenkins

For reference, this is the command I use to run jenkins:

docker run --rm --name jenkins --network host -u root -d -v jenkins:/var/jenkins_home -v /var/run/docker.sock:/var/run/docker.sock jenkinsci/blueocean:1.16.0

You will also want to update the config with the Root URL:

echo "<?xml version='1.1' encoding='UTF-8'?><jenkins.model.JenkinsLocationConfiguration><jenkinsUrl>http://<IP>:8080/</jenkinsUrl></jenkins.model.JenkinsLocationConfiguration>" > jenkins.model.JenkinsLocationConfiguration.xml
exit
docker restart jenkins


问:
Rails remove subarray from array
In my Rails 5 app I have something like this:

```<code>a = [1,2,3]

a.map do |entry|
  entry.delete if condition == true
end
</code>```

This removes the entry if the condition is true.

Now I have this:

```<code>a = [[1,2],[2,3],[3,4]]

a.map do |entry|
  entry.delete if condition == true
end
</code>```

This loops through a but now entry is an array and delete should remove the entire entry but instead I get:

```<code>wrong number of arguments (given 0, expected 1)
</code>```

Dos anybody know how I can loop through an array of arrays and remove an entire subarray?

答:
Try this:
a.delete_if {condition}

For example:

```<code>a = [[1,2],[2,3],[3,4]]
a.delete_if {|entry| entry[0] == 1 }
# returns [[2, 3], [3, 4]]
</code>```

Title: Rails remove subarray from array

Body:
In my Rails 5 app I have something like this:

a = [1,2,3]

a.map do |entry|
  entry.delete if condition == true
end

This removes the entry if the condition is true.

Now I have this:

a = [[1,2],[2,3],[3,4]]

a.map do |entry|
  entry.delete if condition == true
end

This loops through a but now entry is an array and delete should remove the entire entry but instead I get:

wrong number of arguments (given 0, expected 1)

Dos anybody know how I can loop through an array of arrays and remove an entire subarray?

Body:
Try this:
a.delete_if {condition}

For example:

a = [[1,2],[2,3],[3,4]]
a.delete_if {|entry| entry[0] == 1 }
# returns [[2, 3], [3, 4]]


问:
Matlab optimproblem: Possible to use 3rd party ILP solver?
I've been browsing the Matlab's [mixed] integer linear program ([M]ILP) commands/classes documentation to see if there is a way to define an "optimization problem" (optimproblem) and call out to an external [M]ILP solver using an API rather than using the native intlinprog.  I haven't yet found any indication that this is possible, short of converting the problem to matrix/solver-based format (prob2struct) and creating my own intermediate ILP data file.  That would be beyond what I am willing to do.

Is there in fact no way to directly invoke a 3rd party solver?

If there is a way, can someone please direct me to the proper documentation page?

If there is in fact no way, can someone please confirm this?

Thanks.

Clarification: Question emphasizes use of optimproblem

I appreciate the answers and comments to date, but I realize from them that I need to emphasize a key point in the question. My aim is to exploit the high level problem specification of optimproblem, which uses Matlab's array syntax to compactly represent a large number of constraints, lengthy inner products for them, and for the objective function.  This is the so-called problem-based approach, which is akin in high level to AMPL.

In contrast, my impression from initial browsings of the cited documents on 3rd party solvers is that their inputs are at a lower level of abstraction.  This is the so-called solver-based approach, which colleagues have also called the "matrix level", for the following reason: The archetypal arrays x, Aeq, beq, Aineq, bineq, etc., are assumed to have been composed, and it is up to the analyst to keep track of which elements in x correspond to which (more) real-world parameters, i.e., those in the problem-based approach.

I was hoping that there was a way to use optimproblem and have it use a 3rd party solver so that I don't have to deal with the matrix level.  An example of the latter would be using prob2struct to generate arrays to explicitly pass to external solvers via Matlab APIs (if they have them).  I want to avoid this because I don't want to keep track of which problem-based variables map to which solver-based variables, especially since the former is often of high dimensionality. Granted, varindex simplifies the bookkeeping, but not having to code for such bookkeeping is much preferable.

答: Yes -- various 3rd-party optimization solvers have MATLAB APIs. For example, CPLEX and Gurobi both have MATLAB APIs. But you invoke them through their own function calls, not through intlinprog.


问:
Efficient way to substitute repeating np.vstack in python?
I am trying to implement this post in python.

```<code>import numpy as np
x = np.array([0,0,0])
for r in range(3):
    x = np.vstack((x, np.array([-r, r, -r])))
</code>```

x gets this value

```<code>array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])
</code>```

I am concerned the runtime efficiency about the repeating np.vstack. Is there a more efficient way to do this?

答:
You can use np.block as  following:

First create a block which you are currently doing inside the for loop

Finally, vertically stack a row of zeros using np.vstack to get the final desired answer

```<code>import numpy as np

size = 3
sign = np.ones(3)*((-1)**np.arange(1, size+1)) # General sign array of repeating -1, 1

A = np.ones((size, size), int)
B = np.arange(0, size) * A
B = sign * np.block([B.T])

# array([[ 0,  0,  0],
#        [ -1, 1, -1],
#        [ -2, 2, -2]])

answer = np.vstack([B[0], B])

# array([[ 0,  0,  0],
#        [ 0,  0,  0],
#        [ -1, 1, -1],
#        [ -2, 2, -2]])
</code>```

Body:
I am trying to implement this post in python.

import numpy as np
x = np.array([0,0,0])
for r in range(3):
    x = np.vstack((x, np.array([-r, r, -r])))

x gets this value

array([[ 0,  0,  0],
       [ 0,  0,  0],
       [-1,  1, -1],
       [-2,  2, -2]])

I am concerned the runtime efficiency about the repeating np.vstack. Is there a more efficient way to do this?

Body:
You can use np.block as  following:

First create a block which you are currently doing inside the for loop

Finally, vertically stack a row of zeros using np.vstack to get the final desired answer

import numpy as np

size = 3
sign = np.ones(3)*((-1)**np.arange(1, size+1)) # General sign array of repeating -1, 1

A = np.ones((size, size), int)
B = np.arange(0, size) * A
B = sign * np.block([B.T])

# array([[ 0,  0,  0],
#        [ -1, 1, -1],
#        [ -2, 2, -2]])

answer = np.vstack([B[0], B])

# array([[ 0,  0,  0],
#        [ 0,  0,  0],
#        [ -1, 1, -1],
#        [ -2, 2, -2]])


问:
Convert values of two dictionaries to DateTime
Is there a way to convert string values of two dictionaries to DateTime recursively with only one loop  ( foreach for example) ?

(Thanks for the help in advance)

Check the code below:

```<code>static void Main(string[] args)
{

        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();

        Dictionary<string, string> Dict = new Dictionary<string, string>();
        Dictionary<string, string> Dict2 = new Dictionary<string, string>();

        foreach (var item in Dict)
        {
            foreach (var item2 in Dict2)
            {
                if (item.Key == item2.Key)
                {
                    DateTime date1 = DateTime.Parse(item.Value);
                    DateTime date2 = DateTime.Parse(item2.Value);

                    var diffInSeconds = (date1 - date2).TotalSeconds;
                    Console.WriteLine(diffInSeconds);
                }

            }

        }

        stopwatch.Stop();
        Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

 }
</code>```

答:
less line of code, an elegant syntax I hope it meets your needs</p>

```<code>    static void Main(string[] args)
    {
        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();

        Dictionary<string, string> Dict = new Dictionary<string, string>();
        Dictionary<string, string> Dict2 = new Dictionary<string, string>();

        foreach (var item in Dict)
        {
            if (Dict2.TryGetValue(item.Key, out string date))
            {
                var diffInSeconds = (DateTime.Parse(item.Value) - DateTime.Parse(date)).TotalSeconds;
                Console.WriteLine(diffInSeconds);
            }

        }

        stopwatch.Stop();
        Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

    }
</code>```

Body:
Is there a way to convert string values of two dictionaries to DateTime recursively with only one loop  ( foreach for example) ?

(Thanks for the help in advance)

Check the code below:

static void Main(string[] args)
{

        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();

        Dictionary<string, string> Dict = new Dictionary<string, string>();
        Dictionary<string, string> Dict2 = new Dictionary<string, string>();

        foreach (var item in Dict)
        {
            foreach (var item2 in Dict2)
            {
                if (item.Key == item2.Key)
                {
                    DateTime date1 = DateTime.Parse(item.Value);
                    DateTime date2 = DateTime.Parse(item2.Value);

                    var diffInSeconds = (date1 - date2).TotalSeconds;
                    Console.WriteLine(diffInSeconds);
                }

            }

        }

        stopwatch.Stop();
        Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

 }

Body:
less line of code, an elegant syntax I hope it meets your needs

    static void Main(string[] args)
    {
        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();

        Dictionary<string, string> Dict = new Dictionary<string, string>();
        Dictionary<string, string> Dict2 = new Dictionary<string, string>();

        foreach (var item in Dict)
        {
            if (Dict2.TryGetValue(item.Key, out string date))
            {
                var diffInSeconds = (DateTime.Parse(item.Value) - DateTime.Parse(date)).TotalSeconds;
                Console.WriteLine(diffInSeconds);
            }

        }

        stopwatch.Stop();
        Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

    }