问:
How to share a object with node + express
I´m using Node + express and I´m trying to figure out how to share objects instances in the main js file with my modules. I have this code at bellow.

```<code>var express = require('express');

//libs
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var conf      = require('config');
var logConf   = conf.get('log');
var winston = require('winston');

//modules
var index = require('./routes/index');
var users = require('./routes/users');
var camera = require('./routes/camera');
var face = require('./routes/face');
var secret = require('./routes/secret');
var attendance = require('./routes/attendance');
var azure = require('./routes/azure-test');

//configuring log
var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: logConf.get('file') })
    ]
  });

require('events').EventEmitter.prototype._maxListeners = 200;

var app = express();

/*Handling CORS*/
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
  next();
});

/*trying to avoid undesirable response code.
 *Ex: you send 200 and express send 304 ... annoying!
 */
app.disable('etag');

//setting image dir for static server
app.use("/tmp", express.static(__dirname + '/tmp'));
app.use("/public", express.static(__dirname + '/public'));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

//putting modules in the game...
app.use('/', index);
app.use('/users', users);
app.use('/camera', camera);
app.use('/face', face);
app.use('/attendance', attendance);

// 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
  console.error("LOCALS ERRORS: " + res.locals.error);
  console.error("LOCALS MESSAGES: " + err.message);
  JSON.stringify(res.locals.error || err.message)});

});

//Set port
app.set('port', process.env.PORT || 7000) ;

//setting public on static server
//app.use(express.static(path.join(__dirname, 'public')));

//setting server up
var server = app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + server.address().port);
});

logger.info('starting application');

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

The goal is not to configure and instance a new 'winston' object in all modules. I´m a noobie in Node and express, so if you have some documentation about it(I was not able to find out), please point to me! If you prefer to give me the answer directly, better!

Thx!

答:
you can make 'shared' module and define there things you need to share

for example

```<code>// shared.js
var winston = require('winston');
var conf      = require('config');
var logConf   = conf.get('log');

var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: logConf.get('file') })
    ]
  });

module.exports = {
    logger: logger
    // other things
}
</code>```

in other files just require shared.js and use

```<code>var shared = require('./shared');
var logger = shared.logger;
</code>```

Body:
I´m using Node + express and I´m trying to figure out how to share objects instances in the main js file with my modules. I have this code at bellow.

var express = require('express');

//libs
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var conf      = require('config');
var logConf   = conf.get('log');
var winston = require('winston');

//modules
var index = require('./routes/index');
var users = require('./routes/users');
var camera = require('./routes/camera');
var face = require('./routes/face');
var secret = require('./routes/secret');
var attendance = require('./routes/attendance');
var azure = require('./routes/azure-test');

//configuring log
var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: logConf.get('file') })
    ]
  });

require('events').EventEmitter.prototype._maxListeners = 200;

var app = express();

/*Handling CORS*/
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
  next();
});

/*trying to avoid undesirable response code.
 *Ex: you send 200 and express send 304 ... annoying!
 */
app.disable('etag');

//setting image dir for static server
app.use("/tmp", express.static(__dirname + '/tmp'));
app.use("/public", express.static(__dirname + '/public'));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

//putting modules in the game...
app.use('/', index);
app.use('/users', users);
app.use('/camera', camera);
app.use('/face', face);
app.use('/attendance', attendance);

// 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
  console.error("LOCALS ERRORS: " + res.locals.error);
  console.error("LOCALS MESSAGES: " + err.message);
  JSON.stringify(res.locals.error || err.message)});

});

//Set port
app.set('port', process.env.PORT || 7000) ;

//setting public on static server
//app.use(express.static(path.join(__dirname, 'public')));

//setting server up
var server = app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + server.address().port);
});

logger.info('starting application');

module.exports = app;

The goal is not to configure and instance a new 'winston' object in all modules. I´m a noobie in Node and express, so if you have some documentation about it(I was not able to find out), please point to me! If you prefer to give me the answer directly, better!

Thx!

Body:
you can make 'shared' module and define there things you need to share

for example

// shared.js
var winston = require('winston');
var conf      = require('config');
var logConf   = conf.get('log');

var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: logConf.get('file') })
    ]
  });

module.exports = {
    logger: logger
    // other things
}

in other files just require shared.js and use

var shared = require('./shared');
var logger = shared.logger;


来源: stackexchange

问:
How can I make elements in one row for small screen?
I hav this two elements:

```<code>  <span>ddd:</span>
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput1" placeholder="Text input" value="">
</code>```

UPDATE

Here is my HTML code:

```<code><div data-role="page" id="layerProperty">
    <div data-role="header" data-position="fixed" data-theme="b">
        <h1 id="layers property"></h1>
        <a href="#mapPage" data-mini="true" data-icon="arrow-l">back</a>
    </div>

    <div data-role="content">
        <div id="vectorLayerProperties" style="display: none;">
            <fieldset style="border: solid 1px #6b6b6b;">
                <legend>data1</legend>
                <div class="ui-content">
                    <form>
                        <div>
                            <span>ddd:</span>
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput1" placeholder="Text input" value="">

                            <span>ddd:</span>
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput2" placeholder="Text input" value="">

                            <span>ddd:</span>
                            <select class="ui-state-disabled" name="select-native-1" id="select-native-1">
                                <option value="1">The 1st Option</option>
                                <option value="2">The 2nd Option</option>
                                <option value="3">The 3rd Option</option>
                                <option value="4">The 4th Option</option>
                            </select>

                            <span>ddd:</span>
                            <select class="ui-state-disabled" name="select-native-1" id="select-native-2">
                                <option value="1">The 1st Option</option>
                                <option value="2">The 2nd Option</option>
                                <option value="3">The 3rd Option</option>
                                <option value="4">The 4th Option</option>
                            </select>
                        </div>

                        <input type="Button" data-inline="true" value="Edit" onclick="editLayerProperty()">
                        <input type="Button" data-inline="true" value="Delete">
                    </form>
                </div>
            </fieldset>
        </div>
        <div id="vectorLayerslist"></div>
    </div>
