问:
Network connectivity should come only when changed
I am using Alamofire NetworkReachabilityManager for managing my connections like below.

```<code>    let reachabilityManager = NetworkReachabilityManager()
   reachabilityManager?.listener = { [weak self] status in
            switch status {
            case .notReachable:
                self?.connectionType = .notReachable
                break
            case .unknown:
                self?.connectionType = .notReachable
                break
            case .reachable(.ethernetOrWiFi):
                self?.connectionType = .wifi
                break
            case .reachable(.wwan):
                self?.connectionType = .cellular

                break
            }

public enum ReachabilityStatus {
    case unknown
    case notReachable
    case wifi
    case cellular
}
</code>```

I am getting this callback when i am launching the application itself but I don't want this callback I need callback only when there is a change in network connection.

How can I solve this?

答:
What about creating a variable to store the previous state and checking if the variable is nil on the first call. After that you can always check if the state has changed.</p>

```<code>let reachabilityManager = NetworkReachabilityManager()
var previousStatus: ReachabilityStatus? = nil

reachabilityManager?.listener = { [weak self] status in

    if let p = self.previousStatus, p == status {
        return // status hasn't changed
    } else {
        // status is nil
        self.previousStatus = status
        return
    }

    switch status {
    case .notReachable:
        self?.connectionType = .notReachable
        break
    case .unknown:
        self?.connectionType = .notReachable
        break
    case .reachable(.ethernetOrWiFi):
        self?.connectionType = .wifi
        break
    case .reachable(.wwan):
        self?.connectionType = .cellular

        break
}
</code>```

Body:
I am using Alamofire NetworkReachabilityManager for managing my connections like below.

    let reachabilityManager = NetworkReachabilityManager()
   reachabilityManager?.listener = { [weak self] status in
            switch status {
            case .notReachable:
                self?.connectionType = .notReachable
                break
            case .unknown:
                self?.connectionType = .notReachable
                break
            case .reachable(.ethernetOrWiFi):
                self?.connectionType = .wifi
                break
            case .reachable(.wwan):
                self?.connectionType = .cellular

                break
            }

public enum ReachabilityStatus {
    case unknown
    case notReachable
    case wifi
    case cellular
}

I am getting this callback when i am launching the application itself but I don't want this callback I need callback only when there is a change in network connection.

How can I solve this?

Body:
What about creating a variable to store the previous state and checking if the variable is nil on the first call. After that you can always check if the state has changed.

let reachabilityManager = NetworkReachabilityManager()
var previousStatus: ReachabilityStatus? = nil

reachabilityManager?.listener = { [weak self] status in

    if let p = self.previousStatus, p == status {
        return // status hasn't changed
    } else {
        // status is nil
        self.previousStatus = status
        return
    }

    switch status {
    case .notReachable:
        self?.connectionType = .notReachable
        break
    case .unknown:
        self?.connectionType = .notReachable
        break
    case .reachable(.ethernetOrWiFi):
        self?.connectionType = .wifi
        break
    case .reachable(.wwan):
        self?.connectionType = .cellular

        break
}


来源: stackexchange

问:
Aligning the divs in a single line
I am trying to align two divs inside one div in a single line . I have tried with the following code:

```<code><div style="width:100%">
 <div id="id1" style="width:40%;float:left;background-color:green;position:relative">
   float-left
 </div>
 <div id="id2" style="width:60%;float:right;background-color:yellow;position:relative">
 float-right
   <div id="id3" style="position:relative;left:0px">
   button1
   </div>
    <div id="id4" style="position:absolute;right:0px">
   button2
   </div>
 </div>
</div>
</code>```

I need divs with id3 and id4 in the same line similar to span but I dont want to use a span tag , within id2 div?

I tried using position as both absolute and relative and combinations but it is not aligning within same line. What is it that I am missing?

答:
Try this.

   float-left

 float-right

   button1

   button2

```

ContentLicense: CC BY-SA 3.0

Title: Aligning the divs in a single line

Body:
I am trying to align two divs inside one div in a single line . I have tried with the following code:

   float-left

 float-right

   button1

   button2

I need divs with id3 and id4 in the same line similar to span but I dont want to use a span tag , within id2 div?

I tried using position as both absolute and relative and combinations but it is not aligning within same line. What is it that I am missing?

Body:
Try this.

<div style="width:100%">
 <div id="id1" style="width:40%;float:left;background-color:green;position:relative">
   float-left
 </div>
 <div id="id2" style="width:60%;float:right;background-color:yellow;position:relative">
 float-right
   <div id="id3" style="position:relative;display:inline-block">
   button1
   </div>
    <div id="id4" style="position:absolute;right:0px;top:0">
   button2
   </div>
 </div>
 <div style="clear:both"></div>
</div>


问:
adding web app as a library to another web project
I have a web application, basically the rest api built on struts framework. Whie building the code, it can create .war file as well and can be run on tomcat server.Now, I have another web application project implementing logging and other security  features. Is it possible to add the prior web application as a library to the latter web application so that i can implement some security featues to my rest-api's ?

In other words, I simply like to add web app (.war) file as library to another web project. Is it possible ? if possible, how ??

答:
If it is a maven project, open pom.xml file. Change the packaging to jar. For that add this inside your  tag to convert it as jar.

```<code><packaging>jar</packaging>
</code>```

If it is not a maven project, you can convert it to a maven project and follow the above steps and continue with your development.

To add the jar file to the new project
Inside the new project's pom.xml, add the jar as a dependency.

```<code><dependencies>
    <dependency>
        <groupId>com.groupName</groupId>
        <artifactId>libraryName</artifactId>
        <version>versionNumber</version>
    </dependency>
<dependencies>
</code>```

Please Note: The new project must be a maven project to do so.

Body:
If it is a maven project, open pom.xml file. Change the packaging to jar. For that add this inside your  tag to convert it as jar.

<packaging>jar</packaging>

If it is not a maven project, you can convert it to a maven project and follow the above steps and continue with your development.

To add the jar file to the new project
Inside the new project's pom.xml, add the jar as a dependency.

<dependencies>
    <dependency>
        <groupId>com.groupName</groupId>
        <artifactId>libraryName</artifactId>
        <version>versionNumber</version>
    </dependency>
<dependencies>

Please Note: The new project must be a maven project to do so.


问:
Manifest start_url is not cached by a Service Worker
I'm using Lighthouse to audit my webapp.  I'm working through the failures, but I'm stuck on this one:

Failures: Manifest start_url is not cached by a Service Worker.

In my manifest.json I have

```<code>"start_url": "index.html",
</code>```

In my worker.js I am caching the following:

```<code>let CACHE_NAME = 'my-site-cache-v1';
let urlsToCache = [
    '/',
    '/scripts/app.js',
    '/index.html'
];
</code>```

Which lines up with what I see in the Application tab in Chrome Dev tools:

So... why is it telling me start_url is not cached?

Here is my full worker.js file:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/worker.js').then(function(registration) {
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

let CACHE_NAME = 'my-site-cache-v1.1';
let urlsToCache = [
  '/',
  '/scripts/app.js',
  '/index.html'
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
    .then(function(cache) {
      console.log('Opened cache');
      return cache.addAll(urlsToCache);
    })
  );
});```

答:
It seems to be that Chrome lighthouse (chrome v62) performs a generic fetch(). See discussion on https://github.com/GoogleChrome/lighthouse/issues/2688#issuecomment-315394447

In my case, an offline.html is served after an "if (event.request.mode === 'navigate'){".
Due to the use of lighthouse´s generic fetch(), lighthouse will not get served this offline.html, and shows the "Manifest start_url is not cached by a Service Worker" error.

I solved this problem by replacing:

```<code>if (event.request.mode === 'navigate'){
</code>```

with

```<code>if (event.request.method === 'GET' ){
</code>```

Body:
I'm using Lighthouse to audit my webapp.  I'm working through the failures, but I'm stuck on this one:

Failures: Manifest start_url is not cached by a Service Worker.

In my manifest.json I have

"start_url": "index.html",

In my worker.js I am caching the following:

let CACHE_NAME = 'my-site-cache-v1';
let urlsToCache = [
    '/',
    '/scripts/app.js',
    '/index.html'
];

Which lines up with what I see in the Application tab in Chrome Dev tools:

So... why is it telling me start_url is not cached?

Here is my full worker.js file:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/worker.js').then(function(registration) {
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

let CACHE_NAME = 'my-site-cache-v1.1';
let urlsToCache = [
  '/',
  '/scripts/app.js',
  '/index.html'
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
    .then(function(cache) {
      console.log('Opened cache');
      return cache.addAll(urlsToCache);
    })
  );
});

Body:
It seems to be that Chrome lighthouse (chrome v62) performs a generic fetch(). See discussion on https://github.com/GoogleChrome/lighthouse/issues/2688#issuecomment-315394447

In my case, an offline.html is served after an "if (event.request.mode === 'navigate'){".
Due to the use of lighthouse´s generic fetch(), lighthouse will not get served this offline.html, and shows the "Manifest start_url is not cached by a Service Worker" error.

I solved this problem by replacing:

