问:
NodeJS: streaming multiple files from readstream (gridFS) to show on frontend
I have uploaded multiple image files into MongoDB using "Multer" and "multer-gridfs-storage". I want to extract these files and show them as thumbnails on the webpage. I have tried to extract these files into ReadStream and storing them into an array which i can loop.

```<code>var streams = [];
    console.log(result)
    for (var i = 0; i < result.length; i++) {

        var gfs = Grid(conn.db);
        var campground = gfs.createReadStream({
            _id: result[i]._id
        });
        streams[i] = campground;
        console.log("   " + i);
    }
</code>```

I want to pass these to the front end where they can be displayed, but they are not displaying. I tried running the following code in loop.

```<code>    var rest
    streams[0].pipe(rest)
    res.writeHead(200, { 'Content-Type': 'image/jpeg' });
    res.write(rest);
    //      res.addTrailers({ 'image/jpeg': rest });
    res.end();
</code>```

is not working. The following works but only displays one file

```<code> streams[i].pipe(res)
</code>```

I want to pass the array of images to my ejs file. The  streams[i] array is grid object and not the final images. How do i accomplish this?

Regards,
Gaurav

答:
Got the answer after some searching    </p>

```<code>    const bufs = [];
    readstream.on('data', function(chunk) {
        bufs.push(chunk);
    });
    readstream.on('end', function() {
        const fbuf = Buffer.concat(bufs);
        res.setHeader('Content-Type', 'image/jpeg');
        res.writeHead(res.statusCode);
        res.write(fbuf);
        /res.end();

    });
</code>```

Body:
I have uploaded multiple image files into MongoDB using "Multer" and "multer-gridfs-storage". I want to extract these files and show them as thumbnails on the webpage. I have tried to extract these files into ReadStream and storing them into an array which i can loop.

var streams = [];
    console.log(result)
    for (var i = 0; i < result.length; i++) {

        var gfs = Grid(conn.db);
        var campground = gfs.createReadStream({
            _id: result[i]._id
        });
        streams[i] = campground;
        console.log("   " + i);
    }

I want to pass these to the front end where they can be displayed, but they are not displaying. I tried running the following code in loop.

    var rest
    streams[0].pipe(rest)
    res.writeHead(200, { 'Content-Type': 'image/jpeg' });
    res.write(rest);
    //      res.addTrailers({ 'image/jpeg': rest });
    res.end();

is not working. The following works but only displays one file

 streams[i].pipe(res)

I want to pass the array of images to my ejs file. The  streams[i] array is grid object and not the final images. How do i accomplish this?

Regards,
Gaurav

Body:
Got the answer after some searching

    const bufs = [];
    readstream.on('data', function(chunk) {
        bufs.push(chunk);
    });
    readstream.on('end', function() {
        const fbuf = Buffer.concat(bufs);
        res.setHeader('Content-Type', 'image/jpeg');
        res.writeHead(res.statusCode);
        res.write(fbuf);
        /res.end();

    });


来源: stackexchange

问:
How to select/get drop down option in Selenium 2
I am converting my selenium 1 code to selenium 2 and can't find any easy way to select a label in a drop down menu or get the selected value of a drop down. Do you know how to do that in Selenium 2?

Here are two statements that work in Selenium 1 but not in 2:

```<code>browser.select("//path_to_drop_down", "Value1");
browser.getSelectedValue("//path_to_drop_down");
</code>```

答:
This method will return the selected value for the drop down,

```<code>public static String getSelected_visibleText(WebDriver driver, String elementType, String value)
  {
    WebElement element = Webelement_Finder.webElement_Finder(driver, elementType, value);
   Select Selector = new Select(element);
    Selector.getFirstSelectedOption();
    String textval=Selector.getFirstSelectedOption().getText();
    return textval;
  }
</code>```

Meanwhile

String textval=Selector.getFirstSelectedOption();

element.getText();

Will return all the elements in the drop down.

ContentLicense: CC BY-SA 3.0

Body:
I am converting my selenium 1 code to selenium 2 and can't find any easy way to select a label in a drop down menu or get the selected value of a drop down. Do you know how to do that in Selenium 2?

Here are two statements that work in Selenium 1 but not in 2:

browser.select("//path_to_drop_down", "Value1");
browser.getSelectedValue("//path_to_drop_down");

Body:
This method will return the selected value for the drop down,

public static String getSelected_visibleText(WebDriver driver, String elementType, String value)
  {
    WebElement element = Webelement_Finder.webElement_Finder(driver, elementType, value);
   Select Selector = new Select(element);
    Selector.getFirstSelectedOption();
    String textval=Selector.getFirstSelectedOption().getText();
    return textval;
  }

Meanwhile

String textval=Selector.getFirstSelectedOption();

element.getText();

Will return all the elements in the drop down.


问:
Read two bytes into an integer?
I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

```<code>byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist
</code>```

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

The above array is just an example. Actual values are unknown to me.

答: You can use ByteBuffer. It has the getInt method you are searching for and many other useful methods</p>

Title: Read two bytes into an integer?

Body:
I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

The above array is just an example. Actual values are unknown to me.

ContentLicense: CC BY-SA 2.5


问:
android:drawableLeft margin and/or padding
Is it possible to set the margin or padding for the image which we added with the android:drawableLeft?

答:
You should consider using layer-list

Create a drawable file like this, name it as ic_calendar.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="@android:color/transparent"/>
    </shape>
</item>
<item android:right="10dp">
    <bitmap android:gravity="center_vertical|left"
        android:src="@drawable/ic_calendar_16dp"
        android:tint="@color/red"
        />
</item>
</layer-list>
</code>```

Under layout file,

```<code><TextView
         android:id="@+id/tvDate"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:drawableLeft="@drawable/ic_calendar"
         android:textColor="@color/colorGrey"
         android:textSize="14sp"
    />
</code>```

Body:
You should consider using layer-list

Create a drawable file like this, name it as ic_calendar.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="@android:color/transparent"/>
    </shape>
</item>
<item android:right="10dp">
    <bitmap android:gravity="center_vertical|left"
        android:src="@drawable/ic_calendar_16dp"
        android:tint="@color/red"
        />
</item>
</layer-list>

Under layout file,

<TextView
         android:id="@+id/tvDate"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:drawableLeft="@drawable/ic_calendar"
         android:textColor="@color/colorGrey"
         android:textSize="14sp"
    />


问:
Color dialog and other dialogs not opening in ckeditor
I am using custom CKEditor(version:4.7.8) plugin in modal popup using jQuery.
It is working fine in chrome and FF but in IE 10 when I am going to select font color or back color then dialog box get flicker. It doesn't keep open to select color.

This is reported bug which was fixed but still it doesnt seems to be.

Is anyone facing same issue. any solution for this?

答:
I found the answer. Added following code to the page.

```<code>$.widget("ui.dialog", $.ui.dialog, {
        _allowInteraction: function (event) {
            if (this._super(event)) {
                return true;
            }

            // address interaction issues with general iframes with the dialog
            if (event.target.ownerDocument != this.document[0]) {
                return true;
            }

            // address interaction issues with dialog window
            if ($(event.target).closest(".cke_dialog").length) {
                return true;
            }

            // address interaction issues with iframe based drop downs in IE
            if ($(event.target).closest(".cke").length) {
                return true;
            }
        }
    });
</code>```

It is working now !!!1

Body:
I found the answer. Added following code to the page.

$.widget("ui.dialog", $.ui.dialog, {
        _allowInteraction: function (event) {
            if (this._super(event)) {
                return true;
            }

            // address interaction issues with general iframes with the dialog
            if (event.target.ownerDocument != this.document[0]) {
                return true;
            }

            // address interaction issues with dialog window
            if ($(event.target).closest(".cke_dialog").length) {
                return true;
            }

            // address interaction issues with iframe based drop downs in IE
            if ($(event.target).closest(".cke").length) {
                return true;
            }
        }
    });

It is working now !!!1


问:
Rails - custom exceptions (errors)
I'm trying to build my own Exception for tagged logging:

```<code>module Exceptions
  class GeneralException < StandardError
    LOGGER_NAME = 'Base'

    def initialize(message)
      @logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
      @logger.tagged(get_logger_name) { @logger.error message }
      @message = message
    end

    def get_logger_name
      self.class::LOGGER_NAME
    end
  end

  class InvalidDataException < GeneralException; end

  class SecurityException < GeneralException
    LOGGER_NAME = 'Security'
  end

  class ElasticSearchException < GeneralException
    LOGGER_NAME = 'Elastic'
  end
end
</code>```

I'm expecting to be able to call this new exception with:

raise Exceptions::SecurityException "Something security related happened.

The problem is that when I call this I get:

NoMethodError: undefined method 'SecurityException' for Exceptions:Module

Any idea how to correctly raise this error?

答:
Well, quite easy, you need to raise the instance of the error:

```<code> raise Exceptions::SecurityException.new "Something security related happend."
</code>```

or

```<code> raise Exceptions::SecurityException, "Something security related happend."
</code>```

Title: Rails - custom exceptions (errors)

Body:
I'm trying to build my own Exception for tagged logging:

module Exceptions
  class GeneralException < StandardError
    LOGGER_NAME = 'Base'

    def initialize(message)
      @logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
      @logger.tagged(get_logger_name) { @logger.error message }
      @message = message
    end

    def get_logger_name
      self.class::LOGGER_NAME
    end
  end

  class InvalidDataException < GeneralException; end

  class SecurityException < GeneralException
    LOGGER_NAME = 'Security'
  end

  class ElasticSearchException < GeneralException
    LOGGER_NAME = 'Elastic'
  end
end

I'm expecting to be able to call this new exception with:

raise Exceptions::SecurityException "Something security related happened.

The problem is that when I call this I get:

NoMethodError: undefined method 'SecurityException' for Exceptions:Module

Any idea how to correctly raise this error?

Body:
Well, quite easy, you need to raise the instance of the error:

 raise Exceptions::SecurityException.new "Something security related happend."

or

 raise Exceptions::SecurityException, "Something security related happend."


问:
Swift: Unable To Set Description on Subclass of NSObject
I have built a custom class that looks something like this:

```<code>import UIKit

