问:
Node js authentication in cross domain
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

```<code>var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

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

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.

答:
If you want to use sessions (ie. instead of jwt, etc)  I think by default they are just in-memory so it will not work as your application scales to multiple hosts. It is easy to configure them to persist though.

See
https://github.com/expressjs/session#compatible-session-stores

Title: Node js authentication in cross domain

Body:
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.


来源: stackexchange

问:
Form submit button onclick does not call my JS function included in JS file

I have an html form with a submit button. I have a js function in a file that I include in the head. I am trying to bind the onclick event of the button to call that function. However, all the methods I tried did not work.</p>

```<code><!DOCTYPE html>
<html>
<body>
    <script src="popup.js" type="text/javascript"></script>
    <button type="button" onclick="displayFormContents();">
</button>

<p id="demo"></p>
First name:<br>
<input type="text" name="firstname" >
<br>
Name:<br>
<input type="text" name="name" >
<br>

<form>
    age : <input type="date" name="Age">
</form>

<form>
    Phone : <input type="number" name="Phone">
</form>

<form>
    email : <input type="email" name="mail">
</form>

<form>
    Student at UCLA? : <input type="checkbox" name="Doe">
</form>

<form>
    <input type="radio" name="gender" value="male" checked> Male<br>
    <input type="radio" name="gender" value="female"> Female<br>
    <input type="radio" name="gender" value="other"> Other
</form>

<input type="submit">
</form>

</body>
</html>
</code>```

答:
Make sure that you have created displayFormContents() method in popup.js file.Then there is no need to use form tag multiple times.Put your all form elements inside one form tag.</p>

```<code><html>
<body>
<script src="popup.js" type="text/javascript"></script>
<form>
<p id="demo"></p>
 First name:<br>
  <input type="text" name="firstname" >
  <br>
  Name:<br>
  <input type="text" name="name" >
  <br>
  age :
  <input type="date" name="Age">
  Phone :
  <input type="number" name="Phone">
  email :
  <input type="email" name="mail">
  Student at UCLA? :

  <input type="checkbox" name="Doe">
    <input type="radio" name="gender" value="male" checked> Male<br>

  <input type="radio" name="gender" value="female"> Female<br>

  <input type="radio" name="gender" value="other"> Other

<button type="button"
onClick="displayFormContents();">Submit
</button>
</form>
</body>

</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an html form with a submit button. I have a js function in a file that I include in the head. I am trying to bind the onclick event of the button to call that function. However, all the methods I tried did not work.

<!DOCTYPE html>

    <button type="button" onclick="displayFormContents();">
</button>

First name:

<input type="text" name="firstname" >

Name:

<input type="text" name="name" >

<form>
    age : <input type="date" name="Age">
</form>

<form>
    Phone : <input type="number" name="Phone">
</form>

<form>
    email : <input type="email" name="mail">
</form>

<form>
    Student at UCLA? : <input type="checkbox" name="Doe">
</form>

<form>
    <input type="radio" name="gender" value="male" checked> Male

    <input type="radio" name="gender" value="female"> Female

    <input type="radio" name="gender" value="other"> Other
</form>

<input type="submit">
</form>

Body:
Make sure that you have created displayFormContents() method in popup.js file.Then there is no need to use form tag multiple times.Put your all form elements inside one form tag.

<html>
<body>
<script src="popup.js" type="text/javascript"></script>
<form>
<p id="demo"></p>
 First name:<br>
  <input type="text" name="firstname" >
  <br>
  Name:<br>
  <input type="text" name="name" >
  <br>
  age :
  <input type="date" name="Age">
  Phone :
  <input type="number" name="Phone">
  email :
  <input type="email" name="mail">
  Student at UCLA? :

  <input type="checkbox" name="Doe">
    <input type="radio" name="gender" value="male" checked> Male<br>

  <input type="radio" name="gender" value="female"> Female<br>

  <input type="radio" name="gender" value="other"> Other

<button type="button"
onClick="displayFormContents();">Submit
</button>
</form>
</body>

</html>


问:
Error in overriding virtual function in templated class
I am having issues with overriding a pure virtual function [getContents()]:
I am trying to inherit a class, fpmessage with a derived class fpmessageImpl

However, the compiler is reporting that fpmessageImpl is virtual when I try to instantiate it, due to getContents() being an unimplemented pure virtual function (despite having no issues with the override).  What is happening here, and is there a way to fix it?
Last section of clang++ error report: (offending code in fpmessagingSystemImpl has been moved to main in MWE)

```<code>src/fpmessagingsystemimpl.h:56:7: note: in instantiation of member function 'fp::utils::fpmessagingSystemImpl<fp::utils::fpMessagingDataStates::States>::send_message' requested here
      fpmessagingSystemImpl(std::map<MessageType,std::type_index> m) noexcept :
      ^
src/fpengineimpl.h:19:21: note: in instantiation of member function 'fp::utils::fpmessagingSystemImpl<fp::utils::fpMessagingDataStates::States>::fpmessagingSystemImpl' requested here
      msg_sys = new fp::utils::fpmessagingSystemImpl<fp::utils::fpMessagingDataStates::States>(ds.get_map());
                    ^
src/fpmessagingsystem.h:32:48: note: unimplemented pure virtual method 'getContents' in 'fpmessage'
      virtual std::tuple<MessageType,std::any> getContents() const noexcept = 0;
</code>```

Reproducible example:
Issue appears to be with how std::make_shared is constructing a new fpmessage (in main):

```<code>#include <memory>
#include <any>
#include <map>
#include <typeindex>

class fpMessagingDataStates {
public:
  enum class States{
    INIT
  };
  const std::map<fpMessagingDataStates::States,std::type_index> get_map() {
    return m;
  }
  fpMessagingDataStates(){
    m = std::map<fpMessagingDataStates::States,std::type_index>();
    m.emplace(std::make_pair(fpMessagingDataStates::States::INIT,std::type_index(typeid(std::wstring))));
  }
private:
  std::map<fpMessagingDataStates::States,std::type_index> m;
};

template<typename MessageType>
class fpmessage{
public:
  fpmessage(MessageType mt, std::any a) noexcept {};
  virtual bool validate_message (const std::map<MessageType,std::type_index>& map) const noexcept {return false;}
  virtual std::tuple<MessageType,std::any> getContents() const noexcept = 0;
  /*virtual ~fpmessage();*/
protected:
  fpmessage() {};
};

template<typename MessageType>
class fpmessageImpl : public fpmessage<MessageType>{
public:
  fpmessageImpl() = delete;
  fpmessageImpl(MessageType mt, std::any a) :
    t(mt),
    contents(a) {}
  // check stored message type against a map
  virtual bool validate_message(const std::map<MessageType,std::type_index>& map) const noexcept override{
    // check the expected message type against the actual type
    auto expected_type = map.find(t);
    return (expected_type->second == std::type_index(contents.type()));
  }
  virtual std::tuple<MessageType,std::any> getContents() const noexcept override {
    return std::make_tuple(t,contents);
  }
private:
  const MessageType t;
  const std::any contents;
};

int main(int argc, char** argv)
{
  std::wstring s = L"Engine Started";
  auto state = fpMessagingDataStates::States::INIT;
  auto m = fpmessageImpl<fpMessagingDataStates::States>(state, s);
  auto mess = std::make_shared<fpmessage<fpMessagingDataStates::States>>(m);
  return 0;
}
</code>```

答:
```<code> auto m = fpmessageImpl<fpMessagingDataStates::States>(state, s);
 auto mess = std::make_shared<fpmessage<fpMessagingDataStates::States>>(m);
</code>```

Renaming and simplifying for illustrative purposes:

```<code>auto d = Derived();
auto bp = std::make_shared<Base>(d);
</code>```

This is a glorified c++11-style wrapper around the old good

```<code> Derived d;
 Base* pb = new Base(d);
</code>```

The second line will not create an object of type Derived. It will create an object of type Base and copy-construct it from the Derived argument, slicing it in process. And of course it will fail to compile if Base is abstract.

In order to copy d one would need to

```<code>Base* pb = new Derived(d);
</code>```

or in C++11-parlance

```<code> std::shared_ptr<Base> = std::make_shared<Derived>(d);
</code>```

Body:
I am having issues with overriding a pure virtual function [getContents()]:
I am trying to inherit a class, fpmessage with a derived class fpmessageImpl

However, the compiler is reporting that fpmessageImpl is virtual when I try to instantiate it, due to getContents() being an unimplemented pure virtual function (despite having no issues with the override).  What is happening here, and is there a way to fix it?
Last section of clang++ error report: (offending code in fpmessagingSystemImpl has been moved to main in MWE)