if (event.request.mode === 'navigate'){

with

if (event.request.method === 'GET' ){


问:
java.lang.NullPointerException: lock == null while get json file from server
I got following error. java.lang.NullPointerException: lock == null while get json file from server.I googled but cant find any solution for this.

My Code:

```<code>try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            Log.i("clock", httpPost.getURI().toString());
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Log.i("Buffer", "1");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            Log.i("Buffer", "2");
            StringBuilder sb = new StringBuilder();
            Log.i("Buffer", "3");
            String line = null;
            Log.i("Buffer", "4");
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            Log.i("Buffer", "5");
            json = sb.toString();
            Log.i("Buffer", "6->"+json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result-> " + e.toString());
        }
</code>```

Logcat:

答:
You just need to give permission for Internet access in Manifests.

```<code><uses-permission android:name="android.permission.INTERNET"></uses-permission>
</code>```

worked for me...

Body:
I got following error. java.lang.NullPointerException: lock == null while get json file from server.I googled but cant find any solution for this.

My Code:

try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            Log.i("clock", httpPost.getURI().toString());
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Log.i("Buffer", "1");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            Log.i("Buffer", "2");
            StringBuilder sb = new StringBuilder();
            Log.i("Buffer", "3");
            String line = null;
            Log.i("Buffer", "4");
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            Log.i("Buffer", "5");
            json = sb.toString();
            Log.i("Buffer", "6->"+json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result-> " + e.toString());
        }

Logcat:

Body:
You just need to give permission for Internet access in Manifests.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

worked for me...


问:
Flickering AVPlayerController Edge (iOS)
I have an AVPlayerController and have shifted it up 100px. The background of the video is solid white and the background in the app is solid white. Yet there's a weird flickering on the edge when it scrolls.

You can see the border right above the signup button and at the edge of the cell. I even tried putting a second view above it with a white stroke to hide it, and it just shifted it in more. The fact it's not a single color and instead flickers is super strange to me.

Any ideas how to fix it?

Video -
https://drive.google.com/file/d/1kBK92teYIm29_tAMFpMizdAMAVw8CknV/view?usp=sharing

答:
As a quick solution, you can make screenshot of the video and put it on overlay view of the AVPlayerViewController while scrolling.

Edited: You can try to set overlay property as UIView with white background color and see if the gap is gone. It may looks like that:

```<code>UIView *overlay = [[UIView alloc] initWithFrame:self.myPlayerVC.bounds];
overlay.backgroundColor = [UIColor whiteColor];
self.myPlayerVC.contentOverlayView = overlay;
</code>```

Body:
As a quick solution, you can make screenshot of the video and put it on overlay view of the AVPlayerViewController while scrolling.

Edited: You can try to set overlay property as UIView with white background color and see if the gap is gone. It may looks like that:

UIView *overlay = [[UIView alloc] initWithFrame:self.myPlayerVC.bounds];
overlay.backgroundColor = [UIColor whiteColor];
self.myPlayerVC.contentOverlayView = overlay;


问:
Writing and closing Notepad++ using speech recognition libraries
I'm trying to write code that will open Notepad++, write to a file, and close it afterward. My code is included below. I'm totally new to C#. Is there any library or way to do this?</p>

```<code>// Button Reference
private void button1_Click(object sender, EventArgs e)
{
    if (button1.Text.Equals("Enable Voice Control"))
    {
        button1.Text = "Stop Voice Control";
        recEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
    else
    {
        button1.Text = "Enable Voice Control";
        recEngine.RecognizeAsyncStop();
    }
}

public void Form1_Load(object sender, EventArgs e)
{
    Choices commands = new Choices();
    commands.Add(myCommands);
    GrammarBuilder gBuilder = new GrammarBuilder();
    gBuilder.Append(commands);
    Grammar grammar = new Grammar(gBuilder);

    recEngine.LoadGrammarAsync(grammar);
    recEngine.SetInputToDefaultAudioDevice();
    recEngine.SpeechRecognized += recEngine_SpeechRecognized;
}

void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
    Process cmd = new Process();
    cmd.StartInfo.FileName = @"notepad++.exe" ;
    //cmd.StartInfo.Arguments =@"\Write.txt";
    cmd.Start();
    cmd.CloseMainWindow();
    cmd.WaitForExit();
    cmd.Refresh();

    //if (cmd.StandardError != null)
    //Console.WriteLine(cmd.StandardError.ReadToEnd());

    var result = e.Result;
    var i = 0;
    foreach (var command in myCommands)
    {
        if (command.StartsWith("close"))
        {
            this.Close();
            //cmd.StartInfo.FileName = @"notepad++";
            cmd.Kill();
        }
        if (command.StartsWith("--") || command == string.Empty) continue;  // Skip commentBlocks and skipEmptylines
        var parts = command.Split(new char[] { '|' }); // Split the lines
        i++;
        if (command.Equals(result.Text))
        {
            Console.WriteLine("Command is  {0}: {1}", i, command);
            break;
        }
    }
}

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
</code>```

答:
You can use the below code to close the notepad:

```<code>Process[] processes = Process.GetProcessesByName("notepad");
foreach (var process in processes)
{
    process.Kill();
}
</code>```

It will close all instances of notepad. So better be sure the notepads are only that of yours (opened by your speech recognition program)

If you actually do not want to open notepad and your requirement is just to capture text and write to file programatically, then use the below code:

```<code>// Create a file to write to.
string createText = "Hello World"; // Replace with voice captured text
File.WriteAllText(path, createText);

// Open the file to read from.
string readText = File.ReadAllText(path);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write code that will open Notepad++, write to a file, and close it afterward. My code is included below. I'm totally new to C#. Is there any library or way to do this?

// Button Reference
private void button1_Click(object sender, EventArgs e)
{
    if (button1.Text.Equals("Enable Voice Control"))
    {
        button1.Text = "Stop Voice Control";
        recEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
    else
    {
        button1.Text = "Enable Voice Control";
        recEngine.RecognizeAsyncStop();
    }
}

public void Form1_Load(object sender, EventArgs e)
{
    Choices commands = new Choices();
    commands.Add(myCommands);
    GrammarBuilder gBuilder = new GrammarBuilder();
    gBuilder.Append(commands);
    Grammar grammar = new Grammar(gBuilder);

    recEngine.LoadGrammarAsync(grammar);
    recEngine.SetInputToDefaultAudioDevice();
    recEngine.SpeechRecognized += recEngine_SpeechRecognized;
}

void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
    Process cmd = new Process();
    cmd.StartInfo.FileName = @"notepad++.exe" ;
    //cmd.StartInfo.Arguments =@"\Write.txt";
    cmd.Start();
    cmd.CloseMainWindow();
    cmd.WaitForExit();
    cmd.Refresh();

    //if (cmd.StandardError != null)
    //Console.WriteLine(cmd.StandardError.ReadToEnd());

    var result = e.Result;
    var i = 0;
    foreach (var command in myCommands)
    {
        if (command.StartsWith("close"))
        {
            this.Close();
            //cmd.StartInfo.FileName = @"notepad++";
            cmd.Kill();
        }
        if (command.StartsWith("--") || command == string.Empty) continue;  // Skip commentBlocks and skipEmptylines
        var parts = command.Split(new char[] { '|' }); // Split the lines
        i++;
        if (command.Equals(result.Text))
        {
            Console.WriteLine("Command is  {0}: {1}", i, command);
            break;
        }
    }
}

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}

Body:
You can use the below code to close the notepad:

Process[] processes = Process.GetProcessesByName("notepad");
foreach (var process in processes)
{
    process.Kill();
}

It will close all instances of notepad. So better be sure the notepads are only that of yours (opened by your speech recognition program)

If you actually do not want to open notepad and your requirement is just to capture text and write to file programatically, then use the below code:

// Create a file to write to.
string createText = "Hello World"; // Replace with voice captured text
File.WriteAllText(path, createText);

// Open the file to read from.
string readText = File.ReadAllText(path);


问:
Automated way to update a view code using sql script?
Lets suppose i have a table A with 4 columns and I've created a view for the same table which consists of all 4 columns. Now i want to write a script/stored procedure which should update the view code whenever new column is added to Table A in a same physical order.

For Example:
Table  A has following columns

```<code>'Name','Age','Gender','Address'
</code>```

Supposed view code is:

```<code>Select Name,Age,Gender,Address from Table A
</code>```

Now i add an additional column PhoneNumber on Table A. When i run script/Stored Procedure this new column should automatically be added to the query as follows:

Desired view code generated after i run script should be like this:

```<code>Select Name,Age,Gender,Address,PhoneNumber from Table A
</code>```

答:
Below is an example that will alter the view, specifying an explicit column list.</p>

```<code>DECLARE @AltereViewSQL nvarchar(MAX);
SELECT @AltereViewSQL = N'ALTER VIEW dbo.YourView AS SELECT '
    + STUFF((SELECT ','  + name
    FROM sys.columns
    WHERE
        object_id = OBJECT_ID(N'dbo.YourTable')
    ORDER BY
        column_id
    FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)'), 1, 1, '')
    + ' FROM dbo.YourTable;'

EXEC(@AltereViewSQL);
</code>```

Body:
Lets suppose i have a table A with 4 columns and I've created a view for the same table which consists of all 4 columns. Now i want to write a script/stored procedure which should update the view code whenever new column is added to Table A in a same physical order.

For Example:
Table  A has following columns

'Name','Age','Gender','Address'

Supposed view code is:

Select Name,Age,Gender,Address from Table A

Now i add an additional column PhoneNumber on Table A. When i run script/Stored Procedure this new column should automatically be added to the query as follows:

Desired view code generated after i run script should be like this:

Select Name,Age,Gender,Address,PhoneNumber from Table A

Body:
Below is an example that will alter the view, specifying an explicit column list.

DECLARE @AltereViewSQL nvarchar(MAX);
SELECT @AltereViewSQL = N'ALTER VIEW dbo.YourView AS SELECT '
    + STUFF((SELECT ','  + name
    FROM sys.columns
    WHERE
        object_id = OBJECT_ID(N'dbo.YourTable')
    ORDER BY
        column_id
    FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)'), 1, 1, '')
    + ' FROM dbo.YourTable;'

EXEC(@AltereViewSQL);


问:
What is this type of PowerShell array using @"..."@?
Recently, I saw a PowerShell array written like this:

```<code>$qCommand = @"
<View Scope="RecursiveAll">
<Query>
    <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
</Query>
<RowLimit Paged="TRUE">5000</RowLimit>
</View>
"@
</code>```

I've not encountered this kind of syntax yet with PowerShell arrays, only the standard @().

What's @"..."@ for?

答:
It's not an array but rather a Here-String.

The Here-String construction provides an easy way for handling text, it's specialty is dealing with speech marks and other delimiters without the need for inserting escape characters.

Quoted from: http://www.computerperformance.co.uk/powershell/powershell_here_string.htm

Body:
Recently, I saw a PowerShell array written like this:

$qCommand = @"
<View Scope="RecursiveAll">
<Query>
    <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
</Query>
<RowLimit Paged="TRUE">5000</RowLimit>
</View>
"@

I've not encountered this kind of syntax yet with PowerShell arrays, only the standard @().

What's @"..."@ for?


问:
Using a taglib tag with MarkupBuilder
I try to call a Grails Tablib in combination with the Groovy MarkupBuilber

```<code>MarkupBuilder html = new MarkupBuilder(out)

html.div {
    g.link(controller: "...", action: "...") {
        ...
    }
}
</code>```

As described in the Grails documentation (http://docs.grails.org/latest/guide/theWebLayer.html#_rendering_a_response) this is not working because the taglib call return some text that will be ignored by the MarkupBuilder

I also found this issue in the grails-gsp project on github (https://github.com/grails/grails-gsp/issues/7) with the same problem. In this issue the solution is to use out <<.

Is this the correct solution and right way or are there other possibilities?

答:
Just use mkp.yield or mkp.yieldUnescaped for custom text added to builder syntax.

```<code>MarkupBuilder html = new MarkupBuilder(out)

html.div {
    mkp.yieldUnescaped g.link(controller: "...", action: "...") {
        ...
    }
}
</code>```

Title: Using a taglib tag with MarkupBuilder

Body:
I try to call a Grails Tablib in combination with the Groovy MarkupBuilber

MarkupBuilder html = new MarkupBuilder(out)

html.div {
    g.link(controller: "...", action: "...") {
        ...
    }
}

As described in the Grails documentation (http://docs.grails.org/latest/guide/theWebLayer.html#_rendering_a_response) this is not working because the taglib call return some text that will be ignored by the MarkupBuilder

I also found this issue in the grails-gsp project on github (https://github.com/grails/grails-gsp/issues/7) with the same problem. In this issue the solution is to use out <<.

Is this the correct solution and right way or are there other possibilities?

Body:
Just use mkp.yield or mkp.yieldUnescaped for custom text added to builder syntax.

MarkupBuilder html = new MarkupBuilder(out)

html.div {
    mkp.yieldUnescaped g.link(controller: "...", action: "...") {
        ...
    }
}


问:
load matching files in table
I have a folder that contains multiple .csv files for each employee like empname_date.csv and I want to load files in one table.
Not all files but only files where file name matches the data with tbl_empmaster table that contains the master list of employees.

I do not want to check each file because it will take too much of time. I need to filter files as per master list and then load the matching employee files.

Please help what I can do in this case.

I am using SSIS to do the same.

答:
Create an SSIS Package to with a For Each Loop Container to Read all the CSV files of the given Folder.

Read the File Name without extension to a variable and Before inserting perform a table lookup to see whether the given File Name exists in your table and insert only if the match is found

Title: load matching files in table


问:
VPAID preroll example
It's been a long time that I have been looking for a VPAID code example for a sample preroll ad but I can't find it.

Can anyone who knows one please help me?
Thanks

P.S. I am using videojs

答:
Google have an example VPAID Preroll ad on their Github page, you can look at the javascript here:
Javascript VPAID Preroll Creative

And this is the example tag to go with it:
VPAID Preroll VAST Tag

...Which you can test on their test page here:
Google IMA Test Player

That should be everything you need! :)

Title: VPAID preroll example


问:
how to pass dynamic/optional filter in mongodb?
I want to select data from mongodb based on given filter. I am getting proper result if I pass static filter.

i.e.

```<code>var filter = {'categories ':'business'};
</code>```

If I put dynamic values it is not showing up. I am able to see variable type as object and value is also correct.

```<code>static async getArticle(req, res, next) {
   try {

      var filter = {};
   if(req.body.categories || req.body.categories != "") {
       filter.categories = req.body.categories;
   }
   console.log('val: '+JSON.stringify(filter));
   console.log('org val: '+filter);
   console.log('obj type: '+typeof(filter));
   let totalArticle = await Models.Article.find(filter).count().exec();

  res.send({
       success: true,
       totalArticle: totalArticle
   });
   } catch (error) {
       console.error(error);
       res.send({success: false, error});
   }
}
</code>```

Output in console is

```<code>val: {"categories":"business"}
org val: [object Object]
obj type: object
</code>```

If I pass static value as above I get following response.

```<code>{
    "success": true,
    "totalArticle": 2
}
</code>```

and in console it is also same:

```<code>val: {"categories":"business"}
org val: [object Object]
obj type: object
</code>```

Can someone please tell what I am doing wrong?

答:
Maybe you have an error because you are setting "filter1" instead of "filter" in :

```<code>   let totalArticle = await Models.Article.find(filter1).count().exec();
</code>```

Hope it helps.

Body:
I want to select data from mongodb based on given filter. I am getting proper result if I pass static filter.

i.e.

var filter = {'categories ':'business'};

If I put dynamic values it is not showing up. I am able to see variable type as object and value is also correct.

static async getArticle(req, res, next) {
   try {

      var filter = {};
   if(req.body.categories || req.body.categories != "") {
       filter.categories = req.body.categories;
   }
   console.log('val: '+JSON.stringify(filter));
   console.log('org val: '+filter);
   console.log('obj type: '+typeof(filter));
   let totalArticle = await Models.Article.find(filter).count().exec();

  res.send({
       success: true,
       totalArticle: totalArticle
   });
   } catch (error) {
       console.error(error);
       res.send({success: false, error});
   }
}

Output in console is

val: {"categories":"business"}
org val: [object Object]
obj type: object

If I pass static value as above I get following response.

{
    "success": true,
    "totalArticle": 2
}

and in console it is also same:

val: {"categories":"business"}
org val: [object Object]
obj type: object

Can someone please tell what I am doing wrong?

Body:
Maybe you have an error because you are setting "filter1" instead of "filter" in :

   let totalArticle = await Models.Article.find(filter1).count().exec();

Hope it helps.


问:
Find a phrase in defined list with a file
I have a list name my= ['cbs is down','abnormal']
and I have opened a file in read mode

Now I want to search any of the string available in list that exist in that file and perform the if action

```<code>fopen  =  open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
    if my in line:
            print ("down")
</code>```

and when I execute it, I get the following

```<code>Traceback (most recent call last):
  File "E:/python/fileread.py", line 4, in <module>
    if my in line:
TypeError: 'in <string>' requires string as left operand, not list
</code>```

答:
The reason for your error:

The in operator as used in:

```<code>if my in line: ...
   ^       ^
   |_ left | hand side
           |
           |_ right hand side
</code>```

for a string operand on the right side (i.e. line) requires a corresponding string operand on the left hand side. This operand consistency check is implemented by the str.__contains__ method, where the call to __contains__ is made from the string on the right hand side (see cpython implemenetation). Same as:

```<code>if line.__contains__(my): ...
</code>```

You're however passing a list, my, instead of a string.

An easy way to resolve this is by check that any  of the items in the list are contained in the current line using the builtin any  function:

```<code>for line in fopen:
    if any(item in line for item in my):
       ...
</code>```

Or since you have just two items use the or operator (pun unintended) which short-circuits in the same way as any:

```<code>for line in fopen:
    if 'cbs is down' in line or 'abnormal' in line:
       ...
</code>```

Body:
I have a list name my= ['cbs is down','abnormal']
and I have opened a file in read mode

Now I want to search any of the string available in list that exist in that file and perform the if action

fopen  =  open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
    if my in line:
            print ("down")

and when I execute it, I get the following

Traceback (most recent call last):
  File "E:/python/fileread.py", line 4, in <module>
    if my in line:
TypeError: 'in <string>' requires string as left operand, not list

Body:
The reason for your error:

The in operator as used in:

if my in line: ...
   ^       ^
   |_ left | hand side
           |
           |_ right hand side

for a string operand on the right side (i.e. line) requires a corresponding string operand on the left hand side. This operand consistency check is implemented by the str.__contains__ method, where the call to __contains__ is made from the string on the right hand side (see cpython implemenetation). Same as:

if line.__contains__(my): ...

You're however passing a list, my, instead of a string.

An easy way to resolve this is by check that any  of the items in the list are contained in the current line using the builtin any  function:

for line in fopen:
    if any(item in line for item in my):
       ...

Or since you have just two items use the or operator (pun unintended) which short-circuits in the same way as any:

for line in fopen:
    if 'cbs is down' in line or 'abnormal' in line:
       ...


问:
Ionic state reset not working
I had an older Ionic app, it was built a little bit ago, and I wanted to update some of it and reset the state. I updated the Ionic CLI and Cordova, and then I also did a state reset by doing: sudo ionic state reset

Every time I do this I receive this I receive the same error when it tries to update the Ionic keyboard plugin. This error never shows up if I do a state reset before updating the CLI, but it only shows up after. Tried manually adding and removing the plugin but it doesn't show up when using cordova plugins list Any help would be nice. Here's the error:

```<code>Removed platforms and plugins
Attempting to restore your Ionic application from package.json

Restoring Platforms

cordova platform add browser
cordova platform add ios

Restore platforms is complete

Restoring Plugins

cordova plugin add cordova-plugin-device
cordova plugin add cordova-plugin-console
cordova plugin add cordova-plugin-splashscreen
cordova plugin add com.ionic.keyboard

/usr/local/lib/node_modules/ionic/node_modules/ionic-app-lib/lib/state.js:543
        throw 'Error executing "' + pluginCommand + '":\n' + output;
        ^
Error executing "cordova plugin add com.ionic.keyboard":
Fetching plugin "com.ionic.keyboard" via npm
Error: Failed to fetch plugin com.ionic.keyboard via registry.
Probably this is either a connection problem, or plugin spec is incorrect.
Check your connection and plugin name/version/URL.
Error: Registry returned 404 for GET on https://registry.npmjs.org/com.ionic.keyboard
</code>```

答:
state has been removed from CLI v3. So on cordova 7 you need to run:</p>

```<code>ionic cordova prepare
</code>```

Title: Ionic state reset not working

Body:
I had an older Ionic app, it was built a little bit ago, and I wanted to update some of it and reset the state. I updated the Ionic CLI and Cordova, and then I also did a state reset by doing: sudo ionic state reset

Every time I do this I receive this I receive the same error when it tries to update the Ionic keyboard plugin. This error never shows up if I do a state reset before updating the CLI, but it only shows up after. Tried manually adding and removing the plugin but it doesn't show up when using cordova plugins list Any help would be nice. Here's the error:

Removed platforms and plugins
Attempting to restore your Ionic application from package.json

Restoring Platforms

cordova platform add browser
cordova platform add ios

Restore platforms is complete

Restoring Plugins

cordova plugin add cordova-plugin-device
cordova plugin add cordova-plugin-console
cordova plugin add cordova-plugin-splashscreen
cordova plugin add com.ionic.keyboard

/usr/local/lib/node_modules/ionic/node_modules/ionic-app-lib/lib/state.js:543
        throw 'Error executing "' + pluginCommand + '":\n' + output;
        ^
Error executing "cordova plugin add com.ionic.keyboard":
Fetching plugin "com.ionic.keyboard" via npm
Error: Failed to fetch plugin com.ionic.keyboard via registry.
Probably this is either a connection problem, or plugin spec is incorrect.
Check your connection and plugin name/version/URL.
Error: Registry returned 404 for GET on https://registry.npmjs.org/com.ionic.keyboard

Body:
state has been removed from CLI v3. So on cordova 7 you need to run:

ionic cordova prepare


问:
Procedure pointers in RPGLE (PROCPTR)
Can anyone provide any interesting usage examples of these?</p>

答: For example, CEEHDLR/CEEHDLU (un)registers a user-written condition handler for the current stack (entry) frame. </p>

ContentLicense: CC BY-SA 2.5

Title: Procedure pointers in RPGLE (PROCPTR)


问:
Mirth channel XML : how to read value from inside of an element
How to read a list of values from Mirth Channel XML's <mapping> element? I can use msg to read one value. But what if there are list of values? Example:

```<code><patient>
    <name>names</name>
<patient>
</code>```

If there is one value fornames defined, then simply performing <mapping>msg['patient']['name']</mapping> will return the value. But how to get only values if the names return more than one name? How to iterate and display in the same XML? I am doing Mirth for the first time and any help is appreciated.

答:
I understand your question in this way.. so you mean if you receive the XML in this fashion

```<code><patient>
    <name>names</name>
    <name>name1</name>
</patient>
</code>```

then how to iterate and fetch only 'name' tags value. If my understanding is correct then place the below code in your source transformer.

```<code>var nameLen = msg['name'].length();
for(i=0;i<nameLen;i++){
    // Your Mapping Logic
    logger.debug(msg['name'][i].toString());
}
</code>```

Body:
How to read a list of values from Mirth Channel XML's <mapping> element? I can use msg to read one value. But what if there are list of values? Example:

<patient>
    <name>names</name>
<patient>

If there is one value fornames defined, then simply performing <mapping>msg['patient']['name']</mapping> will return the value. But how to get only values if the names return more than one name? How to iterate and display in the same XML? I am doing Mirth for the first time and any help is appreciated.

Body:
I understand your question in this way.. so you mean if you receive the XML in this fashion

<patient>
    <name>names</name>
    <name>name1</name>
</patient>

then how to iterate and fetch only 'name' tags value. If my understanding is correct then place the below code in your source transformer.

var nameLen = msg['name'].length();
for(i=0;i<nameLen;i++){
    // Your Mapping Logic
    logger.debug(msg['name'][i].toString());
}


问:
Single cell or multiple cells?
I'm working on an iOS project, writing in Swift. It's a social network app where people have profiles and they can post different type of content. There should be 9 type of posts/content:

Normal (text only) post

Images post

Gif post

Video post

Audio post

Quote post

Chat post

Poll post

Link post

My question is related to how should I display it on the feed. The feed obviously would be some type of a collection (I think I'll stick with UICollectionView) but should I create 1 type of a cell, add every single element that I might need to display each type of a content embedded into a UIStackView and if it's the database request returns nil for an object (i.e that particular post doesn't have video or an audio, a poll, etc - all it contains is just some images) then I'll hide those UIStackViews from the cell OR should I create a separate type of a cell and its xib file, depending on the the content type?

I feel like the latter would be easier, but I'm not how to that? Meaning, how should I check what type of a content is it? Imagine something like Twitter for example, you see many different type of content, how should you approach the cell creation and displaying them?

PS: Keep in mind that the users should be able to filter their content based on the content type (i.e display only images, only text, only audio, etc). How should I approach this?

答: Better option is create the different cell for different posts/content, and use the model classes variable/enum for know which type of content is it. its easy for filtering and managing the all type of posts.</p>

Title: Single cell or multiple cells?


问:
Drool condition in different lines vs condition in same line
I have a rule as follows --

```<code>when
      $myobj :
                       myObject( eval( condition1))//new line
                       myObject( eval(condition 2) && condition3)
</code>```

In above case if my condition2 is evaluating to false even then condition 3 is executed.

However in my below code where all conditions are in same line, the short circuit && works as expected - when condition 2 is false , condition 3 is not evaluated.

```<code>when
      $myobj :
                       myObject( eval( condition1) && eval(condition 2) && condition3))
</code>```

Why are the above blocks of code behaving differently

答:
Drools syntax is free-format and line ends do not matter.

The two left hand sides are fundamentally different.

```<code>myObject( eval( condition1) )
myObject( eval( condition2 ) && condition3 )
</code>```

The preceding LHS matches if you have one myObject fulfilling all constraints or if you have one myObject matching condition1 and another myObject matching condition2 and condition3.

```<code>myObject( eval( condition1 ) && eval( condition2 ) && condition3 )
</code>```

The preceding pattern requires all three constraints to be true for one myObject.

Body:
I have a rule as follows --

when
      $myobj :
                       myObject( eval( condition1))//new line
                       myObject( eval(condition 2) && condition3)

In above case if my condition2 is evaluating to false even then condition 3 is executed.

However in my below code where all conditions are in same line, the short circuit && works as expected - when condition 2 is false , condition 3 is not evaluated.

when
      $myobj :
                       myObject( eval( condition1) && eval(condition 2) && condition3))

Why are the above blocks of code behaving differently

Body:
Drools syntax is free-format and line ends do not matter.

The two left hand sides are fundamentally different.

myObject( eval( condition1) )
myObject( eval( condition2 ) && condition3 )

The preceding LHS matches if you have one myObject fulfilling all constraints or if you have one myObject matching condition1 and another myObject matching condition2 and condition3.

myObject( eval( condition1 ) && eval( condition2 ) && condition3 )

The preceding pattern requires all three constraints to be true for one myObject.


问:
What is the difference between match_parent and fill_parent?
I'm a little confused about two XML properties: match_parent and fill_parent. It seems that both are the same. Is there any difference between them?

答: FILL_PARENT was renamed MATCH_PARENT in API Level 8 and higher which means that the view wants to be as big as its parent (minus padding) - Google</p>


问:
Distinct count of users grouped by a column and distributed across bins
I have several users that each have a department they belong to and a integer which denotes (in days) when they last logged in.
A user can have several departments.

I am trying to group the users by department, vertically distribute them across three bins depending on when they logged in, and then uniquely count them.
If a user belongs to several departments i only want to count them once, it dosen't matter under which department they are being counted.

In my current solution a user with several departments gets counted once for
each department, which, given my solution, makes sense, but is not what I want.
If i try a distinct count it returns the same as each row is unique.

I'm using the MsSql Fiddle example except that I have added a DaysSinceLastLogin (int) column that denotes when the user last logged in.
Uncomment the first sql block to see the 6 users and which departments they belong to.
Fiddle here

答:
Try this:

```<code> WITH DataSource AS
 (
     SELECT *
          ,ROW_NUMBER() OVER (PARTITION BY [User] ORDER BY (SELECT 1))   AS [RowID]
     FROM yourtable
)
select Department,
COUNT(case when DaysSinceLastLogin < 10 then 1 end) as 'Last Login within 10 days',
COUNT(case when DaysSinceLastLogin > 10 and  DaysSinceLastLogin <= 20 then 1 end) as 'Last Login within 10-20 days',
COUNT(case when DaysSinceLastLogin > 20  then 1 end) 'Last Login more then 20 days'
FROM DataSource
WHERE [RowID] = 1
GROUP BY Department;
</code>```

The idea is to use ROW_NUMBER to set ID for each department for particular user. Then to get data only for the first one of this departments.

Body:
Try this:

 WITH DataSource AS
 (
     SELECT *
          ,ROW_NUMBER() OVER (PARTITION BY [User] ORDER BY (SELECT 1))   AS [RowID]
     FROM yourtable
)
select Department,
COUNT(case when DaysSinceLastLogin < 10 then 1 end) as 'Last Login within 10 days',
COUNT(case when DaysSinceLastLogin > 10 and  DaysSinceLastLogin <= 20 then 1 end) as 'Last Login within 10-20 days',
COUNT(case when DaysSinceLastLogin > 20  then 1 end) 'Last Login more then 20 days'
FROM DataSource
WHERE [RowID] = 1
GROUP BY Department;

The idea is to use ROW_NUMBER to set ID for each department for particular user. Then to get data only for the first one of this departments.


问:
iphone app on windows or android mobile
Can iphone apps run on windows or android phones?

Is there any tool or framework available?

答:
PhoneGap is also multiplatform.

Supports iPhone, Android, Windows Mobile, Blackberry, and more.

http://www.phonegap.com/

From their website:

PhoneGap is an open source development
  framework for building cross-platform
  mobile apps. Build apps in HTML and
  JavaScript and still take advantage of
  core features in iPhone/iPod touch,
  iPad, Google Android, Palm, Symbian
  and Blackberry SDKs.

Title: iphone app on windows or android mobile


问:
Selenium webdriver Exceptional
Getting this exceptional

```<code>Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
    at com.google.common.base.Preconditions.checkState(Preconditions.java:738)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
    at org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
    at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:115)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:330)
    at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:104)
    at dT.Dt.main(Dt.java:21)
