问:
How to stop onCreateView method being call in custom ViewPager
As i have Fragment there is ViewPager in which i am displaying three another fragment, now the onCreateView method is called from all three fragment.
Here is my code.

```<code>public class CustomViewPager extends ViewPager {
private boolean enabled;

public CustomViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.enabled = true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (this.enabled) {
        return super.onTouchEvent(event);
    }
    return false;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    if (this.enabled) {
        return super.onInterceptTouchEvent(event);
    }
    return false;
}

public void setPagingEnabled(boolean enabled) {
    this.enabled = enabled;
}
}
</code>```

Xml

```<code><com.customView.CustomViewPager
            android:id="@+id/newOrderContainerPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/layout_next_previous"
            android:layout_below="@+id/newTitle"
            android:layout_marginBottom="@dimen/ten_dp">
</com.customView.CustomViewPager>
</code>```

Here is adapter

```<code>public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {`enter code here`

    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFrag(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    return super.instantiateItem(container, position);
}
}
</code>```

Main Fragment which display ViewPager

```<code>@Override
public View setContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_new_order, container, false);

    setupViewPager(customViewPager);
    customViewPager.setPagingEnabled(false);

    return view;
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
    adapter.addFrag(new NewOrderFragmentFirstPage(), NewOrderFragmentFirstPage.class.getName());
    adapter.addFrag(new NewOrderFragmentSecondPage(), NewOrderFragmentFirstPage.class.getName());
    adapter.addFrag(new NewOrderFragmentThirdPage(), NewOrderFragmentThirdPage.class.getName());
    viewPager.setAdapter(adapter);
}

 public void onClick(View view) {
    switch (view.getId()) {
        case R.id.txt_Next:
            txt_Previous.setVisibility(View.VISIBLE);
            if (count < 3) {
                count++;
            }
            customViewPager.setCurrentItem(customViewPager.getCurrentItem() + 1);
            textView.setText(count + "/3");
            break;
        case R.id.txt_previous:
            if (count > 1) {
                count--;
            }
            if (count == 1) {
                txt_Previous.setVisibility(View.INVISIBLE);
            }
            customViewPager.setCurrentItem(customViewPager.getCurrentItem() - 1);
            textView.setText(count + "/3");
            break;
    }
}
</code>```

Please help.
Thanks

答: You can add the code that you want to execute only single time in onActivityCreated() this will prevent its call from all the 3 fragments</p>

Body:
As i have Fragment there is ViewPager in which i am displaying three another fragment, now the onCreateView method is called from all three fragment.
Here is my code.

public class CustomViewPager extends ViewPager {
private boolean enabled;

public CustomViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.enabled = true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (this.enabled) {
        return super.onTouchEvent(event);
    }
    return false;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    if (this.enabled) {
        return super.onInterceptTouchEvent(event);
    }
    return false;
}

public void setPagingEnabled(boolean enabled) {
    this.enabled = enabled;
}
}

Xml

<com.customView.CustomViewPager
            android:id="@+id/newOrderContainerPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/layout_next_previous"
            android:layout_below="@+id/newTitle"
            android:layout_marginBottom="@dimen/ten_dp">
</com.customView.CustomViewPager>

Here is adapter

public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {`enter code here`

    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFrag(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    return super.instantiateItem(container, position);
}
}

Main Fragment which display ViewPager

@Override
public View setContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_new_order, container, false);

    setupViewPager(customViewPager);
    customViewPager.setPagingEnabled(false);

    return view;
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
    adapter.addFrag(new NewOrderFragmentFirstPage(), NewOrderFragmentFirstPage.class.getName());
    adapter.addFrag(new NewOrderFragmentSecondPage(), NewOrderFragmentFirstPage.class.getName());
    adapter.addFrag(new NewOrderFragmentThirdPage(), NewOrderFragmentThirdPage.class.getName());
    viewPager.setAdapter(adapter);
}

 public void onClick(View view) {
    switch (view.getId()) {
        case R.id.txt_Next:
            txt_Previous.setVisibility(View.VISIBLE);
            if (count < 3) {
                count++;
            }
            customViewPager.setCurrentItem(customViewPager.getCurrentItem() + 1);
            textView.setText(count + "/3");
            break;
        case R.id.txt_previous:
            if (count > 1) {
                count--;
            }
            if (count == 1) {
                txt_Previous.setVisibility(View.INVISIBLE);
            }
            customViewPager.setCurrentItem(customViewPager.getCurrentItem() - 1);
            textView.setText(count + "/3");
            break;
    }
}

Please help.
Thanks


来源: stackexchange

问:
Echo printing variables in a completely wrong order
I am trying to create a string with a query that will be save / send to another location, this string contains different variables.

The issue that I am having is that the echo of the variables are completely upside down and mix.

See code below:

```<code>tokenID=$(docker exec -ti $dockerContainerID /bin/sh -c "cat /tempdir/tokenfile.txt")
serverName="asdasd"
attQuery="$tokenID $serverName"
agentRegQuery="$./opt/mule/bin/amc_setup -H $attQuery"

echo TOKEN ID $tokenID
echo SERVER NAME $serverName
echo $attQuery
echo $agentRegQuery
</code>```

Find below the output I am receiving:

```<code>TOKEN ID 29a6966f-fa0e-4f08-87eb-418722872d80---46407
SERVER NAME asdasd
 asdasdf-fa0e-4f08-87eb-418722872d80---46407
 asdasdmule/bin/amc_setup -H 29a6966f-fa0e-4f08-87eb-418722872d80---46407
</code>```

答:
I think everything works as it should

```<code>echo TOKEN ID $tokenID             -> TOKEN ID 29a6966f-fa0e-4f08-87eb-418722872d80---46407
echo SERVER NAME $serverName       -> SERVER NAME asdasd
echo $attQuery                     -> asdasdf-fa0e-4f08-87eb-418722872d80---46407
echo $agentRegQuery                -> asdasdmule/bin/amc_setup -H 29a6966f-fa0e-4f08-87eb-418722872d80---46407
</code>```

Why do you think something is wron here?
Best regards, Georg

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a string with a query that will be save / send to another location, this string contains different variables.

The issue that I am having is that the echo of the variables are completely upside down and mix.

See code below:

tokenID=$(docker exec -ti $dockerContainerID /bin/sh -c "cat /tempdir/tokenfile.txt")
serverName="asdasd"
attQuery="$tokenID $serverName"
agentRegQuery="$./opt/mule/bin/amc_setup -H $attQuery"

echo TOKEN ID $tokenID
echo SERVER NAME $serverName
echo $attQuery
echo $agentRegQuery

Find below the output I am receiving:

TOKEN ID 29a6966f-fa0e-4f08-87eb-418722872d80---46407
SERVER NAME asdasd
 asdasdf-fa0e-4f08-87eb-418722872d80---46407
 asdasdmule/bin/amc_setup -H 29a6966f-fa0e-4f08-87eb-418722872d80---46407

Body:
I think everything works as it should

echo TOKEN ID $tokenID             -> TOKEN ID 29a6966f-fa0e-4f08-87eb-418722872d80---46407
echo SERVER NAME $serverName       -> SERVER NAME asdasd
echo $attQuery                     -> asdasdf-fa0e-4f08-87eb-418722872d80---46407
echo $agentRegQuery                -> asdasdmule/bin/amc_setup -H 29a6966f-fa0e-4f08-87eb-418722872d80---46407

Why do you think something is wron here?
Best regards, Georg


问:
Magento keep alive response: connection close
I am trying to add a KeepAlive statement to my htaccess. I've set it like this:

```<code><IfModule mod_headers.c>  Header set Connection keep-alive </IfModule>
</code>```

I i tested this, I got the response close on the connection!

Does someone know how to resolve this?
I am on magento 1.7.

答:
For those who search for an answer: </p>

<p>KeepAlive have to be activated by your Hoster. Then you can enable it in your htaccess. </p>

Body:
I am trying to add a KeepAlive statement to my htaccess. I've set it like this:

<IfModule mod_headers.c>  Header set Connection keep-alive </IfModule>

I i tested this, I got the response close on the connection!

Does someone know how to resolve this?
I am on magento 1.7.

Body:
For those who search for an answer:

KeepAlive have to be activated by your Hoster. Then you can enable it in your htaccess.


问:
Passport.js & Express Session - req.user undefined causing .isAuthenticted() to return false
I've spent more time than I'd like to admit scouring countless posts online that have the same problem as me, to no avail. The majority of solutions seemed to be things like not including

passReqToCallback: true in my LocalStrategy.

passport.serializeUser() and passport.deserializeUser() in my init file.

app.use(passport.initialize()) and app.use(passport.session()) in app.js.

Requiring and using app.use(cookieParser()) in app.js.

Passing cookie parser my secret key.

Adding proxy and cookie attributes to my expressSession variable in app.js.

Invoking req.login inside passport.authenticate within my page route.

And several other little tweaks I can't remember...

My login.js is as follows;

```<code>var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user');
var bCrypt = require('bcrypt-nodejs');

module.exports = function(passport) {
    passport.use('login', new LocalStrategy({passReqToCallback: true},
        function(req, username, password, done) {
            //Queries MongoDB For User
            User.findOne({'username':  username}, function(err, user) {
                //In The Event Of An Error, Throw It
                if (err) {
                    return done(err);
                }

                //Username Does Not Exist, Log Error, Callback, Flash Error Message
                if (!user){
                    console.log('User: '+ username + ", does not exist.");
                    return done(null, false, req.flash('message', 'User Not found.'));
                }

                //User Exists, But Password Is Incorrect
                if (!isValidPassword(user, password)){
                    console.log('Invalid Password');
                    return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
                }

                //If No Previous Error Conditions Are Met - Username/Password Are Correct
                console.log("Validated User: " + username + ".");
                //req.user = user;
                return done(null, user);
            }); //End of User.findOne()
        }) //End of new LocalStrategy
    ); //End of passport.use()

    /*
    var isValidPassword = function(user, password){
        return bCrypt.compareSync(password, user.password);
    }
    */

    //Passwords are not currently hashed in my DB, so ignore bcrypt for now.
    var isValidPassword = function(user, password) {
        return user.password == password;
    }
}
</code>```