class Device: NSObject {

    var id = String()
    var name = String()
    var type = String()
    //var description = String()  //Cannot override with a stored property 'description'

}
</code>```

Very simple class, and I am inheriting NSObject so I can use "setValue(value, forKey: keyName)".  However, when I do the following:

```<code>device.setValue("My Description", forKey: "description")
</code>```

I am getting the following error:

'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key description.'

So insummary, I can't override the NSObject.description, but when I try to set it I am getting an error.  Anyone run into this before?

答:
You can only get the description property, you can't set it.

In Objective-C string classes, the class description for NSMutableString specifies that the class inherits from NSString. description, when you try to set description it will be getting an error.

Method 1

While using setValue(value, forKey: keyName) Use can store property value by using.

```<code>class ObjName: NSObject{
    var id: String?
    var descriptions : String?

    override var description: String {
        get {
            return self.description
        }
        set(newvalue) {
            descriptions = newvalue
        }
    }
}
</code>```

Using above code, method setValue for key description value store into the descriptions. while you get the value you can use descriptions. Also, it does not affect on description get.

Method 2

Overriding setValue function. like below.

```<code>class ObjName: NSObject{
    var id: String?
    var descriptions : String?

    override func setValue(_ value: Any?, forKey key: String) {
        if key == "description"{
           if let desc = value as? String{
               self.descriptions = String()
               self.descriptions = desc
            }
        }else{
            super.setValue(value, forKey: key)
        }
    }
}
</code>```

Body:
I have built a custom class that looks something like this:

import UIKit

class Device: NSObject {

    var id = String()
    var name = String()
    var type = String()
    //var description = String()  //Cannot override with a stored property 'description'

}

Very simple class, and I am inheriting NSObject so I can use "setValue(value, forKey: keyName)".  However, when I do the following:

device.setValue("My Description", forKey: "description")

I am getting the following error:

'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key description.'

So insummary, I can't override the NSObject.description, but when I try to set it I am getting an error.  Anyone run into this before?

Body:
You can only get the description property, you can't set it.

In Objective-C string classes, the class description for NSMutableString specifies that the class inherits from NSString. description, when you try to set description it will be getting an error.

Method 1

While using setValue(value, forKey: keyName) Use can store property value by using.

class ObjName: NSObject{
    var id: String?
    var descriptions : String?

    override var description: String {
        get {
            return self.description
        }
        set(newvalue) {
            descriptions = newvalue
        }
    }
}

Using above code, method setValue for key description value store into the descriptions. while you get the value you can use descriptions. Also, it does not affect on description get.

Method 2

Overriding setValue function. like below.

class ObjName: NSObject{
    var id: String?
    var descriptions : String?

    override func setValue(_ value: Any?, forKey key: String) {
        if key == "description"{
           if let desc = value as? String{
               self.descriptions = String()
               self.descriptions = desc
            }
        }else{
            super.setValue(value, forKey: key)
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
Python: List of dictionaries: How to - nice printout using sys.stdout
I have the following list of dictionaries:

```<code>[{'Sequence': 'TGACCCTGCTTGGCGATCCCGGCGTTTC', 'Start': '52037', 'Strand': '+', 'End': '52064'}, {'Sequence': 'TGATCGCGCAACTGCAGCGGGAGTTAC', 'Start': '188334', 'Strand': '+', 'End': '188360'}, {'Sequence': 'TGATCCGGCACTCGTTGGAGTTCGTATC', 'Start': '245882', 'Strand': '+', 'End': '245909'}, {'Sequence': 'TGACCTTGGTCAGATCGATGACCGTAAT', 'Start': '318422', 'Strand': '+', 'End': '318449'}, {'Sequence': 'TGACCCGCGTATTTTGGAGCAGAAGTATC', 'Start': '343421', 'Strand': '+', 'End': '343449'}, {'Sequence': 'TGATCCGGCACTCGTTGGAGTTCGTATC', 'Start': '359576', 'Strand': '+', 'End': '359603'}, {'Sequence': 'TGATCGGCAATTCCTATGGCAAGTATC', 'Start': '457457', 'Strand': '+', 'End': '457483'}, {'Sequence': 'TGATCGAGGCGCCAGTTGTGCCCGTATT', 'Start': '627296', 'Strand': '+', 'End': '627323'}, {'Sequence': 'TGATCCAAGTGAACCCCCGCCCAGTAAA', 'Start': '637265', 'Strand': '+', 'End': '637292'}, {'Sequence': 'TGACCGGAAGACCGCCGTCGAGCGTATC', 'Start': '829035', 'Strand': '+', 'End': '829062'}, {'Sequence': 'TGATCGCGGCACCGACACCGGTCGTAAT', 'Start': '864440', 'Strand': '+', 'End': '864467'}, {'Sequence': 'TGATCGTTTCCGTGCTCGGAGCGTATC', 'Start': '934160', 'Strand': '+', 'End': '934186'}, {'Sequence': 'TGACCTGGCTCGAGGCCTGAGGAGTAAA', 'Start': '1162006', 'Strand': '+', 'End': '1162033'}, {'Sequence': 'TGACCCGCCGCAACATCCCCTTCGTAAA', 'Start': '1294515', 'Strand': '+', 'End': '1294542'}]
</code>```

I would like to acquire the following output (redirecting prints via sys.stdout):

```<code>Start:1234  End:5678  Strand:+  Sequence:ABCDEFG
...
</code>```

So far, my idea involves looping through the list and using the get-method to get the value of the key and then do a manual printout, basically like this:

```<code>for item in dictList:
    print("Start"+item.get('Start'))
    print("End"+item.get('End'))
    ...
</code>```

I am not sure how to deal with the newlines though. I read about sys.stdout flush to avoid
newlines, but since I do not want to avoid all newlines, I am not sure if this would suit my aim.

Is there a smarter/shorter way to do this?

Update

Thanks to Aleksey, I thought of changing my print statement to:

```<code>for item in dictList:
    print("Start"+str(item.get('Start'))+"  "+"End"+str(item.get('End'))+"  "+"Strand"+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))
</code>```

Update2

so far, I am sticking to this:

```<code>print(ecf+"  "+replicon+"  -  "+"Validated results: Total number of hits: "+str(len(finalList)))
print("")

for item in finalList:
    print("Start: "+str(item.get('Start'))+"  "+"End: "+str(item.get('End'))+"  "+"Strand: "+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))
</code>```

which prints:

```<code>ECF02  pSymA  -  Validated results: Total number of hits: 284

