问:
switch statement with multiple conditions in r
I want to write a switch statement in r with three conditions but can't seem to get it to work. What am I doing wrong?

# assigning some values
test.type <- "p"
var.equal<- TRUE
  paired <- FALSE

# preparing text for which p-value adjustment method was used
test.description <- switch(
    EXPR = test.type & var.equal & paired,
    "p" & TRUE & TRUE = "Student's t-test",
    "p" & FALSE & TRUE = "Student's t-test",
    "p" & TRUE & FALSE = "Student's t-test",
    "p" & FALSE & FALSE = "Games-Howell test",
    "np" & TRUE & TRUE = "Durbin-Conover test"
  )
#> Error: <text>:10:23: unexpected '='
#> 9:     EXPR = test.type & var.equal & paired,
#> 10:     "p" & TRUE & TRUE =
#>                           ^
```

<p><sup>Created on 2018-11-08 by the reprex package (v0.2.1)</sup></p>

<p>A simpler version of this statement with just one condition <em>does</em> work-</p>

<pre class="lang-r prettyprint-override"><code># simpler switch
(test.description <- switch(
  EXPR = test.type,
  "p"  = "Student's t-test",
  "np" = "Durbin-Conover test"
))
#> [1] "Student's t-test"
</code>```

Created on 2018-11-08 by the reprex package (v0.2.1)

答:
Another solution could be to use dplyr's case_when, which uses syntax more similar to your switch statements:

```<code>library(dplyr)

## initial dataframe
df <- data.frame(
  test.type = c("p", "p", "p", "p", "np", "np"),
  var.equal = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE),
  paired = c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE)
  )

## add column test.description
mutate(df,
  test.description = case_when(
      test.type == "p" & !var.equal & !paired  ~ "Games-Howell test",
      test.type == "p"                         ~ "Student's t-test",
      test.type == "np" & var.equal & paired   ~ "Durbin-Conover test",
      TRUE                                     ~ "Unknown combination"
     )
)
</code>```

Body:
I want to write a switch statement in r with three conditions but can't seem to get it to work. What am I doing wrong?

# assigning some values
test.type <- "p"
var.equal<- TRUE
  paired <- FALSE

# preparing text for which p-value adjustment method was used
test.description <- switch(
    EXPR = test.type & var.equal & paired,
    "p" & TRUE & TRUE = "Student's t-test",
    "p" & FALSE & TRUE = "Student's t-test",
    "p" & TRUE & FALSE = "Student's t-test",
    "p" & FALSE & FALSE = "Games-Howell test",
    "np" & TRUE & TRUE = "Durbin-Conover test"
  )
#> Error: <text>:10:23: unexpected '='
#> 9:     EXPR = test.type & var.equal & paired,
#> 10:     "p" & TRUE & TRUE =
#>                           ^

Created on 2018-11-08 by the reprex package (v0.2.1)

A simpler version of this statement with just one condition does work-

# simpler switch
(test.description <- switch(
  EXPR = test.type,
  "p"  = "Student's t-test",
  "np" = "Durbin-Conover test"
))
#> [1] "Student's t-test"

Created on 2018-11-08 by the reprex package (v0.2.1)

Body:
Another solution could be to use dplyr's case_when, which uses syntax more similar to your switch statements:

library(dplyr)

## initial dataframe
df <- data.frame(
  test.type = c("p", "p", "p", "p", "np", "np"),
  var.equal = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE),
  paired = c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE)
  )

## add column test.description
mutate(df,
  test.description = case_when(
      test.type == "p" & !var.equal & !paired  ~ "Games-Howell test",
      test.type == "p"                         ~ "Student's t-test",
      test.type == "np" & var.equal & paired   ~ "Durbin-Conover test",
      TRUE                                     ~ "Unknown combination"
     )
)


来源: stackexchange

问:
ModuleNotFoundError: No module named 'message_board'
I ran this command on the terminal

```<code>coverage run test_message_board_urls.py
</code>```

and I got an error

ModuleNotFoundError: No module named 'message_board

I have a statement in the test_message_board_urls.py file that says

```<code>from message_board.views import xxx,yyy,zzz
</code>```

Thanks for your help

答: It does look for the module message_board in order to import the functions xxx, yyy and zzz from the package views, but it does not find the module message_board. Either you have not installed the module message_board or it is located at a path, where it is not found by the script.</p>

ContentLicense: CC BY-SA 4.0

Body:
I ran this command on the terminal

coverage run test_message_board_urls.py

and I got an error

ModuleNotFoundError: No module named 'message_board

I have a statement in the test_message_board_urls.py file that says

from message_board.views import xxx,yyy,zzz

Thanks for your help


问:
jQuery - how can I get a value of the next option in a dropdown after the selected one?
I have a drop down with a selected option at index = 0.
How can I in jquery get the value of the next option at index = 1?
Of course I need to do that without specifying the value of the next option because I can;t assume what it will be at this point.

thx

答:
```<code> $('#selectid option:selected').next().val()
</code>```

ContentLicense: CC BY-SA 3.0


问:
Group by different categories
This turns out to be pretty easy for some of you: theoretically is about using the group_by() function and the filter() function. However to me is still problematic

```<code>library(dplyr)

df <- data.frame(Serial=c(1010,1010,1102,1102,1102,1103), Value=c(1,2,1,2,3,1))
df

 Serial Value
1   1010     1
2   1010     2
3   1102     1
4   1102     2
5   1102     3
6   1103     1
</code>```

I would like to create an id variable based on serial number and Value such as

```<code>Serial    Value  Id
1   1010     1     1
2   1010     2     1
3   1102     1     2
4   1102     2     2
5   1102     3     2
6   1103     1     3
</code>```

Any help is welcomed

答:
An option would be

```<code>df$Id <- cumsum(df$Value == 1)
df$Id
#[1] 1 1 2 2 2 3
</code>```

Or with factor

```<code>as.integer(factor(df$Serial))
</code>```

Or using match

```<code>with(df, match(Serial, unique(Serial))
</code>```

Title: Group by different categories

Body:
This turns out to be pretty easy for some of you: theoretically is about using the group_by() function and the filter() function. However to me is still problematic

library(dplyr)

df <- data.frame(Serial=c(1010,1010,1102,1102,1102,1103), Value=c(1,2,1,2,3,1))
df

 Serial Value
1   1010     1
2   1010     2
3   1102     1
4   1102     2
5   1102     3
6   1103     1

I would like to create an id variable based on serial number and Value such as

Serial    Value  Id
1   1010     1     1
2   1010     2     1
3   1102     1     2
4   1102     2     2
5   1102     3     2
6   1103     1     3

Any help is welcomed

Body:
An option would be

df$Id <- cumsum(df$Value == 1)
df$Id
#[1] 1 1 2 2 2 3

Or with factor

as.integer(factor(df$Serial))

Or using match

with(df, match(Serial, unique(Serial))


问:
Calling functions on my SavingsAccount object and printing the result
I have a SavingsAccount object and I am trying to use my functions to manipulate the balance of the account. Now I get no errors but no output. I have the feeling that I have done something wrong and I don't quite understand how to call my functions on the object.

If I try to print the output for one of the accounts I make I get a memory adress.

I got all kinds of different errors while tweaking and its finally error free. But still no output and I am afraid I got it quite wrong and its just buggy and I don't call my functions the right way, or my constructor is not coded as its ment to be.

public class SavingsAccount {
  // Class
  int balance;
  int amountToDeposit;
  int amountToWithdraw;

  //Constructor
  public SavingsAccount(int initialBalance, int deposit, int withdraw){
    balance = initialBalance;
    amountToDeposit = deposit;
    amountToWithdraw = withdraw;
  }

  //Functions thats I wanna call

  // Setting balance
    public void checkBalance() {
        System.out.println("Hello!");
        System.out.println("Your balance is " + balance);
    }

  // Depositing amounts
    public void deposit(int amountToDeposit) {
        balance = balance + amountToDeposit;
        System.out.println("You just deposited" + amountToDeposit);
  }

  // Withdrawing amounts
    public int withdraw(int amountToWithdraw) {
        balance = balance - amountToWithdraw;
        System.out.println("You just withdrew" + amountToWithdraw);

      return amountToWithdraw;
  }

  // Main
  public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    //Check balance
     System.out.println(test); // Will give a memory adress
  }
}
```

I would like to use my functions on the object I make and print the result.

Thanks for reading.

答:
Hello you can implement toString to print the object as below:

```<code>package com.stuart.livealert;

public class SavingsAccount {
    // Class
    int balance;
    int amountToDeposit;
    int amountToWithdraw;

    //Constructor
    public SavingsAccount(int initialBalance, int deposit, int withdraw){
        balance = initialBalance;
        amountToDeposit = deposit;
        amountToWithdraw = withdraw;
    }

    //Functions thats I wanna call

    // Setting balance
    public void checkBalance() {
        System.out.println("Hello!");
        System.out.println("Your balance is " + balance);
    }

    // Depositing amounts
    public void deposit(int amountToDeposit) {
        balance = balance + amountToDeposit;
        System.out.println("You just deposited" + amountToDeposit);
    }
    // Withdrawing amounts
    public int withdraw(int amountToWithdraw) {
        balance = balance - amountToWithdraw;
        System.out.println("You just withdrew" + amountToWithdraw);

        return amountToWithdraw;
    }

    @Override
    public String toString() {
        return "{balance : " + balance + " deposit : " + amountToDeposit + " withdraw : " + amountToWithdraw + " }";
    }

    // Main
    public static void main(String[] args){
        //Setting values, balance, deposit, withdraw.
        SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
        SavingsAccount test = new SavingsAccount(5000, 200, 100);

        //Check balance
        System.out.println(test); // Will give {balance : 5000 deposit : 200 withdraw : 100 }

    }
}