</div>
</code>```

Inside element with id=vectorLayerProperties   I have span element and textbox which I want to make in single line.

How can I make them in one row for screen with size 250px width?

答:
use media queries and display block like the example, to reproduce it you will have to resize your browser window to 250px..

UPDATE

Wrap your span and input, inside div, a div has display block by default....

@media (max-width: 250px) {
  .span,.input {
    display: block;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="span">ddd:</span>
                            <input type="text" class="input ui-state-disabled" name="textinput-hide" id="textinput1" placeholder="Text input" value="">

<div data-role="page" id="layerProperty">
    <div data-role="header" data-position="fixed" data-theme="b">
        <h1 id="layers property"></h1>
        back
    </div>

    <div data-role="content">
        <div id="vectorLayerProperties" >
            <fieldset style="border: solid 1px #6b6b6b;">
                <legend>data1</legend>
                <div class="ui-content">
                    <form>
                        <div>
                            <span>ddd:</span>
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput1" placeholder="Text input" value="">
                        </div>
                        <div>
                            <span>ddd:</span>
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput2" placeholder="Text input" value="">
                        </div>
                        <div>
                            <span>ddd:</span>
                            <select class="ui-state-disabled" name="select-native-1" id="select-native-1">
                                <option value="1">The 1st Option</option>
                                <option value="2">The 2nd Option</option>
                                <option value="3">The 3rd Option</option>
                                <option value="4">The 4th Option</option>
                            </select>
                         </div>
                         <div>
                            <span>ddd:</span>
                            <select class="ui-state-disabled" name="select-native-1" id="select-native-2">
                                <option value="1">The 1st Option</option>
                                <option value="2">The 2nd Option</option>
                                <option value="3">The 3rd Option</option>
                                <option value="4">The 4th Option</option>
                            </select>

                        </div>

                        <input type="Button" data-inline="true" value="Edit" onclick="editLayerProperty()">
                        <input type="Button" data-inline="true" value="Delete">
                    </form>
                </div>
            </fieldset>
        </div>
        <div id="vectorLayerslist"></div>
    </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I hav this two elements:

  ddd:
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput1" placeholder="Text input" value="">

UPDATE

Here is my HTML code:

        back

            <fieldset style="border: solid 1px #6b6b6b;">
                <legend>data1</legend>

                    <form>

                            ddd:
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput1" placeholder="Text input" value="">

                            ddd:
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput2" placeholder="Text input" value="">

                            ddd:
                            <select class="ui-state-disabled" name="select-native-1" id="select-native-1">
                                <option value="1">The 1st Option</option>
                                <option value="2">The 2nd Option</option>
                                <option value="3">The 3rd Option</option>
                                <option value="4">The 4th Option</option>
                            </select>

                            ddd:
                            <select class="ui-state-disabled" name="select-native-1" id="select-native-2">
                                <option value="1">The 1st Option</option>
                                <option value="2">The 2nd Option</option>
                                <option value="3">The 3rd Option</option>
                                <option value="4">The 4th Option</option>
                            </select>

                        <input type="Button" data-inline="true" value="Edit" onclick="editLayerProperty()">
                        <input type="Button" data-inline="true" value="Delete">
                    </form>

            </fieldset>

Inside element with id=vectorLayerProperties   I have span element and textbox which I want to make in single line.

How can I make them in one row for screen with size 250px width?

Body:
use media queries and display block like the example, to reproduce it you will have to resize your browser window to 250px..

UPDATE

Wrap your span and input, inside div, a div has display block by default....

@media (max-width: 250px) {
  .span,.input {
    display: block;
  }
}

<span class="span">ddd:</span>
                            <input type="text" class="input ui-state-disabled" name="textinput-hide" id="textinput1" placeholder="Text input" value="">

<div data-role="page" id="layerProperty">
    <div data-role="header" data-position="fixed" data-theme="b">
        <h1 id="layers property"></h1>
        <a href="#mapPage" data-mini="true" data-icon="arrow-l">back</a>
    </div>

    <div data-role="content">
        <div id="vectorLayerProperties" >
            <fieldset style="border: solid 1px #6b6b6b;">
                <legend>data1</legend>
                <div class="ui-content">
                    <form>
                        <div>
                            <span>ddd:</span>
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput1" placeholder="Text input" value="">
                        </div>
                        <div>
                            <span>ddd:</span>
                            <input type="text" class="ui-state-disabled" name="textinput-hide" id="textinput2" placeholder="Text input" value="">
                        </div>
                        <div>
                            <span>ddd:</span>
                            <select class="ui-state-disabled" name="select-native-1" id="select-native-1">
                                <option value="1">The 1st Option</option>
                                <option value="2">The 2nd Option</option>
                                <option value="3">The 3rd Option</option>
                                <option value="4">The 4th Option</option>
                            </select>
                         </div>
                         <div>
                            <span>ddd:</span>
                            <select class="ui-state-disabled" name="select-native-1" id="select-native-2">
                                <option value="1">The 1st Option</option>
                                <option value="2">The 2nd Option</option>
                                <option value="3">The 3rd Option</option>
                                <option value="4">The 4th Option</option>
                            </select>

                        </div>

                        <input type="Button" data-inline="true" value="Edit" onclick="editLayerProperty()">
                        <input type="Button" data-inline="true" value="Delete">
                    </form>
                </div>
            </fieldset>
        </div>
        <div id="vectorLayerslist"></div>
    </div>
</div>


问:
WPF Prism - Navigation without views?
I have a WPF MVVM application using strongly-typed DataTemplates to represent the views for my view models. These DataTemplates are in resource dictionaries and automatically link up to the view models - standard stuff.

I want to fit Prism navigation to my app, but the navigation methods require a Uri for the view, which isn't part of this particular style of MVVM.

Can a region (on a ContentControl) simply navigate to a new view-model only?

Does Prism for WPF support this kind of view-less implementation

Thanks

答:
You could use the RegisterTypeForNavigation method to register the view model type for navigation with a unique name, for example in your bootstrapper class:

```<code>Container.RegisterTypeForNavigation<ViewAViewModel>("a");
</code>```

You should then be able to use this name to navigate to it:

```<code>regionManager.RequestNavigate("YourRegionName", "a");
</code>```

The view will be resolved as usual using DataTemplates, e.g.:

```<code><ContentControl prism:RegionManager.RegionName="YourRegionName">
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type viewModels:ViewAViewModel}">
            <views:ViewA/>
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>
</code>```

Title: WPF Prism - Navigation without views?

Body:
You could use the RegisterTypeForNavigation method to register the view model type for navigation with a unique name, for example in your bootstrapper class:

Container.RegisterTypeForNavigation<ViewAViewModel>("a");

You should then be able to use this name to navigate to it:

regionManager.RequestNavigate("YourRegionName", "a");

The view will be resolved as usual using DataTemplates, e.g.:

<ContentControl prism:RegionManager.RegionName="YourRegionName">
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type viewModels:ViewAViewModel}">
            <views:ViewA/>
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>


问:
js find min difference in date array
I have a sorted array:

```<code>[new Date('2017-01-02'), new Date('2017-01-07'), new Date('2017-01-09'), new Date('2017-01-17')]
</code>```

Now I want to find the minimum time difference occuring in the array between any two adjacent elements. eg in this case:

```<code>new Date('2017-01-09').getTime() - new Date('2017-01-07').getTime()
</code>```

is there some elegant way with map or something similar or do I have to loop, remember the smalles interval so far and then replace the value if a smaller one occurs?

Current solution:

```<code> let timestamps = Gps.find().map(doc => doc.timestamp);
                    timestamps.sort();
                    let minimumDifference;
                    let previousTimestamp;
                    timestamps.forEach(timestamp => {
                        if(!previousTimestamp) {
                            previousTimestamp = timestamp;
                        }
                        else{
                            let difference = timestamp.getTime() - previousTimestamp.getTime();
                            if(!minimumDifference || minimumDifference > difference){
                                minimumDifference = difference;
                            }
                            previousTimestamp = timestamp;
                        }

                    });
</code>```

答:
I would like to go back into olden days. plain old javascript. Not creating unnecessory copy

```<code>var timestamps = [1,2,5,9];
timestamps.sort();
var result = timestamps[timestamps.length-1];
for(var i=1;i<timestamps.length;i++){
   result = (timestamps[i]-timestamps[i-1])<result?(timestamps[i]-timestamps[i-1]):result;
}
</code>```

take mills and proceed same way

Title: js find min difference in date array

Body:
I have a sorted array:

[new Date('2017-01-02'), new Date('2017-01-07'), new Date('2017-01-09'), new Date('2017-01-17')]

Now I want to find the minimum time difference occuring in the array between any two adjacent elements. eg in this case:

new Date('2017-01-09').getTime() - new Date('2017-01-07').getTime()

is there some elegant way with map or something similar or do I have to loop, remember the smalles interval so far and then replace the value if a smaller one occurs?

Current solution:

 let timestamps = Gps.find().map(doc => doc.timestamp);
                    timestamps.sort();
                    let minimumDifference;
                    let previousTimestamp;
                    timestamps.forEach(timestamp => {
                        if(!previousTimestamp) {
                            previousTimestamp = timestamp;
                        }
                        else{
                            let difference = timestamp.getTime() - previousTimestamp.getTime();
                            if(!minimumDifference || minimumDifference > difference){
                                minimumDifference = difference;
                            }
                            previousTimestamp = timestamp;
                        }

                    });

Body:
I would like to go back into olden days. plain old javascript. Not creating unnecessory copy

var timestamps = [1,2,5,9];
timestamps.sort();
var result = timestamps[timestamps.length-1];
for(var i=1;i<timestamps.length;i++){
   result = (timestamps[i]-timestamps[i-1])<result?(timestamps[i]-timestamps[i-1]):result;
}

take mills and proceed same way


问:
VBA: How to open most recent two excel files in the folder
I have trying to open the most recent two excel file in the folder so far i did open the latest file in folder but i have to open 2nd latest file in folder. refer below code. please suggest how to open 2nd most recent file?</p>

```<code>Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1 As Workbook
Dim wb2 As Workbook
  FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)

        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

                Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)

End Sub
</code>```

答:
You can do it in one pass</p>

```<code>Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim strFilename, strFilename2
  FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)

        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename2 = strFilename
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

  Set wb1 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)
 Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename2)

End Sub
</code>```

Body:
I have trying to open the most recent two excel file in the folder so far i did open the latest file in folder but i have to open 2nd latest file in folder. refer below code. please suggest how to open 2nd most recent file?

Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1 As Workbook
Dim wb2 As Workbook
  FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)

        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

                Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)

End Sub

Body:
You can do it in one pass

Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim strFilename, strFilename2
  FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)

        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename2 = strFilename
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

  Set wb1 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)
 Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename2)

End Sub


问:
Delete a row with the highest value of a specific column
I want to delete the row with the highest value on specific column

(I know that there are answers for that but none of them work for me for some reason)

All the coding I do in visual studio c# with SQL

MyDatabase: hours

```<code>Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL
</code>```

My Code:

```<code>if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();
</code>```

Don't work either when commandText is

```<code>@"DELETE TOP(1) FROM hours
  WHERE Index in
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";
</code>```

I want to delete the whole row of the highest index - i.e delete the row with the index 6 that it is the highest index

Error at:

```<code>cmd.ExecuteNonQuery();
</code>```

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If
  this is intended as a part of a table hint, A WITH keyword and
  parenthesis are now required. See SQL Server Books Online for proper
  syntax.

答:
```<code> delete from tablename
 where columnname =
 ( select dummytable.maxVal from
    (select max(columnname) as maxVal from tablename)
   dummytable
 );