Start: 2876  End: 2903  Strand: +  Sequence: GAACTACAGGAAGTTCATGGTCTCCTTC
Start: 2876  End: 2900  Strand: +  Sequence: GAACTACAGGAAGTTCATGGTCTCC
Start: 9214  End: 9238  Strand: +  Sequence: GAACGTCGGGCGCAAGAGCCGCTTT
...
</code>```

please note: dictList was replaced by finalList. Due to parts of my script running before those prints

答:
Avoid new lines by simply specifying the ending with:

```<code>print("Start"+item.get('Start'), end=" ")
</code>```

end=" " will continue your string without new lines

Body:
I have the following list of dictionaries:

[{'Sequence': 'TGACCCTGCTTGGCGATCCCGGCGTTTC', 'Start': '52037', 'Strand': '+', 'End': '52064'}, {'Sequence': 'TGATCGCGCAACTGCAGCGGGAGTTAC', 'Start': '188334', 'Strand': '+', 'End': '188360'}, {'Sequence': 'TGATCCGGCACTCGTTGGAGTTCGTATC', 'Start': '245882', 'Strand': '+', 'End': '245909'}, {'Sequence': 'TGACCTTGGTCAGATCGATGACCGTAAT', 'Start': '318422', 'Strand': '+', 'End': '318449'}, {'Sequence': 'TGACCCGCGTATTTTGGAGCAGAAGTATC', 'Start': '343421', 'Strand': '+', 'End': '343449'}, {'Sequence': 'TGATCCGGCACTCGTTGGAGTTCGTATC', 'Start': '359576', 'Strand': '+', 'End': '359603'}, {'Sequence': 'TGATCGGCAATTCCTATGGCAAGTATC', 'Start': '457457', 'Strand': '+', 'End': '457483'}, {'Sequence': 'TGATCGAGGCGCCAGTTGTGCCCGTATT', 'Start': '627296', 'Strand': '+', 'End': '627323'}, {'Sequence': 'TGATCCAAGTGAACCCCCGCCCAGTAAA', 'Start': '637265', 'Strand': '+', 'End': '637292'}, {'Sequence': 'TGACCGGAAGACCGCCGTCGAGCGTATC', 'Start': '829035', 'Strand': '+', 'End': '829062'}, {'Sequence': 'TGATCGCGGCACCGACACCGGTCGTAAT', 'Start': '864440', 'Strand': '+', 'End': '864467'}, {'Sequence': 'TGATCGTTTCCGTGCTCGGAGCGTATC', 'Start': '934160', 'Strand': '+', 'End': '934186'}, {'Sequence': 'TGACCTGGCTCGAGGCCTGAGGAGTAAA', 'Start': '1162006', 'Strand': '+', 'End': '1162033'}, {'Sequence': 'TGACCCGCCGCAACATCCCCTTCGTAAA', 'Start': '1294515', 'Strand': '+', 'End': '1294542'}]

I would like to acquire the following output (redirecting prints via sys.stdout):

Start:1234  End:5678  Strand:+  Sequence:ABCDEFG
...

So far, my idea involves looping through the list and using the get-method to get the value of the key and then do a manual printout, basically like this:

for item in dictList:
    print("Start"+item.get('Start'))
    print("End"+item.get('End'))
    ...

I am not sure how to deal with the newlines though. I read about sys.stdout flush to avoid
newlines, but since I do not want to avoid all newlines, I am not sure if this would suit my aim.

Is there a smarter/shorter way to do this?

Update

Thanks to Aleksey, I thought of changing my print statement to:

for item in dictList:
    print("Start"+str(item.get('Start'))+"  "+"End"+str(item.get('End'))+"  "+"Strand"+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))

Update2

so far, I am sticking to this:

print(ecf+"  "+replicon+"  -  "+"Validated results: Total number of hits: "+str(len(finalList)))
print("")

for item in finalList:
    print("Start: "+str(item.get('Start'))+"  "+"End: "+str(item.get('End'))+"  "+"Strand: "+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))

which prints:

ECF02  pSymA  -  Validated results: Total number of hits: 284

Start: 2876  End: 2903  Strand: +  Sequence: GAACTACAGGAAGTTCATGGTCTCCTTC
Start: 2876  End: 2900  Strand: +  Sequence: GAACTACAGGAAGTTCATGGTCTCC
Start: 9214  End: 9238  Strand: +  Sequence: GAACGTCGGGCGCAAGAGCCGCTTT
...

please note: dictList was replaced by finalList. Due to parts of my script running before those prints

Body:
Avoid new lines by simply specifying the ending with:

print("Start"+item.get('Start'), end=" ")

end=" " will continue your string without new lines


问:
Create a AWS Lambda API Gateway and Lambda Function by API
I am trying to use AWS API Gateway and AWS Lambda(Python) for serving some static request. My use case requires me to create an API Gateway and lambda function once a setting is saved in my web application.

I was wondering if there is a way to create API Gateway and Lambda Function by API.

答:
Rather than using the API, I strongly suggest that you look into The Serverless Framework. It does all of the heavy lifting for you, allowing you to focus on the code, and your business specific logic.

https://serverless.com/framework/docs/providers/aws/guide/quick-start/

This link shows a quickstart guide to deploying a Hello World Lambda and API Gateway resources. The more I use the framework the more I like it :)


问:
Unable to download pdf file in Chrome Browser using Selenium java
My use case: I have to read data from a pdf than opens in chrome browser and check if some specific data is present in the pdf or not.

As I could not achieve the above I thought of downloading the file on my computer and use PDFbox for the verification.
I created a chrome profile with settings to download the pdf file directly(Settings>Content settings>PDF documents).
I have set it as chrome options in my selenium script.
The test works but when the pdf gets opened it does not start downloading.
The PDF file opens in my chrome browser. Chrome version: 62.0.3202.94

I got the chrome profile path from:

```<code>chrome://version/
</code>```

I am not sure what went wrong.
Please help.

```<code>    @Before
      public void beforeTest() throws MalformedURLException{

          System.setProperty("webdriver.chrome.driver","path to chromedriver\\chromedriver.exe");
          ChromeOptions options = new ChromeOptions();
          String chromeProfilePath="path to custom chrome profile";
          options.addArguments("user-data-dir="+chromeProfilePath);
          HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
          DesiredCapabilities cap = DesiredCapabilities.chrome();
          cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
          cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
          cap.setCapability(ChromeOptions.CAPABILITY, options);
          driver = new ChromeDriver(cap);
          //Browser is maximized
          driver.manage().window().maximize();
}
</code>```

答:
check this it is working perfectly to download the pdf

```<code>package testing;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class pdfdownload {
 static String urls ="http://www.staff.amu.edu.pl/~zcht/pliki/Databases%20for%20beginners.pdf";

 public static void main(String[] args) throws IOException {
  URL url = verify(urls);

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  InputStream inputStream = null;
  String filename = url.getFile();
  filename = filename.substring(filename.lastIndexOf('/')+1);
  FileOutputStream outputStream = new FileOutputStream("D:\\HELLO/java" + File.separator+ filename);

  inputStream = connection.getInputStream();

  int read = -1;
  byte[] buffer = new byte[4096];

  while((read = inputStream.read(buffer))!= -1){
   outputStream.write(buffer,0,read);

  }
  inputStream.close();
  outputStream.close();
 }

 private static URL verify(String url){
  if(!url.toLowerCase().startsWith("http://")){
   return null;
  }
  URL verifyURL= null;

  try{
   verifyURL = new URL(url);

  }catch(Exception e){

  }
  return verifyURL;
 }}
</code>```

To verify pdf content use this

```<code>package pdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import org.testng.Assert;

public class pdfreader {

    public static void main(String[] args) throws IOException {

        File file = new File("D://study video tutorials//database testing//Database Testing Quick Guide.pdf");
        FileInputStream fis = new FileInputStream(file);

        PDFParser parser = new PDFParser(fis);
        parser.parse();

        COSDocument cosDoc= parser.getDocument();
        PDDocument pddoc= new PDDocument(cosDoc);
        PDFTextStripper strip= new PDFTextStripper();
        String data = strip.getText(pddoc);
        System.out.println(data);

        Assert.assertTrue(data.contains("keys"));
        cosDoc.close();
        pddoc.close();

    }

}
</code>```

Body:
My use case: I have to read data from a pdf than opens in chrome browser and check if some specific data is present in the pdf or not.

As I could not achieve the above I thought of downloading the file on my computer and use PDFbox for the verification.
I created a chrome profile with settings to download the pdf file directly(Settings>Content settings>PDF documents).
I have set it as chrome options in my selenium script.
The test works but when the pdf gets opened it does not start downloading.
The PDF file opens in my chrome browser. Chrome version: 62.0.3202.94

I got the chrome profile path from:

chrome://version/

I am not sure what went wrong.
Please help.

    @Before
      public void beforeTest() throws MalformedURLException{

          System.setProperty("webdriver.chrome.driver","path to chromedriver\\chromedriver.exe");
          ChromeOptions options = new ChromeOptions();
          String chromeProfilePath="path to custom chrome profile";
          options.addArguments("user-data-dir="+chromeProfilePath);
          HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
          DesiredCapabilities cap = DesiredCapabilities.chrome();
          cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
          cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
          cap.setCapability(ChromeOptions.CAPABILITY, options);
          driver = new ChromeDriver(cap);
          //Browser is maximized
          driver.manage().window().maximize();
}

Body:
check this it is working perfectly to download the pdf

package testing;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class pdfdownload {
 static String urls ="http://www.staff.amu.edu.pl/~zcht/pliki/Databases%20for%20beginners.pdf";

 public static void main(String[] args) throws IOException {
  URL url = verify(urls);

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  InputStream inputStream = null;
  String filename = url.getFile();
  filename = filename.substring(filename.lastIndexOf('/')+1);
  FileOutputStream outputStream = new FileOutputStream("D:\\HELLO/java" + File.separator+ filename);

  inputStream = connection.getInputStream();

  int read = -1;
  byte[] buffer = new byte[4096];

  while((read = inputStream.read(buffer))!= -1){
   outputStream.write(buffer,0,read);

  }
  inputStream.close();
  outputStream.close();
 }

 private static URL verify(String url){
  if(!url.toLowerCase().startsWith("http://")){
   return null;
  }
  URL verifyURL= null;

  try{
   verifyURL = new URL(url);

  }catch(Exception e){

  }
  return verifyURL;
 }}

To verify pdf content use this

package pdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import org.testng.Assert;

public class pdfreader {

    public static void main(String[] args) throws IOException {

        File file = new File("D://study video tutorials//database testing//Database Testing Quick Guide.pdf");
        FileInputStream fis = new FileInputStream(file);

        PDFParser parser = new PDFParser(fis);
        parser.parse();

        COSDocument cosDoc= parser.getDocument();
        PDDocument pddoc= new PDDocument(cosDoc);
        PDFTextStripper strip= new PDFTextStripper();
        String data = strip.getText(pddoc);
        System.out.println(data);

        Assert.assertTrue(data.contains("keys"));
        cosDoc.close();
        pddoc.close();

    }

}


问:
statistic test on univariate time series without replicates in R
I'm having the following data on an experiment, where I want to find out, how an bacterium reacts on two similar levels (nucleic acids) to a treatment.

Treatment happened after the sampling on day 0 (vertical dashed line). As you can see, it got more abundant (line is average, dots are measured triplicates). I have 3 technical replicates (doing the lab work 3 times on the same sample) but no biological replicates.
For publication purposes, I want to show that the induced change is significant. So far I used a two tailed t test for heteroscedastic samples, using the 3 sample points day -25 to 0 as sample group 1 and 5 sample points day 3 to 17 as sample group 2 (this is the range where most of my bacteria reacted).
Afterwards I performed the Bonferroni correction on the p values to correct for multiple testing. But is this the correct way and is it possible with only technical replicates?

I'm finding many hints on fitting models to my graph, but I only want to test for statistic significance of difference between before and after treatment. So I'm searching for the correct statistics and also how to apply it in R. Any help appreciated!

here is the plot:

```<code>require(ggplot2)
require(scales)
ggplot(data=sample_data, aes(x=days-69,y=value,colour=nucleic_acid,group=nucleic_acid,lty=nucleic_acid))+
    geom_vline(aes(xintercept=0),linetype="dashed", size=1.2)+
    geom_point(aes(),colour="black")+
    stat_summary(aes(colour=nucleic_acid),colour="black",fun.y="mean", geom="line", size=1.5)+
    scale_linetype_manual(values=c("dna"=1,"cdna"=4),
                        name="Nucleic acid  ",
                        breaks=c("cdna","dna"),
                        labels=c("16S rRNA","16S rDNA"))+
    scale_x_continuous(breaks = scales::pretty_breaks(n = 20))+
    theme_bw()+
    scale_y_continuous(label= function(x) {ifelse(x==0, "0", parse(text=gsub("[+]", "", gsub("e", " %*% 10^", scientific_format()(x)))))})+
    theme(axis.title.y = element_text(angle=90,vjust=0.5))+
    theme(axis.text=element_text(size=12))+
    theme(legend.text=element_text(size=11))+
    theme(panel.grid.major=element_line(colour = NA, size = 0.2))+
    theme(panel.grid.minor=element_line(colour = NA, size = 0.5))+
    theme(legend.position="bottom")+
    theme(legend.background = element_rect(fill="grey90",linetype="solid"))+
    labs(x="Days",
             y=expression(atop("Absolute abundance in cell equivalents",bgroup("[",relative~abundance~x~cells~mL^{-1},"]"))))