</code>```

Body:
I have a SavingsAccount object and I am trying to use my functions to manipulate the balance of the account. Now I get no errors but no output. I have the feeling that I have done something wrong and I don't quite understand how to call my functions on the object.

If I try to print the output for one of the accounts I make I get a memory adress.

I got all kinds of different errors while tweaking and its finally error free. But still no output and I am afraid I got it quite wrong and its just buggy and I don't call my functions the right way, or my constructor is not coded as its ment to be.

public class SavingsAccount {
  // Class
  int balance;
  int amountToDeposit;
  int amountToWithdraw;

  //Constructor
  public SavingsAccount(int initialBalance, int deposit, int withdraw){
    balance = initialBalance;
    amountToDeposit = deposit;
    amountToWithdraw = withdraw;
  }

  //Functions thats I wanna call

  // Setting balance
    public void checkBalance() {
        System.out.println("Hello!");
        System.out.println("Your balance is " + balance);
    }

  // Depositing amounts
    public void deposit(int amountToDeposit) {
        balance = balance + amountToDeposit;
        System.out.println("You just deposited" + amountToDeposit);
  }

  // Withdrawing amounts
    public int withdraw(int amountToWithdraw) {
        balance = balance - amountToWithdraw;
        System.out.println("You just withdrew" + amountToWithdraw);

      return amountToWithdraw;
  }

  // Main
  public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    //Check balance
     System.out.println(test); // Will give a memory adress
  }
}

I would like to use my functions on the object I make and print the result.

Thanks for reading.

Body:
Hello you can implement toString to print the object as below:

package com.stuart.livealert;

public class SavingsAccount {
    // Class
    int balance;
    int amountToDeposit;
    int amountToWithdraw;

    //Constructor
    public SavingsAccount(int initialBalance, int deposit, int withdraw){
        balance = initialBalance;
        amountToDeposit = deposit;
        amountToWithdraw = withdraw;
    }

    //Functions thats I wanna call

    // Setting balance
    public void checkBalance() {
        System.out.println("Hello!");
        System.out.println("Your balance is " + balance);
    }

    // Depositing amounts
    public void deposit(int amountToDeposit) {
        balance = balance + amountToDeposit;
        System.out.println("You just deposited" + amountToDeposit);
    }
    // Withdrawing amounts
    public int withdraw(int amountToWithdraw) {
        balance = balance - amountToWithdraw;
        System.out.println("You just withdrew" + amountToWithdraw);

        return amountToWithdraw;
    }

    @Override
    public String toString() {
        return "{balance : " + balance + " deposit : " + amountToDeposit + " withdraw : " + amountToWithdraw + " }";
    }

    // Main
    public static void main(String[] args){
        //Setting values, balance, deposit, withdraw.
        SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
        SavingsAccount test = new SavingsAccount(5000, 200, 100);

        //Check balance
        System.out.println(test); // Will give {balance : 5000 deposit : 200 withdraw : 100 }

    }
}


问:
<rejected> TypeError: promisify is not a function
Can anyone let me know the solution of my problem. I got an error again and again whenever i run this setup. i checked a lot but i didn't get that. please look on my code files and tell me the solution.whenever
 i send some data through the form page then, this error will show, sometimes i think, is it the problem of modern ecmascript or not.

```<code>start.js

const mongoose = require('mongoose');
const dotenv = require('dotenv');

// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variable.env' });

// Connect to our Database and handle any bad connections
mongoose.connect(process.env.DATABASE, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
  console.error(`sir your error → ${err.message}`);
});

process.on('unhandledRejection', function(reason, promise) {
  console.log(promise);
});

require('./models/User');

// READY?! Let's go!

// Start our app!
const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
  console.log(`Express running → PORT ${server.address().port}`);
});

</code>```

```<code>userController.js

const mongoose = require('mongoose');
const User = mongoose.model('User');
const promisify = require('es6-promisify');

exports.loginForm = (req, res) => {
  res.render('login', { title: 'Login' })
};

exports.registerForm = (req, res) => {
  res.render('register', { title: 'Register' })
};

  exports.validateRegister = (req, res, next) => {
  req.sanitizeBody('user2');
  req.checkBody('user2', 'You must supply a name!').notEmpty();
  req.checkBody('user9', 'That Email is not valid!').isEmail();
  req.sanitizeBody('user9').normalizeEmail({
    gmail_remove_dots: false,
    remove_extension: false,
    gmail_remove_subaddress: false
  });
  req.checkBody('password', 'Password Cannot be Blank!').notEmpty();
  req.checkBody('confirmPassword', 'Confirmed Password cannot be blank!').notEmpty();
  req.checkBody('confirmPassword', 'Oops! Your passwords do not match').equals(req.body.password);

  const errors = req.validationErrors();
  if (errors) {
    req.flash('error', errors.map(err => err.msg));
    res.render('register');
    return; // stop the fn from running
  }
  next(); // there were no errors!
};

exports.register = async (req, res, next) => {
    const user = new User({

      Representing: req.body.user1,
      Name:req.body.user2,
      companyName:req.body.user3,
      companyNumber:req.body.user4,
      userAddress:req.body.user5,
      companyAddress:req.body.user6,
      activePhone:req.body.user7,
      companyPhone:req.body.user8,
      activeEmail:req.body.user9,
      companyEmail:req.body.user10,
      Aadhar:req.body.user11,
      Pan:req.body.user12,
      Term1:req.body.userTerm1,
      Term2:req.body.userTerm2
  });

    const register = promisify(User.register, User);
    await register(user, req.body.password);
    res.send("all has been saved")
    next(); // pass to authController.login
  };

</code>```

```<code>
User.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
const md5 = require('md5');
const validator = require('validator');
const mongooseErrorHandler = require('mongoose-mongodb-errors');
const passportLocalMongoose = require('passport-local-mongoose');

const userSchema = new Schema({
    Representing: {
        type: String,
        required: 'Please enter your representing',
        trim: true,
        unique:true
    },

    Name:{
        type: String,
        required: 'Please enter your Name',
        trim: true,
        unique:true
    },
    companyName:{
        type: String,
        required: 'Please enter your  Institute Name',
        trim: true,
        unique:true
    },
    companyNumber:{
        type: Number,
        required: 'Please enter your  Institute Number',
        trim: true,
        unique:true
    },
    userAddress:{
        type: String,
        required: 'Please enter your Address',
        trim: true,
        unique:true
    },
    companyAddress:{
        type: String,
        required: 'Please enter your Institute Address',
        trim: true,
        unique:true
    },
    activePhone:{
        type: Number,
        required: 'Please enter your active number',
        trim: true,
        unique:true
    },
    companyPhone:{
        type: Number,
        required: 'Please enter your institute phone number',
        trim: true,
        unique:true
    },
    activeEmail:{
        type: String,
        lowercase: true,
        unique: true,
        trim: true,
        validate:[validator.isEmail,'Invalid Email Address'],
        trim: true
    },
     companyEmail:{
        type: String,
        lowercase: true,
        unique: true,
        trim: true,
        validate:[validator.isEmail,'Invalid Email Address'],
        required: 'Please enter your institute phone number',
        trim: true
    },

    Aadhar:{
        type: Number,
        required: 'Please enter your institute phone number',
        trim: true,
        unique:true
    },
    Pan:{
        type: Number,
        required: 'Please enter your institute phone number',
        trim: true,
        unique:true
    },
    Term1:{
         type: [String]
    },
    Term2:{
        type: [String]
    }

})

userSchema.plugin(passportLocalMongoose, {usernameField: 'user9'});
userSchema.plugin(mongooseErrorHandler);

module.exports = mongoose.model('User', userSchema);

</code>```

```<code>
start.js

const express = require('express')
const mongoose = require('mongoose');
const session = require('express-session');
const expressValidator = require('express-validator');
const MongoStore = require('connect-mongo')(session);
const path = require('path');
const passport = require('passport');
const bodyParser = require('body-parser');
const flash = require('connect-flash');
const routes = require('./routes/index');
const errorHandlers = require('./handlers/errorHandlers');

const app = express();

app.use(express.static(path.join(__dirname + '/views')));
app.set('views', path.join(__dirname, 'views'));
//app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(expressValidator());

// populates req.cookies with any cookies that came along with the request
//app.use(cookieParser());

app.use(session({
  secret: process.env.SECRET,
  key: process.env.KEY,
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

app.use(passport.initialize());
app.use(passport.session());

app.use(flash());

app.use((req, res, next) => {
  res.locals.flashes = req.flash();
  next();
});

// After allllll that above middleware, we finally handle our own routes!
app.use('/', routes);

// If that above routes didnt work, we 404 them and forward to error handler
app.use(errorHandlers.notFound);

// One of our error handlers will see if these errors are just validation errors
//app.use(errorHandlers.flashValidationErrors);

// Otherwise this was a really bad error we didn't expect! Shoot eh
//if (app.get('env') === 'development') {
  /* Development Error Handler - Prints stack trace */
  //app.use(errorHandlers.developmentErrors);
//}

// production error handler
//app.use(errorHandlers.productionErrors);

// done! we export it so we can start the site in start.js
module.exports = app;

</code>```

```<code>package.json

{
  "name": "user-login",
  "version": "1.0.0",
  "description": "a little login or sign up page",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon start.js"
  },
  "keywords": [
    "prateek"
  ],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "connect-flash": "^0.1.1",
    "connect-mongo": "^2.0.3",
    "dotenv": "^8.0.0",
    "ejs": "^2.6.1",
    "es6-promisify": "^6.0.1",
    "express": "^4.17.0",
    "express-session": "^1.16.1",
    "express-validator": "^5.3.1",
    "md5": "^2.2.1",
    "mongoose": "^5.5.11",
    "mongoose-mongodb-errors": "0.0.2",
    "nodemon": "^1.19.0",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^5.0.1",
    "path": "^0.12.7",
    "validator": "^11.0.0"
  }
}

</code>```

```<code>
error

 <rejected> TypeError: promisify is not a function
      at exports.register (C:\Users\Kulfi\Desktop\user-login\controllers\userController.js:55:22)
      at Layer.handle [as handle_request] (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\layer.js:95:5)
      at next (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\route.js:137:13)
      at Route.dispatch (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\route.js:112:3)
      at Layer.handle [as handle_request] (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\layer.js:95:5)
      at C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:281:22
      at Function.process_params (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:335:12)
      at next (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:275:10)
      at Function.handle (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:174:3)
      at router (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:47:12)
      at Layer.handle [as handle_request] (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\layer.js:95:5)
      at trim_prefix (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:317:13)
      at C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:335:12)
      at next (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:275:10)
      at app.use (C:\Users\Kulfi\Desktop\user-login\app.js:47:3) }