My passport-init.js file

```<code>var login = require('./login');
var User = require('../../models/user');

module.exports = function(passport){
    //Serialise User
    passport.serializeUser(function(user, done) {
        console.log("Serializing User: " + user.username + "\n" + user + ".");
        done(null, user._id);
    });

    //De-Serialise User
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            console.log("Deserializing User: " + user.username + "\n" + user);
            done(err, user);
        });
    });

    //Setting up Passport Strategy for Login
    login(passport);
}
</code>```

My index.js file contains the POST Login route

```<code>/* POST Login Page*/
router.post('/login', passport.authenticate('login', {
    successRedirect: '/dashboard',
    failureRedirect: '/login',
    failureFlash: true
}));
</code>```

And dashboard.js contains all the routing for /dashboard/other-pages.
These ones are protected by the isAuthenticated function.

```<code>var express = require('express');
var router = express.Router();
var database = require('../public/javascripts/db-connect.js');

var isAuthenticated = function(req, res, next) {
    console.log("User: " + req.user);
    console.log("Authenticated?: " + req.isAuthenticated());
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect('/unauthorised');
    }
}

module.exports = function(passport) {
    //Routes /dashboard --> dashboard.pug
    router.get('/', isAuthenticated, function(req, res, next) {
        database.getData("busdata", function(err, data) {
            if (err) {
                console.error(err);
            } else {
                res.render('dashboard', {title: 'Dashboard', busdata: data});
            }
        });
    });

    //Routes /dashboard/journeys --> journeys.pug
    router.get('/journeys', isAuthenticated, function(req, res, next) {
        database.getData("journeydata", function(err, data) {
            if (err) {
                console.error(err);
            } else {
                res.render('journeys', {title: 'Journey Graphs', journeydata: data});
            }
        });
    });

    return router;
}
</code>```

So when I run the app;

I check localhost:3000/dashboard and localhost:3000/dashboard/journeys. They correctly re-direct me to /unauthorised.

Navigate to /login.

Enter a correct username and password, the console then spits out:

Validated User: TomPlum. Meaning passport.use() reached return done(null, user)

Serialising User: TomPlum + the objects properties

POST /login 302 time ms

User: undefined from isAuthenticated

isAuthenticated? false

GET /dashboard 302 time ms

Deserialising User: TomPlum + the objects properties

I'm then redirected to /unauthorised as isAuthenticated() evaluates to false.

Why is req.user undefined? Should I be using a LocalStrategy if my MongoDB is not-local? (Amazon Atlas Server). Other forum posts have suggested it could be a cookie issue but I've included the relevant cookie-parser includes in my app.js file.

app.js is here in-case it's an order issue.

```<code>//Require Variables
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js

//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var dashboard = require('./routes/dashboard')(passport);

var app = express();
app.d3 = require('d3');

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

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

//app.use('/', index);
app.use('/dashboard', dashboard);
app.use('/users', users);

//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.enable('trust-proxy');
app.use(expressSession({
    secret: 'urban_sensing',
    resave: true,
    saveUninitialized: true,
    proxy: true,
    cookie: {
        secure: true,
        maxAge: 3600000
    }
}));
app.use(passport.initialize());
app.use(passport.session());

//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());

//Initialize Passport

var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);

var index = require('./routes/index')(passport);
app.use('/', index);

//Catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

//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
  res.status(err.status || 500);
  res.render('error');
});

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

Some of the app.use(expressSession({..})); properties may currently be unnecessary as they've been added in an attempt to fix the issue.

Any help would be appreciated.

答:
After too much time on this, turns out it was simply the order of app.js.

By moving

var dashboard = require('./routes/dashboard')(passport);

app.use('/dashboard', dashboard);

below all the passport configuration. It now works correctly. It seems that something wasn't initialised correctly during the routing of /dashboard when it was before the passport code.

Updated app.js

```<code>//Require Variables
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js

//Page Routing
//var index = require('./routes');
var users = require('./routes/users');

var app = express();
app.d3 = require('d3');

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

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

//app.use('/', index);

app.use('/users', users);

//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
    secret: 'urban_sensing',
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 3600000 //1 Hour
    }
}));
app.use(passport.initialize());
app.use(passport.session());

//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());

//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);

var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);

var index = require('./routes/index')(passport);
app.use('/', index);

//Catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

//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
  res.status(err.status || 500);
  res.render('error');
});

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

Body:
I've spent more time than I'd like to admit scouring countless posts online that have the same problem as me, to no avail. The majority of solutions seemed to be things like not including

passReqToCallback: true in my LocalStrategy.

passport.serializeUser() and passport.deserializeUser() in my init file.

app.use(passport.initialize()) and app.use(passport.session()) in app.js.

Requiring and using app.use(cookieParser()) in app.js.

Passing cookie parser my secret key.

Adding proxy and cookie attributes to my expressSession variable in app.js.

Invoking req.login inside passport.authenticate within my page route.

And several other little tweaks I can't remember...

My login.js is as follows;

var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user');
var bCrypt = require('bcrypt-nodejs');

module.exports = function(passport) {
    passport.use('login', new LocalStrategy({passReqToCallback: true},
        function(req, username, password, done) {
            //Queries MongoDB For User
            User.findOne({'username':  username}, function(err, user) {
                //In The Event Of An Error, Throw It
                if (err) {
                    return done(err);
                }

                //Username Does Not Exist, Log Error, Callback, Flash Error Message
                if (!user){
                    console.log('User: '+ username + ", does not exist.");
                    return done(null, false, req.flash('message', 'User Not found.'));
                }

                //User Exists, But Password Is Incorrect
                if (!isValidPassword(user, password)){
                    console.log('Invalid Password');
                    return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
                }

                //If No Previous Error Conditions Are Met - Username/Password Are Correct
                console.log("Validated User: " + username + ".");
                //req.user = user;
                return done(null, user);
            }); //End of User.findOne()
        }) //End of new LocalStrategy
    ); //End of passport.use()

    /*
    var isValidPassword = function(user, password){
        return bCrypt.compareSync(password, user.password);
    }
    */

    //Passwords are not currently hashed in my DB, so ignore bcrypt for now.
    var isValidPassword = function(user, password) {
        return user.password == password;
    }
}

My passport-init.js file

var login = require('./login');
var User = require('../../models/user');

module.exports = function(passport){
    //Serialise User
    passport.serializeUser(function(user, done) {
        console.log("Serializing User: " + user.username + "\n" + user + ".");
        done(null, user._id);
    });

    //De-Serialise User
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            console.log("Deserializing User: " + user.username + "\n" + user);
            done(err, user);
        });
    });

    //Setting up Passport Strategy for Login
    login(passport);
}

My index.js file contains the POST Login route

/* POST Login Page*/
router.post('/login', passport.authenticate('login', {
    successRedirect: '/dashboard',
    failureRedirect: '/login',
    failureFlash: true
}));

And dashboard.js contains all the routing for /dashboard/other-pages.
These ones are protected by the isAuthenticated function.

var express = require('express');
var router = express.Router();
var database = require('../public/javascripts/db-connect.js');

var isAuthenticated = function(req, res, next) {
    console.log("User: " + req.user);
    console.log("Authenticated?: " + req.isAuthenticated());
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect('/unauthorised');
    }
}

module.exports = function(passport) {
    //Routes /dashboard --> dashboard.pug
    router.get('/', isAuthenticated, function(req, res, next) {
        database.getData("busdata", function(err, data) {
            if (err) {
                console.error(err);
            } else {
                res.render('dashboard', {title: 'Dashboard', busdata: data});
            }
        });
    });

    //Routes /dashboard/journeys --> journeys.pug
    router.get('/journeys', isAuthenticated, function(req, res, next) {
        database.getData("journeydata", function(err, data) {
            if (err) {
                console.error(err);
            } else {
                res.render('journeys', {title: 'Journey Graphs', journeydata: data});
            }
        });
    });

    return router;
}

So when I run the app;

I check localhost:3000/dashboard and localhost:3000/dashboard/journeys. They correctly re-direct me to /unauthorised.

Navigate to /login.

Enter a correct username and password, the console then spits out:

Validated User: TomPlum. Meaning passport.use() reached return done(null, user)

Serialising User: TomPlum + the objects properties

POST /login 302 time ms

User: undefined from isAuthenticated

isAuthenticated? false

GET /dashboard 302 time ms

Deserialising User: TomPlum + the objects properties

I'm then redirected to /unauthorised as isAuthenticated() evaluates to false.

Why is req.user undefined? Should I be using a LocalStrategy if my MongoDB is not-local? (Amazon Atlas Server). Other forum posts have suggested it could be a cookie issue but I've included the relevant cookie-parser includes in my app.js file.

app.js is here in-case it's an order issue.

//Require Variables
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js

//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var dashboard = require('./routes/dashboard')(passport);

var app = express();
app.d3 = require('d3');

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

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

//app.use('/', index);
app.use('/dashboard', dashboard);
app.use('/users', users);

//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.enable('trust-proxy');
app.use(expressSession({
    secret: 'urban_sensing',
    resave: true,
    saveUninitialized: true,
    proxy: true,
    cookie: {
        secure: true,
        maxAge: 3600000
    }
}));
app.use(passport.initialize());
app.use(passport.session());

//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());

//Initialize Passport

var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);

var index = require('./routes/index')(passport);
app.use('/', index);

//Catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

//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
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Some of the app.use(expressSession({..})); properties may currently be unnecessary as they've been added in an attempt to fix the issue.

Any help would be appreciated.

Body:
After too much time on this, turns out it was simply the order of app.js.

By moving

var dashboard = require('./routes/dashboard')(passport);

app.use('/dashboard', dashboard);

below all the passport configuration. It now works correctly. It seems that something wasn't initialised correctly during the routing of /dashboard when it was before the passport code.

Updated app.js

//Require Variables
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js

//Page Routing
//var index = require('./routes');
var users = require('./routes/users');

var app = express();
app.d3 = require('d3');

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

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

//app.use('/', index);

app.use('/users', users);

//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
    secret: 'urban_sensing',
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 3600000 //1 Hour
    }
}));
app.use(passport.initialize());
app.use(passport.session());

//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());

//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);

var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);

var index = require('./routes/index')(passport);
app.use('/', index);

//Catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

//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
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


问:
Restore contrast of image after modifying it in Android or OpenCV
I am playing with images changing their contrast but I don't know how to restore the contrast back of an image after modifying it first.

I understand with a value greater than 1 I increase the contrast and with a value between 0 and 1 I decrease it.

I tried with OpenCV and with a ColorMatrix in Android.

For example, using OpenCV, first I double the contrast of an image like this:

src.convertTo(dst, -1, 2, 0);

and then I decrease it by half:

src.convertTo(dst, -1, 0.5, 0);

but after decreasing it the resulting image is not the same as the original one I had before doubling the contrast.

With Android, I was using this colorMatrix to double the contrast:

```<code>ColorMatrix cm = new ColorMatrix();
        cm.set(new float[] {
                2, 0, 0, 0, 0,
                0, 2, 0, 0, 0,
                0, 0, 2, 0, 0,
                0, 0, 0, 1, 0});
</code>```

and this to decrease it by half:

```<code>ColorMatrix cm = new ColorMatrix();
        cm.set(new float[] {
                0.5, 0, 0, 0, 0,
                0, 0.5, 0, 0, 0,
                0, 0, 0.5, 0, 0,
                0, 0, 0, 1, 0});
</code>```

I tried with different values and research on the Internet but I can't figure out the equivalences between increasing and decreasing contrast.

Does anybody know how to do this?

答:
Hi you may change contrast using below method</p>

```<code>  /**
     * Set contrast and brightness in bitmap
     *
     * @param bmp        bitmap to change
     * @param contrast   contrast value from 1 to 10
     * @param brightness brightness value from 1 to 100
     * @return tuned bitmap
     */
    public static Bitmap ChangeBitmapContrastBrightness(Bitmap bmp, float contrast, float brightness) {
        ColorMatrix cm = new ColorMatrix(new float[]
                {
                        contrast, 0, 0, 0, brightness,
                        0, contrast, 0, 0, brightness,
                        0, 0, contrast, 0, brightness,
                        0, 0, 0, 1, 0
                });

        Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());

        Canvas canvas = new Canvas(ret);

        Paint paint = new Paint();
        paint.setColorFilter(new ColorMatrixColorFilter(cm));
        canvas.drawBitmap(bmp, 0, 0, paint);

        return ret;
    }
</code>```

Body:
I am playing with images changing their contrast but I don't know how to restore the contrast back of an image after modifying it first.

I understand with a value greater than 1 I increase the contrast and with a value between 0 and 1 I decrease it.

I tried with OpenCV and with a ColorMatrix in Android.

For example, using OpenCV, first I double the contrast of an image like this:

src.convertTo(dst, -1, 2, 0);

and then I decrease it by half:

src.convertTo(dst, -1, 0.5, 0);

but after decreasing it the resulting image is not the same as the original one I had before doubling the contrast.

With Android, I was using this colorMatrix to double the contrast:

ColorMatrix cm = new ColorMatrix();
        cm.set(new float[] {
                2, 0, 0, 0, 0,
                0, 2, 0, 0, 0,
                0, 0, 2, 0, 0,
                0, 0, 0, 1, 0});

and this to decrease it by half:

ColorMatrix cm = new ColorMatrix();
        cm.set(new float[] {
                0.5, 0, 0, 0, 0,
                0, 0.5, 0, 0, 0,
                0, 0, 0.5, 0, 0,
                0, 0, 0, 1, 0});

I tried with different values and research on the Internet but I can't figure out the equivalences between increasing and decreasing contrast.

Does anybody know how to do this?

Body:
Hi you may change contrast using below method

  /**
     * Set contrast and brightness in bitmap
     *
     * @param bmp        bitmap to change
     * @param contrast   contrast value from 1 to 10
     * @param brightness brightness value from 1 to 100
     * @return tuned bitmap
     */
    public static Bitmap ChangeBitmapContrastBrightness(Bitmap bmp, float contrast, float brightness) {
        ColorMatrix cm = new ColorMatrix(new float[]
                {
                        contrast, 0, 0, 0, brightness,
                        0, contrast, 0, 0, brightness,
                        0, 0, contrast, 0, brightness,
                        0, 0, 0, 1, 0
                });

        Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());

        Canvas canvas = new Canvas(ret);

        Paint paint = new Paint();
        paint.setColorFilter(new ColorMatrixColorFilter(cm));
        canvas.drawBitmap(bmp, 0, 0, paint);

        return ret;
    }


问:
How to break string by separator into multidimensional array in PHP
I have a string 'value1/value2'. The required output is $_SESSION['value1']['value2']. i tried using explode and then array_reduce over explode values but with no success.

My code looks like

```<code>function set($key, $value){
/* code */
}

set('key1/key2', 'some_text');
</code>```

required output like $_SESSION['key1']['key2'] = 'some_text';

key1/key2 is not fixed it may be 'key1' or 'key1/key2/key3' and so on.
Anyone be make fiddle of it is Highly appreciable.
Thanks

答:
Accessing a value via a key-path string, as in your original question, using your original idea and let array_reduce do the work looks like:

```<code>$session = ['value1' => [ 'value2' => [ 'value3' => 'there you are!' ]]];
$path = explode('/', 'value1/value2/value3');
$val = array_reduce($path,
                    function(&$carry, $key) { return $carry[$key];},
                    $session);
echo $val
--> "there you are!"
</code>```

Setting a value can be done e.g. like this, following the path by reference, creating arrays as needed:

```<code>function set($path, $value) {
    $path = explode('/', $path);
    $key = array_pop($path);
    $arr = &$_SESSION;
    foreach($path as $part) {
        // carefull, this might lose values to accommodate
        // the structure wanted with $path
        (isset($arr[$part]) && is_array($arr[$part])) || ($arr[$part] = []);
        $arr =& $arr[$part];
    }
    $arr[$key] = $value;
};
</code>```

Body:
I have a string 'value1/value2'. The required output is $_SESSION['value1']['value2']. i tried using explode and then array_reduce over explode values but with no success.

My code looks like

function set($key, $value){
/* code */
}

set('key1/key2', 'some_text');

required output like $_SESSION['key1']['key2'] = 'some_text';

key1/key2 is not fixed it may be 'key1' or 'key1/key2/key3' and so on.
Anyone be make fiddle of it is Highly appreciable.
Thanks

Body:
Accessing a value via a key-path string, as in your original question, using your original idea and let array_reduce do the work looks like:

$session = ['value1' => [ 'value2' => [ 'value3' => 'there you are!' ]]];
$path = explode('/', 'value1/value2/value3');
$val = array_reduce($path,
                    function(&$carry, $key) { return $carry[$key];},
                    $session);
echo $val
--> "there you are!"

Setting a value can be done e.g. like this, following the path by reference, creating arrays as needed:

function set($path, $value) {
    $path = explode('/', $path);
    $key = array_pop($path);
    $arr = &$_SESSION;
    foreach($path as $part) {
        // carefull, this might lose values to accommodate
        // the structure wanted with $path
        (isset($arr[$part]) && is_array($arr[$part])) || ($arr[$part] = []);
        $arr =& $arr[$part];
    }
    $arr[$key] = $value;
};


问:
how to continuously watch for scope variable until update
In angular.js there is $watch to watch the scoped variables for updates. but is there anything that I can do, such as execute a function until the variable gets updated</p>

答:
```<code>   //try this (please inject $interval service to your controller)
    var execueMe = function () {
        //your stuff
    }

    $interval(execueMe, 3000); //will trigger every 3 seconds
</code>```


问:
How to send fb app invites like Kiwi App
I got a app invite on fb from a friend via Kiwi app.

When I clicked this notification it redirected me to their Google Play Store app page.
I downloaded it and signed up with facebook giving basic info, friend list and email address permissions.

When I logged in, the first screen I get to see is the one below. It is an 'invite your friends' page but what amuses me is that it does not show a fb invite dialog as mentioned in official docs. The official docs does not mention any method to build your own custom UI.

So how does Kiwi manage to build a custom UI, load all my friends(all 2000+) and ask me to invite them all. There is not even a limit of max 50 requests.

I want to implement this in my app as well. Please can anyone post a snippet for this.

答:
To create custom invites like the Kiwi app your app should be a game, and use Game requests to invite friends

https://developers.facebook.com/docs/games/services/gamerequests


问:
Regex Replace between groups
So I have the following regex.replace in C#:

```<code>Regex.Replace(inputString, @"^([^,]*,){5}(.*)", @"$1somestring,$2");
</code>```

where 5 is a variable number in code, but that's not really relevant since at the time of execution it will always have a set value (like 5, for example). Same with somestring,.

Essentially I want to input somestring, between the two groups. The output works for somestring,$2, but $1 is just printed as $1. So say whatever (.*) grabs = "2, a, f2" the resulting string I'd get out is $1somestring,2,a,f2 no matter what $1 is. Is this because of the repeating group feature {5}? If so, how do I grab the collection of repeats and put it in place of where I have $1 right now?