src/fpmessagingsystemimpl.h:56:7: note: in instantiation of member function 'fp::utils::fpmessagingSystemImpl<fp::utils::fpMessagingDataStates::States>::send_message' requested here
      fpmessagingSystemImpl(std::map<MessageType,std::type_index> m) noexcept :
      ^
src/fpengineimpl.h:19:21: note: in instantiation of member function 'fp::utils::fpmessagingSystemImpl<fp::utils::fpMessagingDataStates::States>::fpmessagingSystemImpl' requested here
      msg_sys = new fp::utils::fpmessagingSystemImpl<fp::utils::fpMessagingDataStates::States>(ds.get_map());
                    ^
src/fpmessagingsystem.h:32:48: note: unimplemented pure virtual method 'getContents' in 'fpmessage'
      virtual std::tuple<MessageType,std::any> getContents() const noexcept = 0;

Reproducible example:
Issue appears to be with how std::make_shared is constructing a new fpmessage (in main):

#include <memory>
#include <any>
#include <map>
#include <typeindex>

class fpMessagingDataStates {
public:
  enum class States{
    INIT
  };
  const std::map<fpMessagingDataStates::States,std::type_index> get_map() {
    return m;
  }
  fpMessagingDataStates(){
    m = std::map<fpMessagingDataStates::States,std::type_index>();
    m.emplace(std::make_pair(fpMessagingDataStates::States::INIT,std::type_index(typeid(std::wstring))));
  }
private:
  std::map<fpMessagingDataStates::States,std::type_index> m;
};

template<typename MessageType>
class fpmessage{
public:
  fpmessage(MessageType mt, std::any a) noexcept {};
  virtual bool validate_message (const std::map<MessageType,std::type_index>& map) const noexcept {return false;}
  virtual std::tuple<MessageType,std::any> getContents() const noexcept = 0;
  /*virtual ~fpmessage();*/
protected:
  fpmessage() {};
};

template<typename MessageType>
class fpmessageImpl : public fpmessage<MessageType>{
public:
  fpmessageImpl() = delete;
  fpmessageImpl(MessageType mt, std::any a) :
    t(mt),
    contents(a) {}
  // check stored message type against a map
  virtual bool validate_message(const std::map<MessageType,std::type_index>& map) const noexcept override{
    // check the expected message type against the actual type
    auto expected_type = map.find(t);
    return (expected_type->second == std::type_index(contents.type()));
  }
  virtual std::tuple<MessageType,std::any> getContents() const noexcept override {
    return std::make_tuple(t,contents);
  }
private:
  const MessageType t;
  const std::any contents;
};

int main(int argc, char** argv)
{
  std::wstring s = L"Engine Started";
  auto state = fpMessagingDataStates::States::INIT;
  auto m = fpmessageImpl<fpMessagingDataStates::States>(state, s);
  auto mess = std::make_shared<fpmessage<fpMessagingDataStates::States>>(m);
  return 0;
}

Body:
 auto m = fpmessageImpl<fpMessagingDataStates::States>(state, s);
 auto mess = std::make_shared<fpmessage<fpMessagingDataStates::States>>(m);

Renaming and simplifying for illustrative purposes:

auto d = Derived();
auto bp = std::make_shared<Base>(d);

This is a glorified c++11-style wrapper around the old good

 Derived d;
 Base* pb = new Base(d);

The second line will not create an object of type Derived. It will create an object of type Base and copy-construct it from the Derived argument, slicing it in process. And of course it will fail to compile if Base is abstract.

In order to copy d one would need to

Base* pb = new Derived(d);

or in C++11-parlance

 std::shared_ptr<Base> = std::make_shared<Derived>(d);


问:
Accessing Properties of the code-behind from aspx page in web application project
I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<div>
<%= x2 %>
<%# x2 %>
</div>
</form>
</body>
</html>
</code>```

Codebehind file :

```<code>using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   }
}
</code>```

It is working fine when I use the same technique in my website project
Kindly help
Thanks

答: Your code is perfectly okay. While accessing the variable/property initillay, the red underline may appear under the expression indicating the compile error, but when you build the solution, there should be no error. </p>

Body:
I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

<%= x2 %>
<%# x2 %>

</form>

Codebehind file :

using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   }
}

It is working fine when I use the same technique in my website project
Kindly help
Thanks


问:
Javascript: Set Value of Form inside of iFrame Not Working
I'm working on setting a value for the credit card number on this website and I can't seem to figure it out. I was told that the form is inside of an iFrame and it can't be accessed. How would I set the value for the card number through the console. I've seen other auto-fill successfully accomplish this successfully. Thank you.

On my console I just keep getting this error:

VM531:3 Uncaught TypeError: Cannot set property 'value' of null at
  :3:11

var numb = document.getElementById('number');
numb.value = "222";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe class="card-fields-iframe" id="card-fields-number-s80xmtdp1g000000" name="card-fields-number-s80xmtdp1g000000" scrolling="no" src="https://checkout.shopifycs.com/number?identifier=61d81845e21cfa9cd0cc2e43a6a8c9a1&location=https%3A%2F%2Fyeezysupply.com%2F17655971%2Fcheckouts%2F61d81845e21cfa9cd0cc2e43a6a8c9a1%3F_ga%3D2.37031328.1462446110.1512281869-2081311403.1511598208" style="height: 43px;" frameborder="0"></iframe>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, height=device-height, minimum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" media="all" href="https://checkout.shopifycs.com/build/inputs-2762b8ff87.css">

  </head>
  <body>
    <form>

        <label for="number" class="visually-hidden" aria-hidden="true">Credit Card Number</label>

          <input autocomplete="cc-number" id="number" name="number" aria-describedby="error-for-number tooltip-for-number" data-current-field="number" class="input-placeholder-color--lvl-30" style="color: rgb(171, 171, 171); font-family: Helvetica\ Neue, sans-serif; padding: 0.94em 0.8em; transition: padding 0.2s ease-out 0s;" placeholder="Card number" type="tel">
          <span id="error-for-number" class="input-error-message visually-hidden"></span>

        <label for="name" class="visually-hidden" aria-hidden="true">Name on card</label>

          <input autocomplete="cc-name" id="name" name="name" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="text">

        <label for="expiry_month" class="visually-hidden" aria-hidden="true">Expiry month</label>

          <input autocomplete="cc-exp-month" id="expiry_month" name="expiry_month" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="expiry_year" class="visually-hidden" aria-hidden="true">Expiry year</label>

          <input autocomplete="cc-exp-year" id="expiry_year" name="expiry_year" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="expiry" class="visually-hidden" aria-hidden="true">MM / YY</label>

          <input autocomplete="cc-exp" id="expiry" name="expiry" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="verification_value" class="visually-hidden" aria-hidden="true">CVV</label>

          <input autocomplete="off" id="verification_value" name="verification_value" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="issue_date" class="visually-hidden" aria-hidden="true">Issue date (MM / YY)</label>

          <input autocomplete="off" id="issue_date" name="issue_date" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="issue_number" class="visually-hidden" aria-hidden="true">Issue number</label>

          <input autocomplete="off" id="issue_number" name="issue_number" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

      <button type="submit" class="visually-hidden" tabindex="-1"></button>
    </form>
    <script src="https://checkout.shopifycs.com/build/boot-6e4b6e821a.js"></script>

</body></code>```

答:
Assuming this is not a cross-domain issue, try this if it works:</p>

```<code>var element = $('#card-fields-iframe').contents().find('#number');
</code>```

Body:
I'm working on setting a value for the credit card number on this website and I can't seem to figure it out. I was told that the form is inside of an iFrame and it can't be accessed. How would I set the value for the card number through the console. I've seen other auto-fill successfully accomplish this successfully. Thank you.

On my console I just keep getting this error:

VM531:3 Uncaught TypeError: Cannot set property 'value' of null at
  :3:11

var numb = document.getElementById('number');
numb.value = "222";

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, height=device-height, minimum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" media="all" href="https://checkout.shopifycs.com/build/inputs-2762b8ff87.css">

    <form>

        Credit Card Number

          <input autocomplete="cc-number" id="number" name="number" aria-describedby="error-for-number tooltip-for-number" data-current-field="number" class="input-placeholder-color--lvl-30" style="color: rgb(171, 171, 171); font-family: Helvetica\ Neue, sans-serif; padding: 0.94em 0.8em; transition: padding 0.2s ease-out 0s;" placeholder="Card number" type="tel">

        Name on card

          <input autocomplete="cc-name" id="name" name="name" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="text">

        Expiry month

          <input autocomplete="cc-exp-month" id="expiry_month" name="expiry_month" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        Expiry year

          <input autocomplete="cc-exp-year" id="expiry_year" name="expiry_year" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        MM / YY

          <input autocomplete="cc-exp" id="expiry" name="expiry" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        CVV

          <input autocomplete="off" id="verification_value" name="verification_value" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        Issue date (MM / YY)

          <input autocomplete="off" id="issue_date" name="issue_date" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        Issue number

          <input autocomplete="off" id="issue_number" name="issue_number" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

      <button type="submit" class="visually-hidden" tabindex="-1"></button>
    </form>