</code>```

and here is my data:

```<code>sample_data<-structure(list(time = c(10L, 10L, 10L, 10L, 10L, 10L, 11L, 11L,
11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L,
13L, 13L, 13L, 14L, 14L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L,
15L, 15L, 16L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L, 18L,
18L, 18L, 18L, 18L, 18L, 19L, 19L, 19L, 19L, 19L, 19L, 4L, 4L,
4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L,
7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L,
9L, 9L), days = c(83L, 83L, 83L, 83L, 83L, 83L, 86L, 86L, 86L,
86L, 86L, 86L, 91L, 91L, 91L, 91L, 91L, 91L, 98L, 98L, 98L, 98L,
98L, 98L, 105L, 105L, 105L, 105L, 105L, 105L, 112L, 112L, 112L,
112L, 112L, 112L, 119L, 119L, 119L, 119L, 119L, 119L, 126L, 126L,
126L, 126L, 133L, 133L, 133L, 133L, 133L, 133L, 140L, 140L, 140L,
140L, 140L, 140L, 44L, 44L, 44L, 44L, 44L, 44L, 62L, 62L, 62L,
62L, 62L, 62L, 69L, 69L, 69L, 69L, 69L, 69L, 72L, 72L, 72L, 72L,
72L, 72L, 76L, 76L, 76L, 76L, 76L, 76L, 79L, 79L, 79L, 79L, 79L,
79L), parallel = c(3L, 1L, 2L, 2L, 3L, 1L, 2L, 3L, 3L, 2L, 1L,
1L, 2L, 1L, 3L, 3L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 3L, 1L,
1L, 3L, 2L, 1L, 1L, 2L, 3L, 3L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 3L,
1L, 1L, 3L, 2L, 3L, 1L, 1L, 2L, 3L, 1L, 2L, 3L, 3L, 1L, 2L, 2L,
3L, 3L, 1L, 1L, 2L, 2L, 3L, 1L, 1L, 3L, 2L, 1L, 2L, 3L, 3L, 1L,
2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 3L, 3L, 1L, 2L, 3L,
3L, 1L, 2L), nucleic_acid = structure(c(1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L,
1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L,
2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L,
2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("cdna", "dna"), class = "factor"),
    habitat = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "water", class = "factor"),
    value = c(5316639.62, 6402573.912, 6294710.95, 2369809.996,
    2679661.691, 2105693.166, 2108794.224, 2487177.041, 6021765.438,
    5524939.499, 6016021.786, 2628427.206, 3164229.113, 896068.7656,
    2966515.364, 4436008.425, 1860580.149, 3911309.508, 888489.0268,
    1004334.365, 1141636.992, 961140.0729, 1072009.18, 1134997.852,
    668013.4333, 459645.1058, 645944.1129, 702293.6865, 590620.3693,
    642136.7523, 932531.1588, 1224299.065, 1502344.5, 1545034.46,
    1122002.798, 1411050.57, 1465061.711, 1378876.488, 810348.2823,
    1361496.248, 1056558.288, 897876.4169, 931519.9524, 1165768.09,
    957873.9045, 746011.7558, 624116.5603, 522209.2283, 551120.1371,
    440096.4446, 565108.4447, 373304.8604, 266595.7171, 333767.4042,
    185612.6681, 144899.8736, 173739.3969, 211490.827, 223815.0867,
    296455.4243, 1278759.217, 247292.4355, 1171554.199, 1146278.577,
    227443.8462, 233542.6719, 253224.2629, 875040.4892, 1151921.616,
    1285744.479, 355381.9156, 110724.7928, 252238.9632, 912865.3372,
    608269.6498, 500307.5301, 774955.9598, 1374106.94, 3121909.308,
    1071086.757, 3033665.589, 2984567.998, 1396313.444, 1356465.773,
    4480581.956, 4273141.231, 4957691.655, 1910056.657, 5520085.32,
    5094686.657, 5990052.759, 2272441.566, 1513268.608, 1821716.75
    ), treatment2 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Treatment", class = "factor")), .Names = c("time",
"days", "parallel", "nucleic_acid", "habitat", "value", "treatment2"
), class = "data.frame", row.names = c(51243L, 51244L, 51245L,
51246L, 51247L, 51248L, 51255L, 51256L, 51257L, 51258L, 51259L,
51260L, 51267L, 51268L, 51269L, 51270L, 51271L, 51272L, 51279L,
51280L, 51281L, 51282L, 51283L, 51284L, 51291L, 51292L, 51293L,
51294L, 51295L, 51296L, 51303L, 51304L, 51305L, 51306L, 51307L,
51308L, 51315L, 51316L, 51317L, 51318L, 51319L, 51320L, 51326L,
51327L, 51328L, 51329L, 51336L, 51337L, 51338L, 51339L, 51340L,
51341L, 51348L, 51349L, 51350L, 51351L, 51352L, 51353L, 51360L,
51361L, 51362L, 51363L, 51364L, 51365L, 51372L, 51373L, 51374L,
51375L, 51376L, 51377L, 51384L, 51385L, 51386L, 51387L, 51388L,
51389L, 51396L, 51397L, 51398L, 51399L, 51400L, 51401L, 51408L,
51409L, 51410L, 51411L, 51412L, 51413L, 51420L, 51421L, 51422L,
51423L, 51424L, 51425L))
</code>```

答:
If you want to test for significance of the effect of your treatment and you know how to fit model(s) on your data, you can simply fit a model which includes your treatment effect and a model which doesn't. Then compare the models by means of a likelihood ratio test.

In R it is pretty straightforward (I assume for simplicity a linear model, which anyway may not be the best choice, based on your data):

```<code> # Models fit
 model_effect <- lm(y~Time + Treatment, data)
 model_null   <- lm(y~Time, data)

 # Models comparison
 anova(model_effect, model_null)