</code>```

Body:
I want to delete the row with the highest value on specific column

(I know that there are answers for that but none of them work for me for some reason)

All the coding I do in visual studio c# with SQL

MyDatabase: hours

Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL

My Code:

if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();

Don't work either when commandText is

@"DELETE TOP(1) FROM hours
  WHERE Index in
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";

I want to delete the whole row of the highest index - i.e delete the row with the index 6 that it is the highest index

Error at:

cmd.ExecuteNonQuery();

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If
  this is intended as a part of a table hint, A WITH keyword and
  parenthesis are now required. See SQL Server Books Online for proper
  syntax.


问:
How to place a div beside input box on focus?
I have a scenario,that I used css for extending search box on focus,when I focussed on search box then the search box must decrease and the cancel button must be placed beside of search box.

Css:

```<code>.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
 }

: content-box;
font-size: 100%;

.clrble .frmcntr:focus {
    width: 70%;
    text-align: left;
    background-color: #fff;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
    background-color:rgba(247, 247, 247, 1);
    background:url("images/search.png") no-repeat  10px center;
    padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing

}
</code>```

Here is my plunker link:

https://plnkr.co/edit/Z7mfglWEoDyjbDfFDbLM?p=preview

And the expected output will be like this:

Is it possible with Angularjs or JavaScript?

答:
with float property you can mange the side by side positions.

use float:left; css property for you textbox class and that will work for your requirement and the placement of button also can be handle by css also.

css for textbox

```<code>.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
float:left;
</code>```

}

Body:
I have a scenario,that I used css for extending search box on focus,when I focussed on search box then the search box must decrease and the cancel button must be placed beside of search box.

Css:

.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
 }

: content-box;
font-size: 100%;

.clrble .frmcntr:focus {
    width: 70%;
    text-align: left;
    background-color: #fff;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
    background-color:rgba(247, 247, 247, 1);
    background:url("images/search.png") no-repeat  10px center;
    padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing

}

Here is my plunker link:

https://plnkr.co/edit/Z7mfglWEoDyjbDfFDbLM?p=preview

And the expected output will be like this:

Is it possible with Angularjs or JavaScript?

Body:
with float property you can mange the side by side positions.

use float:left; css property for you textbox class and that will work for your requirement and the placement of button also can be handle by css also.

css for textbox

.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
float:left;

}


问:
IdentityServer4 - Call an API as a User from MVC
I'm getting my knickers in a twist trying to understand how to call an API protected via IdentityServer4.

Basically, I have the following sites:
- an IdentityServer application,
- a web API and
- a client web application.

My setup is just like the IdentityServer samples here.

I define a Client which represents my client web application, and an APIResource which represents my Web Api.

From within my client web application I want to make an HTTP call to the WebAPI, but I want to appear as if I am the logged in user, so I want to make the 'email' scope available to the Web Api.

The way I'm doing from within the Web Application is to grab the 'access_token', and to pass it to the Web API:

```<code>var accessToken = await httpContextAccessor.HttpContext.Authentication.GetTokenAsync($"access_token");
            var client = new HttpClient();
            client.SetBearerToken(accessToken);
</code>```

This allows me to call the Client, so the authorization step is working, but the User Claims on the Web Api do not have the appropriate scopes.

Am I doing something wrong?

答:
You can add scopes in your web api like

```<code>app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "https://demo.identityserver.io",
    ApiName = "api1",

    AllowedScopes = { "api1.read", "api1.write" }
});
</code>```

How did you configure your web api? Post the code if it still doesn't work!

Body:
I'm getting my knickers in a twist trying to understand how to call an API protected via IdentityServer4.

Basically, I have the following sites:
- an IdentityServer application,
- a web API and
- a client web application.

My setup is just like the IdentityServer samples here.

I define a Client which represents my client web application, and an APIResource which represents my Web Api.

From within my client web application I want to make an HTTP call to the WebAPI, but I want to appear as if I am the logged in user, so I want to make the 'email' scope available to the Web Api.

The way I'm doing from within the Web Application is to grab the 'access_token', and to pass it to the Web API:

var accessToken = await httpContextAccessor.HttpContext.Authentication.GetTokenAsync($"access_token");
            var client = new HttpClient();
            client.SetBearerToken(accessToken);

This allows me to call the Client, so the authorization step is working, but the User Claims on the Web Api do not have the appropriate scopes.

Am I doing something wrong?

Body:
You can add scopes in your web api like

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "https://demo.identityserver.io",
    ApiName = "api1",

    AllowedScopes = { "api1.read", "api1.write" }
});

How did you configure your web api? Post the code if it still doesn't work!


问:
Recuperate the history of Internet Explorer V11 using command Prompt or
I'm developing a C application that analyzes history of browsers (No Problem when analyzing chrome history) but i didn't find where Internet Explorer 11 stores its history  ,So, I want to recuperate the History using cmd (command Prompt ) . Can someone know the physical path where IE stores History .
Rq:ipconfig /displaydns doesn't solve my problem . </p>

答: On Windows 10 the browsing history of IE 11 is named WebCacheV01.dat (I read that on Windows 8 it was named WebCacheV24.dat) and can be found here: C:\Users\<USER NAME>\AppData\Local\Microsoft\Windows\WebCache\

ContentLicense: CC BY-SA 4.0


问:
@angular/forms/index"' has no exported mng 'FormsModule'
I'm totally new to Angular 2 and I'm getting this error when trying to import FormsModule on my app.module.ts file.

```<code>import { FormsModule } from '@angular/forms';
</code>```

This is the dependencies on my package.json:

```<code>"dependencies": {
"@angular/common": "2.0.0-rc.5",
"@angular/compiler": "2.0.0-rc.5",
"@angular/core": "2.0.0-rc.5",
"@angular/forms": "0.2.0",
"@angular/http": "2.0.0-rc.5",
"@angular/platform-browser": "2.0.0-rc.5",
"@angular/platform-browser-dynamic": "2.0.0-rc.5",
"@angular/router": "3.0.0-beta.2",
"es6-shim": "0.35.1",
"reflect-metadata": "0.1.3",
"rxjs": "5.0.0-beta.6",
"systemjs": "0.19.26",
"zone.js": "0.6.12"
</code>```

},

答:
update dependencies to

```<code> "dependencies": {
     "@angular/common": "2.0.0",
     "@angular/compiler": "2.0.0",
     "@angular/core": "2.0.0",
     "@angular/forms": "2.0.0",
     "@angular/http": "2.0.0",
     "@angular/platform-browser": "2.0.0",
     "@angular/platform-browser-dynamic": "2.0.0",
     "@angular/router": "3.0.0",
     "@angular/upgrade": "2.0.0",
     "core-js": "^2.4.1",
     "reflect-metadata": "^0.1.3",
     "rxjs": "5.0.0-beta.12",
     "systemjs": "0.19.27",
     "zone.js": "^0.6.23",
     "angular2-in-memory-web-api": "0.0.20",
     "bootstrap": "^3.3.6"   },
</code>```

Run again:

npm install

Body:
I'm totally new to Angular 2 and I'm getting this error when trying to import FormsModule on my app.module.ts file.

import { FormsModule } from '@angular/forms';

This is the dependencies on my package.json:

"dependencies": {
"@angular/common": "2.0.0-rc.5",
"@angular/compiler": "2.0.0-rc.5",
"@angular/core": "2.0.0-rc.5",
"@angular/forms": "0.2.0",
"@angular/http": "2.0.0-rc.5",
"@angular/platform-browser": "2.0.0-rc.5",
"@angular/platform-browser-dynamic": "2.0.0-rc.5",
"@angular/router": "3.0.0-beta.2",
"es6-shim": "0.35.1",
"reflect-metadata": "0.1.3",
"rxjs": "5.0.0-beta.6",
"systemjs": "0.19.26",
"zone.js": "0.6.12"

},

Body:
update dependencies to

 "dependencies": {
     "@angular/common": "2.0.0",
     "@angular/compiler": "2.0.0",
     "@angular/core": "2.0.0",
     "@angular/forms": "2.0.0",
     "@angular/http": "2.0.0",
     "@angular/platform-browser": "2.0.0",
     "@angular/platform-browser-dynamic": "2.0.0",
     "@angular/router": "3.0.0",
     "@angular/upgrade": "2.0.0",
     "core-js": "^2.4.1",
     "reflect-metadata": "^0.1.3",
     "rxjs": "5.0.0-beta.12",
     "systemjs": "0.19.27",
     "zone.js": "^0.6.23",
     "angular2-in-memory-web-api": "0.0.20",
     "bootstrap": "^3.3.6"   },

Run again:

npm install


问:
GTM - Trigg a floodlight pixel when someone has navigated to two random page URLs from landing page
I'm trying to implement a floodlight pixel that measures quality visitors on a website. In this case a quality visitor will be defined as a visitor that has visited two pages on the webpage like the flow below:

Entered the websites landing page (www.example.com)

Navigated to one page (www.example.com/page1)

Navigated to one more page (www.example.com/page2)

My ambition is to implement this through GTM. There's a lot of guides on how to trigg pixels with a certain amount of scrolling, time etc. but I can't find anything with above problem.

Do someone have any good ideas how to do?

Thanks in advance!

答:
Your idea is:

Fire tag, when user visited any 3 pages per user session. Steps how to setup that in GTM:

Create variable

Go to Variables -> User Defined - Create

Type: JavaScript variable

Name: Visited Pages Per Session

Code:

```<code>function () {
    function createCookie(name,value) {
        document.cookie = name + "=" + value + "; path=/";
    }
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return 0;
    }
    var visits = parseInt(readCookie('visitedPagesPerSession')) || 0;
    visits++;
    createCookie('visitedPagesPerSession',visits)
    return visits;
}
</code>```

Create trigger

This trigger should fire, when number of visited pages is 3

Go to Triggers -> New

Trigger Name: VisitedThreePagesTrigger

Type: Custom Event

EventName: VisitedThreePages

Fires on: Some Custom Events

Condition:

Visited Pages Per Session - equals - 3

Usage

Then you can create any tag and assign this trigger VisitedThreePagesTrigger

Body:
Your idea is:

Fire tag, when user visited any 3 pages per user session. Steps how to setup that in GTM:

Create variable

Go to Variables -> User Defined - Create

Type: JavaScript variable

Name: Visited Pages Per Session

Code:

function () {
    function createCookie(name,value) {
        document.cookie = name + "=" + value + "; path=/";
    }
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return 0;
    }
    var visits = parseInt(readCookie('visitedPagesPerSession')) || 0;
    visits++;
    createCookie('visitedPagesPerSession',visits)
    return visits;
}

Create trigger

This trigger should fire, when number of visited pages is 3

Go to Triggers -> New

Trigger Name: VisitedThreePagesTrigger

Type: Custom Event

EventName: VisitedThreePages

Fires on: Some Custom Events

Condition:

Visited Pages Per Session - equals - 3

Usage

Then you can create any tag and assign this trigger VisitedThreePagesTrigger


问:
What is the best comment in source code you have ever encountered?
What is the best comment in source code you have ever encountered?</p>

答:
Linux Comments

There are heaps of good ones here ...

These are all comments in linux

http://lwn.net/1998/1015/a/f-word.html

My Favourites:

```<code>./arch/sparc/kernel/ptrace.c
/* Fuck me gently with a chainsaw... */