Edit: I know the first group captures correctly, as well. I grab the content of somestring, using this regex:

```<code>Regex.Match(line, @"^([^,]*,){5}([0-9]+\.[0-9]+),.*");
</code>```

The first part is identical the the first group in the replacement regex, and it works fine, so there shouldn't be an issue (and they're both used on the same string).

Edit2:

Ok I'll try to explain more of the process since someone said it was hard to understand. I have three variables, line a string I work with, and latIndex and lonIndex which are just ints (tells me between what ,'s two doubles I look for are located). I have the two following matches:

```<code>var latitudeMatch = Regex.Match(line, @"^([^,]*,){" + latIndex + @"}([0-9]+\.[0-9]+),.*");
var longitudeMatch = Regex.Match(line, @"^([^,]*,){" + lonIndex + @"}([0-9]+\.[0-9]+),.*");
</code>```

I then grab the doubles:

```<code>var latitude = latitudeMatch.Groups[2].Value;
var longitude = longitudeMatch.Groups[2].Value;
</code>```

I use these doubles to get a string from a web API, which i store in a variable called veiRef. Then I want to insert these after the doubles, using the following code (insert after lat or lon, depending on which one appears last):

```<code>if (latIndex > lonIndex)
{
    line = Regex.Replace(line, @"^([^,]*,){" + (latIndex+1) + @"}(.*)",$@"$1{veiRef},$2");
}
else
{
    line = Regex.Replace(line, @"^([^,]*,){" + (lonIndex + 1) + @"}(.*)", $@"$1{veiRef},$2");
}
</code>```

However, this results in a string line which doesn't have the content of $1 inserted before it ($2 works fine).

答:
Adding an extra group around the repeating capturing group seems to provide the desired output for the example you gave.

```<code>Regex.Replace("a, s, f, double, double, 12, sd, 1", @"^(([^,]*,){5})(.*)", @"$1somestring,$3");
</code>```

I'm not an expert on RegEx and someone can probably explain it better than I, but:-

Group 1 is the set of 5 repeating capture groups
Group 2 is the last of the repeating capture groups
Group 3 is the text after the 5 repeating capture groups.

Title: Regex Replace between groups

Body:
So I have the following regex.replace in C#:

Regex.Replace(inputString, @"^([^,]*,){5}(.*)", @"$1somestring,$2");

where 5 is a variable number in code, but that's not really relevant since at the time of execution it will always have a set value (like 5, for example). Same with somestring,.

Essentially I want to input somestring, between the two groups. The output works for somestring,$2, but $1 is just printed as $1. So say whatever (.*) grabs = "2, a, f2" the resulting string I'd get out is $1somestring,2,a,f2 no matter what $1 is. Is this because of the repeating group feature {5}? If so, how do I grab the collection of repeats and put it in place of where I have $1 right now?

Edit: I know the first group captures correctly, as well. I grab the content of somestring, using this regex:

Regex.Match(line, @"^([^,]*,){5}([0-9]+\.[0-9]+),.*");

The first part is identical the the first group in the replacement regex, and it works fine, so there shouldn't be an issue (and they're both used on the same string).

Edit2:

Ok I'll try to explain more of the process since someone said it was hard to understand. I have three variables, line a string I work with, and latIndex and lonIndex which are just ints (tells me between what ,'s two doubles I look for are located). I have the two following matches:

var latitudeMatch = Regex.Match(line, @"^([^,]*,){" + latIndex + @"}([0-9]+\.[0-9]+),.*");
var longitudeMatch = Regex.Match(line, @"^([^,]*,){" + lonIndex + @"}([0-9]+\.[0-9]+),.*");

I then grab the doubles:

var latitude = latitudeMatch.Groups[2].Value;
var longitude = longitudeMatch.Groups[2].Value;

I use these doubles to get a string from a web API, which i store in a variable called veiRef. Then I want to insert these after the doubles, using the following code (insert after lat or lon, depending on which one appears last):

if (latIndex > lonIndex)
{
    line = Regex.Replace(line, @"^([^,]*,){" + (latIndex+1) + @"}(.*)",$@"$1{veiRef},$2");
}
else
{
    line = Regex.Replace(line, @"^([^,]*,){" + (lonIndex + 1) + @"}(.*)", $@"$1{veiRef},$2");
}

However, this results in a string line which doesn't have the content of $1 inserted before it ($2 works fine).

Body:
Adding an extra group around the repeating capturing group seems to provide the desired output for the example you gave.

Regex.Replace("a, s, f, double, double, 12, sd, 1", @"^(([^,]*,){5})(.*)", @"$1somestring,$3");

I'm not an expert on RegEx and someone can probably explain it better than I, but:-

Group 1 is the set of 5 repeating capture groups
Group 2 is the last of the repeating capture groups
Group 3 is the text after the 5 repeating capture groups.


问:
How to avoid instant saving of the model with ajax validation?
I want to add Ajax validation to check the form before updating. In the view, added to the required field

```<code>['enableAjaxValidation' => true]
</code>```

In the controller in the actionUpdate

```<code>if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($modelForm->validate()) {
                $model->setAttributes($modelForm->getAttributes());

                if ($model->save()) {
                    return $this->redirect([my way]);
                }

                if ($model->hasErrors()) {
                    return ActiveForm::validate($model);
                } else {
                    return ['success' => 1, 'html' =>
                        $this->renderPartial('view', [my data];
                }
            } else {
                return ActiveForm::validate($modelForm);
            }
        }
</code>```

The problem is that the choice of any value in the field, which is "enableAjaxValidation" => true, immediately leads to the saving of the model (even without pressing the save button). How can this be avoided?

答:
In controller try it like this:

```<code>$model = new ExampleForm;

// validate any AJAX requests fired off by the form
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    return ActiveForm::validate($model);
}
</code>```

Add this before your if statement, and remove Yii::$app->request->isAjax from your if statement.

Body:
I want to add Ajax validation to check the form before updating. In the view, added to the required field

['enableAjaxValidation' => true]

In the controller in the actionUpdate

if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($modelForm->validate()) {
                $model->setAttributes($modelForm->getAttributes());

                if ($model->save()) {
                    return $this->redirect([my way]);
                }

                if ($model->hasErrors()) {
                    return ActiveForm::validate($model);
                } else {
                    return ['success' => 1, 'html' =>
                        $this->renderPartial('view', [my data];
                }
            } else {
                return ActiveForm::validate($modelForm);
            }
        }

The problem is that the choice of any value in the field, which is "enableAjaxValidation" => true, immediately leads to the saving of the model (even without pressing the save button). How can this be avoided?

Body:
In controller try it like this:

$model = new ExampleForm;

// validate any AJAX requests fired off by the form
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    return ActiveForm::validate($model);
}

Add this before your if statement, and remove Yii::$app->request->isAjax from your if statement.


问:
Java Static
Duplicate: What does the 'static' keyword do in a class?

I've read this post already.

What does the "static" keyword in a method do?

I remember being told that static != clingy...but that is pretty much all I know about this keyword.

答:
Static variables and methods belong to the class and not instance, although you can refer them from an instance reference. Usually, you use the Class name to access them.

If a method is declared as static, you don't need the object's instance in which it is defined to invoke it. Now, you might want to know when could such a situation arise? Consider the main method of java

public static void  main(String[] args)

Why is it declared static? It's because in order to start your program this method should begin execution. And, since the program hasn't initialized there is no way you could create an instance of the class in which it is declared. Therefore, you are required to declare the class as public. And, this static method gets called when the class is loaded in memory through

java YourClassName

Besides this, static methods are used to modify static variables. They cannot manipulate non-static instance variables.

Also, be aware, that static holds a different meaning in another language like C.

OwnerDisplayName: koldfyre

ContentLicense: CC BY-SA 2.5

Title: Java Static

LastEditorDisplayName: nemo

OwnerDisplayName: Pat


问:
I want to apply a overlay image on hover
But I am struggling.

Code I have for css is:

```
#gallery img {
width:700px;
height:213px;
margin:0;
padding:0;
}
```

So I thought ...

```
#gallery img:hover {
    width:700px;
    height:213px;
    position: relative;
    z-index:10000;
    background: transparent url(../images/imgOverlay-Zoom.png) no-repeat center center;
}
```

Would work, but it doesnt.

The image I am transparently overlaying on hover is:

What am I doing wrong.
I think I may have a corrupt css tag somewhere.

Any help appreciated.

答:
Make the #gallery have a background image rather than having an image tag inside it... otherwise it'll be on top of the background. Then have another div inside it which has the :hover pseudo-class. If it still doesn't work, take out the word transparent.

Or you could not overlay the image and just swap the original image for the combined image?

Body:
But I am struggling.

Code I have for css is:

#gallery img {
width:700px;
height:213px;
margin:0;
padding:0;
}

So I thought ...

#gallery img:hover {
    width:700px;
    height:213px;
    position: relative;
    z-index:10000;
    background: transparent url(../images/imgOverlay-Zoom.png) no-repeat center center;
}

Would work, but it doesnt.

The image I am transparently overlaying on hover is:

What am I doing wrong.
I think I may have a corrupt css tag somewhere.

Any help appreciated.


问:
disable past date in datepicker wpf?
How can i disable past date in date picker?I am using ModernUI for my desktop application  </p>

```<code><DatePicker Grid.Column="0" Name="datepicker"  SelectedDate="{x:Static sys:DateTime.Now}" />
</code>```

答:
Thanks @GauravKP for your help.
I used   xmlns:sys="clr-namespace:System;assembly=mscorlib" for getting Current date as

```<code> SelectedDate="{x:Static sys:DateTime.Now}"
</code>```