</code>```

Body:
I'm having the following data on an experiment, where I want to find out, how an bacterium reacts on two similar levels (nucleic acids) to a treatment.

Treatment happened after the sampling on day 0 (vertical dashed line). As you can see, it got more abundant (line is average, dots are measured triplicates). I have 3 technical replicates (doing the lab work 3 times on the same sample) but no biological replicates.
For publication purposes, I want to show that the induced change is significant. So far I used a two tailed t test for heteroscedastic samples, using the 3 sample points day -25 to 0 as sample group 1 and 5 sample points day 3 to 17 as sample group 2 (this is the range where most of my bacteria reacted).
Afterwards I performed the Bonferroni correction on the p values to correct for multiple testing. But is this the correct way and is it possible with only technical replicates?

I'm finding many hints on fitting models to my graph, but I only want to test for statistic significance of difference between before and after treatment. So I'm searching for the correct statistics and also how to apply it in R. Any help appreciated!

here is the plot:

require(ggplot2)
require(scales)
ggplot(data=sample_data, aes(x=days-69,y=value,colour=nucleic_acid,group=nucleic_acid,lty=nucleic_acid))+
    geom_vline(aes(xintercept=0),linetype="dashed", size=1.2)+
    geom_point(aes(),colour="black")+
    stat_summary(aes(colour=nucleic_acid),colour="black",fun.y="mean", geom="line", size=1.5)+
    scale_linetype_manual(values=c("dna"=1,"cdna"=4),
                        name="Nucleic acid  ",
                        breaks=c("cdna","dna"),
                        labels=c("16S rRNA","16S rDNA"))+
    scale_x_continuous(breaks = scales::pretty_breaks(n = 20))+
    theme_bw()+
    scale_y_continuous(label= function(x) {ifelse(x==0, "0", parse(text=gsub("[+]", "", gsub("e", " %*% 10^", scientific_format()(x)))))})+
    theme(axis.title.y = element_text(angle=90,vjust=0.5))+
    theme(axis.text=element_text(size=12))+
    theme(legend.text=element_text(size=11))+
    theme(panel.grid.major=element_line(colour = NA, size = 0.2))+
    theme(panel.grid.minor=element_line(colour = NA, size = 0.5))+
    theme(legend.position="bottom")+
    theme(legend.background = element_rect(fill="grey90",linetype="solid"))+
    labs(x="Days",
             y=expression(atop("Absolute abundance in cell equivalents",bgroup("[",relative~abundance~x~cells~mL^{-1},"]"))))

and here is my data:

sample_data<-structure(list(time = c(10L, 10L, 10L, 10L, 10L, 10L, 11L, 11L,
11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L,
13L, 13L, 13L, 14L, 14L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L,
15L, 15L, 16L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L, 18L,
18L, 18L, 18L, 18L, 18L, 19L, 19L, 19L, 19L, 19L, 19L, 4L, 4L,
4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L,
7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L,
9L, 9L), days = c(83L, 83L, 83L, 83L, 83L, 83L, 86L, 86L, 86L,
86L, 86L, 86L, 91L, 91L, 91L, 91L, 91L, 91L, 98L, 98L, 98L, 98L,
98L, 98L, 105L, 105L, 105L, 105L, 105L, 105L, 112L, 112L, 112L,
112L, 112L, 112L, 119L, 119L, 119L, 119L, 119L, 119L, 126L, 126L,
126L, 126L, 133L, 133L, 133L, 133L, 133L, 133L, 140L, 140L, 140L,
140L, 140L, 140L, 44L, 44L, 44L, 44L, 44L, 44L, 62L, 62L, 62L,
62L, 62L, 62L, 69L, 69L, 69L, 69L, 69L, 69L, 72L, 72L, 72L, 72L,
72L, 72L, 76L, 76L, 76L, 76L, 76L, 76L, 79L, 79L, 79L, 79L, 79L,
79L), parallel = c(3L, 1L, 2L, 2L, 3L, 1L, 2L, 3L, 3L, 2L, 1L,
1L, 2L, 1L, 3L, 3L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 3L, 1L,
1L, 3L, 2L, 1L, 1L, 2L, 3L, 3L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 3L,
1L, 1L, 3L, 2L, 3L, 1L, 1L, 2L, 3L, 1L, 2L, 3L, 3L, 1L, 2L, 2L,
3L, 3L, 1L, 1L, 2L, 2L, 3L, 1L, 1L, 3L, 2L, 1L, 2L, 3L, 3L, 1L,
2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 3L, 3L, 1L, 2L, 3L,
3L, 1L, 2L), nucleic_acid = structure(c(1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L,
1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L,
2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L,
2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("cdna", "dna"), class = "factor"),
    habitat = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "water", class = "factor"),
    value = c(5316639.62, 6402573.912, 6294710.95, 2369809.996,
    2679661.691, 2105693.166, 2108794.224, 2487177.041, 6021765.438,
    5524939.499, 6016021.786, 2628427.206, 3164229.113, 896068.7656,
    2966515.364, 4436008.425, 1860580.149, 3911309.508, 888489.0268,
    1004334.365, 1141636.992, 961140.0729, 1072009.18, 1134997.852,
    668013.4333, 459645.1058, 645944.1129, 702293.6865, 590620.3693,
    642136.7523, 932531.1588, 1224299.065, 1502344.5, 1545034.46,
    1122002.798, 1411050.57, 1465061.711, 1378876.488, 810348.2823,
    1361496.248, 1056558.288, 897876.4169, 931519.9524, 1165768.09,
    957873.9045, 746011.7558, 624116.5603, 522209.2283, 551120.1371,
    440096.4446, 565108.4447, 373304.8604, 266595.7171, 333767.4042,
    185612.6681, 144899.8736, 173739.3969, 211490.827, 223815.0867,
    296455.4243, 1278759.217, 247292.4355, 1171554.199, 1146278.577,
    227443.8462, 233542.6719, 253224.2629, 875040.4892, 1151921.616,
    1285744.479, 355381.9156, 110724.7928, 252238.9632, 912865.3372,
    608269.6498, 500307.5301, 774955.9598, 1374106.94, 3121909.308,
    1071086.757, 3033665.589, 2984567.998, 1396313.444, 1356465.773,
    4480581.956, 4273141.231, 4957691.655, 1910056.657, 5520085.32,
    5094686.657, 5990052.759, 2272441.566, 1513268.608, 1821716.75
    ), treatment2 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Treatment", class = "factor")), .Names = c("time",
"days", "parallel", "nucleic_acid", "habitat", "value", "treatment2"
), class = "data.frame", row.names = c(51243L, 51244L, 51245L,
51246L, 51247L, 51248L, 51255L, 51256L, 51257L, 51258L, 51259L,
51260L, 51267L, 51268L, 51269L, 51270L, 51271L, 51272L, 51279L,
51280L, 51281L, 51282L, 51283L, 51284L, 51291L, 51292L, 51293L,
51294L, 51295L, 51296L, 51303L, 51304L, 51305L, 51306L, 51307L,
51308L, 51315L, 51316L, 51317L, 51318L, 51319L, 51320L, 51326L,
51327L, 51328L, 51329L, 51336L, 51337L, 51338L, 51339L, 51340L,
51341L, 51348L, 51349L, 51350L, 51351L, 51352L, 51353L, 51360L,
51361L, 51362L, 51363L, 51364L, 51365L, 51372L, 51373L, 51374L,
51375L, 51376L, 51377L, 51384L, 51385L, 51386L, 51387L, 51388L,
51389L, 51396L, 51397L, 51398L, 51399L, 51400L, 51401L, 51408L,
51409L, 51410L, 51411L, 51412L, 51413L, 51420L, 51421L, 51422L,
51423L, 51424L, 51425L))

Body:
If you want to test for significance of the effect of your treatment and you know how to fit model(s) on your data, you can simply fit a model which includes your treatment effect and a model which doesn't. Then compare the models by means of a likelihood ratio test.

In R it is pretty straightforward (I assume for simplicity a linear model, which anyway may not be the best choice, based on your data):

 # Models fit
 model_effect <- lm(y~Time + Treatment, data)
 model_null   <- lm(y~Time, data)

 # Models comparison
 anova(model_effect, model_null)


问:
Chrome extension- JavaScript to retrieve data from MySQL database and display in extention
we are creating a chrome extension that can able to retrieve a data from MYSQL database and display in extension.is it possible? second question is it possible to authenticate localhost .aspx website from java script.</p>

答:
If you want to make a native database connection I think it would be possible with npapi, see https://developer.chrome.com/extensions/npapi. However it sounds to make like a big security risk due to the fact the username and password will be stored in the extension code that can be early access, a better solution would be to develop some http service/api that will connect to the database and return some information, then you can just make an ajax request to your service and display any information you want.
About the second question, you can make any http request just like the browser using chrome extensions.</p>


问:
Getting 'dispatch is not defined' in redux component
I am trying to get a list of names stored in firebase to save to the redux store when the component loads. This list then gets sent to a dropdown component as props which are rendered as selectable options in the dropdown. For some reason I am getting 'dispatch is not defined' and I am not sure how to fix.

This is my code:

```<code>  //store
  import * as redux from 'redux';
  import thunk from 'redux-thunk';
  import {userReducer, exampleReducer, namesReducer} from 'reducers';

  export var configure = (initialState = {}) => {
    const reducer = redux.combineReducers({
            user: userReducer,
            example: exampleReducer,
            names: namesReducer
        })

  var store = redux.createStore(reducer, initialState, redux.compose(
      redux.applyMiddleware(thunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    ));

    return store;
  };

  //reducers
  export var namesReducer = (state = [], action) => {
    switch (action.type) {
      case 'GET_NAMES':
        return [
          action.names
        ]
      default:
      return state;
    }
  }

  //actions
  export var getNames = (names) => {
    return {
        type: 'GET_NAMES',
        names
    }
  };

  export var startGetNames = () => {
    console.log("action started")
    return (dispatch) => {
        var nameRef = firebase.database().ref().child('names');
        return nameRef.once('value').then((snapshot) => {
                var data = snapshot.val();
                _.map(data, function(name) {return finalArr.push(
              {
                display: `${name.first_name} ${name.last_name}`,
                value: name.id
              }
            )});
           dispatch(getNames(finalArr));
        })
      }
  }

  //component
  import _ from 'underscore';
  import React from 'react';
  import { render } from "react-dom";
  import {connect} from 'react-redux';
  import Modal from 'react-responsive-modal';
  var actions = require('actions');
  var firebase = require('firebase/app');
  require('firebase/auth');
  require('firebase/database');
  //components
  import roomBookingForm from 'roomBookingForm';

  import PanelHeader from 'PanelHeader';
  import PanelItem from 'PanelItem';
  import Table from 'Table';
  import TableRow from 'TableRow';
  import TableHeaderCell from 'TableHeaderCell';
  import TextInput from 'TextInput';
  import Dropdown from 'Dropdown';

  class roomBooking extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      pageTitle: "Appointment Creation",
      openForm: false
    }
  }

  componentWillMount() {
   this.props.clinicians
  }

   onOpenModal = () => {
    this.setState({openForm: true});
  }

   modalClose = () => {
    this.setState({ openForm: false });
  };

    render() {
      return (
        <div className="main-container">
          <div className="options-menu">
            <PanelHeader >
              Options
            </PanelHeader>
              <PanelItem onClick={this.onOpenModal} propClassLeft="left-item" propClassRight="right-item">Create Appointment</PanelItem>
          </div>
        <div>
          <Table className="display-table">
            <TableRow className="display-table-head">
              <TableHeaderCell className="name" displayText="Name" />
            </TableRow>
          </Table>
        </div>
        <roomBookingForm open={this.state.openForm} onClose={this.modalClose} options={this.props.names} />
      </div>
      )
    }
  }

  const mapDispatchToProps = (dispatch) => {
    names : dispatch(actions.startGetNames())
  }

  export default connect()(roomBooking);
</code>```

答:
you should pass mapDisPatchToProps to connect function:

```<code>  const mapDispatchToProps = (dispatch) => {
    names : dispatch(actions.startGetNames())
  }

  export default connect(function(){},mapDispatchToProps)(roomBooking);