./drivers/scsi/qlogicpti.h
/* Am I fucking pedantic or what? */
</code>```

OwnerDisplayName: endpoint

LastEditorDisplayName: Brian

Body:
Linux Comments

There are heaps of good ones here ...

These are all comments in linux

http://lwn.net/1998/1015/a/f-word.html

My Favourites:

./arch/sparc/kernel/ptrace.c
/* Fuck me gently with a chainsaw... */

./drivers/scsi/qlogicpti.h
/* Am I fucking pedantic or what? */

OwnerDisplayName: Bash

ContentLicense: CC BY-SA 2.5


问:
C++ String Interview Question
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

```<code>std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}
</code>```

My code:

```<code>bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}
</code>```

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

```<code>void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}
</code>```

答:
If you don't need to maintain the contents of the original string, then you can copy the last n characters into positions [n+1, 2n] of the original string and truncate it at 2n. You will have to be careful to first expand the string and also be careful not to overwrite any characters before writing to them if the string is shorter than 2n.

This will halve the number of operations to construct the string, as well as remove the need to create a new string. So its theoretically between 2 and 4 times faster. But of course you have just destroyed the original string, which you'd have to ask the interviewer if it is acceptable.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

Title: C++ String Interview Question

Body:
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}

My code:

bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}


问:
How to set username and password for SVN repository in Xcode ?
I'm new to SVN when committing the code to svn repository it was not asking username and password and it will raise issue showing author name was empty in repository commit history. How could set for username every time while committing the code to svn repository in Xcode ?  </p>

答:
You should be able to run svn info <REPOSITORY-URL> -username <USERNAME> and the <USERNAME> will be specified as svn:author for your commits.

The actual problem is that your server allows anonymous and non-authenticated access. I guess that your admin may want to reconsider that and make the server require authentication or at least reject commits with empty svn:author property. Users should not be able to enter arbitrary usernames / commit author names. How are you going to distinguish was an author of some revision in future? How are you going to search repository history for commits made by a particular user if this user can enter anything he wants as his username?


问:
How to save multiple user details in user defaults?
I got a task to store multiple user details.

```<code>@IBOutlet weak var userName: UITextField!

@IBOutlet weak var email_id: UITextField!

@IBOutlet weak var password: UITextField!
</code>```

I know in user defaults we can store a value for a particular key and retrieve it but i would like to know how to save multiple values. like the key should be the email_id i have mentioned above and all the three fields should be its values, also i need to maintain all the details even if there is n number of users.

答:
For saving user's data, using local db is the most appropriate solution.But if you don't want to go into depth of Core data / Sqlite, use Realm framework.

With Realm you just have to have a user class with dynamic properties & call basic functions like

Initialize RealmDb with

```<code>let objRealm = try! Realm()
</code>```

Create a user class

```<code>class UserDataModel: Object {
    dynamic var name:String = ""
    dynamic var ID = ""
     // MARK : Primary Key
    override static func primaryKey() -> String? {
        return "ID"
    }
}
</code>```

Add user into DB with write function

```<code>  let obj = UserDataModel(value: ["name": userName,
                                        "ID": userID])
        try! objRealm.write {
            objRealm.add(obj)
        }
</code>```

Read object from Realm DB

```<code>return objRealm.objects(UserDataModel.self)
</code>```

Body:
I got a task to store multiple user details.

@IBOutlet weak var userName: UITextField!

@IBOutlet weak var email_id: UITextField!

@IBOutlet weak var password: UITextField!

I know in user defaults we can store a value for a particular key and retrieve it but i would like to know how to save multiple values. like the key should be the email_id i have mentioned above and all the three fields should be its values, also i need to maintain all the details even if there is n number of users.

Body:
For saving user's data, using local db is the most appropriate solution.But if you don't want to go into depth of Core data / Sqlite, use Realm framework.

With Realm you just have to have a user class with dynamic properties & call basic functions like

Initialize RealmDb with

let objRealm = try! Realm()

Create a user class

class UserDataModel: Object {
    dynamic var name:String = ""
    dynamic var ID = ""
     // MARK : Primary Key
    override static func primaryKey() -> String? {
        return "ID"
    }
}

Add user into DB with write function

  let obj = UserDataModel(value: ["name": userName,
                                        "ID": userID])
        try! objRealm.write {
            objRealm.add(obj)
        }

Read object from Realm DB

return objRealm.objects(UserDataModel.self)


问:
width device-width What is what? Confused
I've read two articles:
https://www.quirksmode.org/mobile/viewports.html
https://www.quirksmode.org/mobile/viewports2.html

I am really confused why is width size of window in first article and size of screen in second article.
What have I missed?

答:
see below image

Device Screen or Device Width is the width of entire desktop or monitor. In my case it is 1679px wide.  (marked with yellow highlighter.. I have highlighted Screen height instead of width. Sorry for that.

And width Screen size window with id width of browser window . in my case this is 1100px wide approximate . i have marked this with red pen.

Hope this will help you.


问:
How can I avoid entering a character in an EditBox in Android Studio?
I want to prevent the user from entering a character in an EditText a second time, for example, if you enter the number zero, it's OK but if you want to enter the number zero for the second time, that action should be canceled.

In other words, I don't want the user to write 00.

Is there any way to do it?

答:
Try this. This implementation deletes surplus character, but you'll get an idea:</p>

```<code>mEditText.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
            int length = s.length();
            for(int i=1;i<length;i++){
                if (s.charAt(i-1) == s.charAt(i)) {
                    mEditText.setText(s.subSequence(0, i));
                    mEditText.setSelection(i);
                }
            }
      }

      @Override
      public void afterTextChanged(Editable s) {

      }
  });
}
</code>```

Body:
Try this. This implementation deletes surplus character, but you'll get an idea:

mEditText.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
            int length = s.length();
            for(int i=1;i<length;i++){
                if (s.charAt(i-1) == s.charAt(i)) {
                    mEditText.setText(s.subSequence(0, i));
                    mEditText.setSelection(i);
                }
            }
      }

      @Override
      public void afterTextChanged(Editable s) {

      }
  });
}


问:
How to develop windows 10 uwp on real device (mobile)?
I'm trying to debbuging my app on real device (lumia 830 with windows 10 mobile 10.0.10581.0)
Developer Mode is ON on both devices (mobile and PC), but when i'm trying to emulate app on my device  I've got an error (DEP6100 and DEP6200). However i can easily emulate on emulators and my PC. Can't understand what's the problem.

Has anyone been able to successfully deploy a UWP app on phone and debug it?
How to register your phone for development for Windows 10 mobile?

答: This problem may be caused by development environment, such as VS version, SDK version, etc. Please update your SDK version and phone OS version to the latest one, and I recommend you to use VS2017 to develop Windows 10 apps. I have met this problem when I used VS2015.</p>


问:
Math - Generating Point in Rotated 2D Disc in 3D Space
I've been trying to generate points along the ring of a 2D disc (both translated and rotated) in 3D space using only the disc's position and normal.

I've been using the following code to generate points and have been testing it in Matlab (but will be utilising this in c#) to check that the points are generated correctly, however it doesn't seem to be generating points correctly.

```<code>numPoints = 25;
radius = 1;
pos = [1; 2; 3];
dir = normc([3; 4; 6]); % normalised