</code>```

答:
You need to use geckodriver to interact with Firefox since Selenium 3.0.
Download the geckodriver.exe.

And then add the below code before driver initialization.

```<code>System.setProperty("webdriver.gecko.driver","c:/your/path/to/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
</code>```

Title: Selenium webdriver Exceptional

Body:
Getting this exceptional

Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
    at com.google.common.base.Preconditions.checkState(Preconditions.java:738)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
    at org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
    at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:115)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:330)
    at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:104)
    at dT.Dt.main(Dt.java:21)

Body:
You need to use geckodriver to interact with Firefox since Selenium 3.0.
Download the geckodriver.exe.

And then add the below code before driver initialization.

System.setProperty("webdriver.gecko.driver","c:/your/path/to/geckodriver.exe");
WebDriver driver = new FirefoxDriver();


问:
PowerShell disable and enable a driver
Sometimes after restart/coldboot I got a problem with my touchscreen driver in Win8, so I've to restart it manually by now.

So I want to write a script that starts after login, which will disable the driver and enables it again.

I actually found out to find the driver and that I can get a object list of the drivers via:

```<code>Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like "I2C*"}
</code>```

But adding "| Disable-Device" to the end of the line will not work.

Can anyone tell me how I have to write the command correctly and start the script like an batch file?

答:
at least with Windows 10 it is a lot easier:</p>

```<code>$d = Get-PnpDevice| where {$_.friendlyname -like "I2Cwhatever*"}
$d  | Disable-PnpDevice -Confirm:$false
$d  | Enable-PnpDevice -Confirm:$false
</code>```

Title: PowerShell disable and enable a driver

Body:
Sometimes after restart/coldboot I got a problem with my touchscreen driver in Win8, so I've to restart it manually by now.

So I want to write a script that starts after login, which will disable the driver and enables it again.

I actually found out to find the driver and that I can get a object list of the drivers via:

Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like "I2C*"}

But adding "| Disable-Device" to the end of the line will not work.

Can anyone tell me how I have to write the command correctly and start the script like an batch file?

Body:
at least with Windows 10 it is a lot easier:

$d = Get-PnpDevice| where {$_.friendlyname -like "I2Cwhatever*"}
$d  | Disable-PnpDevice -Confirm:$false
$d  | Enable-PnpDevice -Confirm:$false


问:
Inserting snippets from macros
In Visual Studio 2008 I had a macro which would insert a snippet and input today's date in one of the replacements. When I try to run this macro in VS 2010 it doesn't work. No matter how I try it will not insert a snippet. When I try the following command:

```<code>DTE.ExecuteCommand("Edit.InvokeSnippetFromShortcut", "snippetName")
</code>```

This fails with error "Error HRESULT E_FAIL has been returned from a call to a COM component.

I tried recording a new macro and when I pressed the keyboard shortcut for inserting a snippet (Ctrl+K, Ctrl+X) VS gave the error "The command Insert Snippet is not currently available."

Did MS remove the ability to insert snippets from macros? If so this really is a shame because macros have functionality not found in snippets and vice versa.

答:
I finally had some time to revisit this and found a solution.

While I cannot use the "Edit.InvokeSnippetFromShortcut" command the workaround is as follows:

```<code>DTE.ActiveDocument.Selection.Text = "snippetshortcut"
DTE.ExecuteCommand("Edit.InsertTab")
DTE.ExecuteCommand("Edit.InsertTab")
</code>```

In VS 2008 you only had to have the 1 call to DTE.ExecuteCommand("Edit.InsertTab"). For whatever reason you need 2 now in order for the snippet to work.

Title: Inserting snippets from macros

Body:
In Visual Studio 2008 I had a macro which would insert a snippet and input today's date in one of the replacements. When I try to run this macro in VS 2010 it doesn't work. No matter how I try it will not insert a snippet. When I try the following command:

DTE.ExecuteCommand("Edit.InvokeSnippetFromShortcut", "snippetName")

This fails with error "Error HRESULT E_FAIL has been returned from a call to a COM component.

I tried recording a new macro and when I pressed the keyboard shortcut for inserting a snippet (Ctrl+K, Ctrl+X) VS gave the error "The command Insert Snippet is not currently available."

Did MS remove the ability to insert snippets from macros? If so this really is a shame because macros have functionality not found in snippets and vice versa.

Body:
I finally had some time to revisit this and found a solution.

While I cannot use the "Edit.InvokeSnippetFromShortcut" command the workaround is as follows:

DTE.ActiveDocument.Selection.Text = "snippetshortcut"
DTE.ExecuteCommand("Edit.InsertTab")
DTE.ExecuteCommand("Edit.InsertTab")

In VS 2008 you only had to have the 1 call to DTE.ExecuteCommand("Edit.InsertTab"). For whatever reason you need 2 now in order for the snippet to work.


问:
Reduce durability to improve performace in db2
In db2 10.5, is it possible that  transaction commit  does not wait for log IO to finish and return control to the client, like SQL server's delayed durability?
Is there any way to reduce the number of log IOs when there are large number of serial small transactions?</p>

答:
Db2 LUW has a database configuration parameter called mincommit. The value of mincommit indicates how many transactions will commit before flushing out the log buffer to disk. This is probably what you are looking for.

From Db2 LUW v10.5 and higher, this parameter is ignored, and the value is only meaningful on versions of Db2 LUW up to v10.1.

For older versions of Db2 LUW, the recommendation is to leave the value at 1. In most cases there is no performance improvement while at the same time introducing risk. Hence, the configuration parameter has been deprecated in version 10.1. My advice: Do not use it even though it still exists.


问:
Ext.ux app build vs app watch (ExtJS 6.2.0 GPL)
I have a problem I cannot solve regardless of books and google - but I assume is stupidly simple to answer for someone more skilled than me :-)

Using CMD 6.5.2 and ExtJS 6.2.0 GPL

I am trying to build a desktop application, using the sample desktop as a starting point.

I can get my desktop up and running fine, modify it, show my data - as long as I use "sencha app watch classic".

I have put "ux" in the requires list in app.json, and also using extend: 'Ext.ux.desktop.App' in Application.js

So running "sencha app watch classic" shows me my desktop, but running "sencha app build classic production", and then moving the files in build/production/Desktop/ to my web server does not work at all.

I get an error like this in Chrome console: GET http://localhost/desktop/.js 404 (Not Found) (index) : 72

So the script is trying to load a js-file with an empty name, this is quite hard to explore for me, a more verbose error would have been nice :-)

Anyone have a clue as to what is going on?!

//Jonas

答:
When you open your uncompiled version of the application in a browser (through a local web server), you may see one or more of the following warnings in the browser console:

[W] [Ext.Loader] Synchronously loading 'MyApp.view.Test'; consider adding Ext.require('MyApp.view.Test') above Ext.onReady

This means that you reference MyApp.view.Test somewhere, but the app does not know it is required, and thus does not load it beforehand - nor compiles it into the built version.


问:
Showing error while i am trying to insert data to table SQLite
SQLite Create table Query MainActivity

```<code>sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS DETAILS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, phone VARCHAR, location VARCHAR, remarks VARCHAR)");
</code>```

insert data query SQLiteHelper.class

```<code>  public void insertData(String name, String phone, String location,String remarks)
{
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO DETAILS VALUES (NULL,?, ?, ?, ?)";
    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, phone);
    statement.bindString(3, location);
    statement.bindString(4, remarks);

    statement.executeInsert();
}
</code>```

OnClick Save MainActivity.class

```<code> mSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

           try {
                sqLiteHelper.insertData(
                        eName.getText().toString().trim(),
                        ePhonenumber.getText().toString().trim(),
                        eLocation.getText().toString().trim(),
                        eRemarks.getText().toString().trim());

                Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
                eName.setText("");
                ePhonenumber.setText("");
                eLocation.setText("");
                eRemarks.setText("");

                }
                catch(Exception e){
                    e.printStackTrace();
                }

            }

    });