</code>```

Body:
I am trying to get a list of names stored in firebase to save to the redux store when the component loads. This list then gets sent to a dropdown component as props which are rendered as selectable options in the dropdown. For some reason I am getting 'dispatch is not defined' and I am not sure how to fix.

This is my code:

  //store
  import * as redux from 'redux';
  import thunk from 'redux-thunk';
  import {userReducer, exampleReducer, namesReducer} from 'reducers';

  export var configure = (initialState = {}) => {
    const reducer = redux.combineReducers({
            user: userReducer,
            example: exampleReducer,
            names: namesReducer
        })

  var store = redux.createStore(reducer, initialState, redux.compose(
      redux.applyMiddleware(thunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    ));

    return store;
  };

  //reducers
  export var namesReducer = (state = [], action) => {
    switch (action.type) {
      case 'GET_NAMES':
        return [
          action.names
        ]
      default:
      return state;
    }
  }

  //actions
  export var getNames = (names) => {
    return {
        type: 'GET_NAMES',
        names
    }
  };

  export var startGetNames = () => {
    console.log("action started")
    return (dispatch) => {
        var nameRef = firebase.database().ref().child('names');
        return nameRef.once('value').then((snapshot) => {
                var data = snapshot.val();
                _.map(data, function(name) {return finalArr.push(
              {
                display: `${name.first_name} ${name.last_name}`,
                value: name.id
              }
            )});
           dispatch(getNames(finalArr));
        })
      }
  }

  //component
  import _ from 'underscore';
  import React from 'react';
  import { render } from "react-dom";
  import {connect} from 'react-redux';
  import Modal from 'react-responsive-modal';
  var actions = require('actions');
  var firebase = require('firebase/app');
  require('firebase/auth');
  require('firebase/database');
  //components
  import roomBookingForm from 'roomBookingForm';

  import PanelHeader from 'PanelHeader';
  import PanelItem from 'PanelItem';
  import Table from 'Table';
  import TableRow from 'TableRow';
  import TableHeaderCell from 'TableHeaderCell';
  import TextInput from 'TextInput';
  import Dropdown from 'Dropdown';

  class roomBooking extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      pageTitle: "Appointment Creation",
      openForm: false
    }
  }

  componentWillMount() {
   this.props.clinicians
  }

   onOpenModal = () => {
    this.setState({openForm: true});
  }

   modalClose = () => {
    this.setState({ openForm: false });
  };

    render() {
      return (

            <PanelHeader >
              Options
            </PanelHeader>
              <PanelItem onClick={this.onOpenModal} propClassLeft="left-item" propClassRight="right-item">Create Appointment</PanelItem>

            <TableRow className="display-table-head">
              <TableHeaderCell className="name" displayText="Name" />
            </TableRow>

        <roomBookingForm open={this.state.openForm} onClose={this.modalClose} options={this.props.names} />

      )
    }
  }

  const mapDispatchToProps = (dispatch) => {
    names : dispatch(actions.startGetNames())
  }

  export default connect()(roomBooking);

Body:
you should pass mapDisPatchToProps to connect function:

  const mapDispatchToProps = (dispatch) => {
    names : dispatch(actions.startGetNames())
  }

  export default connect(function(){},mapDispatchToProps)(roomBooking);


问:
Android app with Google Maps Navigation and a text overlay
I have searched this issue for hours...
Is it possible to launch google maps navigation within my app and display a textview with some information on it? I have to create an app which passes the destination address to Maps Navigation and while Navigation is working show a textview with the cars model name on the bottom of the app. Is this doable?</p>

答:
Try this.</p>

```<code>public class FloatingOverNewBooking extends Service {

    private WindowManager windowManager;
    private FrameLayout frameLayout;
    private String str_ride_id;
    public static final String BROADCAST_ACTION = "com.yourpackage.YourActivity";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        timerLocation = new Timer();
        createFloatingBackButton();
    }

    Timer timerLocation;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // to receive any data from activity
        str_ride_id = intent.getStringExtra("RIDE_ID");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (frameLayout != null) {
            //((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(frameLayout);

            windowManager.removeView(frameLayout);
            frameLayout = null;
        }

        timerLocation.cancel();
    }

    private void createFloatingBackButton() {
        ClientLocatedActivity.isFloatingIconServiceAlive = true;
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager.LayoutParams windowManagerParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY ,
                WindowManager.LayoutParams. FLAG_DIM_BEHIND, PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        frameLayout = new FrameLayout(this);

        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        // Here is the place where you can inject whatever layout you want in the frame layout
        layoutInflater.inflate(R.layout.share_new_booking_alert, frameLayout);

        final TextView txtName = (TextView) frameLayout.findViewById(R.id.txtName);
        Button backOnMap = (Button) frameLayout.findViewById(R.id.dialog_button);

        if(!ObjectUtility.isNullOrEmpty(Config.Share.newPassenger)){
            txtName.setText(Config.Share.newPassenger.getUsername());
        }

        backOnMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    am.killBackgroundProcesses("com.google.android.apps.maps");
                    //MainActivity.getInstance().getShareRideDataById("go");
                    FloatingOverNewBooking.this.stopSelf();
                    ClientLocatedActivity.isFloatingIconServiceAlive = false;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        windowManager.addView(frameLayout, windowManagerParams);
    }
}
</code>```

Body:
Try this.

public class FloatingOverNewBooking extends Service {

    private WindowManager windowManager;
    private FrameLayout frameLayout;
    private String str_ride_id;
    public static final String BROADCAST_ACTION = "com.yourpackage.YourActivity";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        timerLocation = new Timer();
        createFloatingBackButton();
    }

    Timer timerLocation;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // to receive any data from activity
        str_ride_id = intent.getStringExtra("RIDE_ID");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (frameLayout != null) {
            //((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(frameLayout);

            windowManager.removeView(frameLayout);
            frameLayout = null;
        }

        timerLocation.cancel();
    }

    private void createFloatingBackButton() {
        ClientLocatedActivity.isFloatingIconServiceAlive = true;
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager.LayoutParams windowManagerParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY ,
                WindowManager.LayoutParams. FLAG_DIM_BEHIND, PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        frameLayout = new FrameLayout(this);

        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        // Here is the place where you can inject whatever layout you want in the frame layout
        layoutInflater.inflate(R.layout.share_new_booking_alert, frameLayout);

        final TextView txtName = (TextView) frameLayout.findViewById(R.id.txtName);
        Button backOnMap = (Button) frameLayout.findViewById(R.id.dialog_button);

        if(!ObjectUtility.isNullOrEmpty(Config.Share.newPassenger)){
            txtName.setText(Config.Share.newPassenger.getUsername());
        }

        backOnMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    am.killBackgroundProcesses("com.google.android.apps.maps");
                    //MainActivity.getInstance().getShareRideDataById("go");
                    FloatingOverNewBooking.this.stopSelf();
                    ClientLocatedActivity.isFloatingIconServiceAlive = false;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        windowManager.addView(frameLayout, windowManagerParams);
    }
}


问:
disable reporting TFS 2008
We have assumed maintenance of a legacy 32bit application.  I installed TFS 2008 to use in maintaining the project.

We will never use reporting or sharepoint.  I cant create a project because of issues with SSRS.

(The Project Creation Wizard encountered a problem while creating reports on the SQL Server Reporting Services on OHSENSS801. The reason for the failure cannot be determined at this time. Because the operation failed, the wizard was not able to finish creating the SQL Server Reporting Services site. )

How can I disable reporting and sharepoint in TFS 2008?

Thank you.

答:
Unlike  TFS 2010 and above version, you have to install the SharePoint components for TF2008.

TFS2008 is a very old server version and out of support for a long time. You could use TFS2010 instead,  the SharePoint is no longer a prerequisite when you install TFS2010. You can go for TFS2010 Basic Configuration which is the most compact TFS installation possible.

In Basic Configuration, SharePoint and Reporting Integration will not be possible. It will install and configure Source Control, Work Item tracking and Build Services only.

Highly recommend you to move to a newly versioned TFS server. If you insist on using TFS2008, you could try to troubleshoot the configuration of SQL Server Reporting Services. Details please refer this thread in MSDN: SQL Server Reporting Services is not configured correctly

About how to remove Sharepoint and Reporting Services from TFS, you could go through this question. However, afraid removing these components, you will still not able to create team project. After all, if it will work, there is no need to be a prerequisite for installing TFS2008.

Title: disable reporting TFS 2008


问:
How to simply fill a TableView for iPhone
I have got an UITableView. How to simply fill it with three elements, for example "e1", "e2", "e3" ?

答:
set DataSource of your table to your class and define in your class 3 methods:</p>

```<code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *cellId = @"identifier";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellId];
  if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellId] autorelease];
  }
  [cell setText:[NSString stringWithFormat:@"e%i",indexPath:[indexPath row]];
  return cell;
}
</code>```

OwnerDisplayName: bigzpanda

LastEditorDisplayName: Chris Hanson

Body:
set DataSource of your table to your class and define in your class 3 methods:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *cellId = @"identifier";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellId];
  if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellId] autorelease];
  }
  [cell setText:[NSString stringWithFormat:@"e%i",indexPath:[indexPath row]];
  return cell;
}


问:
Understanding event listeners in java
I'm new to java and I'm still trying to understand the language, so I apologize if this question might sound noobish.

There's something I don't understand about listeners, sometime you can see a listener declared in such a fashion:

```<code>    private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {

// Some code

}

};
</code>```

or:

```<code>javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
</code>```

The thing that perplex me the most is that semicolon and parenthesis after the end of the method.

I understand inner classes for the purpose of having multiple listeners, but I don't understand this mixed declaration of variables and method.

Which purpose it has?

How is it declared?

WTF? :P

cheers :)

答:
Normally defining a class, instantiating an instance, and then using that instance are done separately:

```<code>class MyListener extends OnClickListener {
    public void onClick(View v) {
        // my onClick code goes here
    }
}

MyListener foo = new MyListener();

button.setOnClickListener(foo);
</code>```

But sometimes you need a subclass that you will instantiate only once immediately, which is often the case for event handlers. It is convenient to define it and instantiate it together using an anonymous (inner) class:

```<code>OnClickListener foo =
    new OnClickListener() {
        public void onClick(View v) {
            // my onClick code goes here
        }
    };