</code>```

答:
In userController.js, change this:

```<code>const promisify = require("es6-promisify");
</code>```

to this:

```<code>const { promisify } = require("es6-promisify");
</code>```

Another option if you do not want to use object destructuring is this:

```<code>const promisify = require("es6-promisify").promisify;
</code>```

You need to require es6-promisify this way because the package currently exports the promisify function inside of an object instead of exporting the function directly.

Body:
Can anyone let me know the solution of my problem. I got an error again and again whenever i run this setup. i checked a lot but i didn't get that. please look on my code files and tell me the solution.whenever
 i send some data through the form page then, this error will show, sometimes i think, is it the problem of modern ecmascript or not.

start.js

const mongoose = require('mongoose');
const dotenv = require('dotenv');

// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variable.env' });

// Connect to our Database and handle any bad connections
mongoose.connect(process.env.DATABASE, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
  console.error(`sir your error → ${err.message}`);
});

process.on('unhandledRejection', function(reason, promise) {
  console.log(promise);
});

require('./models/User');

// READY?! Let's go!

// Start our app!
const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
  console.log(`Express running → PORT ${server.address().port}`);
});

userController.js

const mongoose = require('mongoose');
const User = mongoose.model('User');
const promisify = require('es6-promisify');

exports.loginForm = (req, res) => {
  res.render('login', { title: 'Login' })
};

exports.registerForm = (req, res) => {
  res.render('register', { title: 'Register' })
};

  exports.validateRegister = (req, res, next) => {
  req.sanitizeBody('user2');
  req.checkBody('user2', 'You must supply a name!').notEmpty();
  req.checkBody('user9', 'That Email is not valid!').isEmail();
  req.sanitizeBody('user9').normalizeEmail({
    gmail_remove_dots: false,
    remove_extension: false,
    gmail_remove_subaddress: false
  });
  req.checkBody('password', 'Password Cannot be Blank!').notEmpty();
  req.checkBody('confirmPassword', 'Confirmed Password cannot be blank!').notEmpty();
  req.checkBody('confirmPassword', 'Oops! Your passwords do not match').equals(req.body.password);

  const errors = req.validationErrors();
  if (errors) {
    req.flash('error', errors.map(err => err.msg));
    res.render('register');
    return; // stop the fn from running
  }
  next(); // there were no errors!
};

exports.register = async (req, res, next) => {
    const user = new User({

      Representing: req.body.user1,
      Name:req.body.user2,
      companyName:req.body.user3,
      companyNumber:req.body.user4,
      userAddress:req.body.user5,
      companyAddress:req.body.user6,
      activePhone:req.body.user7,
      companyPhone:req.body.user8,
      activeEmail:req.body.user9,
      companyEmail:req.body.user10,
      Aadhar:req.body.user11,
      Pan:req.body.user12,
      Term1:req.body.userTerm1,
      Term2:req.body.userTerm2
  });

    const register = promisify(User.register, User);
    await register(user, req.body.password);
    res.send("all has been saved")
    next(); // pass to authController.login
  };

User.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
const md5 = require('md5');
const validator = require('validator');
const mongooseErrorHandler = require('mongoose-mongodb-errors');
const passportLocalMongoose = require('passport-local-mongoose');

const userSchema = new Schema({
    Representing: {
        type: String,
        required: 'Please enter your representing',
        trim: true,
        unique:true
    },

    Name:{
        type: String,
        required: 'Please enter your Name',
        trim: true,
        unique:true
    },
    companyName:{
        type: String,
        required: 'Please enter your  Institute Name',
        trim: true,
        unique:true
    },
    companyNumber:{
        type: Number,
        required: 'Please enter your  Institute Number',
        trim: true,
        unique:true
    },
    userAddress:{
        type: String,
        required: 'Please enter your Address',
        trim: true,
        unique:true
    },
    companyAddress:{
        type: String,
        required: 'Please enter your Institute Address',
        trim: true,
        unique:true
    },
    activePhone:{
        type: Number,
        required: 'Please enter your active number',
        trim: true,
        unique:true
    },
    companyPhone:{
        type: Number,
        required: 'Please enter your institute phone number',
        trim: true,
        unique:true
    },
    activeEmail:{
        type: String,
        lowercase: true,
        unique: true,
        trim: true,
        validate:[validator.isEmail,'Invalid Email Address'],
        trim: true
    },
     companyEmail:{
        type: String,
        lowercase: true,
        unique: true,
        trim: true,
        validate:[validator.isEmail,'Invalid Email Address'],
        required: 'Please enter your institute phone number',
        trim: true
    },

    Aadhar:{
        type: Number,
        required: 'Please enter your institute phone number',
        trim: true,
        unique:true
    },
    Pan:{
        type: Number,
        required: 'Please enter your institute phone number',
        trim: true,
        unique:true
    },
    Term1:{
         type: [String]
    },
    Term2:{
        type: [String]
    }

})

userSchema.plugin(passportLocalMongoose, {usernameField: 'user9'});
userSchema.plugin(mongooseErrorHandler);

module.exports = mongoose.model('User', userSchema);

start.js

const express = require('express')
const mongoose = require('mongoose');
const session = require('express-session');
const expressValidator = require('express-validator');
const MongoStore = require('connect-mongo')(session);
const path = require('path');
const passport = require('passport');
const bodyParser = require('body-parser');
const flash = require('connect-flash');
const routes = require('./routes/index');
const errorHandlers = require('./handlers/errorHandlers');

const app = express();

app.use(express.static(path.join(__dirname + '/views')));
app.set('views', path.join(__dirname, 'views'));
//app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(expressValidator());

// populates req.cookies with any cookies that came along with the request
//app.use(cookieParser());

app.use(session({
  secret: process.env.SECRET,
  key: process.env.KEY,
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

app.use(passport.initialize());
app.use(passport.session());

app.use(flash());

app.use((req, res, next) => {
  res.locals.flashes = req.flash();
  next();
});

// After allllll that above middleware, we finally handle our own routes!
app.use('/', routes);

// If that above routes didnt work, we 404 them and forward to error handler
app.use(errorHandlers.notFound);

// One of our error handlers will see if these errors are just validation errors
//app.use(errorHandlers.flashValidationErrors);

// Otherwise this was a really bad error we didn't expect! Shoot eh
//if (app.get('env') === 'development') {
  /* Development Error Handler - Prints stack trace */
  //app.use(errorHandlers.developmentErrors);
//}

// production error handler
//app.use(errorHandlers.productionErrors);

// done! we export it so we can start the site in start.js
module.exports = app;

package.json

{
  "name": "user-login",
  "version": "1.0.0",
  "description": "a little login or sign up page",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon start.js"
  },
  "keywords": [
    "prateek"
  ],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "connect-flash": "^0.1.1",
    "connect-mongo": "^2.0.3",
    "dotenv": "^8.0.0",
    "ejs": "^2.6.1",
    "es6-promisify": "^6.0.1",
    "express": "^4.17.0",
    "express-session": "^1.16.1",
    "express-validator": "^5.3.1",
    "md5": "^2.2.1",
    "mongoose": "^5.5.11",
    "mongoose-mongodb-errors": "0.0.2",
    "nodemon": "^1.19.0",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^5.0.1",
    "path": "^0.12.7",
    "validator": "^11.0.0"
  }
}

error

 <rejected> TypeError: promisify is not a function
      at exports.register (C:\Users\Kulfi\Desktop\user-login\controllers\userController.js:55:22)
      at Layer.handle [as handle_request] (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\layer.js:95:5)
      at next (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\route.js:137:13)
      at Route.dispatch (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\route.js:112:3)
      at Layer.handle [as handle_request] (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\layer.js:95:5)
      at C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:281:22
      at Function.process_params (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:335:12)
      at next (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:275:10)
      at Function.handle (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:174:3)
      at router (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:47:12)
      at Layer.handle [as handle_request] (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\layer.js:95:5)
      at trim_prefix (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:317:13)
      at C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:335:12)
      at next (C:\Users\Kulfi\Desktop\user-login\node_modules\express\lib\router\index.js:275:10)
      at app.use (C:\Users\Kulfi\Desktop\user-login\app.js:47:3) }

Body:
In userController.js, change this:

const promisify = require("es6-promisify");

to this:

const { promisify } = require("es6-promisify");

Another option if you do not want to use object destructuring is this:

const promisify = require("es6-promisify").promisify;

You need to require es6-promisify this way because the package currently exports the promisify function inside of an object instead of exporting the function directly.


问:
If I assign a method to a variable is the method called in java?
these are my two classes

```<code>   public class Main {
         public static void main(String[] args) throws IOException {
          Init init = new Init();
         final String init1 = init.init(); }}