function [pointsT, points] = GenerateDiscPoints(numPoints, radius, pos, dir)
    points = zeros(numPoints, 3);
    pointsT = zeros(numPoints, 3);

    % Angle between points
    angle = 2 * pi / numPoints;

    for i = 1:numPoints+1
        % Current point angle
        theta = angle * i;

        % Generate point in flat disc (y is vertical axis in Unity)
        x = radius * cos(theta) + pos(1);
        y = 0 + pos(2);
        z = radius * sin(theta) + pos(3);

        % Save points
        points(i, 1) = x;
        points(i, 2) = y;
        points(i, 3) = z;

        % Calculate t value to translate points
        t = (dir(1) * pos(1) - dir(1) * x + dir(2) * pos(2) - dir(2) * y + dir(3) * pos(3) - dir(3) * z) / (dir(1)*dir(1) + dir(2)*dir(2) + dir(3)*dir(3));

        % Translate points to correct location
        xT = x + t*dir(1);
        yT = y + t*dir(2);
        zT = z + t*dir(3);

        % Save translated points
        pointsT(i, 1) = xT;
        pointsT(i, 2) = yT;
        pointsT(i, 3) = zT;
    end

    % Plot
    figure;
    hold all;
    grid on;
    scatter3(points(:,1), points(:,2), points(:,3), 25, 'r');
    scatter3(pointsT(:,1), pointsT(:,2), pointsT(:,3), 25, 'g');
    p3 = line([pos(1) pos(1)+dir(1)], [pos(2) pos(2)+dir(2)], [pos(3) pos(3)+dir(3)]);
    set(p3, 'Color', 'blue');
end
</code>```

The blue line is the normal of the disc, the red points are the points before being translated, and the green points are the points after being translated. To my eye it appears that the translated points don't seem to be generating in a disc that has the normal specified.

What's wrong with my current algorithm? What would a better way to do this be?

答:
A simple linear translation along the direction of dir is insufficient - you'll end up with the projection of the circle on the plane at pos with normal dir, i.e. an ellipse.

You could either:

Use quaternions to construct a rotation matrix to re-orientate your generated circle to dir.

Creating this quaternion: https://stackoverflow.com/a/1171995/8204776

Converting it to a matrix: https://stackoverflow.com/a/1556470/8204776

or

Construct an orthogonal basis at pos where one axis is dir.

Easy way to do this:

Check if the X-axis is parallel to dir - ideally do abs(dot(dir, X)) < 0.8 (assuming both are normalized), so they are not too close to each other

If (1) is true then take dir2 = Y, else dir2 = X.

To create the first basis vector, A = normalize(cross(dir, dir2)).

To create the second, B = cross(dir, A).

Now you can generate points at each value of theta by pos + radius * (A * cos(theta) + B * sin(theta)) (in vector notation).

Body:
I've been trying to generate points along the ring of a 2D disc (both translated and rotated) in 3D space using only the disc's position and normal.

I've been using the following code to generate points and have been testing it in Matlab (but will be utilising this in c#) to check that the points are generated correctly, however it doesn't seem to be generating points correctly.

numPoints = 25;
radius = 1;
pos = [1; 2; 3];
dir = normc([3; 4; 6]); % normalised

function [pointsT, points] = GenerateDiscPoints(numPoints, radius, pos, dir)
    points = zeros(numPoints, 3);
    pointsT = zeros(numPoints, 3);

    % Angle between points
    angle = 2 * pi / numPoints;

    for i = 1:numPoints+1
        % Current point angle
        theta = angle * i;

        % Generate point in flat disc (y is vertical axis in Unity)
        x = radius * cos(theta) + pos(1);
        y = 0 + pos(2);
        z = radius * sin(theta) + pos(3);

        % Save points
        points(i, 1) = x;
        points(i, 2) = y;
        points(i, 3) = z;

        % Calculate t value to translate points
        t = (dir(1) * pos(1) - dir(1) * x + dir(2) * pos(2) - dir(2) * y + dir(3) * pos(3) - dir(3) * z) / (dir(1)*dir(1) + dir(2)*dir(2) + dir(3)*dir(3));

        % Translate points to correct location
        xT = x + t*dir(1);
        yT = y + t*dir(2);
        zT = z + t*dir(3);

        % Save translated points
        pointsT(i, 1) = xT;
        pointsT(i, 2) = yT;
        pointsT(i, 3) = zT;
    end

    % Plot
    figure;
    hold all;
    grid on;
    scatter3(points(:,1), points(:,2), points(:,3), 25, 'r');
    scatter3(pointsT(:,1), pointsT(:,2), pointsT(:,3), 25, 'g');
    p3 = line([pos(1) pos(1)+dir(1)], [pos(2) pos(2)+dir(2)], [pos(3) pos(3)+dir(3)]);
    set(p3, 'Color', 'blue');
end

The blue line is the normal of the disc, the red points are the points before being translated, and the green points are the points after being translated. To my eye it appears that the translated points don't seem to be generating in a disc that has the normal specified.

What's wrong with my current algorithm? What would a better way to do this be?


问:
How to get specific index values and store in a array from multiple php arrays
I've multiple arrays received from db table. now i'm trying to check "is their birth date == current date" if yes then their contact numbers saved in a array called birthdays

Here is my try

```<code>$curr_date = date('m/d');

$birthday = array(); // array initialization
$anniversary = array(); // array initialization

$con=mysqli_connect("localhost","root","","birthdays");

$sql="SELECT * FROM users";

$result=mysqli_query($con,$sql);

$row=mysqli_fetch_assoc($result);

echo "```";