button.setOnClickListener(foo);
</code>```

But since foo is only used once, we can takes this one step further and eliminate the local variable foo as well, so:

```<code>button.setOnClickListener(foo);
</code>```

can be formatted as:

```<code>button.setOnClickListener(
    foo
);
</code>```

substitute in the value of foo:

```<code>button.setOnClickListener(
    new OnClickListener() {
        public void onClick(View v) {
            // my onClick code goes here
        }
    }
);
</code>```

reformatted again without some much whitespace to see it as it is often written:

```<code>button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // my onClick code goes here
    }
});
</code>```

I think this last format hurts readability.  I format my anonymous classes similar to how it is in the next to last format - the better readability (IMHO) is worth a little extra whitespace.

Title: Understanding event listeners in java

Body:
I'm new to java and I'm still trying to understand the language, so I apologize if this question might sound noobish.

There's something I don't understand about listeners, sometime you can see a listener declared in such a fashion:

    private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {

// Some code

}

};

or:

javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });

The thing that perplex me the most is that semicolon and parenthesis after the end of the method.

I understand inner classes for the purpose of having multiple listeners, but I don't understand this mixed declaration of variables and method.

Which purpose it has?

How is it declared?

WTF? :P

cheers :)

Body:
Normally defining a class, instantiating an instance, and then using that instance are done separately:

class MyListener extends OnClickListener {
    public void onClick(View v) {
        // my onClick code goes here
    }
}

MyListener foo = new MyListener();

button.setOnClickListener(foo);

But sometimes you need a subclass that you will instantiate only once immediately, which is often the case for event handlers. It is convenient to define it and instantiate it together using an anonymous (inner) class:

OnClickListener foo =
    new OnClickListener() {
        public void onClick(View v) {
            // my onClick code goes here
        }
    };

button.setOnClickListener(foo);

But since foo is only used once, we can takes this one step further and eliminate the local variable foo as well, so:

button.setOnClickListener(foo);

can be formatted as:

button.setOnClickListener(
    foo
);

substitute in the value of foo:

button.setOnClickListener(
    new OnClickListener() {
        public void onClick(View v) {
            // my onClick code goes here
        }
    }
);

reformatted again without some much whitespace to see it as it is often written:

button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // my onClick code goes here
    }
});

I think this last format hurts readability.  I format my anonymous classes similar to how it is in the next to last format - the better readability (IMHO) is worth a little extra whitespace.


问:
How to add a class that does controls on an entire table?
in our project we have an SQL Database with a table representing all users

```<code>CREATE TABLE `user_table` (
`firstname` varchar(20) NOT NULL,
  `lastName` varchar(20) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(24) NOT NULL,
  `accessToken` varchar(64) NOT NULL,
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
)
</code>```

and we have a class UserDAO. We need to add methods such as

```<code>public boolean areUserCredentialsValid(String email, String password) {...}
public boolean isAccessTokenValid(String accessToken) {...}
public boolean isEmailInUse(String email) {...}
</code>```

I think the names are pretty self-explicative: we want to perform operations on the entire table in order to return boolean values, so we thought it may not be correct to add these methods in UserDAO, as they do not perform CRUD operations on a single User, instead they perform R-only operations on the entire User Table, so we were thinking about a new class AllUsersDAO but it does not seem convincing. What is the best solution here and why?

I don't know if we are overthinking this, but this is a project for an University course and we are evaluated especially for our software engineering abilities, so we want to be sure to adopt the best solution.

Thank you all in advance!

答: From my point of view, you can put CRUD operations in UserDao, but the methods you mentioned should be put in the UserService to implement the methods you mentioned by calling the methods in UserDao in the UserService.</p>

Body:
in our project we have an SQL Database with a table representing all users

CREATE TABLE `user_table` (
`firstname` varchar(20) NOT NULL,
  `lastName` varchar(20) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(24) NOT NULL,
  `accessToken` varchar(64) NOT NULL,
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
)

and we have a class UserDAO. We need to add methods such as

public boolean areUserCredentialsValid(String email, String password) {...}
public boolean isAccessTokenValid(String accessToken) {...}
public boolean isEmailInUse(String email) {...}

I think the names are pretty self-explicative: we want to perform operations on the entire table in order to return boolean values, so we thought it may not be correct to add these methods in UserDAO, as they do not perform CRUD operations on a single User, instead they perform R-only operations on the entire User Table, so we were thinking about a new class AllUsersDAO but it does not seem convincing. What is the best solution here and why?

I don't know if we are overthinking this, but this is a project for an University course and we are evaluated especially for our software engineering abilities, so we want to be sure to adopt the best solution.

Thank you all in advance!


问:
How to determine if an Android Service is running in the foreground?
I have a service which I believe to have running in the foreground, How do I check if my implementation is working?</p>

答:
A more efficient variation of answer: https://stackoverflow.com/a/36127260/1275265</p>

```<code>public static boolean isServiceRunningInForeground(Context context, Class<?> serviceClass) {
   ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
      if (serviceClass.getName().equals(service.service.getClassName())) {
         return service.foreground;
      }
   }
   return false;
}
</code>```

Body:
A more efficient variation of answer: https://stackoverflow.com/a/36127260/1275265

public static boolean isServiceRunningInForeground(Context context, Class<?> serviceClass) {
   ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
      if (serviceClass.getName().equals(service.service.getClassName())) {
         return service.foreground;
      }
   }
   return false;
}


问:
Invoke Ansible playbook in Jenkins
I have jenkins build and I am trying to invoke a ansible playbook file for an s3 upload. When I execute a post-build-script for invoking an ansible playbook file, I am ending with below error.
Cannot run program "ansible-playbook" (in directory "/var/jenkins_home/workspace/mybuild"): error=2, No such file or directory

Below screenshot is ansible post build script configuration.

FYI: There is a file(ansibledemo.yml) in my build folder. I tried giving absolute path(/var/jenkins_home/workspace/mybuild/ansibledemo.yml). Still no go.

When I try running ansible-playbook myplaybook.yml directly in jenkins image(terminal) I am ending up with bash: ansible-playbook: command not found

When I tried installing ansible in my jenkins server, I couldn't execute any installation commands. Please see the below screenshot.

答:
You can try to install using pip version as an alternative and try, Please see the below steps,

```<code>$ virtualenv venv
$ source venv/bin/activate
$ pip install ansible-container[docker,openshift]
</code>```

You can see more options to install in docs: https://docs.ansible.com/ansible-container/installation.html

But always it is a good option to keep a separate vm / docker like "ansible-controller" and use that as a slave to jenkins, So that you don't need ansible plugins in ansible. And jenkins will be always stable  without much load

Title: Invoke Ansible playbook in Jenkins

Body:
You can try to install using pip version as an alternative and try, Please see the below steps,

$ virtualenv venv
$ source venv/bin/activate
$ pip install ansible-container[docker,openshift]

You can see more options to install in docs: https://docs.ansible.com/ansible-container/installation.html

But always it is a good option to keep a separate vm / docker like "ansible-controller" and use that as a slave to jenkins, So that you don't need ansible plugins in ansible. And jenkins will be always stable  without much load


问:
Give the classes a specific id
I have a question about the class, and give the class a specific id.

For example I've got a html code like this:

```<code><div class="test">text1</div>
<div class="test">text2</div>
<div class="test">text3</div>
<div class="test">text4</div>
<div class="test">text5</div>
</code>```

My question is how can I add an id by each .test class.

I thought something like this in Jquery:

```<code>var i = 1;
$('.test').each(function(){
   $('.test').attr('id','id_'+i+'');
   i++
});
</code>```

This doesn't work I think it's something with .closest() or .next()
to solve this problem.

Regards,

Frank

EDIT:

I solved the problem by myself the answer is:

```<code>    $('.test').each(function(){
        $(this).attr('class','test').attr('id','id_'+i+'');
        i++;
    });
</code>```

答:
Use $(this) to refer to the current element the in callback function:

```<code>var i = 1;
$('.test').each(function(){
   $(this).attr('id','id_'+i);
   i++
});
</code>```

Title: Give the classes a specific id

Body:
I have a question about the class, and give the class a specific id.

For example I've got a html code like this:

text1

text2

text3

text4

text5

My question is how can I add an id by each .test class.

I thought something like this in Jquery:

var i = 1;
$('.test').each(function(){
   $('.test').attr('id','id_'+i+'');
   i++
});

This doesn't work I think it's something with .closest() or .next()
to solve this problem.

Regards,

Frank

EDIT:

I solved the problem by myself the answer is:

    $('.test').each(function(){
        $(this).attr('class','test').attr('id','id_'+i+'');
        i++;
    });

Body:
Use $(this) to refer to the current element the in callback function:

var i = 1;
$('.test').each(function(){
   $(this).attr('id','id_'+i);
   i++
});


问:
'Data type mismatch in criteria expression' with LabVIEW database query
I have two tables:

table 1 : info1 -> where i have pid(primary key),name,address,sex etc.

table 2 : visit -> where i have the pid(foreign key),
                  visit_date,next_visit,details

I used a query

```<code>SELECT info1.Patient_ID, visit.Visit_Date, visit.Next_Visit,
visit.Visit_Details from info1, visit WHERE info1.Patient_ID ="%"
</code>```

Is this query correct??

LabVIEW code:

Front panel:

Table 1 (info1):

Table 2 (visit):

Error:

答:
Your query needs a JOIN:

```<code>SELECT info1.Patient_ID, visit.Visit_Date, visit.Next_Visit, visit.Visit_Details
FROM info1 INNER JOIN visit ON info1.Patient_ID = visit.Patient_ID
WHERE info1.Patient_ID ="%"
</code>```

If you use an INNER JOIN as shown above, then you'll only get a result for Patient_ID's that have an entry in both of the two tables. If you wanted to see all Patient_ID's whether or not they had a visit record, for example, you would use a LEFT OUTER JOIN.

Note: in the LabVIEW code you've shown, you are constructing the query by building a string from user-supplied data (the Patient ID front panel control). This is a really bad idea because it enables SQL injection attacks by malicious users. You should look up how to supply the value as a parameter to your LabVIEW database functions instead.

Body:
I have two tables:

table 1 : info1 -> where i have pid(primary key),name,address,sex etc.

table 2 : visit -> where i have the pid(foreign key),
                  visit_date,next_visit,details

I used a query

SELECT info1.Patient_ID, visit.Visit_Date, visit.Next_Visit,
visit.Visit_Details from info1, visit WHERE info1.Patient_ID ="%"

Is this query correct??

LabVIEW code:

Front panel:

Table 1 (info1):

Table 2 (visit):

Error:

Body:
Your query needs a JOIN:

SELECT info1.Patient_ID, visit.Visit_Date, visit.Next_Visit, visit.Visit_Details
FROM info1 INNER JOIN visit ON info1.Patient_ID = visit.Patient_ID
WHERE info1.Patient_ID ="%"

If you use an INNER JOIN as shown above, then you'll only get a result for Patient_ID's that have an entry in both of the two tables. If you wanted to see all Patient_ID's whether or not they had a visit record, for example, you would use a LEFT OUTER JOIN.

Note: in the LabVIEW code you've shown, you are constructing the query by building a string from user-supplied data (the Patient ID front panel control). This is a really bad idea because it enables SQL injection attacks by malicious users. You should look up how to supply the value as a parameter to your LabVIEW database functions instead.


问:
Uncaught TypeError: (intermediate value)(...) is not a function
Everything works fine when I wrote the js logic in a closure as a single js file, as:

```<code>(function(win){
   //main logic here
   win.expose1 = ....
   win.expose2 = ....
})(window)
</code>```

but when I try to insert a logging alternative function before that closure in the same js file,

```<code> window.Glog = function(msg){
     console.log(msg)
 }
 // this was added before the main closure.

 (function(win){
   //the former closure that contains the main javascript logic;
 })(window)