Body:
Assuming this is not a cross-domain issue, try this if it works:

var element = $('#card-fields-iframe').contents().find('#number');


问:
automatic href to div when page loaded
I have html code

```<code><h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
<a class="button" href="#popup1">Let me Pop up</a>
</div>

<div id="popup1" class="overlay">
  <div class="popup">
    <h2>Here i am</h2>
    <a class="close" href="#">×</a>
    <div class="content">
        Thank to pop me out of that button, but now i'm done so you can
    </div>
  </div>
</div>
</code>```

I want popup window show when page is loaded. not waiting when i click to button. How to make with javascript or jquery? This example i found in here

答:
use this:

```<code>window.onload = function() {
  yourFunction(url);
};

function yourFunction(url) {
    newwindow=window.open(url,'name','height=200,width=150');
    if (window.focus) {newwindow.focus()}
    return false;
}
</code>```

In html you can also write :

```<code><a href="popupex.html" onclick="return yourFunction('popupex.html')"
    >Link to popup</a>
</code>```

Title: automatic href to div when page loaded

Body:
I have html code

Popup/Modal Windows without JavaScript

Let me Pop up

Here i am

    ×

        Thank to pop me out of that button, but now i'm done so you can

I want popup window show when page is loaded. not waiting when i click to button. How to make with javascript or jquery? This example i found in here

Body:
use this:

window.onload = function() {
  yourFunction(url);
};

function yourFunction(url) {
    newwindow=window.open(url,'name','height=200,width=150');
    if (window.focus) {newwindow.focus()}
    return false;
}

In html you can also write :

<a href="popupex.html" onclick="return yourFunction('popupex.html')"
    >Link to popup</a>


问:
Multiple if statements, it deletes what is already in cells when if is not fulfilled
I am trying to get Excel to copy some values if the active sheet is a specific sheet. The problem I am having is that if the values from one sheet is transferred to the sheet it needs to be on, it overwrites the cells mentioned in the other if statements, but I need those values not to be overwritten. Can anybody help me solve this problem?</p>

```<code>If ActiveSheet = Sheets("Parts for site") Then
    Sheets("INTERNAL").Cells(35, 4) = Sheets("Parts for site").Cells(i + 3 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for options") Then
    Sheets("INTERNAL").Cells(52, 4) = Sheets("Parts for options").Cells(i + 3 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for renovation") Then
    Sheets("EXTERNAL").Cells(29, 4) = Sheets("Parts for renovation").Cells(i + 2 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for site") Then
    Sheets("EXTERNAL").Cells(35, 4) = Sheets("Parts for site").Cells(i + 2 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for options") Then
    Sheets("EXTERNAL").Cells(52, 4) = Sheets("Parts for options").Cells(i + 2 - n, 17)
    Else
End If
</code>```

答:
You can simply use the "&" to combine both values. </p>

<p>Here an example: </p>

```<code>If ActiveSheet = Sheets("Parts for site") Then
    Sheets("INTERNAL").Cells(35, 4) = Sheets("INTERNAL").Cells(35, 4) & Sheets("Parts for site").Cells(i + 3 - n, 17)
    Else
End If
</code>```

Body:
I am trying to get Excel to copy some values if the active sheet is a specific sheet. The problem I am having is that if the values from one sheet is transferred to the sheet it needs to be on, it overwrites the cells mentioned in the other if statements, but I need those values not to be overwritten. Can anybody help me solve this problem?