if ($result=mysqli_query($con,$sql))
{
    while ($row=mysqli_fetch_assoc($result))
    {
        print_r ($row);
    }
}
```

Here is a image of current code with expected description

I'm trying lot of time but unable to achieve exact result. kindly guide me. Thanks

答:
Obviously you got a result from the database, so you pull all the results in an array:

```<code>$sql = "SELECT * FROM xyztable";
$result = $con->query($sql);
$users = array();
while($row = $result->fetch_assoc()) {
    $users[] = $row;
}
</code>```

So now we are at the same point.
Now you can do a loop trough the arrays, create a Birthdays array and you should explode the birth date:

```<code>$birthdays = array();
for($users as $user) {
  $birth = explode("/", $user['birth_date']);

  $new_birth = "$birth[0]/$birth[1]";
  $actual_date = date("m/d");
  if($new_birth == $actual_date) {
     $birthdays[] = $user['customer_mobile'];
  }
}
</code>```

That should be it.

Body:
I've multiple arrays received from db table. now i'm trying to check "is their birth date == current date" if yes then their contact numbers saved in a array called birthdays

Here is my try

$curr_date = date('m/d');

$birthday = array(); // array initialization
$anniversary = array(); // array initialization

$con=mysqli_connect("localhost","root","","birthdays");

$sql="SELECT * FROM users";

$result=mysqli_query($con,$sql);

$row=mysqli_fetch_assoc($result);

echo "
";

if ($result=mysqli_query($con,$sql))
{
    while ($row=mysqli_fetch_assoc($result))
    {
        print_r ($row);
    }
}

Here is a image of current code with expected description

I'm trying lot of time but unable to achieve exact result. kindly guide me. Thanks

Body:
Obviously you got a result from the database, so you pull all the results in an array:

$sql = "SELECT * FROM xyztable";
$result = $con->query($sql);
$users = array();
while($row = $result->fetch_assoc()) {
    $users[] = $row;
}

So now we are at the same point.
Now you can do a loop trough the arrays, create a Birthdays array and you should explode the birth date:

$birthdays = array();
for($users as $user) {
  $birth = explode("/", $user['birth_date']);

  $new_birth = "$birth[0]/$birth[1]";
  $actual_date = date("m/d");
  if($new_birth == $actual_date) {
     $birthdays[] = $user['customer_mobile'];
  }
}

That should be it.


问:
JSF 2.X on IBM Domino 9 (Servlet 2.5) - is it feasible at all?
Just curious whether it is possible to run JSF 2.3 on IBM Domino?

I have tried to deploy (JSF versions 2.0, 2.1, 2.2, 2.3) via the UpdateSite Plugin install following Sven's post HowTo: Vaadin on Domino. But was not really successful as got the following exceptions (listing from v2.3, but other versions are similar):

```<code>Unable to obtain InjectionProvider from init time FacesContext. Does this container implement the Mojarra Injection SPI?
Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory. Attempting to find backup.
Uncaught init() exception thrown by servlet {0}: {2}
CWPWC0005E: Error occurred while initializing servlet wrapper. javax.servlet.ServletException: Uncaught initialization exception thrown by servlet Thread[Thread-6,5,main]
CWPWC0005E: Error occurred while initializing servlet wrapper. javax.servlet.ServletException: Uncaught initialization exception thrown by servlet
</code>```

Any suggestions what to adjust? I do understand that Servlet version could not match JSF spec, but is it feasible at all?
Thanks!

答:
The short answer: don't bother

The long answer:
Domino modified quite some number of OSGi elements to run. The Domino JSF has been extended to include SSJS. So you fight with a lot of moving parts.

What you want to do:

put an nginx in front of your Domino on 80/443

run Domino on a different port only accepting 127.0.0.1 connections

run your Primefaces Websphere liberty Glasfish app on yet another port

have nginx redirects point to old/new server based on url

Users will see one server, https can be handled by nginx, you can have http2, offload static resources.

While you are on it: give vert.x a shot. Way more fun than JEE

Body:
Just curious whether it is possible to run JSF 2.3 on IBM Domino?

I have tried to deploy (JSF versions 2.0, 2.1, 2.2, 2.3) via the UpdateSite Plugin install following Sven's post HowTo: Vaadin on Domino. But was not really successful as got the following exceptions (listing from v2.3, but other versions are similar):

Unable to obtain InjectionProvider from init time FacesContext. Does this container implement the Mojarra Injection SPI?
Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory. Attempting to find backup.
Uncaught init() exception thrown by servlet {0}: {2}
CWPWC0005E: Error occurred while initializing servlet wrapper. javax.servlet.ServletException: Uncaught initialization exception thrown by servlet Thread[Thread-6,5,main]
CWPWC0005E: Error occurred while initializing servlet wrapper. javax.servlet.ServletException: Uncaught initialization exception thrown by servlet

Any suggestions what to adjust? I do understand that Servlet version could not match JSF spec, but is it feasible at all?
Thanks!


问:
Set ViewController for a specific Index in TabbarController
I have a UITabbarController with 5 ViewControllers as index number 0,1,2,3,4, Now, If its run in iPhone then 5 viewcontrollers loaded on it, that's fine, but if I changed iPhone to iPad, index number 4 should be different ViewControllers.

Ex.

```<code>if iPad{
    tabbarcontroller's index 4 should be B Viewcontroller
}else{
    tabbarcontroller's index 4 should be A Viewcontroller
}
</code>```

I got an answer in objective c, link here but I can not make it out for Swift, Here is my code:

```<code>let settingVc = self.storyboard?.instantiateViewController(withIdentifier: "SettingTabbarController") as! SettingTabbarController

var controllers : NSMutableArray =  [self.viewControllers!][0] as! NSMutableArray

print(controllers)

controllers.replaceObject(at: 4, with: settingVc)

self.setViewControllers(controllers, animated: true)
</code>```

Any help will be appreciated.

答:
Here you can change the viewController for specific index like below

in your UITabbarController

```<code>   self.viewControllers?.remove(at: 4)
   let newItemController = UIStoryboard(name: "Settings", bundle: nil).instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController
   newItemController.title = "Settings"
   newItemController.tabBarItem.image = UIImage(named: "ic_tab_settings")
   newItemController.tabBarItem.isEnabled = true
   self.viewControllers?.insert(newItemController, at:4)
</code>```

Body:
I have a UITabbarController with 5 ViewControllers as index number 0,1,2,3,4, Now, If its run in iPhone then 5 viewcontrollers loaded on it, that's fine, but if I changed iPhone to iPad, index number 4 should be different ViewControllers.

Ex.

if iPad{
    tabbarcontroller's index 4 should be B Viewcontroller
}else{
    tabbarcontroller's index 4 should be A Viewcontroller
}

I got an answer in objective c, link here but I can not make it out for Swift, Here is my code:

let settingVc = self.storyboard?.instantiateViewController(withIdentifier: "SettingTabbarController") as! SettingTabbarController

var controllers : NSMutableArray =  [self.viewControllers!][0] as! NSMutableArray

print(controllers)

controllers.replaceObject(at: 4, with: settingVc)

self.setViewControllers(controllers, animated: true)

Any help will be appreciated.

Body:
Here you can change the viewController for specific index like below

in your UITabbarController

   self.viewControllers?.remove(at: 4)
   let newItemController = UIStoryboard(name: "Settings", bundle: nil).instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController
   newItemController.title = "Settings"
   newItemController.tabBarItem.image = UIImage(named: "ic_tab_settings")
   newItemController.tabBarItem.isEnabled = true
   self.viewControllers?.insert(newItemController, at:4)


问:
modify grid-data for external filter in ng-grid angularJS
I have to modify data of grid based on external generic filter for data grid.
I have searched and find out 2 ways to do so,

After changing grid data according to filter, use $scope.gridApi.core.notifydatachange(uiGridConstants.dataChange.ALL)

add $scope.gridApi.grid.registerRowsProcessor( $scope.singleFilter, 200 ); in $scope.gridOptions.onRegisterApi and then inside $scope.singleFilter function change visibility of data according to filter.

Is it possible to filter data according to external filter and column filter together?

If YES, I want to know which method will go very well with column filtering?

答: It is good idea to modify data for filter using $scope.gridApi.core.notifydatachange(uiGridConstants.dataChange.ALL) function. As $scope.gridApi.grid.registerRowsProcessor() is used by ng-grid internally for single column filter. And hence if we try to modify it, By default functionality of column filter will behave un-expectedly.


问:
what is the TextMargin size added default in DrawString method
While drawing string using MeasureString, it draws the given text in given position with some padding.

```<code>protected override void OnPaint(PaintEventArgs e)
{
   base.OnPaint(e);

   Size size = Size.Ceiling(e.Graphics.MeasureString("like", this.Font));

   Rectangle rect = new Rectangle(15, 15, size.Width, size.Height);

   e.Graphics.FillRectangle(Brushes.Blue, rect);
   e.Graphics.DrawString("like", this.Font, Brushes.Violet, rect);
}
</code>```

I want to know, what is the padding difference added to the given point for drawing measurestring.

Please anyone clarify on this.

答: Sorry, I can't comment yet -- I assume your question about padding is "why there is still a little bit of blue colour on the left of the word 'like'" -- I'm guessing that's related with the font OR possibly because of the Ceiling of the 'size'?  </p>

Body:
While drawing string using MeasureString, it draws the given text in given position with some padding.

protected override void OnPaint(PaintEventArgs e)
{
   base.OnPaint(e);

   Size size = Size.Ceiling(e.Graphics.MeasureString("like", this.Font));

   Rectangle rect = new Rectangle(15, 15, size.Width, size.Height);

   e.Graphics.FillRectangle(Brushes.Blue, rect);
   e.Graphics.DrawString("like", this.Font, Brushes.Violet, rect);
}

I want to know, what is the padding difference added to the given point for drawing measurestring.

Please anyone clarify on this.


问:
How to check container log of tomcat?
How do I check the container log of tomcat?

I get this error from the catalina.out log:

```<code>SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
</code>```

But where can I find the "appropriate container log" that this log is referring to?

Thanks in advance.

答: You'll find the referenced log file in the same directory containing the log referencing the other log file.  With a default installation of Tomcat, the directory is $CATALINA_HOME/logs.  The log file containing the information referenced will usually be the one named with the hostname on which Tomcat is running.  On a simple server (e.g. development environment) this is localhost.<datestamp>.log.  The additional error information can be found in this log file at the same timestamp as the noted reference in the referring log file.

Title: How to check container log of tomcat?

Body:
How do I check the container log of tomcat?

I get this error from the catalina.out log:

SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file

But where can I find the "appropriate container log" that this log is referring to?

Thanks in advance.


问:
What is the conditional code to affect IE8 browser?
I don't mean conditional comments embedded into the html. I am refering to the conditional code that can be put directly into the css file. Like:

```<code>*+html .myClass {} is for IE7
* html .myClass {} is for IE 6
</code>```

what is the one for IE 8?

答:
According to this site, you can do the following:

```<code>.selector {
    property: value\0/;
}
</code>```

There are several similar variants of this hack, but this is the easiest. It’s very easy to remember. Just add the \0/ at the end of a CSS rule.

Body:
I don't mean conditional comments embedded into the html. I am refering to the conditional code that can be put directly into the css file. Like:

*+html .myClass {} is for IE7
* html .myClass {} is for IE 6

what is the one for IE 8?

Body:
According to this site, you can do the following:

.selector {
    property: value\0/;
}

There are several similar variants of this hack, but this is the easiest. It’s very easy to remember. Just add the \0/ at the end of a CSS rule.


问:
Jenkins: Failed to connect to repository
I'm trying to connect jenkins on a github repo.

When I specify the Repo URL jenkins return the following error message:

Failed to connect to repository : Command "git ls-remote -h git@github.com:adolfosrs/jenkins-test.git HEAD" returned status code 128:
  stdout:
  stderr: Host key verification failed.
  fatal: Could not read from remote repository.
  Please make sure you have the correct access rights
  and the repository exists.

When using the HTTPS:// Url jenkins returns:

Failed to connect to repository : Failed to connect to
  https://github.com/adolfosrs/jenkins-test.git (status = 407)

I could successfully clone the repo at the same machine where jenkins is running and I also run the git ls-remote -h git@github.com:adolfosrs/jenkins-test.git HEAD command. So I have the right SSH at github.

答:
In my case, I edited the known_hosts file with root user. So it changed the file ownership to root and jenkins user started throwing "git@github.com:xxxxxx/xxxx.git HEAD" returned status code 128: stdout: stderr: Host key verification failed" error while cloning git image.
Reverting the ownership resolved the issue.</p>


问:
How do I time a method's execution in Java?

How do I get a method's execution time?

Is there a Timer utility class for things like timing how long a task takes, etc?

Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.

答:
A strategy that works to me in java ee was:

Create a class with a method annotated with @AroundInvoke;

```<code>@Singleton
public class TimedInterceptor implements Serializable {