public class Init {

protected String init() throws IOException {
     final String command = "ipconfig";
     Runtime rt = Runtime.getRuntime(); //executing commands on cmd
     Process process = rt.exec(command);
     InputStream is = process.getInputStream();
    Scanner s = new Scanner(is).useDelimiter("\\A");
    String val = "";

    if (s.hasNext()){
        val = s.next();
    } else {
        val = "";
    }

    return val;
</code>```

would init1 being initialized cause my program to execute the command line command? or would i have to call init.init(); everytime i wanted the command to run?

答:
You're not assigning the method itself to a variable - you're calling the method, and then assigning the return value of the method to a variable.

With regards to

or would i have to call init.init(); everytime i wanted the command to run?

As written, the method call will definitely be executed. If you wanted to run init() a second time, though, then yes, you'd have to call it again.

Body:
these are my two classes

   public class Main {
         public static void main(String[] args) throws IOException {
          Init init = new Init();
         final String init1 = init.init(); }}

public class Init {

protected String init() throws IOException {
     final String command = "ipconfig";
     Runtime rt = Runtime.getRuntime(); //executing commands on cmd
     Process process = rt.exec(command);
     InputStream is = process.getInputStream();
    Scanner s = new Scanner(is).useDelimiter("\\A");
    String val = "";

    if (s.hasNext()){
        val = s.next();
    } else {
        val = "";
    }

    return val;

would init1 being initialized cause my program to execute the command line command? or would i have to call init.init(); everytime i wanted the command to run?


问:
How to Identify if the rate of an event (moving average) exceeds a threshold
EDIT Added information

Originally this was just about a general algorithm and language/platform agnostic. However I'm going to answer this question myself and the answer is in fact specific to the tools in use.

This is for event detection on an IBM mainframe under z/OS , using the Ops/MVS automation tool running a REXX script.

So the answers posted may be applicable in Python, Perl, bash, Java etc; it's just that the product being used in this particular case has a specific function that does the trick.

End of added information

My question is very similar to this:

How to calculate continuous smooth event rate based on event times?

and this would be an answer:

This can be implemented with a moving average. Take your last N events
  where N is the size of your averaging window. Compute the time
  difference between the first and the last of these N events. If you
  are measuring in seconds and want the rate in event per minute you
  would then divide 60 seconds by your time difference expressed in
  seconds and you multiply by N-1.

except I'd like to avoid storing information about previous events. I'm also only interested if the moving average exceeds a threshold, so I'm not interested in keeping a trend of  rate.

So for example, I want to know if I get more than 3 events/min. This was my first approach:

When the first event comes in, I create a count of 1 and log the
start time.

When another event comes in, I increment the count and calculate the
rate from the count and the elapsed time

If rate exceed permitted value, generate alert.

I realised this wouldn’t work because if you had an event a week ago and then nothing until 10 events in the last minute, the average ‘rate’ is 11 in a week i.e. 3.6/day, rather than the current rate of 10/min.

So I'm thinking of trying the following:

When the first event comes in, I create a count of 1 and log the
start time.

When another event comes in, if the time since the previous event exceeds the interval over which I want to measure the rate (1 min in my example), I effectively discard the previous event and record a count of 1 and the current time as the new start time (because if it's been over 1 min since the previous event, the rate can't exceed x/min right?).

If the time since the previous event hasn't exceeded the monitoring
interval, increment the count and calculate the rate from the count
and the elapsed time

If rate exceed permitted value, generate alert.

This seems simple but other posts on SO (specifically this question: Estimating rate of occurrence of an event with exponential smoothing and irregular events and it's accepted answer: https://stackoverflow.com/a/23617678/1430420) seem to imply that there's a lot more to it than I think.

答:
Use the following pseudo-code:

```<code>boolean update(long timestamp, History h, int windowSize, int minEventsToTrigger) {
    h.removeOlderThan(timestamp - windowSize);
    h.addEvent(timestamp);
    return h.size() >= minEventsToTrigger;
}
</code>```

Where h is a circular buffer storing timestamps with the following operations:

removeOlderThan(t): removes all events that happened before t. This operation is amortized O(1), since each event will be removed exactly once, and events (except the oldest) will never be queried more than once for removal.

addEvent(t): adds an event at the end of the buffer, or if the buffer is full, removes the oldest event first, and then adds the new event. The operation O(1); and discarding an old event for a newer one guarantees that sudden influxes of events will not overwhelm the system, require extra memory, or break this code -- as long as minEventsToTrigger is smaller than the capacity of h, the results will always be correct.

This pseudo-code is, I believe, optimal in time, and probably also in space. Importantly, it does not require any kind of dynamic allocation.

The update function returns true if, given the new event, at least minEventsToTrigger have been received within windowSize time units, or false otherwise. Note that it is intended to be invoked only when each event is received, and therefore can only accurately rising edges (falling edges will not be detected until the next event). If you wish to remedy this, you have two options:

poll regularly to see if, after calling h.removeOlderThan(timestamp - windowSize);, the condition return h.size() >= minEventsToTrigger; ceases to be true. This can be wasteful if events are very infrequent; if you only do this when the alert is triggered, then you may save a lot of unnecessary operations.

use some kind of timer mechanism to, once an alert is triggered, wake up just after the oldest event is due to expire. This would guarantee minimal delay between events expiring and a check for h.size() >= minEventsToTrigger.

Body:
Use the following pseudo-code:

boolean update(long timestamp, History h, int windowSize, int minEventsToTrigger) {
    h.removeOlderThan(timestamp - windowSize);
    h.addEvent(timestamp);
    return h.size() >= minEventsToTrigger;
}

Where h is a circular buffer storing timestamps with the following operations:

removeOlderThan(t): removes all events that happened before t. This operation is amortized O(1), since each event will be removed exactly once, and events (except the oldest) will never be queried more than once for removal.

addEvent(t): adds an event at the end of the buffer, or if the buffer is full, removes the oldest event first, and then adds the new event. The operation O(1); and discarding an old event for a newer one guarantees that sudden influxes of events will not overwhelm the system, require extra memory, or break this code -- as long as minEventsToTrigger is smaller than the capacity of h, the results will always be correct.

This pseudo-code is, I believe, optimal in time, and probably also in space. Importantly, it does not require any kind of dynamic allocation.

The update function returns true if, given the new event, at least minEventsToTrigger have been received within windowSize time units, or false otherwise. Note that it is intended to be invoked only when each event is received, and therefore can only accurately rising edges (falling edges will not be detected until the next event). If you wish to remedy this, you have two options:

poll regularly to see if, after calling h.removeOlderThan(timestamp - windowSize);, the condition return h.size() >= minEventsToTrigger; ceases to be true. This can be wasteful if events are very infrequent; if you only do this when the alert is triggered, then you may save a lot of unnecessary operations.

use some kind of timer mechanism to, once an alert is triggered, wake up just after the oldest event is due to expire. This would guarantee minimal delay between events expiring and a check for h.size() >= minEventsToTrigger.


问:
Create a Redirect with additional query params for another plugin
I use the news plugin where I add an another Plugin (lets call it 'Form') as a CE für the Detail view.

When I fill out the Form in the Detail view and submit it, then my redirect inside my Controller only passes the Arguments for my Extension.

$this->redirect('success');

But I would like that he also pass the Arguments for the News extensions, so that I land at the Details view of the news and my Form plugin gets his other action informations from the redirect.

But as far as I can see, the redirect method only takes arguments for one plugin.

Did anyone have an Idea?

答:
As addition to @Rudy Gnodde answer:

The uriBuilder has an option "addQueryString", equal to the typolink function from typoscript. If this option is enabled it attach the configured query strings to the url. This way you dont need to address each parameter for each extension:

```<code>$uriBuilder = $this->getControllerContext()->getUriBuilder();
$uri = $uriBuilder->reset()
  ->setAddQueryString(true)
  ->setAddQueryStringMethod('GET')
  ->uriFor('success');
$this->redirectToUri($uri);
</code>```

For the form ViewHelper f:form you should add the option addQueryString="true", too!

Body:
As addition to @Rudy Gnodde answer:

The uriBuilder has an option "addQueryString", equal to the typolink function from typoscript. If this option is enabled it attach the configured query strings to the url. This way you dont need to address each parameter for each extension:

$uriBuilder = $this->getControllerContext()->getUriBuilder();
$uri = $uriBuilder->reset()
  ->setAddQueryString(true)
  ->setAddQueryStringMethod('GET')
  ->uriFor('success');
$this->redirectToUri($uri);

For the form ViewHelper f:form you should add the option addQueryString="true", too!


问:
Entity Framework creates a new record per foreign key in another table while seeding
I'm trying to seed a database using EF.

I have a table that holds products (phones) and a Category table that differentiates between different types of products.

```<code>public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public DateTimeOffset? CreationDate { get; set; }
    public DateTimeOffset? UpdateDate { get; set; }

    public virtual List<IProduct> Products{ get; set; }

    public Category()
    {
        this.CreationDate = DateTimeOffset.UtcNow;
    }

}

public interface IProduct
{
    int ProductId { get; set; }
    string Brand { get; set; }
    string Model { get; set; }

    decimal? Price { get; set; }
    string Image { get; set; }