and using DisplayDateStart="{x:Static sys:DateTime.Now}" to hide previous date.

```<code><DatePicker Grid.Column="0" Name="datepicker" DisplayDateStart="{x:Static sys:DateTime.Now}" SelectedDate="{x:Static sys:DateTime.Now}" ></DatePicker>
</code>```

Title: disable past date in datepicker wpf?

Body:
How can i disable past date in date picker?I am using ModernUI for my desktop application

<DatePicker Grid.Column="0" Name="datepicker"  SelectedDate="{x:Static sys:DateTime.Now}" />

Body:
Thanks @GauravKP for your help.
I used   xmlns:sys="clr-namespace:System;assembly=mscorlib" for getting Current date as

 SelectedDate="{x:Static sys:DateTime.Now}"

and using DisplayDateStart="{x:Static sys:DateTime.Now}" to hide previous date.

<DatePicker Grid.Column="0" Name="datepicker" DisplayDateStart="{x:Static sys:DateTime.Now}" SelectedDate="{x:Static sys:DateTime.Now}" ></DatePicker>


问:
expressjs: typescript: Argument of type 'typeof <express.Router>' is not assignable to parameter of type 'RequestHandlerParams'
I am using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped.
I defined a router and would like to use it from a subpath as is stated in the official 4.x documentation (app.use('/calendar', router);), but I get following error

```<code>Error: /Users/matthias/Documents/private workspace/universal/src/server/server.ts (161,34): Argument of type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"' is not assignable to parameter of type 'RequestHandlerParams'.
  Type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"' is not assignable to type '(RequestHandler | ErrorRequestHandler)[]'.
    Property 'length' is missing in type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"'.
</code>```

This is the router I am using, ommiting the actual code...

```<code>const router : express.Router = express.Router();
let loginController = new LoginController();

router.post('/signin', function(req: express.Request, res: express.Response, next: express.NextFunction) {

  ...

  })(req, res, next);
});

...

export default router;
</code>```

... and this is the shortened version of the call to it.

```<code>import * as loginRouter from './routes/login.router';

private app = express();
this.app.use('/api/v1/auth', loginRouter);
</code>```

Am I doing something wrong or is this usecase just not properly defined in the typescript definition files?

Kind Regards

答:
Found it, import * as ... seems to lose its typescript information (IRouter, Router)

Solution is to use import loginRouter from './routes/login.router'; instead

Body:
I am using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped.
I defined a router and would like to use it from a subpath as is stated in the official 4.x documentation (app.use('/calendar', router);), but I get following error

Error: /Users/matthias/Documents/private workspace/universal/src/server/server.ts (161,34): Argument of type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"' is not assignable to parameter of type 'RequestHandlerParams'.
  Type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"' is not assignable to type '(RequestHandler | ErrorRequestHandler)[]'.
    Property 'length' is missing in type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"'.

This is the router I am using, ommiting the actual code...

const router : express.Router = express.Router();
let loginController = new LoginController();

router.post('/signin', function(req: express.Request, res: express.Response, next: express.NextFunction) {

  ...

  })(req, res, next);
});

...

export default router;

... and this is the shortened version of the call to it.

import * as loginRouter from './routes/login.router';

private app = express();
this.app.use('/api/v1/auth', loginRouter);

Am I doing something wrong or is this usecase just not properly defined in the typescript definition files?

Kind Regards


问:
Android studio doesn't show my LG G5 under connected devices
I'm new to android and I'm trying to run my app on my G5 (not a virtual emulator) but cant somehow make my android studio recognize my phone.

I've already installed Google USB Driver, tried to switch the settings on my phone to PTP and reinstalled my phone in the device manager.

Can someone help me with this issue?

that's what I keep seeing:

答:
Install PdaNEt+ in your computer
http://pdanet.co/

Enable USB Debugging of your device through Developers Mode
http://www.syncios.com/android/how-to-debug-lg-g5.html

And then Connect your device.
If you found any issue ,feel free to ask me


问:
python graph_tool: get _all_ shortest paths
I want to compute all shortest paths between all pairs in a graph. To achieve this, I am using graph_tool's all_shortest_paths function for every node pair in the graph. According to the documentation, the function is able to respect edge weights, if given. At first glance this works fine. I found, however, that the returned list of shortest paths is incomplete. It seemingly only includes shortest paths, which also use the least amount of hops from the complete set of shortest paths.

Here is a small example:

```<code>import graph_tool
import graph_tool.topology

#setup graph
g = graph_tool.Graph()
g.add_vertex(5)
edges = [(0,1),(1,2),(3,2),(0,4),(4,3)]
metrics = [3, 4, 2, 1, 3]
g.edge_properties["metric"] = g.new_edge_property("int")
for i in range(len(metrics)):
    e = g.add_edge(*(edges[i]))
    g.edge_properties["metric"][e] = metrics[i]

#compute all shortest paths from 0 to 2
paths = graph_tool.topology.all_shortest_paths(g, 0, 2, weights=g.edge_properties["metric"])

for path in paths:
    print(path)

print("-"*10)

#increase metric of edge 0-4
g.edge_properties["metric"][g.edge(0,4)] = 2

#recompute all shortest paths from 0 to 2
paths = graph_tool.topology.all_shortest_paths(g, 0, 2, weights=g.edge_properties["metric"])

for path in paths:
    print(path)
</code>```

It generates a graph with 5 vertices and edges that form 2 paths from vertex 0 to vertex 2 like so:

```<code>0 --- 1 --- 2
 \         /
  \       /
   4 --- 3
</code>```

Obviously, the path [0, 1, 2] is shorter than [0, 4, 3, 2] in terms of hop count. If no metric is given, this is correctly recognized (not demonstrated here).

In the beginning of the example, the edges are weighted in such a way, that the second path, which has more hops, is 'shorter'. The sum of the metrics is 6, whereas the other path has a total value of 7. Consequently, the algorithm correctly returns [0, 4, 3, 2].

Then, the metric of the edge between 0 and 4 is increased by 1. Now both paths have the same total value and should both be returned. Yet, the algorithm only returns [0, 1, 2]. I can only assume that hop count is still somehow factored in, even though I specified a metric, and this is why the second path is neglected. As far as I've seen, there is no mention of this behavior in the official documentation.

Am I overlooking something? Is there a better function to do this, perhaps even if a different library? I already looked into igraph as an alternative, but it does appear to only be capable of computing one shortest path per node pair.

答:
This is behavior is indeed a bug in graph-tool, that occurs when weights are being used! I have just committed a fix that solves it: https://git.skewed.de/count0/graph-tool/commit/dc06771604dfd8f38d40e68ce16b537bc1afc272

Thanks for catching this, and for the very clear example!

Body:
I want to compute all shortest paths between all pairs in a graph. To achieve this, I am using graph_tool's all_shortest_paths function for every node pair in the graph. According to the documentation, the function is able to respect edge weights, if given. At first glance this works fine. I found, however, that the returned list of shortest paths is incomplete. It seemingly only includes shortest paths, which also use the least amount of hops from the complete set of shortest paths.

Here is a small example:

import graph_tool
import graph_tool.topology

#setup graph
g = graph_tool.Graph()
g.add_vertex(5)
edges = [(0,1),(1,2),(3,2),(0,4),(4,3)]
metrics = [3, 4, 2, 1, 3]
g.edge_properties["metric"] = g.new_edge_property("int")
for i in range(len(metrics)):
    e = g.add_edge(*(edges[i]))
    g.edge_properties["metric"][e] = metrics[i]

#compute all shortest paths from 0 to 2
paths = graph_tool.topology.all_shortest_paths(g, 0, 2, weights=g.edge_properties["metric"])

for path in paths:
    print(path)

print("-"*10)

#increase metric of edge 0-4
g.edge_properties["metric"][g.edge(0,4)] = 2

#recompute all shortest paths from 0 to 2
paths = graph_tool.topology.all_shortest_paths(g, 0, 2, weights=g.edge_properties["metric"])

for path in paths:
    print(path)

It generates a graph with 5 vertices and edges that form 2 paths from vertex 0 to vertex 2 like so:

0 --- 1 --- 2
 \         /
  \       /
   4 --- 3

Obviously, the path [0, 1, 2] is shorter than [0, 4, 3, 2] in terms of hop count. If no metric is given, this is correctly recognized (not demonstrated here).

In the beginning of the example, the edges are weighted in such a way, that the second path, which has more hops, is 'shorter'. The sum of the metrics is 6, whereas the other path has a total value of 7. Consequently, the algorithm correctly returns [0, 4, 3, 2].

Then, the metric of the edge between 0 and 4 is increased by 1. Now both paths have the same total value and should both be returned. Yet, the algorithm only returns [0, 1, 2]. I can only assume that hop count is still somehow factored in, even though I specified a metric, and this is why the second path is neglected. As far as I've seen, there is no mention of this behavior in the official documentation.

Am I overlooking something? Is there a better function to do this, perhaps even if a different library? I already looked into igraph as an alternative, but it does appear to only be capable of computing one shortest path per node pair.


问:
Java Swing close ONLY one application
Hi all:
I have a Java Swing App. There is a button allow user to create open up a new window of the application. I use System.Exit(0) when user decides to close the application, however when I press "Close" button, both Application windows closed.

```<code>public static void main(String[] args)
{
 ghMain = new GreenHouseMain();
}
</code>```

Above is how I initialize the first application, then use the same code to create new GreenHouseMain Object to open second application window.

So my question is how do I close only one application window which the close button I pressed from?

Thanks all

答: call dispose() instead of System.exit() on the Window object that you want to close.  When there are no more visible windows, the Event Dispatch thread will exit.</p>

Title: Java Swing close ONLY one application

Body:
Hi all:
I have a Java Swing App. There is a button allow user to create open up a new window of the application. I use System.Exit(0) when user decides to close the application, however when I press "Close" button, both Application windows closed.