</code>```

Error while inserting data into table: It was working fine previously when i didn't added the remarks column

```<code>E/SQLiteLog: (1) table DETAILS has 4 columns but 5 values were supplied
W/System.err: android.database.sqlite.SQLiteException: table DETAILS has 4  columns but 5 values were supplied (code 1): , while compiling: INSERT INTO DETAILS VALUES (NULL,?, ?, ?, ?)

W/System.err:     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
W/System.err:     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
W/System.err:     at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1070)
W/System.err:     at com.example.alpha.SQLiteHelper.insertData(SQLiteHelper.java:28)
W/System.err:     at com.example.alpha.MainActivity$1.onClick(MainActivity.java:61)
</code>```

答:
Edit Insert query.</p>

```<code>public void insertData(String name, String phone, String location,String remarks)
{
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO DETAILS VALUES (?, ?, ?, ?)";
    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, phone);
    statement.bindString(3, location);
    statement.bindString(4, remarks);

    statement.executeInsert();
}
</code>```

Body:
SQLite Create table Query MainActivity

sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS DETAILS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, phone VARCHAR, location VARCHAR, remarks VARCHAR)");

insert data query SQLiteHelper.class

  public void insertData(String name, String phone, String location,String remarks)
{
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO DETAILS VALUES (NULL,?, ?, ?, ?)";
    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, phone);
    statement.bindString(3, location);
    statement.bindString(4, remarks);

    statement.executeInsert();
}

OnClick Save MainActivity.class

 mSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

           try {
                sqLiteHelper.insertData(
                        eName.getText().toString().trim(),
                        ePhonenumber.getText().toString().trim(),
                        eLocation.getText().toString().trim(),
                        eRemarks.getText().toString().trim());

                Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
                eName.setText("");
                ePhonenumber.setText("");
                eLocation.setText("");
                eRemarks.setText("");

                }
                catch(Exception e){
                    e.printStackTrace();
                }

            }

    });

Error while inserting data into table: It was working fine previously when i didn't added the remarks column

E/SQLiteLog: (1) table DETAILS has 4 columns but 5 values were supplied
W/System.err: android.database.sqlite.SQLiteException: table DETAILS has 4  columns but 5 values were supplied (code 1): , while compiling: INSERT INTO DETAILS VALUES (NULL,?, ?, ?, ?)

W/System.err:     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
W/System.err:     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
W/System.err:     at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1070)
W/System.err:     at com.example.alpha.SQLiteHelper.insertData(SQLiteHelper.java:28)
W/System.err:     at com.example.alpha.MainActivity$1.onClick(MainActivity.java:61)

Body:
Edit Insert query.

public void insertData(String name, String phone, String location,String remarks)
{
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO DETAILS VALUES (?, ?, ?, ?)";
    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, phone);
    statement.bindString(3, location);
    statement.bindString(4, remarks);

    statement.executeInsert();
}


问:
How can I make a class diagram for F#?
I am using Visual Studio 2015 with F#.  In C# projects, you can create class diagram files (*.cd) to visualize the types in your solution and their dependencies on each other.  Is there anything available like that for F#?

I tried manually creating a *.cd in my project but a dialog popped up saying that those diagrams are only supported for C#, C++, and VB.

I also have Resharper, which has a Type Dependency diagram tool, which also does not work with F# projects.

答:
If you are looking just to visualize your types relation, you can use dotPeek from Resharper.

In dotPeek:

Load the dll of your f# project.

Select the types you want in the menu on the right.

Click on the Inspect/Show Type Dependency Diagram

Title: How can I make a class diagram for F#?


问:
Disable a division
I want to disable a division using the click function

For Example:
I am having a search box on my website. After clicking the search box all the things in my website must be disabled except the search box suggestions

Thanks

答:
The pointer-events property allows for control over how HTML elements respond to mouse/touch events – including CSS hover/active states, click/tap events in Javascript, and whether or not the cursor is visible.

add pointer-events: none; CSS in div for disable

$("div").on("click",function(){
 alert("test");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{width:50px;height:50px;margin:5px;}
#div1{background-color:pink;}
#div2{background-color:lightgrey;}
.disable{pointer-events: none;}</code>```