    @AroundInvoke
    public Object logMethod(InvocationContext ic) throws Exception {
        Date start = new Date();
        Object result = ic.proceed();
        Date end = new Date();
        System.out.println("time: " + (end.getTime - start.getTime()));
        return result;
    }
}
</code>```

Annotate the method that you want to monitoring:

```<code>@Interceptors(TimedInterceptor.class)
public void onMessage(final Message message) { ...
</code>```

I hope this can help.

OwnerDisplayName: Ogre Psalm33

Body:
A strategy that works to me in java ee was:

Create a class with a method annotated with @AroundInvoke;

@Singleton
public class TimedInterceptor implements Serializable {

    @AroundInvoke
    public Object logMethod(InvocationContext ic) throws Exception {
        Date start = new Date();
        Object result = ic.proceed();
        Date end = new Date();
        System.out.println("time: " + (end.getTime - start.getTime()));
        return result;
    }
}

Annotate the method that you want to monitoring:

@Interceptors(TimedInterceptor.class)
public void onMessage(final Message message) { ...

I hope this can help.


问:
Kafka error: SLF4J: Failed toString() invocation on an object of type [org.apache.kafka.common.Cluster]
I am trying to use Gatling with Kafka, but every so often get this error:

```<code>01:32:53.933 [kafka-producer-network-thread | producer-1] DEBUG o.apache.kafka.clients.NetworkClient - Sending metadata request ClientRequest(expectResponse=true, payload=null, request=RequestSend(header={api_key=3,api_version=0,correlation_id=12,client_id=producer-1}, body={topics=[test]})) to node 1011
SLF4J: Failed toString() invocation on an object of type [org.apache.kafka.common.Cluster]
java.lang.NullPointerException
at org.apache.kafka.common.PartitionInfo.toString(PartitionInfo.java:72)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at java.util.AbstractCollection.toString(AbstractCollection.java:462)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at org.apache.kafka.common.Cluster.toString(Cluster.java:151)
    at org.slf4j.helpers.MessageFormatter.safeObjectAppend(MessageFormatter.java:305)
    at org.slf4j.helpers.MessageFormatter.deeplyAppendParameter(MessageFormatter.java:277)
    at org.slf4j.helpers.MessageFormatter.arrayFormat(MessageFormatter.java:231)
    at ch.qos.logback.classic.spi.LoggingEvent.getFormattedMessage(LoggingEvent.java:298)
    at ch.qos.logback.classic.spi.LoggingEvent.prepareForDeferredProcessing(LoggingEvent.java:208)
    at ch.qos.logback.core.OutputStreamAppender.subAppend(OutputStreamAppender.java:212)
    at ch.qos.logback.core.OutputStreamAppender.append(OutputStreamAppender.java:103)
    at ch.qos.logback.core.UnsynchronizedAppenderBase.doAppend(UnsynchronizedAppenderBase.java:88)
    at ch.qos.logback.core.spi.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:48)
    at ch.qos.logback.classic.Logger.appendLoopOnAppenders(Logger.java:273)
    at ch.qos.logback.classic.Logger.callAppenders(Logger.java:260)
    at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:442)
    at ch.qos.logback.classic.Logger.filterAndLog_2(Logger.java:433)
    at ch.qos.logback.classic.Logger.debug(Logger.java:511)
    at org.apache.kafka.clients.producer.internals.Metadata.update(Metadata.java:133)
    at org.apache.kafka.clients.NetworkClient.handleMetadataResponse(NetworkClient.java:313)
    at org.apache.kafka.clients.NetworkClient.handleCompletedReceives(NetworkClient.java:298)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:199)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:191)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:122)
    at java.lang.Thread.run(Thread.java:745)
01:32:53.937 [kafka-producer-network-thread | producer-1] DEBUG o.a.k.c.producer.internals.Metadata - Updated cluster metadata version 14 to [FAILED toString()]
</code>```

I'm not sure if the error is related to the code, but here is my BasicSimulation.scala:

```<code>class BasicSimulation extends Simulation {

val kafkaConf = kafka
    .topic("test")
    .properties(
      Map(
        ProducerConfig.ACKS_CONFIG -> "1",
        ProducerConfig.BOOTSTRAP_SERVERS_CONFIG -> "kafka:9092",
        ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG ->
          "org.apache.kafka.common.serialization.ByteArraySerializer",
        ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG ->
          "org.apache.kafka.common.serialization.ByteArraySerializer"))

  val scn = scenario("Kafka Test")
    .feed(csv("data.csv").circular)
    .exec(kafka("request")
    .send("${data}".getBytes: Array[Byte]))

  setUp(
    scn
      .inject(constantUsersPerSec(10) during(10 seconds)))
    .protocols(kafkaConf)
}
</code>```

Here is the kafka-related segment of my docker-compose.yml:

```<code>zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - "2181:2181"

  kafka:
    image: wurstmeister/kafka
    ports:
      - "9092:9092"
    depends_on:
      - zookeeper
    environment:
      KAFKA_ADVERTISED_HOST_NAME: kafka
      KAFKA_ADVERTISED_PORT: 9092
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_CREATE_TOPICS: "test:1:1"
      KAFKA_LOG_CLEANER_ENABLE: 'true'
    volumes:
      - /tmp/docker.sock:/var/run/docker.sock