public static void main(String[] args)
{
 ghMain = new GreenHouseMain();
}

Above is how I initialize the first application, then use the same code to create new GreenHouseMain Object to open second application window.

So my question is how do I close only one application window which the close button I pressed from?

Thanks all


问:
CMake, shared library linking fail
I'm currently getting used to cmake and I'm trying to compile a small project with a .so library linking.

My project is the following.

```<code>/
   CMakeLists.txt
   inc/
       Als.h
   src/
       main.c
       CMakeLists.txt
   lib/
       libals.so
   build/
</code>```

I'm compiling from the build directory with:

```<code>$ cmake ..
-- DIR:
-- Configuring done
-- Generating done
-- Build files have been written to: /home/julien/tmp/cmakeTest/build
</code>```

And then:

```<code>$ make
Linking C executable cmakeTest
/usr/bin/ld: ne peut trouver -lals
collect2: error: ld returned 1 exit status
src/CMakeFiles/cmakeTest.dir/build.make:85: recipe for target 'src/cmakeTest' failed
make[2]: *** [src/cmakeTest] Error 1
CMakeFiles/Makefile2:75: recipe for target 'src/CMakeFiles/cmakeTest.dir/all' failed
make[1]: *** [src/CMakeFiles/cmakeTest.dir/all] Error 2
Makefile:76: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

The linker seems to be unable to find the libals.so file.

Here is the file /CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 2.8)

PROJECT(cmaketest)

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3")

INCLUDE_DIRECTORIES(
  inc
)

ADD_SUBDIRECTORY(src)

get_directory_property(OUT_VAR LINK_DIRECTORIES)
message(STATUS "DIR: ${OUT_VAR}")
</code>```

And here is the file /src/CMakeLists.txt:

```<code>PROJECT(cmakeTest)

FILE(
    GLOB
    ${PROJECT_NAME}_Sources
    *.c
)

INCLUDE_DIRECTORIES(
        inc
        inc
)

ADD_EXECUTABLE(
    ${PROJECT_NAME}
    ${${PROJECT_NAME}_Sources}
)

LINK_DIRECTORIES(
    /home/julien/tmp/cmakeTest/lib/
)

TARGET_LINK_LIBRARIES(
    ${PROJECT_NAME}
    als
    pthread
)
</code>```

Maybe I missed something but if I change the /src/CMakeLists.txt to:

```<code>PROJECT(cmakeTest)

FILE(
    GLOB
    ${PROJECT_NAME}_Sources
    *.c
)

INCLUDE_DIRECTORIES(
        inc
        inc
)

ADD_EXECUTABLE(
    ${PROJECT_NAME}
    ${${PROJECT_NAME}_Sources}
)

TARGET_LINK_LIBRARIES(
    ${PROJECT_NAME}
    /home/julien/tmp/cmakeTest/lib/libals.so
    pthread
)
</code>```

The compilation is ok. Does someone know why the linker is unable to find libals.so when I'm giving him the good directory path to look in?

The LINK_DIRECTORIES functions seems not to be working.

答:
Besides the solution you already have, and my solution in a comment, the problem you have with the CMake file shown is the order in which you invoke the CMake commands.

From the link_directories command reference:

The command will apply only to targets created after it is called.

[Emphasis mine]

You simply need to call link_directories before you call add_executable.

Title: CMake, shared library linking fail

Body:
I'm currently getting used to cmake and I'm trying to compile a small project with a .so library linking.

My project is the following.

/
   CMakeLists.txt
   inc/
       Als.h
   src/
       main.c
       CMakeLists.txt
   lib/
       libals.so
   build/

I'm compiling from the build directory with:

$ cmake ..
-- DIR:
-- Configuring done
-- Generating done
-- Build files have been written to: /home/julien/tmp/cmakeTest/build

And then:

$ make
Linking C executable cmakeTest
/usr/bin/ld: ne peut trouver -lals
collect2: error: ld returned 1 exit status
src/CMakeFiles/cmakeTest.dir/build.make:85: recipe for target 'src/cmakeTest' failed
make[2]: *** [src/cmakeTest] Error 1
CMakeFiles/Makefile2:75: recipe for target 'src/CMakeFiles/cmakeTest.dir/all' failed
make[1]: *** [src/CMakeFiles/cmakeTest.dir/all] Error 2
Makefile:76: recipe for target 'all' failed
make: *** [all] Error 2

The linker seems to be unable to find the libals.so file.

Here is the file /CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

PROJECT(cmaketest)

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3")

INCLUDE_DIRECTORIES(
  inc
)

ADD_SUBDIRECTORY(src)

get_directory_property(OUT_VAR LINK_DIRECTORIES)
message(STATUS "DIR: ${OUT_VAR}")

And here is the file /src/CMakeLists.txt:

PROJECT(cmakeTest)

FILE(
    GLOB
    ${PROJECT_NAME}_Sources
    *.c
)

INCLUDE_DIRECTORIES(
        inc
        inc
)

ADD_EXECUTABLE(
    ${PROJECT_NAME}
    ${${PROJECT_NAME}_Sources}
)

LINK_DIRECTORIES(
    /home/julien/tmp/cmakeTest/lib/
)

TARGET_LINK_LIBRARIES(
    ${PROJECT_NAME}
    als
    pthread
)

Maybe I missed something but if I change the /src/CMakeLists.txt to:

PROJECT(cmakeTest)

FILE(
    GLOB
    ${PROJECT_NAME}_Sources
    *.c
)

INCLUDE_DIRECTORIES(
        inc
        inc
)

ADD_EXECUTABLE(
    ${PROJECT_NAME}
    ${${PROJECT_NAME}_Sources}
)

TARGET_LINK_LIBRARIES(
    ${PROJECT_NAME}
    /home/julien/tmp/cmakeTest/lib/libals.so
    pthread
)

The compilation is ok. Does someone know why the linker is unable to find libals.so when I'm giving him the good directory path to look in?

The LINK_DIRECTORIES functions seems not to be working.


问:
How to fetch item1 : item2 : item3 itself not there values
Firebase database structure :

-Main

---item1: "Structure"

---item2: "good"

---item3: "something"

+users

答:
Please use this code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mainRef = rootRef.child("Main");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String item = ds.getKey();
            Log.d("TAG", item);
        }
    }

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

And your output will be:

```<code>item1
item2
item3
</code>```

Body:
Please use this code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mainRef = rootRef.child("Main");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String item = ds.getKey();
            Log.d("TAG", item);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
mainRef.addListenerForSingleValueEvent(eventListener);

And your output will be:

item1
item2
item3


问:
Programaticly Limiting number of rows for mysql database using VB.net
Good day I have written a function that needs to limit the number of employees that can be added to the database.

```<code>    <WebMethod()>
Public Function EmployeeSubToken()
    Dim cmd As New SqlCommand("Select vchSubscriptionType FROM BillingInfo", con)
    Dim subtype = "vchSubscriptionType"
    Dim Token

    Select Case subtype
        Case subtype = "Bronze"
            Token = 1
        Case subtype = "Silver"
            Token = 2
        Case subtype = "Gold"
            Token = 3
        Case subtype = "Platinum"
            Token = 4
    End Select

    Dim cmd2

    Select Case Token
        Case Token = 1
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 5")
        Case Token = 2
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 10")
        Case Token = 3
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 25")
        Case Token = 4
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment")
    End Select

End Function
</code>```

Does anyone know how If this is the correct way of doing it? if it is not how would I accomplish this?

答:
maybe TOP(5) your looking for.

is there any order to the rows your returning, i.e. does it matter which 5 are returned?

Body:
Good day I have written a function that needs to limit the number of employees that can be added to the database.

    <WebMethod()>
Public Function EmployeeSubToken()
    Dim cmd As New SqlCommand("Select vchSubscriptionType FROM BillingInfo", con)
    Dim subtype = "vchSubscriptionType"
    Dim Token

    Select Case subtype
        Case subtype = "Bronze"
            Token = 1
        Case subtype = "Silver"
            Token = 2
        Case subtype = "Gold"
            Token = 3
        Case subtype = "Platinum"
            Token = 4
    End Select

    Dim cmd2

    Select Case Token
        Case Token = 1
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 5")
        Case Token = 2
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 10")
        Case Token = 3
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment Where ROWNUM <= 5 LIMIT 25")
        Case Token = 4
            cmd2 = New SqlCommand("SELECT * FROM Subscribers.dtEmployment")
    End Select

End Function

Does anyone know how If this is the correct way of doing it? if it is not how would I accomplish this?


问:
Best way to perform mutually exclusive selection in a tableview in different sections in swift 3
I have a tableview with different sections, I need to be able to multiselect from different sections, but the rows in each section should be able to select mutually exclusive wise. For eg: in below screenshot I should be able to select either Margarita or BBQ Chicken from Pizza and same for Deep dish pizza but I should be able to multiselect between Pizza section and Deep dish pizza

Below is my code so far, I was wondering what would be the best way to approach this.

```<code>   let section = ["Pizza", "Deep dish pizza"]

    let items = [["Margarita", "BBQ Chicken"], ["Sausage", "meat lovers"]]

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.section[section]
    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        return section.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return items[section].count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        // Configure the cell...

        cell.textLabel?.text = items[indexPath.section][indexPath.row]

        return cell
    }
</code>```

答:
First allow multiple selection:

```<code>yourTableView.allowsMultipleSelection = true
</code>```

To get the select rows:

```<code>let selectedRows = tableView.indexPathsForSelectedRows
</code>```

Then within the didselectrow function you can iterate through the selected rows and ensure that only 1 row within the section can be selected.