    int CategoryId { get; set; }
    Category Category { get; set; }
}

public class Phone: IProduct
{
    public int ProductId { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public string network_technology { get; set; }
    public string bands_2G { get;set; }
    public string bands_3G{ get; set; }
    public string bands_4G { get; set; }
    public string network_speed { get; set; }
    public string GPRS { get; set; }
    public string EDGE { get; set; }
    public string announced { get; set; }
    public string status { get; set; }
    public string dimentions { get; set; }
    public float? weight_g { get; set; }
    public float? weight_oz { get; set; }
    public string SIM { get; set; }
    public string display_type { get; set; }
    public string display_resolution { get; set; }
    public string display_size { get; set; }
    public string OS { get; set; }
    public string CPU { get; set; }
    public string Chipset { get; set; }
    public string GPU { get; set; }
    public string memory_card { get; set; }
    public string internal_memory { get; set; }
    public string RAM { get; set; }
    public string primary_camera { get; set; }
    public string secondary_camera { get; set; }
    public string loud_speaker { get; set; }
    public string audio_jack { get; set; }
    public string WLAN { get; set; }
    public string bluetooth { get; set; }
    public string GPS { get; set; }
    public string NFC { get; set; }
    public string radio { get; set; }
    public string USB { get; set; }
    public string sensors { get; set; }
    public string battery { get; set; }
    public string colors { get; set; }
    public decimal? Price { get; set; }
    public string Image { get; set; }
}
</code>```

I don't know what am I doing wrong but after I update the database from nuget console, a new Category record is created per seeded product(phone). That's exactly the opposite of what I want. I want all the phones to have one categoryId that refers to Phones category. does anyone know what's wrong?

Entity Type Configurations (fluent api):

```<code>public class CategoryConfiguration : EntityTypeConfiguration<Category>
{
    public CategoryConfiguration()
    {
        ToTable("Categories");
        HasKey(m => m.CategoryId);
    }
}

public class PhoneConfiguration : EntityTypeConfiguration<Phone>
{
    public PhoneConfiguration()
    {
        ToTable("Phones");
        HasKey(m => m.ProductId);
    }
}
</code>```

Seed method:

```<code>protected override void Seed(BestPhone.Data.BestPhoneDbContext context)
{
       context.Categories.AddOrUpdate(new Category(){Name = "Phones", CategoryId = 1});
       ...
       //getting records from a csv file and holding them in an array.
       var records = csvReader.GetRecords<Phone>().ToArray();

       foreach (var record in records)
       {
           record.CategoryId = 1;
       }

       context.Phones.AddRange(records);
       context.SaveChanges();
   }
}
</code>```

答:
Try to add the next method on your CategoryConfiguration class:

```<code>    public void Configure(EntityTypeBuilder<Category> builder)
    {
        builder
            .HasMany(s => s.Products)
            .WithOne(t => t.Category)
            .HasForeignKey(t => t.CategoryId);
    }
</code>```

I'm not sure but it seems a system does not take into account your foreign key during seeding.

Body:
I'm trying to seed a database using EF.

I have a table that holds products (phones) and a Category table that differentiates between different types of products.

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public DateTimeOffset? CreationDate { get; set; }
    public DateTimeOffset? UpdateDate { get; set; }

    public virtual List<IProduct> Products{ get; set; }

    public Category()
    {
        this.CreationDate = DateTimeOffset.UtcNow;
    }

}

public interface IProduct
{
    int ProductId { get; set; }
    string Brand { get; set; }
    string Model { get; set; }

    decimal? Price { get; set; }
    string Image { get; set; }

    int CategoryId { get; set; }
    Category Category { get; set; }
}

public class Phone: IProduct
{
    public int ProductId { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public string network_technology { get; set; }
    public string bands_2G { get;set; }
    public string bands_3G{ get; set; }
    public string bands_4G { get; set; }
    public string network_speed { get; set; }
    public string GPRS { get; set; }
    public string EDGE { get; set; }
    public string announced { get; set; }
    public string status { get; set; }
    public string dimentions { get; set; }
    public float? weight_g { get; set; }
    public float? weight_oz { get; set; }
    public string SIM { get; set; }
    public string display_type { get; set; }
    public string display_resolution { get; set; }
    public string display_size { get; set; }
    public string OS { get; set; }
    public string CPU { get; set; }
    public string Chipset { get; set; }
    public string GPU { get; set; }
    public string memory_card { get; set; }
    public string internal_memory { get; set; }
    public string RAM { get; set; }
    public string primary_camera { get; set; }
    public string secondary_camera { get; set; }
    public string loud_speaker { get; set; }
    public string audio_jack { get; set; }
    public string WLAN { get; set; }
    public string bluetooth { get; set; }
    public string GPS { get; set; }
    public string NFC { get; set; }
    public string radio { get; set; }
    public string USB { get; set; }
    public string sensors { get; set; }
    public string battery { get; set; }
    public string colors { get; set; }
    public decimal? Price { get; set; }
    public string Image { get; set; }
}

I don't know what am I doing wrong but after I update the database from nuget console, a new Category record is created per seeded product(phone). That's exactly the opposite of what I want. I want all the phones to have one categoryId that refers to Phones category. does anyone know what's wrong?

Entity Type Configurations (fluent api):

public class CategoryConfiguration : EntityTypeConfiguration<Category>
{
    public CategoryConfiguration()
    {
        ToTable("Categories");
        HasKey(m => m.CategoryId);
    }
}

public class PhoneConfiguration : EntityTypeConfiguration<Phone>
{
    public PhoneConfiguration()
    {
        ToTable("Phones");
        HasKey(m => m.ProductId);
    }
}

Seed method:

protected override void Seed(BestPhone.Data.BestPhoneDbContext context)
{
       context.Categories.AddOrUpdate(new Category(){Name = "Phones", CategoryId = 1});
       ...
       //getting records from a csv file and holding them in an array.
       var records = csvReader.GetRecords<Phone>().ToArray();

       foreach (var record in records)
       {
           record.CategoryId = 1;
       }

       context.Phones.AddRange(records);
       context.SaveChanges();
   }
}

Body:
Try to add the next method on your CategoryConfiguration class:

    public void Configure(EntityTypeBuilder<Category> builder)
    {
        builder
            .HasMany(s => s.Products)
            .WithOne(t => t.Category)
            .HasForeignKey(t => t.CategoryId);
    }

I'm not sure but it seems a system does not take into account your foreign key during seeding.


问:
Can scrapy skip the error of empty data and keeping scraping?
I want to scrape product pages from its sitemap, the products page are similar, but not all of them are the same.

for example

Product A
https://www.vitalsource.com/products/environment-the-science-behind-the-stories-jay-h-withgott-matthew-v9780134446400

Product B
https://www.vitalsource.com/products/abnormal-psychology-susan-nolen-hoeksema-v9781259765667

we can see the product A has the subtitle but another one doesn't have.

So I get errors when I trying to scrape all the product pages.

My question is, is there a way to let the spider skip the error for returning no data?

There is a simple way to bypass it. that is not using strip()
But I am wondering if there is a better way to do the job.

```<code>import scrapy
import re
from VitalSource.items import VitalsourceItem
from scrapy.selector import Selector
from scrapy.spiders import SitemapSpider

class VsSpider(SitemapSpider):
    name = 'VS'
    allowed_domains = ['vitalsource.com']
    sitemap_urls = ['https://storage.googleapis.com/vst-stargate-production/sitemap/sitemap1.xml.gz']
    sitemap_rules = [
        ('/products/', 'parse_product'),
    ]
    def parse_product(self, response):
        selector = Selector(response=response)
        item = VitalsourceItem()
        item['Ebook_Title'] = response.css('.product-overview__title-header::text').extract()[1].strip
        item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
        print(item)
        return item
</code>```

error message

```<code>    item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
AttributeError: 'list' object has no attribute 'strip'
</code>```

答:
Since you need only one subtitle you can use get() with setting default value to empty string. This will save you from errors about applying strip() function to empty element.

```<code>item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").get('').strip()
</code>```

Body:
I want to scrape product pages from its sitemap, the products page are similar, but not all of them are the same.

for example

Product A
https://www.vitalsource.com/products/environment-the-science-behind-the-stories-jay-h-withgott-matthew-v9780134446400

Product B
https://www.vitalsource.com/products/abnormal-psychology-susan-nolen-hoeksema-v9781259765667

we can see the product A has the subtitle but another one doesn't have.

So I get errors when I trying to scrape all the product pages.

My question is, is there a way to let the spider skip the error for returning no data?

There is a simple way to bypass it. that is not using strip()
But I am wondering if there is a better way to do the job.

import scrapy
import re
from VitalSource.items import VitalsourceItem
from scrapy.selector import Selector
from scrapy.spiders import SitemapSpider

class VsSpider(SitemapSpider):
    name = 'VS'
    allowed_domains = ['vitalsource.com']
    sitemap_urls = ['https://storage.googleapis.com/vst-stargate-production/sitemap/sitemap1.xml.gz']
    sitemap_rules = [
        ('/products/', 'parse_product'),
    ]
    def parse_product(self, response):
        selector = Selector(response=response)
        item = VitalsourceItem()
        item['Ebook_Title'] = response.css('.product-overview__title-header::text').extract()[1].strip
        item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
        print(item)
        return item

error message

    item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
AttributeError: 'list' object has no attribute 'strip'

Body:
Since you need only one subtitle you can use get() with setting default value to empty string. This will save you from errors about applying strip() function to empty element.

item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").get('').strip()


问:
JUnit Test (w JNA) Silently Failing?
I'm using Java 11, JNA with a DLL on Windows 10 64-bit, JUnit 4.12, Eclipse 20190314-1200, (aka 4.11.0).  This is a gradle-based project, but I ran out of tags.

Quite a bit of that may not be relevant, but context never hurts, right?

While running any unit test that touches the DLL in question, the test silently fails, almost immediately.  Almost.  When I try to step into the goings on, I land in Structure.autoWrite() (the member function, not the static one), and when I step out, poof.  The test ends.  The call stack looks remarkably like I called autoWrite() directly, though it is actually a native method call.  Eclipse's JUnit UI continues to show that test as if it were still running (little blue triangle overlay on the icon), but the tests all stop.  JUnit doesn't even try to run any further tests.

I haven't found any logs.  Standard out simply shows my last output (the path JNA uses to find DLLs).  I got nuthin'.

Does anyone know of a relevant log file (not in user.name/appdata/local/temp, I checked quite thoroughly)?  Some configuration I can tweak for more verbose output?  Where I can find the JVM exit code maybe?  Anything?

答:
The DLL in question wasn't installed properly (by me), and when I first call an initializer function, it logged an error (in an unexpected corner of my hard drive) and called exit(), which is just rude.

Your DLL shouldn't end my program's process.  At least it didn't cause Eclipse to shut down.  That would have been... vexing.

And that was the last hurdle between me and a full suite of passing unit tests.  Whew.

Upward and onward!

Title: JUnit Test (w JNA) Silently Failing?


问:
Mobile responsive top menu
I m using Clarity Design System with angular and the top menu is not mobile response

```<code> <header class="header-2">
  <div class="branding">
      <a class="nav-link">
          <clr-icon shape="home"  size="24"></clr-icon>
          <span class="title">title</span>
      </a>
     </div>
    <div class="header-nav">
      <a class="nav-link nav-text" routerLink="/home">Home</a>
      <a class="active nav-link nav-text"
    routerLink="/login">Login</a>
   </div>
  </header>
</code>```

I m expecting the top menu to turn into few lines (button) when the width is reduce

Or should I use different tags ?

答:
To use responsive navigation, see the documentation on it at https://v2.clarity.design/navigation. You need to use the clr-main-container and clr-header elements to enable this behavior.

Given your markup, it should be something like the following.

<clr-main-container>
    <clr-header class="header-2">

          <clr-icon shape="home"  size="24"></clr-icon>
          title

        Home
        Login

    </clr-header>

            ... the main body content goes here, probably a router-outlet

            ... if you want a sidenav that is, or omit this

</clr-main-container>
```

Title: Mobile responsive top menu

Body:
I m using Clarity Design System with angular and the top menu is not mobile response

          <clr-icon shape="home"  size="24"></clr-icon>
          title