</code>```

答:
In my case it was a version issue. I was using incompatible kafka build and kafka clients library.

When I switched to kafka_2.11-0.10.2.1 and kafka-clients 0.10.2.0, the issue was resolved.

Body:
I am trying to use Gatling with Kafka, but every so often get this error:

01:32:53.933 [kafka-producer-network-thread | producer-1] DEBUG o.apache.kafka.clients.NetworkClient - Sending metadata request ClientRequest(expectResponse=true, payload=null, request=RequestSend(header={api_key=3,api_version=0,correlation_id=12,client_id=producer-1}, body={topics=[test]})) to node 1011
SLF4J: Failed toString() invocation on an object of type [org.apache.kafka.common.Cluster]
java.lang.NullPointerException
at org.apache.kafka.common.PartitionInfo.toString(PartitionInfo.java:72)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at java.util.AbstractCollection.toString(AbstractCollection.java:462)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuilder.append(StringBuilder.java:131)
    at org.apache.kafka.common.Cluster.toString(Cluster.java:151)
    at org.slf4j.helpers.MessageFormatter.safeObjectAppend(MessageFormatter.java:305)
    at org.slf4j.helpers.MessageFormatter.deeplyAppendParameter(MessageFormatter.java:277)
    at org.slf4j.helpers.MessageFormatter.arrayFormat(MessageFormatter.java:231)
    at ch.qos.logback.classic.spi.LoggingEvent.getFormattedMessage(LoggingEvent.java:298)
    at ch.qos.logback.classic.spi.LoggingEvent.prepareForDeferredProcessing(LoggingEvent.java:208)
    at ch.qos.logback.core.OutputStreamAppender.subAppend(OutputStreamAppender.java:212)
    at ch.qos.logback.core.OutputStreamAppender.append(OutputStreamAppender.java:103)
    at ch.qos.logback.core.UnsynchronizedAppenderBase.doAppend(UnsynchronizedAppenderBase.java:88)
    at ch.qos.logback.core.spi.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:48)
    at ch.qos.logback.classic.Logger.appendLoopOnAppenders(Logger.java:273)
    at ch.qos.logback.classic.Logger.callAppenders(Logger.java:260)
    at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:442)
    at ch.qos.logback.classic.Logger.filterAndLog_2(Logger.java:433)
    at ch.qos.logback.classic.Logger.debug(Logger.java:511)
    at org.apache.kafka.clients.producer.internals.Metadata.update(Metadata.java:133)
    at org.apache.kafka.clients.NetworkClient.handleMetadataResponse(NetworkClient.java:313)
    at org.apache.kafka.clients.NetworkClient.handleCompletedReceives(NetworkClient.java:298)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:199)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:191)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:122)
    at java.lang.Thread.run(Thread.java:745)
01:32:53.937 [kafka-producer-network-thread | producer-1] DEBUG o.a.k.c.producer.internals.Metadata - Updated cluster metadata version 14 to [FAILED toString()]

I'm not sure if the error is related to the code, but here is my BasicSimulation.scala:

class BasicSimulation extends Simulation {

val kafkaConf = kafka
    .topic("test")
    .properties(
      Map(
        ProducerConfig.ACKS_CONFIG -> "1",
        ProducerConfig.BOOTSTRAP_SERVERS_CONFIG -> "kafka:9092",
        ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG ->
          "org.apache.kafka.common.serialization.ByteArraySerializer",
        ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG ->
          "org.apache.kafka.common.serialization.ByteArraySerializer"))

  val scn = scenario("Kafka Test")
    .feed(csv("data.csv").circular)
    .exec(kafka("request")
    .send("${data}".getBytes: Array[Byte]))

  setUp(
    scn
      .inject(constantUsersPerSec(10) during(10 seconds)))
    .protocols(kafkaConf)
}

Here is the kafka-related segment of my docker-compose.yml:

zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - "2181:2181"

  kafka:
    image: wurstmeister/kafka
    ports:
      - "9092:9092"
    depends_on:
      - zookeeper
    environment:
      KAFKA_ADVERTISED_HOST_NAME: kafka
      KAFKA_ADVERTISED_PORT: 9092
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_CREATE_TOPICS: "test:1:1"
      KAFKA_LOG_CLEANER_ENABLE: 'true'
    volumes:
      - /tmp/docker.sock:/var/run/docker.sock


问:
How to show SVN diffs matching a regex pattern
I want to see the changes in my repository, but only the chunks that contain comments (in c++ that'd be lines starting by // or enclosed in /**/ )</p>

答: Subversion does not provide any built-in tool for full-text code search. You should write a script that will process diffs or use tools that provide full-text search capabilities for SVN repositories.</p>


问:
Guzzle get result on pool
I am using Guzzle Async pool, however it seems that the documentation is missing part in how can I use the pool to fetch the returns?

As per the documentation:

```<code>$client = new Client();

$requests = function ($total) use ($client) {
    $uri = 'http://localhost/';
    for ($i = 0; $i < $total; $i++) {
        yield function() use ($client, $uri) {
            return $client->requestAsync($uri);
        };
    }
};

$pool = new Pool($client, $requests(100));
</code>```

How can I use the $pool to consume all the reply?

答:
Use Pool::batch() method for that. Also consider to limit concurrency to avoid firing 100 requests at once...

```<code>$responses = Pool::batch(
    $client,
    $requests(100),
    ['concurrency' => 5]
);
</code>```

Title: Guzzle get result on pool

Body:
I am using Guzzle Async pool, however it seems that the documentation is missing part in how can I use the pool to fetch the returns?

As per the documentation:

$client = new Client();

$requests = function ($total) use ($client) {
    $uri = 'http://localhost/';
    for ($i = 0; $i < $total; $i++) {
        yield function() use ($client, $uri) {
            return $client->requestAsync($uri);
        };
    }
};

$pool = new Pool($client, $requests(100));

How can I use the $pool to consume all the reply?

Body:
Use Pool::batch() method for that. Also consider to limit concurrency to avoid firing 100 requests at once...

$responses = Pool::batch(
    $client,
    $requests(100),
    ['concurrency' => 5]
);


问:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: index)'
I am developing a autocomplete text field and this happened

```<code>NSString *substring = [NSString stringWithString:autocompleteTextField.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" CityCode[c] contains %@ OR Zone[c] contains %@ ",substring,substring];
filteredarr =[[searchArray filteredArrayUsingPredicate:predicate] copy];
</code>```

Error occurs at line

filteredarr =[[searchArray filteredArrayUsingPredicate:predicate]
  copy];

filteredarr is an array
searcharray is an array which took json data

please help me
Thanks in advance

答:
```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@" CityCode[c] contains %@ OR Zone[c] contains %@ ",substring,substring];
</code>```

You need to put the [c] (for case insensitive) after the reserved word contains, not on the key

=>

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"CityCode contains[c] %@ OR Zone contains[c] %@ ",substring,substring];
</code>```

For the error itself (message wasn't quite explicit), I guess that is why trying to subscript on CityCode and Zone with c key, get nil, and that's why you got a setObject:forKey: with nil error (you can't put a nil value on an object).

For habits, I like to put reserved predicate words in uppercase, it's easier to read if it's a reserved word and has an "action" => CONTAINS[c], but that's just my tastes.

Body:
I am developing a autocomplete text field and this happened

NSString *substring = [NSString stringWithString:autocompleteTextField.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" CityCode[c] contains %@ OR Zone[c] contains %@ ",substring,substring];
filteredarr =[[searchArray filteredArrayUsingPredicate:predicate] copy];

Error occurs at line

filteredarr =[[searchArray filteredArrayUsingPredicate:predicate]
  copy];

filteredarr is an array
searcharray is an array which took json data

please help me
Thanks in advance

Body:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" CityCode[c] contains %@ OR Zone[c] contains %@ ",substring,substring];

You need to put the [c] (for case insensitive) after the reserved word contains, not on the key

=>

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"CityCode contains[c] %@ OR Zone contains[c] %@ ",substring,substring];

For the error itself (message wasn't quite explicit), I guess that is why trying to subscript on CityCode and Zone with c key, get nil, and that's why you got a setObject:forKey: with nil error (you can't put a nil value on an object).

For habits, I like to put reserved predicate words in uppercase, it's easier to read if it's a reserved word and has an "action" => CONTAINS[c], but that's just my tastes.


答:
If this is the only purpose of fetching data from database then there is no need to push these rows in a separate array. Just push the contact numbers to the array. There is no need to loop it twice.</p>

```<code>    $curr_date = date('m/d');

    $birthday = array(); // array initialization
    $anniversary = array(); // array initialization

    $con=mysqli_connect("localhost","root","","birthdays");

    $sql="SELECT * FROM users";

    $result=mysqli_query($con,$sql);

    $row=mysqli_fetch_assoc($result);

    if ($result=mysqli_query($con,$sql)) {
        while ($row=mysqli_fetch_assoc($result)) {
            if (date('m/d',strtotime($row['birth_date'])) == $curr_date)
                $birthday[] = $row['customer_mobile'];
        }
    }
</code>```

Title: How to get specific index values and store in a array from multiple php arrays

Body:
If this is the only purpose of fetching data from database then there is no need to push these rows in a separate array. Just push the contact numbers to the array. There is no need to loop it twice.

    $curr_date = date('m/d');

    $birthday = array(); // array initialization
    $anniversary = array(); // array initialization

    $con=mysqli_connect("localhost","root","","birthdays");

    $sql="SELECT * FROM users";

    $result=mysqli_query($con,$sql);

    $row=mysqli_fetch_assoc($result);

    if ($result=mysqli_query($con,$sql)) {
        while ($row=mysqli_fetch_assoc($result)) {
            if (date('m/d',strtotime($row['birth_date'])) == $curr_date)
                $birthday[] = $row['customer_mobile'];
        }
    }