Body:
I have a tableview with different sections, I need to be able to multiselect from different sections, but the rows in each section should be able to select mutually exclusive wise. For eg: in below screenshot I should be able to select either Margarita or BBQ Chicken from Pizza and same for Deep dish pizza but I should be able to multiselect between Pizza section and Deep dish pizza

Below is my code so far, I was wondering what would be the best way to approach this.

   let section = ["Pizza", "Deep dish pizza"]

    let items = [["Margarita", "BBQ Chicken"], ["Sausage", "meat lovers"]]

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.section[section]
    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        return section.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return items[section].count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        // Configure the cell...

        cell.textLabel?.text = items[indexPath.section][indexPath.row]

        return cell
    }

Body:
First allow multiple selection:

yourTableView.allowsMultipleSelection = true

To get the select rows:

let selectedRows = tableView.indexPathsForSelectedRows

Then within the didselectrow function you can iterate through the selected rows and ensure that only 1 row within the section can be selected.


问:
RandomStringGenerator to generate alphanumeric strings
Can I use Apache's common-text RandomStringGenerator to generate random alphanumeric strings (numbers and lowercase/uppercase letters)?

答:
Yes, using the following code:</p>

```<code>import static org.apache.commons.text.CharacterPredicates.DIGITS;
import static org.apache.commons.text.CharacterPredicates.LETTERS;

// ...

RandomStringGenerator generator = new RandomStringGenerator.Builder()
        .withinRange('0', 'z')
        .filteredBy(LETTERS, DIGITS)
        .build();
</code>```

Body:
Yes, using the following code:

import static org.apache.commons.text.CharacterPredicates.DIGITS;
import static org.apache.commons.text.CharacterPredicates.LETTERS;

// ...

RandomStringGenerator generator = new RandomStringGenerator.Builder()
        .withinRange('0', 'z')
        .filteredBy(LETTERS, DIGITS)
        .build();


问:
How to use local versions of glide dependencies?
I'm working on a Go project that uses Glide for dependency management. I need to make changes to the project, but also to several dependencies used by the project. I need to test these changes together, before committing the alterations to each project separately.

How can I tell Glide (or Go) to use local versions of these projects (e.g. found in $GOPATH/src/...) rather than pulling down something and stuffing it in the vendor directory)?

To give an example:

github.com/hyperledger/burrow depends on:

github.com/tendermint/tendermint, which depends on:

github.com/tendermint/go-crypto

I need to make some changes spanning all three projects. I want to test the changes by executing things in the burrow project, but I need it to execute my development versions of tendermint and go-crypto, which I have locally.

答:
Given the Go vendoring is first looking up packages in your project root /vendor folder and when not found then in the GOPATH and that Glide installs your dependencies to the /vendor folder means that you can just set up your project with glide install, then manually remove the dependencies that have been locally modified (or you are going to modify) in their local installations from your project's /vendor folder and Go vendoring will then pick your locally modified versions found under GOPATH.

Once you have tested everything, you first have to commit all the modified dependencies and then head back to your project and modify the glide.yaml file to use the new versions of these dependencies.

This should work.


问:
Getting full output from cmd.exe command in VBScript
I'm using the following code to get the output of an nslookup command:

```<code>Dim oShell
Dim strCmdOutput

If DO_DEBUG="n" Then On Error Resume Next

Set oShell = WScript.CreateObject ("WScript.Shell")
Set shellOut = oShell.Exec("cmd.exe /C nslookup www.bbc.co.uk 8.8.8.8")
strCmdOutput = shellOut.StdOut.ReadAll()

WScript.Scho strCmdOutput
</code>```

The output I get into strCmdOutput is different from the output I get by manually running the command.

For example, manually I get:

```
Server:  google-public-dns-a.google.com
Address:  8.8.8.8

<b><i>Non-authoritative answer:</i></b>
Name:    www.bbc.net.uk
Addresses:  212.58.244.71
      212.58.246.95
Aliases:  www.bbc.co.uk
```

And using the script I get:

```
Server:  google-public-dns-a.google.com
Address:  8.8.8.8

Name:    www.bbc.net.uk
Addresses:  212.58.244.69
      212.58.246.93
Aliases:  www.bbc.co.uk
```

The outputs can vary wildly, is there a way I can get the outputs to match?

答:
The line Non-authoritative answer: is written to STDERR, so you need to merge that into STDOUT to get the entire output.

Change the line

```<code>Set shellOut = oShell.Exec("cmd.exe /C nslookup www.bbc.co.uk 8.8.8.8")
</code>```

to

```<code>Set shellOut = oShell.Exec("cmd.exe /C nslookup www.bbc.co.uk 8.8.8.8 2>&1")
</code>```

and the problem will disappear.

Body:
I'm using the following code to get the output of an nslookup command:

Dim oShell
Dim strCmdOutput

If DO_DEBUG="n" Then On Error Resume Next

Set oShell = WScript.CreateObject ("WScript.Shell")
Set shellOut = oShell.Exec("cmd.exe /C nslookup www.bbc.co.uk 8.8.8.8")
strCmdOutput = shellOut.StdOut.ReadAll()

WScript.Scho strCmdOutput

The output I get into strCmdOutput is different from the output I get by manually running the command.

For example, manually I get:

Server:  google-public-dns-a.google.com
Address:  8.8.8.8

Non-authoritative answer:
Name:    www.bbc.net.uk
Addresses:  212.58.244.71
      212.58.246.95
Aliases:  www.bbc.co.uk

And using the script I get:

Server:  google-public-dns-a.google.com
Address:  8.8.8.8

Name:    www.bbc.net.uk
Addresses:  212.58.244.69
      212.58.246.93
Aliases:  www.bbc.co.uk

The outputs can vary wildly, is there a way I can get the outputs to match?

Body:
The line Non-authoritative answer: is written to STDERR, so you need to merge that into STDOUT to get the entire output.

Change the line

Set shellOut = oShell.Exec("cmd.exe /C nslookup www.bbc.co.uk 8.8.8.8")

to

Set shellOut = oShell.Exec("cmd.exe /C nslookup www.bbc.co.uk 8.8.8.8 2>&1")

and the problem will disappear.


问:
How to display the user's game score on-screen in real-time to other user playing on in group with first user?
If multiple or two users are playing a game in team, how change in core of 1 user 1 can be reflected on score of user-2 in real time?</p>

答: You can do it thought back-end. Here and example of NodeJS real-time chat https://socket.io/get-started/chat/ the main idea would be the same.</p>


问:
How to fix border color on mouse click
I have one color box, so when I am hovering on the box the border color is getting appear. Now I want to click on the box then the border color should be remain as it is. It should not get remove when you will remove the mouse from box.

My Scss:

.fill-color1{
    background:$workspace-fill-color2;
    &:hover{
        border:2px solid $work-border-color2;
    }
}
```
<pre class="lang-js prettyprint-override"><code>$(`.fill-color${i}`).click(function () {
    $(this).css('border-color', 'red');
});
</code>```

in the above code, after click the color is getting set but when I am removing the mouse from the box border is also getting remove.