      Home
      Login

I m expecting the top menu to turn into few lines (button) when the width is reduce

Or should I use different tags ?

Body:
To use responsive navigation, see the documentation on it at https://v2.clarity.design/navigation. You need to use the clr-main-container and clr-header elements to enable this behavior.

Given your markup, it should be something like the following.

<clr-main-container>
    <clr-header class="header-2">
       <div class="branding">
         <a class="nav-link">
          <clr-icon shape="home"  size="24"></clr-icon>
          <span class="title">title</span>
        </a>
      </div>
      <div class="header-nav" [clr-nav-level]="1">
        <a class="nav-link nav-text" routerLink="/home">Home</a>
        <a class="active nav-link nav-text" routerLink="/login">Login</a>
      </div>
    </clr-header>
    <div class="content-container">
        <main class="content-area">
            ... the main body content goes here, probably a router-outlet
        </main>
        <nav class="sidenav" [clr-nav-level]="2">
            ... if you want a sidenav that is, or omit this
        </nav>
    </div>
</clr-main-container>


问:
How to do Inference with Custom Preprocessing and Data Files on Google Cloud ML
I want to use a model that I have trained for inference on Google Cloud ML. It is a NLP model, and I want my node.js server to interact with the model to get predictions at train time.

I have a process for running inference on the model manually, that I would like to duplicate in the cloud:

Use Stanford Core NLP to tokenize my text and generate data files that store my tokenized text.

Have the model use those data files, create Tensorflow Examples out of it, and run the model.

Have the model print out the predictions.

Here is how I think I can replicate it in the Cloud:

Send the text to the cloud using my node.js server.

Run my python script to generate the data file. It seems like I will have to do this inside of a custom prediction routine. I'm not sure how I can use Stanford Core NLP here.

Save the data file in a bucket in Google Cloud.

In the custom prediction routine, load the saved data file and execute the model.

Can anyone tell me if this process is correct? Also, how can I run Stanford CoreNLP on Google Cloud custom prediction routine? Also, is there a way for me to just run command line scripts (for example for creating the data files I have a simple command that I normally just run to create them)?

答: You can implement a custom preprocessing method in Python and invoke the Stanford toolkit from there. See this blog and associated sample code for details: https://cloud.google.com/blog/products/ai-machine-learning/ai-in-depth-creating-preprocessing-model-serving-affinity-with-custom-online-prediction-on-ai-platform-serving</p>


问:
Sitecore Query to get the latest item under a folder
I need to get the latest sitecore item created under specific folder as a data source. How I need to achieve this using sitecore query ?
Here I tried :</p>

```<code>fast:/sitecore/content/Home/About//*[@@templatename = 'Artice']
</code>```

答:
You can achieve this by a Sitecore Fast Query and a LINQ statement, the following code sample retrieves the last updated item from MyFolder folder:

```<code>Sitecore.Context.ContentDatabase.SelectItems("fast:/sitecore/content/home/myfolder/*").OrderByDescending(w => w.Statistics.Updated).Take(1);
</code>```

Body:
I need to get the latest sitecore item created under specific folder as a data source. How I need to achieve this using sitecore query ?
Here I tried :

fast:/sitecore/content/Home/About//*[@@templatename = 'Artice']

Body:
You can achieve this by a Sitecore Fast Query and a LINQ statement, the following code sample retrieves the last updated item from MyFolder folder:

Sitecore.Context.ContentDatabase.SelectItems("fast:/sitecore/content/home/myfolder/*").OrderByDescending(w => w.Statistics.Updated).Take(1);


问:
how can i solve lstm dimension error in keras?
Here is my code

```<code>model = Sequential()
model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(1, return_sequences=True))
</code>```

I got this error

```<code>ValueError: Error when checking target: expected lstm_3 to have 3 dimensions, but got array with shape (62796, 1)
</code>```

if I set return_sequences=True then output shape is 3D array

So, why this error occur??

答:
The input and output of the keras LSTM layer should be 3 dimensional, and by default follows the shape,

(Batch_size, Time_steps, Features).

It seems like you are using only two dimensions (62796, 1) from you error message.

following is a minimal working example with synthetic data, which illustrate the input and output shape required by your LSTM network.

from keras.models import Sequential
from keras.layers import LSTM, Dropout
import numpy as np

numb_outputs = 1

batch_size = 10
timesteps = 5
features = 2

x_single_batch = np.random.rand(batch_size, timesteps, features)
y_single_batch = np.random.rand(batch_size, timesteps, numb_outputs)

model = Sequential()
model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(numb_outputs, return_sequences=True))

model.compile(optimizer='adam',loss='mse')
model.fit(x= x_single_batch, y=y_single_batch)
```

Body:
Here is my code

model = Sequential()
model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(1, return_sequences=True))

I got this error

ValueError: Error when checking target: expected lstm_3 to have 3 dimensions, but got array with shape (62796, 1)

if I set return_sequences=True then output shape is 3D array

So, why this error occur??


问:
Null or false value in grails
I have a domain class in which one of its fields is of type Boolean. When I retrieve it, how can I differentiate whether it's set to false or it's null ?

Thanks

答:
Here's a simple example that demonstrates how to test for all 3 possible values of a Boolean

```<code>class Person {

  Boolean isMale = false
  Boolean isFemale = true

  Boolean isAdult = null
}

def p = new Person()

assert !p.isMale
assert p.isFemale
assert p.isAdult == null
</code>```

You can run this code in the Groovy console to verify the expected behaviour

Title: Null or false value in grails

Body:
Here's a simple example that demonstrates how to test for all 3 possible values of a Boolean

class Person {

  Boolean isMale = false
  Boolean isFemale = true

  Boolean isAdult = null
}

def p = new Person()

assert !p.isMale
assert p.isFemale
assert p.isAdult == null

You can run this code in the Groovy console to verify the expected behaviour


问:
Calculate the longest path between two nodes NetworkX
I'm trying to make a Gantt chard using Networkx. All the nodes in the network are "tasks" that need to be performed to complete the project. With Networkx it is easy to calculate the total time of the project. But the make the Gantt chard I need the latest start of each node.

NetworkX includes one function(dag_longest_path_length) but this calculates to longest path in the whole network. Another function(astar_path_length) results in the shortest path between a source and node, but no function is availed which gives the longest path, or latest start in my case. (if a node as two predecessors it will take the fastest route, but in reality it also has to wait on the second before it can start.

I was thinking of one option.
To evaluate the previous attached nodes and selecting the longest path. Unformal I did not succeeded.

```<code>start_time=[]
time=0
DD=nx.DiGraph()
for i in range(df.shape[0]):
        DD.add_edge(str(df.at[i,'blockT'])+'_'+df.at[i,'Task'], str(df.at[i,'blockS'])+'_'+df.at[i,'Succ'], weight=df.at[i,'duration'])

fig, ax = plt.subplots()
labels=[]
for i in range(df.shape[0]):
        labels.append(str(df.at[i,'blockT'])+'_'+df.at[i,'Task'])
        print(nx.astar_path_length(DD, '0_START', str(df.at[i,'blockT'])+'_'+df.at[i,'Task'])  )

ax.broken_barh([(nx.astar_path_length(DD, '0_START', str(df.at[i,'blockT'])+'_'+df.at[i,'Task']), heuristic=None, weight='weight'),df.at[i,'duration'] )],(i-0.4,0.8), facecolors='blue' )
</code>```

答:
Looks like you are using DAGs.

Your problem is rather rare so there is no built-in function for it in networkx. You should do it manually:

max(nx.all_simple_paths(DAG, source, target), key=lambda x: len(x))

Here is the full testing code:

```<code>import networkx as nx
import random
from itertools import groupby

# Create random DAG
G = nx.gnp_random_graph(50,0.3,directed=True)
DAG = nx.DiGraph([(u,v) for (u,v) in G.edges() if u<v])

# Get the longest path from node 1 to node 10
max(nx.all_simple_paths(DAG, 1, 10), key=lambda x: len(x))
</code>```

Body:
I'm trying to make a Gantt chard using Networkx. All the nodes in the network are "tasks" that need to be performed to complete the project. With Networkx it is easy to calculate the total time of the project. But the make the Gantt chard I need the latest start of each node.

NetworkX includes one function(dag_longest_path_length) but this calculates to longest path in the whole network. Another function(astar_path_length) results in the shortest path between a source and node, but no function is availed which gives the longest path, or latest start in my case. (if a node as two predecessors it will take the fastest route, but in reality it also has to wait on the second before it can start.

I was thinking of one option.
To evaluate the previous attached nodes and selecting the longest path. Unformal I did not succeeded.

start_time=[]
time=0
DD=nx.DiGraph()
for i in range(df.shape[0]):
        DD.add_edge(str(df.at[i,'blockT'])+'_'+df.at[i,'Task'], str(df.at[i,'blockS'])+'_'+df.at[i,'Succ'], weight=df.at[i,'duration'])

fig, ax = plt.subplots()
labels=[]
for i in range(df.shape[0]):
        labels.append(str(df.at[i,'blockT'])+'_'+df.at[i,'Task'])
        print(nx.astar_path_length(DD, '0_START', str(df.at[i,'blockT'])+'_'+df.at[i,'Task'])  )

ax.broken_barh([(nx.astar_path_length(DD, '0_START', str(df.at[i,'blockT'])+'_'+df.at[i,'Task']), heuristic=None, weight='weight'),df.at[i,'duration'] )],(i-0.4,0.8), facecolors='blue' )

Body:
Looks like you are using DAGs.

Your problem is rather rare so there is no built-in function for it in networkx. You should do it manually:

max(nx.all_simple_paths(DAG, source, target), key=lambda x: len(x))

Here is the full testing code:

import networkx as nx
import random
from itertools import groupby

# Create random DAG
G = nx.gnp_random_graph(50,0.3,directed=True)
DAG = nx.DiGraph([(u,v) for (u,v) in G.edges() if u<v])

# Get the longest path from node 1 to node 10
max(nx.all_simple_paths(DAG, 1, 10), key=lambda x: len(x))


问:
simple validation form with javascript
i have a 'div' tag included error message on the my form.
this tag displaying when button is clicked and inputs are null.
my code is working but, 'div' tag is hide speedly.

<htlm>

Username Or Password is incorrect.

<form id="Main" method="POST">
<input id="User" type="text" name="Name" placeholder="Enter Your Username">

<input id="Pass" type="password" name="Pass" placeholder="Enter Your Password"/>

<button id="bt">Login</button>
<button >Cancel</button>
</form>

```

<pre class="lang-css prettyprint-override"><code>div#ShowError{
opacity:0.0;
}
</code>```

```<code>var btn = document.getElementById("bt");
btn.addEventListener("click",func);

var Username = document.getElementById("User");
var Password = document.getElementById("Pass");