enable

disable
```

Title: Disable a division

Body:
The pointer-events property allows for control over how HTML elements respond to mouse/touch events – including CSS hover/active states, click/tap events in Javascript, and whether or not the cursor is visible.

add pointer-events: none; CSS in div for disable

$("div").on("click",function(){
 alert("test");
});

div{width:50px;height:50px;margin:5px;}
#div1{background-color:pink;}
#div2{background-color:lightgrey;}
.disable{pointer-events: none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">enable</div>
<div id="div2" class="disable">disable</div>


问:
How to Generate CSV File from PHP Form?
Aware this has been asked before but the solutions I found didn't help.

Currently I receive an email when a user completes the form on my website to download the brochure. I would like to have these details; Name, telephone, email and city store in a CSV file, which I can then manually add to Mailchimp or other site.

PHP:

```<code><?php
  $name    = $_POST['fname'];
  $email   = $_POST['email_from'];
  $phone   = $_POST['phone'];
  $city    = $_POST['city'];
  $content = $_POST['comments'];
  $to      = 'C.PAN@email.com';
  $subject = 'Enquiry';

  $headers = "From: " . strip_tags($email) . "\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

  $message = '<html><body>';
  $message .= '<table rules="all"  cellpadding="10">';
  $message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . $name . "</td></tr>";
  $message .= "<tr style='background: #eee;' ><td><strong>Email:</strong> </td><td>" . $email . "</td></tr>";
  $message .= "<tr style='background: #eee;'><td><strong>Phone:</strong> </td><td>" . $phone . "</td></tr>";
  $message .= "<tr style='background: #eee;'><td><strong>City:</strong> </td><td>" . $city . "</td></tr>";
  $message .= "<tr style='background: #eee;'><td><strong>Message:</strong> </td><td>" . $content . "</td></tr>";
  $message .= "</table>";
  $message .= "</body></html>";

            //Creates the csv file.
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=downloadcsv.csv');

            $dataRow = [
            'first_name' => $name,
            'email' => $email,
            'phone' => $phone,
            'city' => $city,
            'comments' => $comments,
            ];
            $fp = fopen($downloadcsv, 'w');
            fputcsv($fp, $dataRow);
            fclose($fp);

      if (mail($to, $subject, $message, $headers))
      {
      header('brochure.pdf');
      }