答:
$(".Element").on("click",function(){
$(this).removeClass("Element").addClass("Elementfocus");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
width:200px;
height:30px;
padding:10px;
}
.Element{
border:1px #E0E0E0 solid;
}
.Element:hover{
border:1px #e9e solid;
}
.Element:active{
border:2px blue solid;
}
.Elementfocus{
border:2px green solid;
}</code>```

Hello!
```

ContentLicense: CC BY-SA 4.0

Title: How to fix border color on mouse click

Body:
I have one color box, so when I am hovering on the box the border color is getting appear. Now I want to click on the box then the border color should be remain as it is. It should not get remove when you will remove the mouse from box.

My Scss:

.fill-color1{
    background:$workspace-fill-color2;
    &:hover{
        border:2px solid $work-border-color2;
    }
}

$(`.fill-color${i}`).click(function () {
    $(this).css('border-color', 'red');
});

in the above code, after click the color is getting set but when I am removing the mouse from the box border is also getting remove.

Body:
$(".Element").on("click",function(){
$(this).removeClass("Element").addClass("Elementfocus");
});

div{
width:200px;
height:30px;
padding:10px;
}
.Element{
border:1px #E0E0E0 solid;
}
.Element:hover{
border:1px #e9e solid;
}
.Element:active{
border:2px blue solid;
}
.Elementfocus{
border:2px green solid;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Element">Hello!</div>


问:
JQuery '.css' not functioning properly on Firefox - works perfectly on Google Chrome
I have a sort of abstract art piece on the main page of my portfolio that moves about depending on where the mouse cursor is.

This animation works perfectly on Safari, Google Chrome and Opera.

The issue on Firefox is seems to be only when the middle block attempts to move down

Here's a link to my portfolio: http://benjaminthomasgibbs.co.uk/

Okay I know my css code is not properly formatted, I like it this way - could that be the problem:

JS:

```<code>// MIDDLE SLATE ANIMATION

$(document).ready(function() {
    $('#slateMid').mouseenter(function() {
        $('#slateMid').css('top', '160vh');
       // LEFT SLATE
        $('#slate').css('height', '20vh');
        $('#slate').css('top', '45vh');
        $('#slate').css('left', '24vw');
        $('#slate').css('width', '46.5vw')
        $('#slate').css('box-shadow', '0px 0px 0px');
        $('#slate').css('background-color', '#FEBD45');
        // RIGHT SLATE
        $('#slateEnd').css('height', '23.5vh');
        $('#slateEnd').css('top', '19vh');
        $('#slateEnd').css('left', '24vw');
        $('#slateEnd').css('width', '46.5vw');
        $('#slateEnd').css('box-shadow', '0px 0px 0px');
        $('#slateEnd').css('background-color', '#DF4655');
    })
    $('#slateMid').mouseleave(function() {
        $('#slateMid').css('height', '68.5vh');
        $('#slateMid').css('top', '11vh');
        $('#slateMid').css('box-shadow', '10px 10px 10px #888888');
        $('#slateMid').css('border-left', '4px solid #000');
         $('#slateMid').css('border-right', '4px solid #000');
        // LEFT SLATE
        $('#slate').css('height', '34.5vh');
        $('#slate').css('top', '34vh');
        $('#slate').css('left', '26vw');
        $('#slate').css('width', '14vw');
        $('#slate').css('box-shadow', '10px 10px 10px #888888');
        $('#slate').css('background-color', '#DF4655');
        // RIGHT SLATE
        $('#slateEnd').css('height', '45.5vh');
        $('#slateEnd').css('top', '17vh');
        $('#slateEnd').css('left', '56vw');
        $('#slateEnd').css('width', '14vw');
        $('#slateEnd').css('box-shadow', '5px 5px 5px #888888');
        $('#slateEnd').css('background-color', '#FEBD45');
        $('#slateEnd').css('border-left', '4px solid #000');
    })
})
</code>```

HTML:

```<code><div id="changeBottomLeft">
</div>
<div id="changeBottomRight">
</div>
<div id="slate">
</div>
<div id="slateMid">
</div>
<div id="slateEnd">
</div>
</code>```

答:
why do you not use animate() jquery function?

https://www.w3schools.com/jquery/eff_animate.asp

Body:
I have a sort of abstract art piece on the main page of my portfolio that moves about depending on where the mouse cursor is.

This animation works perfectly on Safari, Google Chrome and Opera.

The issue on Firefox is seems to be only when the middle block attempts to move down

Here's a link to my portfolio: http://benjaminthomasgibbs.co.uk/

Okay I know my css code is not properly formatted, I like it this way - could that be the problem:

JS:

// MIDDLE SLATE ANIMATION

$(document).ready(function() {
    $('#slateMid').mouseenter(function() {
        $('#slateMid').css('top', '160vh');
       // LEFT SLATE
        $('#slate').css('height', '20vh');
        $('#slate').css('top', '45vh');
        $('#slate').css('left', '24vw');
        $('#slate').css('width', '46.5vw')
        $('#slate').css('box-shadow', '0px 0px 0px');
        $('#slate').css('background-color', '#FEBD45');
        // RIGHT SLATE
        $('#slateEnd').css('height', '23.5vh');
        $('#slateEnd').css('top', '19vh');
        $('#slateEnd').css('left', '24vw');
        $('#slateEnd').css('width', '46.5vw');
        $('#slateEnd').css('box-shadow', '0px 0px 0px');
        $('#slateEnd').css('background-color', '#DF4655');
    })
    $('#slateMid').mouseleave(function() {
        $('#slateMid').css('height', '68.5vh');
        $('#slateMid').css('top', '11vh');
        $('#slateMid').css('box-shadow', '10px 10px 10px #888888');
        $('#slateMid').css('border-left', '4px solid #000');
         $('#slateMid').css('border-right', '4px solid #000');
        // LEFT SLATE
        $('#slate').css('height', '34.5vh');
        $('#slate').css('top', '34vh');
        $('#slate').css('left', '26vw');
        $('#slate').css('width', '14vw');
        $('#slate').css('box-shadow', '10px 10px 10px #888888');
        $('#slate').css('background-color', '#DF4655');
        // RIGHT SLATE
        $('#slateEnd').css('height', '45.5vh');
        $('#slateEnd').css('top', '17vh');
        $('#slateEnd').css('left', '56vw');
        $('#slateEnd').css('width', '14vw');
        $('#slateEnd').css('box-shadow', '5px 5px 5px #888888');
        $('#slateEnd').css('background-color', '#FEBD45');
        $('#slateEnd').css('border-left', '4px solid #000');
    })
})

HTML:


问:
Center buttons in middle of image
I try to make buttons that will be in the middle of the picture, but the problem is that either those buttons are in the middle of the page or under the picture. Any suggestions how to fix it and what I do wrong? https://jsfiddle.net/m5g16vt7/

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

imageSlide-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: pink;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8)
}

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="imageSlide-container">
  <img class="imageSlide" src="img_nature_wide.jpg" style="width: 100%">

  ❮
  ❯
</div></code>```

答:
add dot(.) infront of imageSlide-container

```<code>.imageSlide-container {
            max-width: 1000px;
            position: relative;
            margin: auto;
}
</code>```

Title: Center buttons in middle of image

Body:
I try to make buttons that will be in the middle of the picture, but the problem is that either those buttons are in the middle of the page or under the picture. Any suggestions how to fix it and what I do wrong? https://jsfiddle.net/m5g16vt7/

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

imageSlide-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: pink;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8)
}

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}

  ❮
  ❯

Body:
add dot(.) infront of imageSlide-container

.imageSlide-container {
            max-width: 1000px;
            position: relative;
            margin: auto;
}


问:
Good Database Solutions for small-medium Traffic Sites and Silverlight
What are some good database solutions that support Silverlight and are solid for a small-medium traffic website

Easy to use/Manage is a very strong plus

edit: Forgot to mention that the database needs to be very smartphone-friendly, it needs to be able to work with devices on iOS, Android, and Windows Phone 7

答:
Considering your edit, it appears to be a windows phone 7 app that you're going to make, and that you want the database stored on the phone (as opposed to connecting to an internet based datasource). In that case, you might want to take a look at SQL Server 2008 Compact.

Scott Hanselman has an article about using EF Code First with SQL Server Compact (His solution does not specifically include Silverlight, but it works just the same iirc) here.


问:
How do I get the standard file extension given a MIME type in Delphi?
Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?

I'm looking for the easiest and most general way to implement a function that would be called like this:

```<code>fileExt := GetExtension('text/xml');
</code>```

答: HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/html, value Extension.</p>

Body:
Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?

I'm looking for the easiest and most general way to implement a function that would be called like this:

fileExt := GetExtension('text/xml');


问:
In Android BLE which callback to use to ensure successful Message Delivery to remote BLE Device?
Which one is the actual confirmation callBack which tells that the data has been successfully delivered to the remote BLE Device from the Android Phone? onCharacteristicWrite() or onCharacteristicChanged() or something else.
The data I am writing is with the BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE.

答: When you use BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE there is no confirmation of successful delivery at all. When you get the onCharacteristicWrite callback it only means the packet has been buffered and the Bluetooth stack has place to accept another packet.</p>


问:
How to resolve duplicate entry error while run project
Here is my build.gradle

```<code> apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.example.demo"
        minSdkVersion 16
        targetSdkVersion 21
        multiDexEnabled true
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7
        }
    }
    aaptOptions
            {
                cruncherEnabled = false
            }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    repositories {
        maven { url "https://jitpack.io" }
    }
}

dependencies {
    compile project(':draggerLibrary')
    compile project(':staggeredGridViewmaster')

    compile files('libs/httpclientandroidlib-1.2.1.jar')
    compile files('libs/httpcore-4.4-beta1.jar')
    compile files('libs/httpmime-4.3.jar')
    compile project(':viewPagerLibrary')
    compile project(path: ':ViewPagerLibrary')

    compile 'com.android.support:multidex:1.0.1'
    compile 'joda-time:joda-time:2.4'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.android.gms:play-services:11.0.2'

    compile 'cn.pedant.sweetalert:library:1.3'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'com.google.guava:guava:20.0'
    compile "com.daimajia.swipelayout:library:1.2.0@aar"
    compile 'com.github.PhilJay:MPAndroidChart:v2.1.6'
    compile 'org.apache.commons:commons-collections4:4.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
}
</code>```

Error:Execution failed for task
  ':DemoProject:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry:
    android/support/v4/provider/DocumentsContractApi19.class

答:
Configure your build.gradle .

Use

```<code>compileSdkVersion 25
buildToolsVersion "25.0.2"
</code>```

Then

```<code>compile 'com.google.android.gms:play-services:11.0.2'
compile 'com.android.support:appcompat-v7:25.3.1'
</code>```

For your MAP problem use getMapAsync()

```<code> SupportMapFragment mapOBJ = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map));
  mapOBJ.getMapAsync(this);
</code>```

Read Replace getMap with getMapAsync

Body:
Here is my build.gradle

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.example.demo"
        minSdkVersion 16
        targetSdkVersion 21
        multiDexEnabled true
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7
        }
    }
    aaptOptions
            {
                cruncherEnabled = false
            }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    repositories {
        maven { url "https://jitpack.io" }
    }
}

dependencies {
    compile project(':draggerLibrary')
    compile project(':staggeredGridViewmaster')

    compile files('libs/httpclientandroidlib-1.2.1.jar')
    compile files('libs/httpcore-4.4-beta1.jar')
    compile files('libs/httpmime-4.3.jar')
    compile project(':viewPagerLibrary')
    compile project(path: ':ViewPagerLibrary')

    compile 'com.android.support:multidex:1.0.1'
    compile 'joda-time:joda-time:2.4'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.android.gms:play-services:11.0.2'

    compile 'cn.pedant.sweetalert:library:1.3'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'com.google.guava:guava:20.0'
    compile "com.daimajia.swipelayout:library:1.2.0@aar"
    compile 'com.github.PhilJay:MPAndroidChart:v2.1.6'
    compile 'org.apache.commons:commons-collections4:4.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
}

Error:Execution failed for task
  ':DemoProject:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry:
    android/support/v4/provider/DocumentsContractApi19.class

Body:
Configure your build.gradle .

Use

compileSdkVersion 25
buildToolsVersion "25.0.2"

Then

compile 'com.google.android.gms:play-services:11.0.2'
compile 'com.android.support:appcompat-v7:25.3.1'

For your MAP problem use getMapAsync()

 SupportMapFragment mapOBJ = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map));
  mapOBJ.getMapAsync(this);

Read Replace getMap with getMapAsync