function func()
{

    if(Username.value == "" || Password.value == "")
    {
        document.getElementById("ShowError").style.opacity = "1.0";
    }
}
</code>```

答:
If I understand you correctly you want to slowdown the opacity change of validation error message. For example, slowly change opacity 0.0 to 1.0, right? If so, for slow change of opacity of the validation error message you have to add the css transition property using javascript to your validation error message div.

```<code>function func(event)
{

    if(Username.value == "" || Password.value == "")
    {

        document.getElementById("ShowError").style.transition = "all 2s"
        document.getElementById("ShowError").style.opacity = 1;
    }
}
</code>```

and also to stop reloading the page when you click login button you can include type="button" in your login button

```<code><button type="button" id="bt">Login</button>
</code>```

Working demo :

var btn = document.getElementById("bt");
btn.addEventListener("click",func);
//document.getElementById("ShowError").style.transition = "all 2s"
var Username = document.getElementById("User");
var Password = document.getElementById("Pass");

Username.addEventListener("input",func2)
Password.addEventListener("input",func2)

function func(event)
{

    if(Username.value == "" || Password.value == "")
    {

        document.getElementById("ShowError").style.transition = "all 2s"
        document.getElementById("ShowError").style.opacity = 1;
    }
}

function func2(){
  if(Username.value !== "" && Password.value !== ""){
            document.getElementById("ShowError").style.transition = "all 2s"
        document.getElementById("ShowError").style.opacity = 0;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div#ShowError{
opacity:0.0;
}</code>```

Username Or Password is incorrect.

<form id="Main" method="POST">
<input id="User" type="text" name="Name" placeholder="Enter Your Username">

<input id="Pass" type="password" name="Pass" placeholder="Enter Your Password"/>

<button type="button" id="bt">Login</button>
<button >Cancel</button>
</form>```

Title: simple validation form with javascript

Body:
i have a 'div' tag included error message on the my form.
this tag displaying when button is clicked and inputs are null.
my code is working but, 'div' tag is hide speedly.

<htlm>

Username Or Password is incorrect.

<form id="Main" method="POST">
<input id="User" type="text" name="Name" placeholder="Enter Your Username">

<input id="Pass" type="password" name="Pass" placeholder="Enter Your Password"/>

<button id="bt">Login</button>
<button >Cancel</button>
</form>

div#ShowError{
opacity:0.0;
}

var btn = document.getElementById("bt");
btn.addEventListener("click",func);

var Username = document.getElementById("User");
var Password = document.getElementById("Pass");

function func()
{

    if(Username.value == "" || Password.value == "")
    {
        document.getElementById("ShowError").style.opacity = "1.0";
    }
}

Body:
If I understand you correctly you want to slowdown the opacity change of validation error message. For example, slowly change opacity 0.0 to 1.0, right? If so, for slow change of opacity of the validation error message you have to add the css transition property using javascript to your validation error message div.

function func(event)
{

    if(Username.value == "" || Password.value == "")
    {

        document.getElementById("ShowError").style.transition = "all 2s"
        document.getElementById("ShowError").style.opacity = 1;
    }
}

and also to stop reloading the page when you click login button you can include type="button" in your login button

<button type="button" id="bt">Login</button>

Working demo :

var btn = document.getElementById("bt");
btn.addEventListener("click",func);
//document.getElementById("ShowError").style.transition = "all 2s"
var Username = document.getElementById("User");
var Password = document.getElementById("Pass");

Username.addEventListener("input",func2)
Password.addEventListener("input",func2)

function func(event)
{

    if(Username.value == "" || Password.value == "")
    {

        document.getElementById("ShowError").style.transition = "all 2s"
        document.getElementById("ShowError").style.opacity = 1;
    }
}

function func2(){
  if(Username.value !== "" && Password.value !== ""){
            document.getElementById("ShowError").style.transition = "all 2s"
        document.getElementById("ShowError").style.opacity = 0;
  }
}

div#ShowError{
opacity:0.0;
}

<div id="ShowError">
<h3>Username Or Password is incorrect.</h3>
</div>
<form id="Main" method="POST">
<input id="User" type="text" name="Name" placeholder="Enter Your Username">
<br>
<input id="Pass" type="password" name="Pass" placeholder="Enter Your Password"/>
<br>
<button type="button" id="bt">Login</button>
<button >Cancel</button>
</form>


问:
Plotting points from two arrays to a graph
I was solving tsp using simulated annealing and I want to plot the optimum distance versus temperature of the optimum distance and join those points to see the nature of the graph.

I've got the distances and temperatures in two different arrays now I need to plot this as a scatter. If putting the values in one array is required for plotting even that can be done but how do I plot such a graph. I tried using libre office to plot the graph but that isn't working at all, the app is crashing.

while (temp > 1) {
     //some code giving distance
     // Cool system
     temp *= 1-coolingRate;
     System.out.println(""+ best.getDistance());
     System.out.println(""+ temp );
     //Outputs to be put in an array and plotted
}

Edit 1:
Both the arrays are single dimensional and the graph I want to plot has points whose X and y co ordinates are taken from these arrays consecutively.
I can't figure out a way to do it.
```

答: Search your code to see if 'temp' is defined in multiple ways in your code. temp is a common variable that is also often used as a temporary holding place while you crunch the numbers. Has it been previously defined?</p>


问:
How to randomly select values from a given column in Excel
So if I have a column that has unique values:

```<code>A
100
110
231
194
572
200
</code>```

And I wanted to randomly select a fixed amount of values from it (ie. 3).

Is there like a code to do that? For example =random(a:a, 3)

答:
Pick a cell and enter:

```<code>=INDEX(A$1:A$6,RANDBETWEEN(1,COUNT(A$1:A$6)))
</code>```

and copy down two cells.  Since each pick is completely independent, duplicates may occur:

EDIT#1:

To help insure that the same item is not picked more than one, in B1 through B6 enter:

```<code>=RAND()
</code>```

and use this formula instead:

```<code>=INDEX(A$1:A$6,MATCH(LARGE($B$1:$B$6,ROW()),$B$1:$B$6,0))
</code>```

Body:
So if I have a column that has unique values:

A
100
110
231
194
572
200

And I wanted to randomly select a fixed amount of values from it (ie. 3).

Is there like a code to do that? For example =random(a:a, 3)

Body:
Pick a cell and enter:

=INDEX(A$1:A$6,RANDBETWEEN(1,COUNT(A$1:A$6)))

and copy down two cells.  Since each pick is completely independent, duplicates may occur:

EDIT#1:

To help insure that the same item is not picked more than one, in B1 through B6 enter:

=RAND()

and use this formula instead:

=INDEX(A$1:A$6,MATCH(LARGE($B$1:$B$6,ROW()),$B$1:$B$6,0))


问:
Persist HTMLSession in Django
What is the best method of persisting a HTMLSession in Django between different views? I use the request.session to persist some data between views, but I can't find a solution to also persist the HTMLSession. For example, I use requests-html to create a HTMLSession to grab a link, but I have a few more views that will do different things but needs access to the same HTMLSession. Data that I need to persist I store in request.session which is working fine, I just can't figure out how to persist the HTMLSession.

I've tried serializing the HTMLSession, however, further investigation lead to me to realize these should NOT be serializable, and only iterate over the HTMLSession data and serialize those.

Custom class

```<code>from requests_html import HTML, HTMLSession

class Foo():
    def __init__(self):
        session = HTMLSession()
</code>```

views.py

```<code>def get_item(request):
    foo = Foo()
    request.session['item'] = 'test'
    return HttpResponse('test')

# Foo() initializes the HTMLSession
# Need to use that same session between each view

def show_item(request):
    item = request.session['item']
    return HttpResponse('test')
</code>```

Code above doesn't make sense, just trying to show what I'm trying to achieve. Is this possible? Or am I completely misunderstanding something?

答:
My solution in case anyone has any similar issue, although probably not the best:

```<code>my_dynamic_dict = {}

my_dynamic_dict['{}'.format(dynamic_key)] = test
</code>```

Use a dict to store the instance of a class which contains the HTMLSession which I can retrieve again later.

Title: Persist HTMLSession in Django

Body:
What is the best method of persisting a HTMLSession in Django between different views? I use the request.session to persist some data between views, but I can't find a solution to also persist the HTMLSession. For example, I use requests-html to create a HTMLSession to grab a link, but I have a few more views that will do different things but needs access to the same HTMLSession. Data that I need to persist I store in request.session which is working fine, I just can't figure out how to persist the HTMLSession.

I've tried serializing the HTMLSession, however, further investigation lead to me to realize these should NOT be serializable, and only iterate over the HTMLSession data and serialize those.

Custom class

from requests_html import HTML, HTMLSession

class Foo():
    def __init__(self):
        session = HTMLSession()

views.py

def get_item(request):
    foo = Foo()
    request.session['item'] = 'test'
    return HttpResponse('test')

# Foo() initializes the HTMLSession
# Need to use that same session between each view

def show_item(request):
    item = request.session['item']
    return HttpResponse('test')

Code above doesn't make sense, just trying to show what I'm trying to achieve. Is this possible? Or am I completely misunderstanding something?

Body:
My solution in case anyone has any similar issue, although probably not the best:

my_dynamic_dict = {}

my_dynamic_dict['{}'.format(dynamic_key)] = test

Use a dict to store the instance of a class which contains the HTMLSession which I can retrieve again later.


问:
What is the correct approach to check if array exists in JS?
I'm getting the below error when I check the length of an array. What would be the correct approach?

main.js

```<code>if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
   //code goes here
}
</code>```

Error

```<code>TypeError: Cannot read property 'length' of undefined
</code>```

答:
Validate your data, swapping the condition may help but it won't prevent, some errors from happeing. For example Array.isArray(drugPrice.mailPrice.rejectMessage) will throw an error if drugPrice.mailPrice is undefined.

```<code>if (drugPrice.mailPrice
    && drugPrice.mailPrice.rejectMessage
    && drugPrice.mailPrice.rejectMessage.length !== 0
    && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
  // code goes here
}
</code>```

var drugPrice = { mailPrice: { rejectMessage: {} } };

if (drugPrice.mailPrice
    && drugPrice.mailPrice.rejectMessage
    && drugPrice.mailPrice.rejectMessage.length !== 0
    && Array.isArray(drugPrice.mailPrice.rejectMessage)) {

  console.log('success');
} else {
  console.log('fail')
}```
</div>
</div>
</p>

<p><strong>NOTE</strong></p>

<p>Always validate your data. Don't assume that you'll always get the right data. When working with objects always validate them, as doing <code>data.name</code>, can break your app, if <code>data</code> is null or undefined. for example, given the following object.</p>

```const drugPrice = { mailPrice: null };
```

<p>doing, throws an error.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const drugPrice = { mailPrice: null };

// throws an error, Cannot read property 'rejectMessage' of undefined
if (Array.isArray(drugPrice.mailPrice.rejectMessage)) {
}</code>```