?>
</code>```

HTML:

```<code><form name="myForm" action="amail_brochure.php" method="post" onsubmit="return validateForm()" class="sidebar-form" accept-charset="ISO-8859-1">
  <div class="main-form">
    <div>
      <input type="text" class="form-control" name="fname" placeholder="Vollständiger Name" required="required"/>
    </div>
    <div>
      <input type="email" class="form-control" name="email_from" id="email_from" placeholder="Email" required="required" />
    </div>
    <div>
      <input type="text" class="form-control" name="phone" placeholder="Telefon" required="required"/>
    </div>
    <div>
      <input type="text" class="form-control" name="city" placeholder="Deine Stadt" required="required" />
    </div>
    <textarea name="comments" id="" rows="6" class="form-control" placeholder="Comments:"></textarea>
    <div class="button-container" style="display: inline-block;">
      <button class="btn cta-button pull-right form-submit" type="submit" formtarget="_blank">Download</button>
    </div>
  </div>
</form>
</code>```

Any help to implement exporting the users information into a CSV file would be greatly appreciated.

With thanks,

答:
Put your data into an array and use fputcsv.</p>

```<code>$name=$_POST['fname'];
$email=$_POST['email_from'];
$phone=$_POST['phone'];
$city=$_POST['city'];
$content=$_POST['comments'];
$dataRow = [
    'first_name' => $name,
    'email' => $email,
    'phone' => $phone,
    'city' => $city,
    'comments' => $comments,
];
// You need to decide where you want the CSV file stored and since you are receiving lots of them you might want to use a timestamp in the filename. If you want the CSV file as part of the email you will need to attach it to the mail() message.
$csvFile = 'some/file/path/csvfile.csv';
$fp = fopen($csvFile, 'w');
fputcsv($fp, $dataRow);
fclose($fp);
</code>```

Title: How to Generate CSV File from PHP Form?

Body:
Aware this has been asked before but the solutions I found didn't help.

Currently I receive an email when a user completes the form on my website to download the brochure. I would like to have these details; Name, telephone, email and city store in a CSV file, which I can then manually add to Mailchimp or other site.

PHP:

<?php
  $name    = $_POST['fname'];
  $email   = $_POST['email_from'];
  $phone   = $_POST['phone'];
  $city    = $_POST['city'];
  $content = $_POST['comments'];
  $to      = 'C.PAN@email.com';
  $subject = 'Enquiry';

  $headers = "From: " . strip_tags($email) . "\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

  $message = '';
  $message .= '
';
  $message .= "
Name: 	" . $name . "
";
  $message .= "
Email: 	" . $email . "
";
  $message .= "
Phone: 	" . $phone . "
";
  $message .= "
City: 	" . $city . "
";
  $message .= "
Message: 	" . $content . "
";
  $message .= "
";
  $message .= "";

            //Creates the csv file.
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=downloadcsv.csv');

            $dataRow = [
            'first_name' => $name,
            'email' => $email,
            'phone' => $phone,
            'city' => $city,
            'comments' => $comments,
            ];
            $fp = fopen($downloadcsv, 'w');
            fputcsv($fp, $dataRow);
            fclose($fp);

      if (mail($to, $subject, $message, $headers))
      {
      header('brochure.pdf');
      }
?>

HTML:

<form name="myForm" action="amail_brochure.php" method="post" onsubmit="return validateForm()" class="sidebar-form" accept-charset="ISO-8859-1">

      <input type="text" class="form-control" name="fname" placeholder="Vollständiger Name" required="required"/>

      <input type="email" class="form-control" name="email_from" id="email_from" placeholder="Email" required="required" />

      <input type="text" class="form-control" name="phone" placeholder="Telefon" required="required"/>

      <input type="text" class="form-control" name="city" placeholder="Deine Stadt" required="required" />

    <textarea name="comments" id="" rows="6" class="form-control" placeholder="Comments:"></textarea>

      <button class="btn cta-button pull-right form-submit" type="submit" formtarget="_blank">Download</button>

</form>

Any help to implement exporting the users information into a CSV file would be greatly appreciated.

With thanks,

Body:
Put your data into an array and use fputcsv.

$name=$_POST['fname'];
$email=$_POST['email_from'];
$phone=$_POST['phone'];
$city=$_POST['city'];
$content=$_POST['comments'];
$dataRow = [
    'first_name' => $name,
    'email' => $email,
    'phone' => $phone,
    'city' => $city,
    'comments' => $comments,
];
// You need to decide where you want the CSV file stored and since you are receiving lots of them you might want to use a timestamp in the filename. If you want the CSV file as part of the email you will need to attach it to the mail() message.
$csvFile = 'some/file/path/csvfile.csv';
$fp = fopen($csvFile, 'w');
fputcsv($fp, $dataRow);
fclose($fp);


问:
Consider marking one of the beans as @Primary
In my Java spring application, I have

```<code>public class BinarySearchImpl {

    @Autowired
    @Qualifier("Quick")
    SortAlgorithem sorter;

    Log log=LogFactory.getLog(BinarySearchImpl.class);

    public BinarySearchImpl(SortAlgorithem sorter) {
        log.info("Binary Search Bean is created");
        this.sorter=sorter;
    }
</code>```

SortAlgorithem is an interface which makes my application loosely coupled:

```<code>public interface SortAlgorithem {

    public int[] sort(int[] arrayNumbers);

}
</code>```

And then there are 2 implementations for this interface. One is BubbleSort:

```<code>@Component
@Qualifier("Bubble")
public class BubbleSort implements SortAlgorithem {

    Log log=LogFactory.getLog(BubbleSort.class);

    public int[] sort(int[] numbers) {
        log.info("Bubble sort is called");
        return numbers;
    }
}
</code>```

and the other is QuickSort:

```<code>@Component
@Qualifier("Quick")
//@Primary
public class QuickSort implements SortAlgorithem{

    Log log= LogFactory.getLog(QuickSort.class);

    public int[] sort(int[] numbers) {
        log.info("Quick Sort is called");
        return numbers;
    }

}
</code>```

At the end, when I call my app it complains with this message:

```<code>Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
</code>```

I am wondering... Why @Qualifier annotation does not work?

答:
You have annotated a field with @Autowired and @Qualifier, but you have also created a constructor which sets the field.

I think that Spring is using the constructor, but doesn't automatically know that the constructor parameter corresponds to the annotated field.

So move the annotations into the constructor declaration:

```<code>private SortAlgorithm sorter;

@Autowired
public BinarySearchImpl(@Qualifier("quick") SortAlgorithm sorter) {
     this.sorter = sorter;
}
</code>```

Alternatively, you could use a zero-arg constructor, keep your field annotation and let Spring inject using reflection. However in my opinion constructor-injection is better -- it allows you to unit test cleanly, without involving Spring or reflection.

As other answers point out, there are other ways to disambiguate autowired beans -- and the Spring docs explain them all -- but using qualifiers like this does work.

Body:
In my Java spring application, I have

public class BinarySearchImpl {

    @Autowired
    @Qualifier("Quick")
    SortAlgorithem sorter;

    Log log=LogFactory.getLog(BinarySearchImpl.class);

    public BinarySearchImpl(SortAlgorithem sorter) {
        log.info("Binary Search Bean is created");
        this.sorter=sorter;
    }

SortAlgorithem is an interface which makes my application loosely coupled:

public interface SortAlgorithem {

    public int[] sort(int[] arrayNumbers);

}

And then there are 2 implementations for this interface. One is BubbleSort:

@Component
@Qualifier("Bubble")
public class BubbleSort implements SortAlgorithem {

    Log log=LogFactory.getLog(BubbleSort.class);

    public int[] sort(int[] numbers) {
        log.info("Bubble sort is called");
        return numbers;
    }
}

and the other is QuickSort:

@Component
@Qualifier("Quick")
//@Primary
public class QuickSort implements SortAlgorithem{

    Log log= LogFactory.getLog(QuickSort.class);

    public int[] sort(int[] numbers) {
        log.info("Quick Sort is called");
        return numbers;
    }

}

At the end, when I call my app it complains with this message:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

I am wondering... Why @Qualifier annotation does not work?

Body:
You have annotated a field with @Autowired and @Qualifier, but you have also created a constructor which sets the field.

I think that Spring is using the constructor, but doesn't automatically know that the constructor parameter corresponds to the annotated field.

So move the annotations into the constructor declaration:

private SortAlgorithm sorter;

@Autowired
public BinarySearchImpl(@Qualifier("quick") SortAlgorithm sorter) {
     this.sorter = sorter;
}

Alternatively, you could use a zero-arg constructor, keep your field annotation and let Spring inject using reflection. However in my opinion constructor-injection is better -- it allows you to unit test cleanly, without involving Spring or reflection.

As other answers point out, there are other ways to disambiguate autowired beans -- and the Spring docs explain them all -- but using qualifiers like this does work.


问:
Why does streaming Dataset fail with "Complete output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets... "?
I use Spark 2.2.0 and have the following error with Spark Structured Streaming on windows:

Complete output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark.

答:
Complete output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark

Streaming aggregations require that you tell the Spark Structured Streaming engine when to output the aggregation (per so-called output mode) since the data that could be part of an aggregation might be late and available only after some time.

The "some time" part is event lateness and described as the time that is watermark ago from the current time.

That's why you have to specify the watermark to let Spark drop/disregard any late events and stop accumulating state that could eventually lead to OutOfMemoryError or similar.

With that said, you should use withWatermark operator on your streaming Dataset.

withWatermark Defines an event time watermark for this Dataset. A watermark tracks a point in time before which we assume no more late data is going to arrive.

And quoting along...

Spark will use this watermark for several purposes:

To know when a given time window aggregation can be finalized and thus can be emitted when using output modes that do not allow updates.

To minimize the amount of state that we need to keep for on-going aggregations, mapGroupsWithState and dropDuplicates operators.

The current watermark is computed by looking at the MAX(eventTime) seen across all of the partitions in the query minus a user specified delayThreshold. Due to the cost of coordinating this value across partitions, the actual watermark used is only guaranteed to be at least delayThreshold behind the actual event time. In some cases we may still process records that arrive more than delayThreshold late.

Check out Spark Structured Streaming's Handling Late Data and Watermarking.


问:
Create RTF file using MFC
I have a task to create a rtf file in MFC. i.e. to read the data from xml file and parse the rft content and create the rtf file. I parsed the RTF content and created a file file1.rtf using CFile, but the output file doesnt display the content properly. Is there any other way to create the file.

Thanks in advance.

答: The simplest way I've found is to use a RichTextBox control (either on a dialog or created dynamically). Use the control's methods to build your content.</p>

Title: Create RTF file using MFC


问:
how to set the rw permission for log files managed by syslog?
I'm working on freebsd (but I think it's the same as on linux), and I'm using syslog to manage my log files, as defined in /etc/syslog.conf:

```<code>local1.notice                                   /var/log/my.log
</code>```

I noticed that my.log will have 600 access permission by default, but I do want to have 666 permission. How can I do this?

Thanks.

答:
Try this

```<code>$FileCreateMode 0666
local1.notice                                   /var/log/my.log
</code>```

Follow the below link.

http://www.rsyslog.com/doc/rsconf1_filecreatemode.html

Body:
I'm working on freebsd (but I think it's the same as on linux), and I'm using syslog to manage my log files, as defined in /etc/syslog.conf:

local1.notice                                   /var/log/my.log

I noticed that my.log will have 600 access permission by default, but I do want to have 666 permission. How can I do this?

Thanks.

Body:
Try this

$FileCreateMode 0666
local1.notice                                   /var/log/my.log

Follow the below link.

http://www.rsyslog.com/doc/rsconf1_filecreatemode.html


问:
Reading from text file and populate to Listbox with Button
I am trying to create a window program where the program reads from a text file and display the data in a listbox. I have tried the below coding but the problem now is that every time I click on the button, it will append and the data will repeat.

How do I do it so that it reads the file and only include new input data?

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
    {
        string line;
        // Read and display lines from the file until the end of
        // the file is reached.
        while ((line = sr.ReadLine()) != null)
        {
            Listbox1.Items.Add(line);
        }
        sr.Close();
    }
}
</code>```

答:
The probably most simple way to do what you want is to read all lines from the file into a collection, and then assign that collection to the ItemsSource property of your ListBox:</p>

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    Listbox1.ItemsSource = File.ReadAllLines(@"C:\Users\jason\Desktop\Outbound.txt");
}
</code>```

Body:
I am trying to create a window program where the program reads from a text file and display the data in a listbox. I have tried the below coding but the problem now is that every time I click on the button, it will append and the data will repeat.

How do I do it so that it reads the file and only include new input data?

private void Button_Click(object sender, RoutedEventArgs e)
{
    using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
    {
        string line;
        // Read and display lines from the file until the end of
        // the file is reached.
        while ((line = sr.ReadLine()) != null)
        {
            Listbox1.Items.Add(line);
        }
        sr.Close();
    }
}

Body:
The probably most simple way to do what you want is to read all lines from the file into a collection, and then assign that collection to the ItemsSource property of your ListBox:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Listbox1.ItemsSource = File.ReadAllLines(@"C:\Users\jason\Desktop\Outbound.txt");
}


问:
Getting selected text with cross frame scripting
I've been struggling with a problem for a few hours now, and I would appreciate either some help in accomplishing my goal, or confirmation that what I'm trying to do is in fact impossible.

I have a webapp that takes the selected text (document.getSelection()) as input, from an arbitrary webpage. While it would be possible to use a bookmarklet to do such scripting fairly easily, it's best for the end-user if I can accomplish this with an iframe.

The parent frame is my site with this script:

```<code>$('#frame').load(function(){
    // this event won't be triggered
    $(window).mouseup(function(){
        doStuff(window.getSelection());
    });

    // this will throw a security error
    $(window.frames[0].document).mouseup(function(){
        doStuff(window.frames[0].document.getSelection());
    });
});
</code>```

An arbitrary site is in the child frame. Unless the child document is from my domain, access is forbidden for XSS security reasons. I've tried several variations and attempted hacks, including setting the iframe src to my domain with the third party URL as an argument, and then redirecting to the third party URL. In a sense, I'm glad that it didn't work (because if it did, then XSS security would still have a long way to go...)

Another option would be downloading the third party page and serving it from my domain like a proxy server, but I've already run into a bunch of problems with relative paths to files, which are sometimes easy to make absolute, but sometimes a fool's errand (such as when the files are accessed via script).

I've concluded that I might just be out of luck. Perhaps an important distinction for my case is that I only want to access the .getSelection() method for the child. No need to be able to access cookies or keystrokes or interact with the DOM. Maybe it doesn't make a difference, but maybe it does.

答:
I didn't fully read your answer :-) but maybe I have a solution,
it involves passing data between parent and child frames, both ways.

You can WRITE (and not READ) the hash (hash is the http://url#HASH_PART) of parent from child.
So, on the parent iframe, just set interval to check the value, say every 50ms.

```<code>function checkHash() {
    if (window.location.hash == "#something") {
        // my child frame set this value using:
        //parent.window.location.hash = "something";
        doSomething();
    }
}
</code>```

For further details, and maybe doing parent to child communications, then
the full article explaining this (also has demo link) can be found here.

OwnerDisplayName: jamtoday

Body:
I've been struggling with a problem for a few hours now, and I would appreciate either some help in accomplishing my goal, or confirmation that what I'm trying to do is in fact impossible.

I have a webapp that takes the selected text (document.getSelection()) as input, from an arbitrary webpage. While it would be possible to use a bookmarklet to do such scripting fairly easily, it's best for the end-user if I can accomplish this with an iframe.

The parent frame is my site with this script:

$('#frame').load(function(){
    // this event won't be triggered
    $(window).mouseup(function(){
        doStuff(window.getSelection());
    });

    // this will throw a security error
    $(window.frames[0].document).mouseup(function(){
        doStuff(window.frames[0].document.getSelection());
    });
});

An arbitrary site is in the child frame. Unless the child document is from my domain, access is forbidden for XSS security reasons. I've tried several variations and attempted hacks, including setting the iframe src to my domain with the third party URL as an argument, and then redirecting to the third party URL. In a sense, I'm glad that it didn't work (because if it did, then XSS security would still have a long way to go...)

Another option would be downloading the third party page and serving it from my domain like a proxy server, but I've already run into a bunch of problems with relative paths to files, which are sometimes easy to make absolute, but sometimes a fool's errand (such as when the files are accessed via script).

I've concluded that I might just be out of luck. Perhaps an important distinction for my case is that I only want to access the .getSelection() method for the child. No need to be able to access cookies or keystrokes or interact with the DOM. Maybe it doesn't make a difference, but maybe it does.

Body:
I didn't fully read your answer :-) but maybe I have a solution,
it involves passing data between parent and child frames, both ways.

You can WRITE (and not READ) the hash (hash is the http://url#HASH_PART) of parent from child.
So, on the parent iframe, just set interval to check the value, say every 50ms.

function checkHash() {
    if (window.location.hash == "#something") {
        // my child frame set this value using:
        //parent.window.location.hash = "something";
        doSomething();
    }
}

For further details, and maybe doing parent to child communications, then
the full article explaining this (also has demo link) can be found here.


问:
4 thread groups in 1 test plan login time for 100 threads in all thread groups
I have included 4 Thread groups in one test plan and recorded script for all thread groups . As all ALL thread groups contain login script , so can i record time for first request of login from all the thread groups ? and then another 4 users entering system and login again and time is recorded -> this i have to do for 100 threads :::: first 4 users come then other 4 come and perform login .please tell if anyone could solve my issue .</p>

答:
If I got your scenario right you need to go for the following configuration:

Thread Group (Number of Threads: 4, Loop Count: 25)

HTTP Request sampler which performs login

Synchronizing Timer (Number of Simulated Users to Group By: 4)

This way you will have 100 requests in total, there will be 25 "login" loops when 4 virtual users will perform login at exactly the same moment.