</code>```

it complains that there is a TypeError:

```<code>Uncaught TypeError: (intermediate value)(...) is not a function
</code>```

What did I do wrong?

答:
Error Case:

```<code>var userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;
</code>```

Output:

```<code>TypeError: (intermediate value)(intermediate value) is not a function
</code>```

Fix: You are missing a semi-colon (;) to separate the expressions

```<code>userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}; // Without a semi colon, the error is produced

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;
</code>```

Body:
Everything works fine when I wrote the js logic in a closure as a single js file, as:

(function(win){
   //main logic here
   win.expose1 = ....
   win.expose2 = ....
})(window)

but when I try to insert a logging alternative function before that closure in the same js file,

 window.Glog = function(msg){
     console.log(msg)
 }
 // this was added before the main closure.

 (function(win){
   //the former closure that contains the main javascript logic;
 })(window)

it complains that there is a TypeError:

Uncaught TypeError: (intermediate value)(...) is not a function

What did I do wrong?

Body:
Error Case:

var userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

Output:

TypeError: (intermediate value)(intermediate value) is not a function

Fix: You are missing a semi-colon (;) to separate the expressions

userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}; // Without a semi colon, the error is produced

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;


问:
Need help to gather data from a txt file and insert in a web page?
could someone advise me on the most efficient way to gather data from one source, select a specific piece of data and insert it in a web page? Specifically, I wish to:

Call up this buoy data text file: http://www.ndbc.noaa.gov/data/realtime2/46237.txt

Find the water temperature and insert that value in my web page.

First big question: What scripting language should I use? (I'm assuming Fortran is not an option :-)

Second not so big question: This same data set is available in graphic and xml format. Would either of these data formats be more useful than the .txt file?

Thanks in advance.

答:
Use Perl.

(Hey, you asked. Normally one programs in whatever language one would normally use.)

The XML format won't be much more useful than the text format.


问:
Adding a search box form to my navbar
I'm new to front end design and am having challenges implementing a search box with filters into my navbar. I know this is potentially trivial but I have found it very challenging, and typically end up with a jumbled mess when I insert the searchbox code into my desired area (commented in the second code block).

The code for the search box is:

```<code><div class="container">
  <div class="row">
    <div class="col-xs-4 col-xs-offset-2">
      <div class="input-group">
        <div class="input-group-btn search-panel">
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            <span id="search_concept">Filter by</span> <span class="caret"></span>
          </button>
          <ul class="dropdown-menu" role="menu">
            <li><a href="#contains">Contains</a></li>
            <li><a href="#its_equal">It's equal</a></li>
            <li><a href="#greather_than">Greather than ></a></li>
            <li><a href="#less_than">Less than < </a></li>
            <li class="divider"></li>
            <li><a href="#all">Anything</a></li>
          </ul>
        </div>
        <input type="hidden" name="search_param" value="all" id="search_param">
        <input type="text" class="form-control" name="x" placeholder="Search term...">
        <span class="input-group-btn">
          <button class="btn btn-default" type="button">
            <span class="glyphicon glyphicon-search"></span>
          </button>
        </span>
      </div>
    </div>
  </div>
</div>
</code>```

The code for my nav bar is as follows, with a comment indicating where I need the search box to go:

```<code><nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Project name</a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>

        <li>
          <!--SEARCH BAR HERE -->
        </li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="./">Log in</a></li>
        <li><a href="./">Join us</a></li>
        <li><a href="#"><i class="fa fa-twitter color-twitter"></i></a></li>
        <li><a href="#"><i class="fa fa-facebook color-facebook"></i></a></li>
      </ul>
    </div>
    <!--/.nav-collapse -->
  </div>
  <!--/.container-fluid -->
</nav>
</code>```

The final result should look something like:

NavBar Desired Result

Sincere gratitude in advance.

答:
Here is a working snippet based on Bootstrap 3 (click to "Expand snippet"):

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

Link (current)

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

      <form class="navbar-form navbar-left" role="search">

                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                    Filter by
                </button>

Contains

It's equal

Greather than >

Less than <

Anything

            <input type="hidden" name="search_param" value="all" id="search_param">
            <input type="text" class="form-control" name="x" placeholder="Search term...">

                <button class="btn btn-default" type="button"></button>

      </form>

Link

          This Link here

Action

Another action

Something else here

Separated link

```

And also the relative CodePen: https://codepen.io/beaver71/pen/pdmBMr

Title: Adding a search box form to my navbar

Body:
I'm new to front end design and am having challenges implementing a search box with filters into my navbar. I know this is potentially trivial but I have found it very challenging, and typically end up with a jumbled mess when I insert the searchbox code into my desired area (commented in the second code block).

The code for the search box is:

          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            Filter by
          </button>

Contains

It's equal

Greather than >

Less than <

Anything

        <input type="hidden" name="search_param" value="all" id="search_param">
        <input type="text" class="form-control" name="x" placeholder="Search term...">

          <button class="btn btn-default" type="button">

          </button>

The code for my nav bar is as follows, with a comment indicating where I need the search box to go:

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      Project name

Home

About

Log in

Join us

The final result should look something like:

NavBar Desired Result

Sincere gratitude in advance.

Body:
Here is a working snippet based on Bootstrap 3 (click to "Expand snippet"):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<nav class="navbar navbar-default">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Brand</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>

      <form class="navbar-form navbar-left" role="search">
        <!--div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button-->

        <div class="input-group">
            <div class="input-group-btn search-panel">
                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                    <span id="search_concept">Filter by</span> <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" role="menu">
                  <li><a href="#contains">Contains</a></li>
                  <li><a href="#its_equal">It's equal</a></li>
                  <li><a href="#greather_than">Greather than ></a></li>
                  <li><a href="#less_than">Less than < </a></li>
                  <li class="divider"></li>
                  <li><a href="#all">Anything</a></li>
                </ul>
            </div>
            <input type="hidden" name="search_param" value="all" id="search_param">
            <input type="text" class="form-control" name="x" placeholder="Search term...">
            <span class="input-group-btn">
                <button class="btn btn-default" type="button"><span class="glyphicon glyphicon-search"></span></button>
            </span>
        </div>

      </form>

      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">This Link here <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
</nav>

And also the relative CodePen: https://codepen.io/beaver71/pen/pdmBMr


问:
Get information on a defunct process (AKA zombie)
How do I get all information about a defunct process?

For example, I would like to know: who is the parent process, what command was used to run this defunct process, reason why its dead, log...

When I run ps aux | grep defunct all I get is this:

```<code>[admin@a ~]# ps aux | grep defunct
admin    30798  1.3  0.0      0     0 ?        Zs   10:03   0:00 [httpd] <defunct>
admin    30799  1.6  0.0      0     0 ?        Zs   10:03   0:00 [httpd] <defunct>
admin    30800  1.3  0.0      0     0 ?        Zs   10:03   0:00 [httpd] <defunct>
admin    30801  4.0  0.0      0     0 ?        Zs   10:03   0:00 [httpd] <defunct>
</code>```

Note: I'm using Red Hat / Centos OS.

答:
Following is how I caught the command that was run, it contains the information I needed.

Run: while true; do ps aux | grep httpd; done

Search the output for the defunct PID.

From the output:

```<code>admin    26741  0.0  0.0  22024  2444 ?        Rs   11:25   0:00 /opt/XYZ/web/Apache/bin/httpd -DFOREGROUND -k start -f /opt/XYZ/conf/httpd.conf -DFLAG1

admin    26741  0.0  0.0      0     0 ?        Zs   11:25   0:00 [httpd] <defunct>
</code>```

Body:
How do I get all information about a defunct process?

For example, I would like to know: who is the parent process, what command was used to run this defunct process, reason why its dead, log...

When I run ps aux | grep defunct all I get is this:

[admin@a ~]# ps aux | grep defunct
admin    30798  1.3  0.0      0     0 ?        Zs   10:03   0:00 [httpd] <defunct>
admin    30799  1.6  0.0      0     0 ?        Zs   10:03   0:00 [httpd] <defunct>
admin    30800  1.3  0.0      0     0 ?        Zs   10:03   0:00 [httpd] <defunct>
admin    30801  4.0  0.0      0     0 ?        Zs   10:03   0:00 [httpd] <defunct>

Note: I'm using Red Hat / Centos OS.

Body:
Following is how I caught the command that was run, it contains the information I needed.

Run: while true; do ps aux | grep httpd; done

Search the output for the defunct PID.

From the output:

admin    26741  0.0  0.0  22024  2444 ?        Rs   11:25   0:00 /opt/XYZ/web/Apache/bin/httpd -DFOREGROUND -k start -f /opt/XYZ/conf/httpd.conf -DFLAG1

admin    26741  0.0  0.0      0     0 ?        Zs   11:25   0:00 [httpd] <defunct>