to prevent that from happening, we need to check if the propery exists, like the following.

const drugPrice = { mailPrice: null };
console.log(drugPrice.mailPrice && Array.isArray(drugPrice.mailPrice.rejectMessage) || 'Price is null or undefined')```

Body:
I'm getting the below error when I check the length of an array. What would be the correct approach?

main.js

if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
   //code goes here
}

Error

TypeError: Cannot read property 'length' of undefined

Body:
Validate your data, swapping the condition may help but it won't prevent, some errors from happeing. For example Array.isArray(drugPrice.mailPrice.rejectMessage) will throw an error if drugPrice.mailPrice is undefined.

if (drugPrice.mailPrice
    && drugPrice.mailPrice.rejectMessage
    && drugPrice.mailPrice.rejectMessage.length !== 0
    && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
  // code goes here
}

var drugPrice = { mailPrice: { rejectMessage: {} } };

if (drugPrice.mailPrice
    && drugPrice.mailPrice.rejectMessage
    && drugPrice.mailPrice.rejectMessage.length !== 0
    && Array.isArray(drugPrice.mailPrice.rejectMessage)) {

  console.log('success');
} else {
  console.log('fail')
}

NOTE

Always validate your data. Don't assume that you'll always get the right data. When working with objects always validate them, as doing data.name, can break your app, if data is null or undefined. for example, given the following object.

const drugPrice = { mailPrice: null };

doing, throws an error.

const drugPrice = { mailPrice: null };

// throws an error, Cannot read property 'rejectMessage' of undefined
if (Array.isArray(drugPrice.mailPrice.rejectMessage)) {
}

to prevent that from happening, we need to check if the propery exists, like the following.

const drugPrice = { mailPrice: null };
console.log(drugPrice.mailPrice && Array.isArray(drugPrice.mailPrice.rejectMessage) || 'Price is null or undefined')


问:
SQL Server: if "datetime2" < 1753, then "datetime" NULL?
My intention is to insert data from source table into target table. Source table has datetime2 column and target table has datetime column. If datetime2 value does not fit (< year 1753) into datetime field, it will be converted to null. Here is an example

```<code>DROP TABLE dbo.test1
--source table
CREATE TABLE dbo.test1 (wday DATETIME2 NULL)
go

INSERT  INTO dbo.test1
        (wday
        )
        SELECT  '2008-02-01 00:00:00.000'
        UNION ALL
        SELECT  '2009-02-01 00:00:00.000'
        UNION ALL
        SELECT  '0001-02-01 00:00:00.000'

DROP TABLE dbo.test2
--target table
CREATE TABLE dbo.test2 (wday DATETIME NULL)
go

--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
        (wday
        )
        SELECT  CASE WHEN DATEDIFF(YEAR, dbo.test1.wday, GETDATE()) < 111
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1
</code>```

The code does not work. Also using datediff here is not valid logic, how to implement this?

答:
Another option:</p>

```<code>--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
        (wday
        )
        SELECT  CASE WHEN DATEPART(YEAR, dbo.test1.wday) < 1753
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1
</code>```

Body:
My intention is to insert data from source table into target table. Source table has datetime2 column and target table has datetime column. If datetime2 value does not fit (< year 1753) into datetime field, it will be converted to null. Here is an example

DROP TABLE dbo.test1
--source table
CREATE TABLE dbo.test1 (wday DATETIME2 NULL)
go

INSERT  INTO dbo.test1
        (wday
        )
        SELECT  '2008-02-01 00:00:00.000'
        UNION ALL
        SELECT  '2009-02-01 00:00:00.000'
        UNION ALL
        SELECT  '0001-02-01 00:00:00.000'

DROP TABLE dbo.test2
--target table
CREATE TABLE dbo.test2 (wday DATETIME NULL)
go

--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
        (wday
        )
        SELECT  CASE WHEN DATEDIFF(YEAR, dbo.test1.wday, GETDATE()) < 111
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1

The code does not work. Also using datediff here is not valid logic, how to implement this?

Body:
Another option:

--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
        (wday
        )
        SELECT  CASE WHEN DATEPART(YEAR, dbo.test1.wday) < 1753
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1


问:
Open up terminal/shell on remote server via tcp request
I have this:

```<code>const http = require('http');
const cp = require('child_process');

const server = http.createServer((req,res) => {

  const bash = cp.spawn('bash');
  req.pipe(bash.stdin, {end:false);
  bash.stdout.pipe(res);
  bash.stderr.pipe(res);

});

server.listen('4004');
</code>```

when I hit the server with:

```<code>curl localhost:4004
</code>```

and I type bash commands, nothing gets outputed to my console, anybody know why?

Note: To address security I plan to run this in a docker container, use https/ssl, and implement authentication (any recommendations on auth schemes lmk).

More importantly, I am looking for shell prompts to appear ... apparently bash by itself doesn't open up a shell/prompt?

答:
Your approaches are quite mixed, nonetheless, when ever you finally connect to the remote server do not use 'bash' as a method to start the connection, BASH is just born again shell with other commands & stuff in it,

Rather use some of the following program, command-line names: i.e :

```<code> ~ $ 'gnome-terminal'

 ~ $ 'xterm'
</code>```

there you will now be referencing a true program in the system, even kernel level C code has its own recognition of these, if not changed.

Body:
I have this:

const http = require('http');
const cp = require('child_process');

const server = http.createServer((req,res) => {

  const bash = cp.spawn('bash');
  req.pipe(bash.stdin, {end:false);
  bash.stdout.pipe(res);
  bash.stderr.pipe(res);

});

server.listen('4004');

when I hit the server with:

curl localhost:4004

and I type bash commands, nothing gets outputed to my console, anybody know why?

Note: To address security I plan to run this in a docker container, use https/ssl, and implement authentication (any recommendations on auth schemes lmk).

More importantly, I am looking for shell prompts to appear ... apparently bash by itself doesn't open up a shell/prompt?

Body:
Your approaches are quite mixed, nonetheless, when ever you finally connect to the remote server do not use 'bash' as a method to start the connection, BASH is just born again shell with other commands & stuff in it,

Rather use some of the following program, command-line names: i.e :

 ~ $ 'gnome-terminal'

 ~ $ 'xterm'

there you will now be referencing a true program in the system, even kernel level C code has its own recognition of these, if not changed.


问:
Add class to parent div that matches label text
I would like to add a class to each parent div and have that class match the content of the label within the div with a hyphen added between each word.

In the example below, the first div would have class child-1-name, the second child-1-last-name, the third child-1-age. Any direction would be greatly appreciated!

Note that the HTML is generated automatically.

    child 1 name
    <input type="text">

    child 1 last name
    <input type="text">

    child 1 age
    <input type="text">

```

答:
This could be an plain JavaScript solution without using jQuery:

Take a look at my comments to understand whats going on.

toarray(document.getElementsByTagName('div')).forEach(div => {  // loop throug each parent
  toarray(div.getElementsByTagName('label')).forEach(label => {  // loop throug each lable
    addclass(label.innerText, div);  // get innerText of label and call the function
  });
});

function toarray(items) {
  return Array.prototype.slice.call(items);
  // done this to make 'forEach' available on 'getElementsByTagName'
}

function addclass(src, target) {
  src = src.replace(new RegExp(' ', 'g'), '-');  // replace all ' ' with '-'
  target.classList.add(src);  // add class to parent div

  console.log(target);  // output to show that its working
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div></code>```

Body:
This could be an plain JavaScript solution without using jQuery:

Take a look at my comments to understand whats going on.

toarray(document.getElementsByTagName('div')).forEach(div => {  // loop throug each parent
  toarray(div.getElementsByTagName('label')).forEach(label => {  // loop throug each lable
    addclass(label.innerText, div);  // get innerText of label and call the function
  });
});

function toarray(items) {
  return Array.prototype.slice.call(items);
  // done this to make 'forEach' available on 'getElementsByTagName'
}

function addclass(src, target) {
  src = src.replace(new RegExp(' ', 'g'), '-');  // replace all ' ' with '-'
  target.classList.add(src);  // add class to parent div

  console.log(target);  // output to show that its working
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div>


问:
Avoid Int to double typecast rounding?
I am converting an int to a double by dividing the integers by powers of 10. For integers with 7 or greater digits, it appears that rounding is performed when I cast an int into a double. Why is this happening and how can I avoid this rounding?

```<code>#include <iostream>
using namespace std;

double add_decimals(int x, int decimal_places)
{
    double ret = 1.0 * x;
    cout << "x= " << x << endl;
    cout << "ret before changes= " << ret << endl;
    for (int i = 0; i < decimal_places; ++i)
    {
        ret /= 10;
    }
    return ret;
}

int main()
{
    double d = add_decimals(1234566, 2);
    cout << "d= " << d << endl;
}
</code>```

答:
There isn't any; you're just not observing the values correctly.

Quick fix:

```<code>std::cout << "d= " << std::fixed << d << endl;
</code>```

You'll need #include <iomanip> to use std::fixed.

Title: Avoid Int to double typecast rounding?

Body:
I am converting an int to a double by dividing the integers by powers of 10. For integers with 7 or greater digits, it appears that rounding is performed when I cast an int into a double. Why is this happening and how can I avoid this rounding?

#include <iostream>
using namespace std;

double add_decimals(int x, int decimal_places)
{
    double ret = 1.0 * x;
    cout << "x= " << x << endl;
    cout << "ret before changes= " << ret << endl;
    for (int i = 0; i < decimal_places; ++i)
    {
        ret /= 10;
    }
    return ret;
}

int main()
{
    double d = add_decimals(1234566, 2);
    cout << "d= " << d << endl;
}

Body:
There isn't any; you're just not observing the values correctly.

Quick fix:

std::cout << "d= " << std::fixed << d << endl;

You'll need #include <iomanip> to use std::fixed.


问:
python program for speech to text
I was trying to build simple AI which listen to me and do some work like playing music and opening youtube videos. I have used speech recognition  but the error is comming asking for PyAudio and it is not getting installed in pycharm .

How do I  install pyaudio in
pycharm?
Alternative way would work too.

答:
Just write this command in your cmd:

pip install pyaudio

it worked for me

Title: python program for speech to text