If ActiveSheet = Sheets("Parts for site") Then
    Sheets("INTERNAL").Cells(35, 4) = Sheets("Parts for site").Cells(i + 3 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for options") Then
    Sheets("INTERNAL").Cells(52, 4) = Sheets("Parts for options").Cells(i + 3 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for renovation") Then
    Sheets("EXTERNAL").Cells(29, 4) = Sheets("Parts for renovation").Cells(i + 2 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for site") Then
    Sheets("EXTERNAL").Cells(35, 4) = Sheets("Parts for site").Cells(i + 2 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for options") Then
    Sheets("EXTERNAL").Cells(52, 4) = Sheets("Parts for options").Cells(i + 2 - n, 17)
    Else
End If

Body:
You can simply use the "&" to combine both values.

Here an example:

If ActiveSheet = Sheets("Parts for site") Then
    Sheets("INTERNAL").Cells(35, 4) = Sheets("INTERNAL").Cells(35, 4) & Sheets("Parts for site").Cells(i + 3 - n, 17)
    Else
End If


问:
How to minimize an object and build an array from an array of objects in JavaScript
I have an array of objects and each object has around 5 properties and respective values. I would like to iterate through each object in the array and pick only two properties from it and rebuild the object and the array.

For example:

```<code>let resArray = [
{"name": "Aaron", "id": 123, "sex": "male", "country": "usa"},
{"name": "Bert", "id": 456, "sex": "male", "country": "usa"},
{"name": "Brenda", "id": 657, "sex": "female", "country": "canada"},
{"name": "Chris", "id": 856, "sex": "male", "country": "usa"},
{"name": "Angela", "id": 113, "sex": "female", "country": "columbia"},
{"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}];
</code>```

I want to remove the "country" and the "sex" properties from the objects and retain the "name" and "id" properties and rebuild the array. i.e., the output should be as follows:

```<code>let outArray = [
{"name": "Aaron", "id": 123},
{"name": "Bert", "id": 456},
{"name": "Brenda", "id": 657},
{"name": "Chris", "id": 856},
{"name": "Angela", "id": 113},
{"name": "Maria", "id": 569}];
</code>```

As of now, I am just using the resArray and iterating through the whole array and getting whatever values I want. But I just think I can minimize the object so that it will be clear of the clutter.

Could anyone help me out with it?
Thank you.

答:
You can simply use .map() as following -

let resArray = [
   {"name": "Aaron", "id": 123, "sex": "male", "country": "usa"},
   {"name": "Bert", "id": 456, "sex": "male", "country": "usa"},
   {"name": "Brenda", "id": 657, "sex": "female", "country": "canada"},
   {"name": "Chris", "id": 856, "sex": "male", "country": "usa"},
   {"name": "Angela", "id": 113, "sex": "female", "country": "columbia"},
   {"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}
];

let outArray = resArray.map(item => ({name: item.name, id: item.id}));

console.log(JSON.stringify(outArray));```

Body:
I have an array of objects and each object has around 5 properties and respective values. I would like to iterate through each object in the array and pick only two properties from it and rebuild the object and the array.

For example:

let resArray = [
{"name": "Aaron", "id": 123, "sex": "male", "country": "usa"},
{"name": "Bert", "id": 456, "sex": "male", "country": "usa"},
{"name": "Brenda", "id": 657, "sex": "female", "country": "canada"},
{"name": "Chris", "id": 856, "sex": "male", "country": "usa"},
{"name": "Angela", "id": 113, "sex": "female", "country": "columbia"},
{"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}];

I want to remove the "country" and the "sex" properties from the objects and retain the "name" and "id" properties and rebuild the array. i.e., the output should be as follows:

let outArray = [
{"name": "Aaron", "id": 123},
{"name": "Bert", "id": 456},
{"name": "Brenda", "id": 657},
{"name": "Chris", "id": 856},
{"name": "Angela", "id": 113},
{"name": "Maria", "id": 569}];

As of now, I am just using the resArray and iterating through the whole array and getting whatever values I want. But I just think I can minimize the object so that it will be clear of the clutter.

Could anyone help me out with it?
Thank you.


问:
Modify python file which was installed using pip inside an Docker image
I installed a python module called requests-aws4auth in docker using RUN pip install requests-aws4auth

Now I want to modify it by going into cd /opt/conda/lib/python2.7/site-packages/requests_aws4auth/ and commenting a line in aws4auth.py file. I already installed vim while building the docker.

Is it possible to do this while building the dockerfile? If yes, then can some one help me out.

I could do it by using sudo docker run -i -t image_name /bin/bash and modifying the file, but this will create a container. Now, is there any way to push the container back to the image.

答:
There are two ways to do this:

Add some sed command that comments the line in the file after pip install command in dockerfile something like this -

RUN pip install requests-aws4auth
RUN sed -e '/BBB/ s/^#*/#/' -i file #some logic to comment the line

Build the docker image and use it.

If option-1 didn't seems to help try committing the container.
docker run the container do docker exec and comment the line in file. Now commit the container docker commit <conatainer-id> <some custom image name> https://docs.docker.com/engine/reference/commandline/commit/
Now use this custom image.


问:
"The parameter is incorrect." When navigating to new pages in WP7
Quite often when navigating to pages in my WP7 app, I get the exception below:

I haven't been able to pin down exactly what It could be. I have implemented a lot of user controls, but I am passing the Page to each control so they may use the same Navigate call. I have also tried doing

```<code>(App.Current.RootVisual as PhoneApplicationFrame).Navigate
</code>```

but that gives the same result often as well.

The page visually changes to the next page if the exception is handled, but the page remains on the previous page.

For example, if I have the page layout A -> B -> C, and I get this exception navigating to C, C will appear, but I will still be on B.

If back is pressed, I will return to A.

If I interact in a way where I would go to D, I will end up on a Blank screen.

Has anyone experienced this? I haven't seen a WP7 navigation related issue that seems to match this one.

The Parameter is incorrect.

Stack Trace:

```<code>  at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper obj, DependencyProperty property, DependencyObject doh)
   at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper doh, DependencyProperty property, Object obj)
   at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet, Boolean isSetByStyle, Boolean isSetByBuiltInStyle, PropertyInvalidationReason reason)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Controls.ContentControl.set_Content(Object value)
   at System.Windows.Navigation.NavigationService.CompleteNavigation(DependencyObject content)
   at System.Windows.Navigation.NavigationService.<>c__DisplayClass5.<NavigateCore_ContinueNavigation>b__4()
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at System.Delegate.DynamicInvokeOne(Object[] args)
   at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
   at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
   at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
   at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
   at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
</code>```

Edit:

The problem was I had code that was attempting to Navigate forward, while also attempting to navigate backwards. This caused a problem because In some situations, When in the OnNavigatedTo of the future page, my code would try to go back, only to try to go forward again. This caused a big problem.

答:
I've seen that error occur when trying to attach a control to the visual tree that is based on an existing control, but forgeting to give it a unique name. It may be worth checking your code to see if this could happen.

Short of that, it seems to be a catch all exception relating to instantiation of controls. It may help to look for what else could be going wrong during page construction along those lines.

It would be nice if the exception could be more specific.

ContentLicense: CC BY-SA 2.5

Body:
Quite often when navigating to pages in my WP7 app, I get the exception below:

I haven't been able to pin down exactly what It could be. I have implemented a lot of user controls, but I am passing the Page to each control so they may use the same Navigate call. I have also tried doing

(App.Current.RootVisual as PhoneApplicationFrame).Navigate

but that gives the same result often as well.

The page visually changes to the next page if the exception is handled, but the page remains on the previous page.

For example, if I have the page layout A -> B -> C, and I get this exception navigating to C, C will appear, but I will still be on B.

If back is pressed, I will return to A.

If I interact in a way where I would go to D, I will end up on a Blank screen.

Has anyone experienced this? I haven't seen a WP7 navigation related issue that seems to match this one.

The Parameter is incorrect.

Stack Trace:

  at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper obj, DependencyProperty property, DependencyObject doh)
   at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper doh, DependencyProperty property, Object obj)
   at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet, Boolean isSetByStyle, Boolean isSetByBuiltInStyle, PropertyInvalidationReason reason)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Controls.ContentControl.set_Content(Object value)
   at System.Windows.Navigation.NavigationService.CompleteNavigation(DependencyObject content)
   at System.Windows.Navigation.NavigationService.<>c__DisplayClass5.<NavigateCore_ContinueNavigation>b__4()
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at System.Delegate.DynamicInvokeOne(Object[] args)
   at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
   at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
   at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
   at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
   at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

Edit:

The problem was I had code that was attempting to Navigate forward, while also attempting to navigate backwards. This caused a problem because In some situations, When in the OnNavigatedTo of the future page, my code would try to go back, only to try to go forward again. This caused a big problem.


问:
Java not exeucting on a Beagleboard Green @
I am running a new Beagleboard Green Wireless, with the following:
OS: Debian 8.5 jessie
Kernel: armv71 Linux 4.4.9-ti-r25

I downloaded the java zip file:
jdk-8u144-linux-arm64-vfp-hflt.tar.gz
unzipped it, and untarred it and move it to /usr/bin

I set the approripate path and when I attempt to run java -version
I get the following error:
-bash: /usr/jdk1.8.0_144/bin/java: cannot execute binary file: Exec format error

It seems that this is not the correct version to run on arm or am I missing something?

答:
ARMv7 (and below) is 32-bit. ARMv8 introduces the 64-bit instruction set.

Judging by the filename jdk-8u144-linux-arm64-vfp-hflt.tar.gz it looks like a 64-bit version of Java. You cannot run 64-bit binaries in an arm7 operating system such as yours.

Download the 32-bit distribution of Java.


问:
Generate Base64 MD5 hash of byte array
I have following security encoding implemented in my c# web api:

```<code>string testStr = "test";
ASCIIEncoding encoding = new ASCIIEncoding();    //using System.Text;
byte[] byteData = encoding.GetBytes(testStr);

MD5 md5 = MD5.Create();    //using System.Security.Cryptography;
string hash = md5.ComputeHash(byteData);
string md5Base64 = Convert.ToBase64String(hash);
</code>```

I bind this md5Base64 string in header and compare it in API request. This works fine when I hit the API from C# code. Now I need to use it in javascript, so will need js equivalent of above code.

I have tried following but it is giving different output:

```<code>var testStr = 'test';
var byteData = testStr.split ('').map(function (c) { return c.charCodeAt (0); });
var hash = MD5(value.join(','));
var md5Base64 = btoa(hash);
</code>```

the MD5 function used here is from https://stackoverflow.com/a/33486055/7519287

Please let me know what is wrong here.

答:
The problem with your JavaScript code is that you're doing unnecessary conversions: MD5 already takes a string. Furthermore, more conversions after hashing are required.

If we have the following C# code:

```<code>string tmp = "test";
byte[] bTmp = System.Text.Encoding.UTF8.GetBytes(tmp);
byte[] hashed = null;
using (System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
{
    hashed = md5.ComputeHash(bTmp);
}

Console.WriteLine(Convert.ToBase64String(hashed));
</code>```

Fiddle

then the equivalent JavaScript code is:

```<code>var tmp = 'test';
var hashed = hex2a(MD5(tmp)); // md5 src: https://stackoverflow.com/a/33486055/7519287

// src: https://stackoverflow.com/a/3745677/3181933
function hex2a(hexx) {
    var hex = hexx.toString();//force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}

alert(btoa(hashed));
</code>```

Fiddle

Because MD5 returns a hex string, you have to convert that to ASCII before you can base64 encode it. I wonder if you need base64 encoding? MD5 is usually represented as a hex string. Perhaps on the C# side, instead of Convert.ToBase64String(hashed), you could use BitConverter.ToString(hashed).Replace("-", "") to get a hex string for the MD5 hash? Then you could simply just use MD5(tmp) in JavaScript.

Title: Generate Base64 MD5 hash of byte array

Body:
I have following security encoding implemented in my c# web api:

string testStr = "test";
ASCIIEncoding encoding = new ASCIIEncoding();    //using System.Text;
byte[] byteData = encoding.GetBytes(testStr);

MD5 md5 = MD5.Create();    //using System.Security.Cryptography;
string hash = md5.ComputeHash(byteData);
string md5Base64 = Convert.ToBase64String(hash);

I bind this md5Base64 string in header and compare it in API request. This works fine when I hit the API from C# code. Now I need to use it in javascript, so will need js equivalent of above code.

I have tried following but it is giving different output:

var testStr = 'test';
var byteData = testStr.split ('').map(function (c) { return c.charCodeAt (0); });
var hash = MD5(value.join(','));
var md5Base64 = btoa(hash);

the MD5 function used here is from https://stackoverflow.com/a/33486055/7519287

Please let me know what is wrong here.

Body:
The problem with your JavaScript code is that you're doing unnecessary conversions: MD5 already takes a string. Furthermore, more conversions after hashing are required.

If we have the following C# code:

string tmp = "test";
byte[] bTmp = System.Text.Encoding.UTF8.GetBytes(tmp);
byte[] hashed = null;
using (System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
{
    hashed = md5.ComputeHash(bTmp);
}

Console.WriteLine(Convert.ToBase64String(hashed));

Fiddle

then the equivalent JavaScript code is:

var tmp = 'test';
var hashed = hex2a(MD5(tmp)); // md5 src: https://stackoverflow.com/a/33486055/7519287

// src: https://stackoverflow.com/a/3745677/3181933
function hex2a(hexx) {
    var hex = hexx.toString();//force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}

alert(btoa(hashed));

Fiddle

Because MD5 returns a hex string, you have to convert that to ASCII before you can base64 encode it. I wonder if you need base64 encoding? MD5 is usually represented as a hex string. Perhaps on the C# side, instead of Convert.ToBase64String(hashed), you could use BitConverter.ToString(hashed).Replace("-", "") to get a hex string for the MD5 hash? Then you could simply just use MD5(tmp) in JavaScript.


问:
Elixir phoenix live reload doesn't work
My operating system is the latest macOS high sierra. I installed elixir and all the dependencies via Homebrew. I created a new Phoenix app. It shows some wrong. The live reload doesn't work. Below is the info.

```<code>[error] Can't find executable `mac_listener`
[warn] Could not start Phoenix live-reload because we cannot listen to the file system.
You don't need to worry! This is an optional feature used during development to
refresh your browser when you save files and it does not affect production.
</code>```

It seems that some file change listener service isn't running. But I don't know how to fix it.

答:
I solved this problem by reinstalling the command line tools.
Open the bash, and type in:

```<code>xcode-select --install
</code>```

And then, run mix deps.compile file_system to recompile the file_system module. done.

Title: Elixir phoenix live reload doesn't work

Body:
My operating system is the latest macOS high sierra. I installed elixir and all the dependencies via Homebrew. I created a new Phoenix app. It shows some wrong. The live reload doesn't work. Below is the info.

[error] Can't find executable `mac_listener`
[warn] Could not start Phoenix live-reload because we cannot listen to the file system.
You don't need to worry! This is an optional feature used during development to
refresh your browser when you save files and it does not affect production.

It seems that some file change listener service isn't running. But I don't know how to fix it.

Body:
I solved this problem by reinstalling the command line tools.
Open the bash, and type in:

xcode-select --install

And then, run mix deps.compile file_system to recompile the file_system module. done.


问:
Setup ASP.NET MVC 4 or 5 project with Angular 2
I am learning angular 2 with Typescript.

I am using following resource.
QuickStart with Angular 2

Now from there and other examples i found that they telling to create package.json file that lists all dependencies for project.

I think creating this package.json file and listing all dependency packages this kind of structure is followed in .NetCore Project.

In MVC 4 or 5 we have packages.config file which lists although packages that we are going to use.

I am not saying we can not use package.json file when we have package.config file.

But is there any simple way to integrate Angular 2 with typescript in MVC Webapplication project using NUGet Packages and get started?

If not available please let me know how can i setup Angular 2 with type script in ASP.Net MVC 4 or 5?

答:
If You want to install Angular4 on nuget package manager console  you can use Install-Package Angular4 -Version 1.1.0 and follow these steps:

```<code>Angular 4
*********

Prerequisites
`````````````
1. Download and Install Node js
2. Install Visual studio 2015 update 3 or above
3. Download and Install TypeScript 2.6.1 for Visual Studio 2015 (https://www.typescriptlang.org/#download-links)

Follow the steps to install package.
````````````````````````````````````
1. Create an new project with empty template and include dependencies for MVC and WebApi to the project
2. Install the package using command 'Install-Package Angular4 -Version 1.1.0'

Follow the steps after package installation
```````````````````````````````````````````
1. Open Node.js Command Prompt
2. Navigate to project location(use commands such as pushd,cd etc)
3. Run the command 'npm install'
</code>```

Body:
If You want to install Angular4 on nuget package manager console  you can use Install-Package Angular4 -Version 1.1.0 and follow these steps:

Angular 4
*********

Prerequisites
`````````````
1. Download and Install Node js
2. Install Visual studio 2015 update 3 or above
3. Download and Install TypeScript 2.6.1 for Visual Studio 2015 (https://www.typescriptlang.org/#download-links)

Follow the steps to install package.
````````````````````````````````````
1. Create an new project with empty template and include dependencies for MVC and WebApi to the project
2. Install the package using command 'Install-Package Angular4 -Version 1.1.0'

Follow the steps after package installation
```````````````````````````````````````````
1. Open Node.js Command Prompt
2. Navigate to project location(use commands such as pushd,cd etc)
3. Run the command 'npm install'


问:
I use the OpenMp in my code and get the error result
```<code>#pragma omp parallel for num_threads(6)
            for (int m = 0; m < k_num; m++) {
                Point(0, 0) = double(data3[j * 3]) - mean1[m].at<double>(0, 0);
                Point(0, 1) = double(data3[j * 3 + 1]) - mean1[m].at<double>(0, 1);
                Point(0, 2) = double(data3[j * 3 + 2]) - mean1[m].at<double>(0, 2);

                end = Point * inv[m] * Point.t();
                distance = sqrt(end(0, 0));
                if (distance < min && distance>0) {
                    color = m;
                    class_success++;
                    //  color_map[i + left_y][j + left_x] = color;
                    data2[(j + left_x) * 3] = lab_k[m][0];
                    data2[(j + left_x) * 3 + 1] = lab_k[m][1];
                    data2[(j + left_x) * 3 + 2] = lab_k[m][2];
                    data4[j * 3] = lab_k[m][0];
                    data4[j * 3 + 1] = lab_k[m][1];
                    data4[j * 3 + 2] = lab_k[m][2];
                }
            }
</code>```

I try to traverse every pixel in the image, calculate the Mahalanobis distance between them and the color model.(i,j)is the point coordinates.I checked the code and all the variables should not be interrelated,but when i use openmp the result is different.Any help? Thanks a lot.

答:
The problem is the variable is private,I declare the variable inside the body of the loop and get the right rsult.</p>

```<code>#pragma omp parallel for num_threads(6)
            for (int m = 0; m < k_num; m++) {
                Mat_<double>end(1, 1);
                double distance = 1000;
                Mat_<double>Point(1, 3);
                ....
                }
            }
</code>```

Body:
#pragma omp parallel for num_threads(6)
            for (int m = 0; m < k_num; m++) {
                Point(0, 0) = double(data3[j * 3]) - mean1[m].at<double>(0, 0);
                Point(0, 1) = double(data3[j * 3 + 1]) - mean1[m].at<double>(0, 1);
                Point(0, 2) = double(data3[j * 3 + 2]) - mean1[m].at<double>(0, 2);

                end = Point * inv[m] * Point.t();
                distance = sqrt(end(0, 0));
                if (distance < min && distance>0) {
                    color = m;
                    class_success++;
                    //  color_map[i + left_y][j + left_x] = color;
                    data2[(j + left_x) * 3] = lab_k[m][0];
                    data2[(j + left_x) * 3 + 1] = lab_k[m][1];
                    data2[(j + left_x) * 3 + 2] = lab_k[m][2];
                    data4[j * 3] = lab_k[m][0];
                    data4[j * 3 + 1] = lab_k[m][1];
                    data4[j * 3 + 2] = lab_k[m][2];
                }
            }

I try to traverse every pixel in the image, calculate the Mahalanobis distance between them and the color model.(i,j)is the point coordinates.I checked the code and all the variables should not be interrelated,but when i use openmp the result is different.Any help? Thanks a lot.

Body:
The problem is the variable is private,I declare the variable inside the body of the loop and get the right rsult.

#pragma omp parallel for num_threads(6)
            for (int m = 0; m < k_num; m++) {
                Mat_<double>end(1, 1);
                double distance = 1000;
                Mat_<double>Point(1, 3);
                ....
                }
            }


问:
....com.android.tools.aapt2.Aapt2Exception:.AAPT2 error:check logs for details
Error:Execution failed for task ':app:mergeDebugResources'.

Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

答:
It will happen, if your one of paths contains non-ASCII or ' ' (space) character.
Try to change your service directory path to: C:/Users/Public/.gradle in Settings->Build, Execution, Deployment->Gradle


问:
How to handle exceptions when reading files with buffered reader?
I have made code to read text (json, xml etc.) from a text file, and convert it into a strings which can then be used by other code to convert into plain old java objects or POJOS that are annotated by jackson.

I am not sure if my code handles the exceptions properly. So far, I have used the principles mentioned after my code (READ THIS DOWN VOTERS !!!), to develop the code. Note that I cannot use try with resources because I am stuck with Java 6 (even though my project JRE is 1.8).

```<code>package com.testing;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class JunkEx {

    public static void main(String[] args) {
        String filePath = ".\\src\\test\\resources\\text-files\\orders\\orders-2017.txt";
        String contents = fileToString(filePath);
        System.out.println(contents);
    }

    private static String fileToString(String filePath) {
        StringBuilder stringBuilder = null;
        BufferedReader br = null;

        try {
        br = new BufferedReader(new FileReader(filePath));
        stringBuilder = new StringBuilder();
        String currentLine;
        while ((currentLine = br.readLine()) != null) {
            stringBuilder.append(currentLine);
            stringBuilder.append("\n");
        }

        }catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        }catch (IOException ex2) {
            ex2.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

}
</code>```

Principles:

1) Catch the most specific exception first, then the one above it in the exception hierarchy. I.e catch FileNotFoundException 1st and IOException later. Refer point 5 here

2) Do NOT return from inside a finally block, because finally is always executed as long as try "completes" fully or abruptly. Refer this SO answer.

3) Cleanup resources like buffered readers in the finally block. Refer point 1 here.

4) Do not make the callers of the "dangerous" method (i.e. which could throw exceptions), have to know/throw each of the exceptions inside it. I.e dangerous method should not "throws FileNotFoundException, IOException...etc". refer this link, specifically the last paragraph

Flaw in the code:
If any of the first two catch blocks are executed, then its likely that the entire file was not read. But, my method will return a string anyway. The string could be null or incomplete.

Questions -

1) I want to throw an exception when the text file is not successfully converted to a string, i.e. one of the three catch blocks is executed. Should I wrap the exception in each catch block inside a generic Exception object and throw that or do something else ?

2) How can I improve/fix the exception handling of this code?

Project structure:

答:
You have two options:

Don't catch the exceptions and let the caller deal with them

Catch the exceptions and throw your own custom exception, say FileToStringFailedException, that wraps the actual exception. The wrapping part is extremely important, so that when someone up the call chain does a printStackTrace() you get a Caused By section that explains the real failure.

Either option works, and which one you choose depends on the overall design.  For something simple I'd just let the exceptions percolate upwards; if I was designing a large complex library with other custom wrapper exceptions I might choose option 2.

Without a lot more context about what you're doing and where this fits into your system, it's not possible to say one option is "better".

Whatever you do, NEVER interfere with the actual exception. Exceptions are for programmers, not users. If you want "friendly" errors for users, do that at the point where the exceptions are displayed to the users, but make sure the original exceptions are logged for the programmers. otherwise you will regret it severely when your "friendly" exception hides crucial information that you need to troubleshoot a problem.

Body:
I have made code to read text (json, xml etc.) from a text file, and convert it into a strings which can then be used by other code to convert into plain old java objects or POJOS that are annotated by jackson.

I am not sure if my code handles the exceptions properly. So far, I have used the principles mentioned after my code (READ THIS DOWN VOTERS !!!), to develop the code. Note that I cannot use try with resources because I am stuck with Java 6 (even though my project JRE is 1.8).

package com.testing;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class JunkEx {

    public static void main(String[] args) {
        String filePath = ".\\src\\test\\resources\\text-files\\orders\\orders-2017.txt";
        String contents = fileToString(filePath);
        System.out.println(contents);
    }

    private static String fileToString(String filePath) {
        StringBuilder stringBuilder = null;
        BufferedReader br = null;

        try {
        br = new BufferedReader(new FileReader(filePath));
        stringBuilder = new StringBuilder();
        String currentLine;
        while ((currentLine = br.readLine()) != null) {
            stringBuilder.append(currentLine);
            stringBuilder.append("\n");
        }

        }catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        }catch (IOException ex2) {
            ex2.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

}

Principles:

1) Catch the most specific exception first, then the one above it in the exception hierarchy. I.e catch FileNotFoundException 1st and IOException later. Refer point 5 here

2) Do NOT return from inside a finally block, because finally is always executed as long as try "completes" fully or abruptly. Refer this SO answer.

3) Cleanup resources like buffered readers in the finally block. Refer point 1 here.

4) Do not make the callers of the "dangerous" method (i.e. which could throw exceptions), have to know/throw each of the exceptions inside it. I.e dangerous method should not "throws FileNotFoundException, IOException...etc". refer this link, specifically the last paragraph

Flaw in the code:
If any of the first two catch blocks are executed, then its likely that the entire file was not read. But, my method will return a string anyway. The string could be null or incomplete.

Questions -

1) I want to throw an exception when the text file is not successfully converted to a string, i.e. one of the three catch blocks is executed. Should I wrap the exception in each catch block inside a generic Exception object and throw that or do something else ?

2) How can I improve/fix the exception handling of this code?

Project structure:


问:
bluez 5.30: "Not enough free handles to register service" error in starting bluetoothd

What I have done correctly: in linux environment

hciattach /dev/ttyUSB0 any 115200

hciconfig hci0 up

addgroup -S messagebus

adduser -S messagebus -G messagebus

dbus-daemon --system

syslogd

In executing /libexec/bluetooth/bluetoothd --plugin=time -d -E -n, The error Not enough free handles to register service happens as below:

```<code>bluetoothd[756]: src/adapter.c:clear_uuids() sending clear uuids command for index 0  <br/>
bluetoothd[756]: src/adapter.c:set_mode() sending set mode command for index 0 <br/>
bluetoothd[756]: src/gatt-database.c:btd_gatt_database_new() GATT Manager registered for adapter: /org/bluez/hci0 <br/>
bluetoothd[756]: src/adapter.c:adapter_service_add() /org/bluez/hci0 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Adding record with handle 0x10002 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000007-0000-1000-8000-00805f9 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000100-0000-1000-8000-00805f9 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001002-0000-1000-8000-00805f9 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001800-0000-1000-8000-00805f9 <br/>
bluetoothd[756]: src/adapter.c:adapter_service_insert() /org/bluez/hci0 <br/>
bluetoothd[756]: src/adapter.c:add_uuid() sending add uuid command for index 0 <br/>
bluetoothd[756]: src/gatt-database.c:gatt_db_service_added() GATT Service added to local database <br/>
bluetoothd[756]: Failed to obtain handles for "Service Changed"  characteristic <br/>
bluetoothd[756]: src/adapter.c:adapter_service_add() /org/bluez/hci0 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Adding record with handle 0x10003 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000007-0000-1000-8000-00805f9 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000100-0000-1000-8000-00805f9 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001002-0000-1000-8000-00805f9 <br/>
bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001801-0000-1000-8000-00805f9 <br/>
bluetoothd[756]: src/adapter.c:adapter_service_insert() /org/bluez/hci0 <br/>
bluetoothd[756]: src/adapter.c:add_uuid() sending add uuid command for index 0 <br/>
bluetoothd[756]: src/gatt-database.c:gatt_db_service_added() GATT Service added to local database <br/>
bluetoothd[756]: src/advertising.c:btd_advertising_manager_new() LE Advertising Manager created for adapter: /org/bluez/hci0 <br/>
bluetoothd[756]: profiles/time/server.c:time_server_init() path /org/bluez/hci0 <br/>
bluetoothd[756]: src/attrib-server.c:attrib_db_find_avail() enter! <br/>
bluetoothd[756]: src/attrib-server.c:attrib_db_find_avail() BT_UUID16! <br/>
***bluetoothd[756]: Not enough free handles to register service*** <br/>
bluetoothd[756]: Current Time Service could not be registered <br/>
bluetoothd[756]: gatt-time-server: Input/output error (5) <br/>
</code>```

I dived into the code for debugging the issue a little bit. The attrib_db_find_avail(adapter, svc_uuid, size)[in function: gatt_service_add()] always return 0.

The root cause is the servers glist parameter is always NULL, which is in g_slist_find_custom(servers, adapter, adapter_cmp)[called from find_uuid16_avail()/find_uuid128_avail()].

I noticed there is the call: **btd_adapter_gatt_server_start**(struct btd_adapter *adapter)to be used to add a server into the servers glist. But the weird thing is no where it gets called through the whole bluez source code tree.

So shall I call btd_adapter_gatt_server_start() somewhere in my code? Or any other steps I should do to resolve the issue?

答:
rfkill is a subsystem that manages the power to the various radio transmitters that your device might have (such as wifi and bluetooth). It has the ability to manage these devices with software switches (so that they can be temporarily disabled such as to save power) or hardware switches (which might need a reboot to re-enable). rfkill has a command line interface which enables you to control this subsystem. More info can be found from Red Hat https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/power_management_guide/rfkill

It is highly likely that your bluetooth is blocked by rfkill which can be called by power management.

ContentLicense: CC BY-SA 4.0

Body:
What I have done correctly: in linux environment

hciattach /dev/ttyUSB0 any 115200

hciconfig hci0 up

addgroup -S messagebus

adduser -S messagebus -G messagebus

dbus-daemon --system

syslogd

In executing /libexec/bluetooth/bluetoothd --plugin=time -d -E -n, The error Not enough free handles to register service happens as below:

bluetoothd[756]: src/adapter.c:clear_uuids() sending clear uuids command for index 0

bluetoothd[756]: src/adapter.c:set_mode() sending set mode command for index 0

bluetoothd[756]: src/gatt-database.c:btd_gatt_database_new() GATT Manager registered for adapter: /org/bluez/hci0

bluetoothd[756]: src/adapter.c:adapter_service_add() /org/bluez/hci0

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Adding record with handle 0x10002

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000007-0000-1000-8000-00805f9

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000100-0000-1000-8000-00805f9

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001002-0000-1000-8000-00805f9

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001800-0000-1000-8000-00805f9

bluetoothd[756]: src/adapter.c:adapter_service_insert() /org/bluez/hci0

bluetoothd[756]: src/adapter.c:add_uuid() sending add uuid command for index 0

bluetoothd[756]: src/gatt-database.c:gatt_db_service_added() GATT Service added to local database

bluetoothd[756]: Failed to obtain handles for "Service Changed"  characteristic

bluetoothd[756]: src/adapter.c:adapter_service_add() /org/bluez/hci0

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Adding record with handle 0x10003

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000007-0000-1000-8000-00805f9

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000100-0000-1000-8000-00805f9

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001002-0000-1000-8000-00805f9

bluetoothd[756]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001801-0000-1000-8000-00805f9

bluetoothd[756]: src/adapter.c:adapter_service_insert() /org/bluez/hci0

bluetoothd[756]: src/adapter.c:add_uuid() sending add uuid command for index 0

bluetoothd[756]: src/gatt-database.c:gatt_db_service_added() GATT Service added to local database

bluetoothd[756]: src/advertising.c:btd_advertising_manager_new() LE Advertising Manager created for adapter: /org/bluez/hci0

bluetoothd[756]: profiles/time/server.c:time_server_init() path /org/bluez/hci0

bluetoothd[756]: src/attrib-server.c:attrib_db_find_avail() enter!

bluetoothd[756]: src/attrib-server.c:attrib_db_find_avail() BT_UUID16!

***bluetoothd[756]: Not enough free handles to register service***

bluetoothd[756]: Current Time Service could not be registered

bluetoothd[756]: gatt-time-server: Input/output error (5)

I dived into the code for debugging the issue a little bit. The attrib_db_find_avail(adapter, svc_uuid, size)[in function: gatt_service_add()] always return 0.

The root cause is the servers glist parameter is always NULL, which is in g_slist_find_custom(servers, adapter, adapter_cmp)[called from find_uuid16_avail()/find_uuid128_avail()].

I noticed there is the call: **btd_adapter_gatt_server_start**(struct btd_adapter *adapter)to be used to add a server into the servers glist. But the weird thing is no where it gets called through the whole bluez source code tree.

So shall I call btd_adapter_gatt_server_start() somewhere in my code? Or any other steps I should do to resolve the issue?


问:
How can I add a new folder in Sublime Text?
I'm in Sublime working on a project that I need to add a folder in; when I right click to try "Add Folder.." I type in name, press enter and nothing happens. It will still allow me to add a file no problem, but that's not what I need just yet.

答: You can add files and folders on the sidebar in Sublime Text. First, go to Project -> Add Folder to Project and select whatever your parent folder is. That'll put your parent folder in the sidebar. Then you can right click on any of the folders in the sidebar to create child files and folders.</p>


问:
Hover / parent/ child + :before
Good morning, everyone,

I have a problem with my css/javascript.

Here is the URL of the problem site: https://www.espace-musculation.com/nutrition-sportive/

I set up a: before on a link to have all the div of the top clickable:

```<code>z-index: 2;
happy:'';
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba (0,0,0,0,0);
</code>```

I'd like to add a shadow on the image with: hover over the image when hovering, but I still haven't found a solution.

If someone has an idea in css or js I'm a taker!

Thank you, thank you!

答:
I am not clear that for which image you are talking about. But for current situation I would suggest to use following code in the same div/img tag class where you need to put shadow:

CSS:

```<code> -webkit-box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);
    -moz-box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);
    box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);
</code>```

Will this work for you?

Title: Hover / parent/ child + :before

Body:
Good morning, everyone,

I have a problem with my css/javascript.

Here is the URL of the problem site: https://www.espace-musculation.com/nutrition-sportive/

I set up a: before on a link to have all the div of the top clickable:

z-index: 2;
happy:'';
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba (0,0,0,0,0);

I'd like to add a shadow on the image with: hover over the image when hovering, but I still haven't found a solution.

If someone has an idea in css or js I'm a taker!

Thank you, thank you!

Body:
I am not clear that for which image you are talking about. But for current situation I would suggest to use following code in the same div/img tag class where you need to put shadow:

CSS:

 -webkit-box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);
    -moz-box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);
    box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);

Will this work for you?


问:
Why does this handler not return anything?
I'm just starting the ASP.NET tutorial and I don't understand why there is no return statement in the method:

```<code>public async Task OnGetAsync()
{
    Movie = await _context.Movie.ToListAsync();
}
</code>```

Are one line methods automatically returned like arrow statements or does it have to do with the Task in ASP?

答:
Its a model that have property Movie. That property gets set when method OnGetAsync is called. So, you don't need return.

Method return type is Task because it has await. Its analogous to void type if it would be a sync method.

Body:
I'm just starting the ASP.NET tutorial and I don't understand why there is no return statement in the method:

public async Task OnGetAsync()
{
    Movie = await _context.Movie.ToListAsync();
}

Are one line methods automatically returned like arrow statements or does it have to do with the Task in ASP?


问:
static content. difference in tomcat6 and tomcat7 behaviors
I'm sorry if i'm asking something which have been asked 1000 times but i searched for it and didn't find anything:)

I have 2 tomcat installations. tomcat 6 on windows and tomcat 7 on linux machine. i have a project which uses spring and has some static content which i'd like to be able to serve without making the requests go through Spring.

here's my servlet configuration:

```<code><servlet-mapping>
  <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>default</servlet-name>
 <url-pattern>/static/*</url-pattern>
</servlet-mapping>
</code>```

my static files are located in "static" folder next to WEB-INF folder.

Now the funny thing is that on tomcat7 when i do a request to http://myserver.com/myproject/static/css/main.css it looks for the file in /webapps/myproject/static/css/main.css but on tomcat6 it looks for it in /webapps/myproject/css/main.css and produces an error saying that there's no such file.

what configuration should i tweak for both servers to work the same way?

答:
You're actually abusing Tomcat's default servlet. The default servlet is not definied by the servlet API and specific to the servlet container. Tomcat's default servlet is known to have a bug to be able to expose all the contents of /WEB-INF and /META-INF when abused this way, hereby putting doors open to sensitive information. This is been reported as issue 50026 and is been fixed in Tomcat 6.0.30 and onwards.

The solution is simple: you should not explicitly be mapping the default servlet in your web.xml at all. As stated in the bug report, you have to use this approach instead.

Body:
I'm sorry if i'm asking something which have been asked 1000 times but i searched for it and didn't find anything:)

I have 2 tomcat installations. tomcat 6 on windows and tomcat 7 on linux machine. i have a project which uses spring and has some static content which i'd like to be able to serve without making the requests go through Spring.

here's my servlet configuration:

<servlet-mapping>
  <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>default</servlet-name>
 <url-pattern>/static/*</url-pattern>
</servlet-mapping>

my static files are located in "static" folder next to WEB-INF folder.

Now the funny thing is that on tomcat7 when i do a request to http://myserver.com/myproject/static/css/main.css it looks for the file in /webapps/myproject/static/css/main.css but on tomcat6 it looks for it in /webapps/myproject/css/main.css and produces an error saying that there's no such file.

what configuration should i tweak for both servers to work the same way?


问:
Automatic Ajax request to controller
How can I send some data via ajax to controller without click event. I mean when user lands on HOME page, i want to obtain his current latitude and longitude and I was able to get his/her current coordinates.But my problem is that I am unable to send this latitude and longitude to particular route,so that i can search nearest hotels based on his current coordinates.

my code:

```<code><script>
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
        console.log(position);
        var lat = position.coords.latitude;//this gives latitude
        var lng = position.coords.longitude;//this gives longitude

        $.ajax({
            url:'http://localhost:8000/coordinates',
            type:'get',
            data:{latitude:lat,longitude:lng},

            success:function(data)
            {
               alert('success');
            }

        });
    });
}

</script>
</code>```

My route

```<code>Route::get('/coordinates', 'SearchController@getCoordinate');
</code>```

Controller:

```<code>public function getCoordinate(Request $request){
    return $request->latitude;// i am getting nothing here. i expect to get
   latitude of user
}
</code>```

How can i obtain this coordinates in getCoordinate function of my controller when user visit the website.

答:
"without click event"

try this

```<code>$(document).ready(function(){
  //paste your script here
})
</code>```

it mean the javascript would run your code when the document is ready

Title: Automatic Ajax request to controller

Body:
How can I send some data via ajax to controller without click event. I mean when user lands on HOME page, i want to obtain his current latitude and longitude and I was able to get his/her current coordinates.But my problem is that I am unable to send this latitude and longitude to particular route,so that i can search nearest hotels based on his current coordinates.

my code:

My route

Route::get('/coordinates', 'SearchController@getCoordinate');

Controller:

public function getCoordinate(Request $request){
    return $request->latitude;// i am getting nothing here. i expect to get
   latitude of user
}

How can i obtain this coordinates in getCoordinate function of my controller when user visit the website.

Body:
"without click event"

try this

$(document).ready(function(){
  //paste your script here
})

it mean the javascript would run your code when the document is ready


问:
AWS Lambda: Unable to import module
please forgive me, I am totally new at Lambda and Node.

I am trying to replicate this git to order a pizza using an AWS IoT button.

My current code is:

var pizzapi = require('dominos');

var myStore = new pizzapi.Store(
    {
        ID: 'Example'
    }
);

var myAddress = new pizzapi.Address(
        {
            Street: 'Example',
            City: 'Example',
            Region: 'Example',
            PostalCode: 'Example'
        }
    );

var myCustomer = new pizzapi.Customer(
    {
        firstName: 'Example',
        lastName: 'Example',
        address: myAddress,
        phone: 'Example',
        email: 'Example@gmail.com'
    }
);

var order = new pizzapi.Order(
    {
        customer: myCustomer,
        storeID: myStore.ID
    }
);

var cardNumber='Example';
var cardInfo = new order.PaymentObject();
cardInfo.Amount = order.Amounts.Customer;
cardInfo.Number = cardNumber;
cardInfo.CardType = order.validateCC(cardNumber);
cardInfo.Expiration = 'Example';
cardInfo.SecurityCode = 'Example';
cardInfo.PostalCode = 'Example';

order.Payments.push(cardInfo);

function orderDominos(event, context) {
  var clickType = event.clickType;
  switch(clickType.toLowerCase()) {
    case "single": {
      order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
    case "double": {
        order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
    case "long": {
        order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
  }
  order.validate(
      function(result) {
          console.log("Order is Validated");
      }
  );
  order.price(
      function(result) {
            console.log("Order is Priced");
      }
  );
  order.place(
      function(result) {
          console.log("Price is", result.result.Order.Amounts, "\nEstimated Wait Time",result.result.Order.EstimatedWaitMinutes, "minutes");
          console.log("Order placed!");
          context.succeed(event);
      }
  );
}

exports.handler = orderDominos;```
</div>
</div>
</p>

<p>The file structure is:</p>

<ul>
<li>orderDominos.js</li>
<li>node_modules/dominos</li>
</ul>

<p>I zipped the files, uploaded to Lambda, and pointed the header to "index.handler"</p>

<p>What am I doing wrong?</p>

<p>Edit: The 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>Unable to import module 'orderDominos': Error
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/node_modules/dominos/src/http-json.js:1:74)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)</code>```

答:
What worked for me was to zip the following files and upload the zip(after doing npm install in the folder):

node_modules/

your_file1.js

your file2.js

your files.js

package.json

package-lock.json

Title: AWS Lambda: Unable to import module

Body:
please forgive me, I am totally new at Lambda and Node.

I am trying to replicate this git to order a pizza using an AWS IoT button.

My current code is:

var pizzapi = require('dominos');

var myStore = new pizzapi.Store(
    {
        ID: 'Example'
    }
);

var myAddress = new pizzapi.Address(
        {
            Street: 'Example',
            City: 'Example',
            Region: 'Example',
            PostalCode: 'Example'
        }
    );

var myCustomer = new pizzapi.Customer(
    {
        firstName: 'Example',
        lastName: 'Example',
        address: myAddress,
        phone: 'Example',
        email: 'Example@gmail.com'
    }
);

var order = new pizzapi.Order(
    {
        customer: myCustomer,
        storeID: myStore.ID
    }
);

var cardNumber='Example';
var cardInfo = new order.PaymentObject();
cardInfo.Amount = order.Amounts.Customer;
cardInfo.Number = cardNumber;
cardInfo.CardType = order.validateCC(cardNumber);
cardInfo.Expiration = 'Example';
cardInfo.SecurityCode = 'Example';
cardInfo.PostalCode = 'Example';

order.Payments.push(cardInfo);

function orderDominos(event, context) {
  var clickType = event.clickType;
  switch(clickType.toLowerCase()) {
    case "single": {
      order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
    case "double": {
        order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
    case "long": {
        order.addItem(
          new pizzapi.Item(
              {
                  code: 'P_14SCREEN',
                  options: {},
                  quantity: 1
              }
          )
      );
      break;
    }
  }
  order.validate(
      function(result) {
          console.log("Order is Validated");
      }
  );
  order.price(
      function(result) {
            console.log("Order is Priced");
      }
  );
  order.place(
      function(result) {
          console.log("Price is", result.result.Order.Amounts, "\nEstimated Wait Time",result.result.Order.EstimatedWaitMinutes, "minutes");
          console.log("Order placed!");
          context.succeed(event);
      }
  );
}

exports.handler = orderDominos;

The file structure is:

orderDominos.js

node_modules/dominos

I zipped the files, uploaded to Lambda, and pointed the header to "index.handler"

What am I doing wrong?

Edit: The error

Unable to import module 'orderDominos': Error
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/node_modules/dominos/src/http-json.js:1:74)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)


问:
Make make rebuild a target when it depends on a deleted file
Suppose I have a make rule like this:

```<code>SOURCES := $(wildcard ./text/*.txt)

$(INDEX) : $(SOURCES)
    $(COMPILER) $(SOURCES)
</code>```

And then one of the text files, ./text/foo.txt, is deleted. The target $(INDEX) does not seem to be rebuilt. How do I make make rebuild in this case?

答:
If your ./text directory contains only your sources and all of them, you can add it as a pre-requisite of your target:

```<code>$(INDEX) : $(SOURCES) ./text
</code>```

Directories are not like regular files: their last modification date is updated when you add, delete or rename a file (or subdirectory) in them, not when an existing file is modified. Think of it as a file containing the list of contained files.

Body:
Suppose I have a make rule like this:

SOURCES := $(wildcard ./text/*.txt)

$(INDEX) : $(SOURCES)
    $(COMPILER) $(SOURCES)

And then one of the text files, ./text/foo.txt, is deleted. The target $(INDEX) does not seem to be rebuilt. How do I make make rebuild in this case?

Body:
If your ./text directory contains only your sources and all of them, you can add it as a pre-requisite of your target:

$(INDEX) : $(SOURCES) ./text

Directories are not like regular files: their last modification date is updated when you add, delete or rename a file (or subdirectory) in them, not when an existing file is modified. Think of it as a file containing the list of contained files.


问:
Python virtualenv: Unable to install Python 3.5
I have created a virtualenv using pip but unable to install python 3.5 in the virtual environment. When I try this:

virtualenv venv1 --python=python3.5

I am getting this error:

The path python3.5 (from --python=python3.5) does not exist

But I am able to install python 2.7 in the virtual environment without any issues. The error message is not clear, please suggest how to install python 3.5 in this virtual environment.

答: You need to install Python 3 by downloading it from official Python Website https://python.org . You can then call 'virtualenv --name' from your command line and this will create a virtual environment at the current directory with the --name you provided. It will also install Python 3 for you. Simple </p>


问:
Hosting Sharepoint and SQL Server off same server
Is it possible to host Sharepoint and SQL Server off the same server for small time testing. Environment would be set up for purely education purposes. Non-production. Thanks.</p>

答:
Your best bet would be to use a simple virtual environment (I quiet like VirtualBox) and then run a server operating system on there, install SQL Server (if it is only for testing SQL Server express would be sufficient) and then install SharePoint.  When you have installed SharePoint you will be better removing the default web application it adds for you and then adding your own as you will be able to link the new application's database easily to the instance of SQL on your SQL server.

Don't forget that if you are looking at using SharePoint 2010 it all has to be 64bit...

Minimum development environment for sharepoint 2007 webparts

Hope this helps anyway...