问:
filter results in an array of objects just like operator(%oil%) using lodash
I want to filter array of objects based on the input change by the user and create a new array of matched array of objects using LODASH (https://lodash.com/).

```<code>let listing = [{title: "Courier/Logistics", id: 1, totalWorkers: 1058, openPositions: 0, omani: 99.72},
{title: "Information Technology", id: 1, totalWorkers: 2, openPositions: 1, omani: 50},
{title: "Oil & Gas", id: 1, totalWorkers: 98, openPositions: 6, omani: 91.84}];
</code>```

I have tried lodash _.filter but this filters exact words and exact case and then return that single searched value.

```<code>const filtered = _.filter(listing, function(o) {
        return o.title === "oi";
      });
      console.log(filtered);
</code>```

I want to get results just like we do in mysql as:

```<code>WHERE title like %oi%
</code>```

and it gives matched values which contained that input.

Thanks

答:
You don't need lodash for that at all,

just use this using regular expression and native filter:

listing.filter(o=>o.title.match(/oi/i))

Body:
I want to filter array of objects based on the input change by the user and create a new array of matched array of objects using LODASH (https://lodash.com/).

let listing = [{title: "Courier/Logistics", id: 1, totalWorkers: 1058, openPositions: 0, omani: 99.72},
{title: "Information Technology", id: 1, totalWorkers: 2, openPositions: 1, omani: 50},
{title: "Oil & Gas", id: 1, totalWorkers: 98, openPositions: 6, omani: 91.84}];

I have tried lodash _.filter but this filters exact words and exact case and then return that single searched value.

const filtered = _.filter(listing, function(o) {
        return o.title === "oi";
      });
      console.log(filtered);

I want to get results just like we do in mysql as:

WHERE title like %oi%

and it gives matched values which contained that input.

Thanks


来源: stackexchange

问:
Finding the idNumber element from this below HTML code
```<code><div id="rightContent" style="display: inline-block; width: 700px; vertical-align: top;">
                <div>
                    <h1><em class="SomethingHeading">Something</em></h1>
                </div>

<div class="content scaffold-list" role="main">
    <h1>Search</h1>

    <form action="/SomethingArchiveUI/search/search" method="post">
        <table>
            <tbody>
            <tr>
                <td>ID/Registration Number:</td>
                <td>
                    <**input type="text" name="idNumber" maxlength="20" value="" id="idNumber"**>
                </td>
            </tr>
            <tr>
                <td>Client Name:</td>
                <td>
                    <input type="text" name="clientName" maxlength="50" value="" id="clientName">
                </td>
            </tr>
            <tr>
                <td>Client Surname:</td>
                <td>
                    <input type="text" name="clientSurname" maxlength="50" value="" id="clientSurname">
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="hidden" name="_dateRange"><input type="checkbox" name="dateRange" value="true" id="dateRange"><label for="dateRange"> Use date range?</label>
                </td>
            </tr>
            <tr>
                <td colspan="2"><p>From: <input type="text" name="fromDate" value="" maxlength="10" id="fromDate" class="hasDatepicker"> To: <input type="text" name="toDate" value="" maxlength="10" id="toDate" class="hasDatepicker"></p></td>
            </tr>
            </tbody>
        </table>
        <div style="display: inline;">
            <div id="divSubmit">
                <input type="submit" name="cmdSearch" class="buttons" value="Search" id="cmdSearch">
            </div>
            <div id="divBusy" style="display: none;">
                Busy Searching...
            </div>
        </div>
    </form>

    <table id="customerIdentificationList" style="display: block;">

    </table>
    <div id="loadingMessage" style="display: none;">
        Loading. Please wait.
    </div>
</div>

            </div>
</code>```

I used this code below for logging into the Application, but similar code doesn't seem to work on this form above. I'm trying to find the 'idNumber' element:

```<code>driver.findElement(By.xpath("//*[@id='idnumber']")).sendKeys("Username");
driver.findElement(By.xpath("//*[@id=\'password\']")).sendKeys("Password");
driver.findElement(By.xpath("//*[@id=\'submit\']")).click();
</code>```

The error i get is: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":

Looking forward to your responses.

答:
Why not just use By.id()?

```<code>driver.findElement(By.id("idNumber"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Something

Search

    <form action="/SomethingArchiveUI/search/search" method="post">

                ID/Registration Number:

                    <**input type="text" name="idNumber" maxlength="20" value="" id="idNumber"**>

                Client Name:

                    <input type="text" name="clientName" maxlength="50" value="" id="clientName">

                Client Surname:

                    <input type="text" name="clientSurname" maxlength="50" value="" id="clientSurname">

                    <input type="hidden" name="_dateRange"><input type="checkbox" name="dateRange" value="true" id="dateRange"> Use date range?

From: <input type="text" name="fromDate" value="" maxlength="10" id="fromDate" class="hasDatepicker"> To: <input type="text" name="toDate" value="" maxlength="10" id="toDate" class="hasDatepicker">

                <input type="submit" name="cmdSearch" class="buttons" value="Search" id="cmdSearch">

                Busy Searching...

    </form>

        Loading. Please wait.

I used this code below for logging into the Application, but similar code doesn't seem to work on this form above. I'm trying to find the 'idNumber' element:

driver.findElement(By.xpath("//*[@id='idnumber']")).sendKeys("Username");
driver.findElement(By.xpath("//*[@id=\'password\']")).sendKeys("Password");
driver.findElement(By.xpath("//*[@id=\'submit\']")).click();

The error i get is: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":

Looking forward to your responses.

Body:
Why not just use By.id()?

driver.findElement(By.id("idNumber"));


问:
Converting string with time to minutes
I am working on an Android app that gets a time (duration) value as string.

For example, the app can get a value like: 6 hours 43 mins

or a value like: 15 mins

I am looking for a way to convert this strings to an integer value in minutes.

I have tried using this function, but I can´t extract the needed values:

```<code>str = str.replaceAll("[^\\d.]", "");
</code>```

Edit:

it could be possible a result like 6 hours, the only known condition is that minutes are always rounded to an integer, the minimum value is 1 min

答:
You could split the String at the whitespace and use the values in the array.

```<code>String value1 = "6 hours 43 mins";
String value2 = "15 mins";

String[] resultList1 = value1.split(" ");
String[] resultList2 = value2.split(" ");

int minutes1 = 0;
int minutes2 = 0;

if(resultList1.length == 4) {
  minutes1 = Integer.parseInt(resultList1[0]) * 60 + Integer.parseInt(resultList1[2]);
} else {
  minutes1 = Integer.parseInt(resultList1[0]);
}

if(resultList2.length == 4) {
  minutes2 = Integer.parseInt(resultList2[0]) * 60 + Integer.parseInt(resultList2[2]);
} else {
  minutes2 = Integer.parseInt(resultList2[0]);
}

System.out.println(minutes1);
System.out.println(minutes2);
</code>```

The result is:

```<code>403
15
</code>```

Title: Converting string with time to minutes

Body:
I am working on an Android app that gets a time (duration) value as string.

For example, the app can get a value like: 6 hours 43 mins

or a value like: 15 mins

I am looking for a way to convert this strings to an integer value in minutes.

I have tried using this function, but I can´t extract the needed values:

str = str.replaceAll("[^\\d.]", "");

Edit:

it could be possible a result like 6 hours, the only known condition is that minutes are always rounded to an integer, the minimum value is 1 min

Body:
You could split the String at the whitespace and use the values in the array.

String value1 = "6 hours 43 mins";
String value2 = "15 mins";

String[] resultList1 = value1.split(" ");
String[] resultList2 = value2.split(" ");

int minutes1 = 0;
int minutes2 = 0;

if(resultList1.length == 4) {
  minutes1 = Integer.parseInt(resultList1[0]) * 60 + Integer.parseInt(resultList1[2]);
} else {
  minutes1 = Integer.parseInt(resultList1[0]);
}

if(resultList2.length == 4) {
  minutes2 = Integer.parseInt(resultList2[0]) * 60 + Integer.parseInt(resultList2[2]);
} else {
  minutes2 = Integer.parseInt(resultList2[0]);
}

System.out.println(minutes1);
System.out.println(minutes2);

The result is:

403
15


问:
Meaning of address' in System.map file
What does this address specify? Address of where these are loaded in memory?</p>

答:
The kernel starts at a fixed location in the virtual address space of a process. The linux kernel usually [depending on your system architecture] is located in the top 1 GB of the 4GB virtual address space. So the kernel for a system architecture with 3G/1G split, starts at the address 0xC0000000. Depending on the platform's memory map, this will be mapped to a physical address in the physical memory.

The system.map file is the kernel symbol table. It has the symbols listed along with their virtual addresses. To find out where these symbols are loaded in the main memory, subtract PAGE_OFFSET [for 3G/1G systems this is 0xC00000000] from the symbol address to get the offset and add this offset to the starting physical address of the kernel in the physical memory as determined from the system memory map.

ContentLicense: CC BY-SA 2.5

Title: Meaning of address' in System.map file


问:
get attribute accessor only for specific method in laravel
I want to modify some values of my query result for API call. here's my query

```<code>public function modules()
{
    Module::select('id','name','image')->get()->toJson();
}
</code>```

so I want to modify image value, add full path to it. I added accessor

```<code>public function getImageAttribute($image)
{
    return asset($image);
}
</code>```

and it works fine, but the problem is now it will be affecting this column every time i try to retrieve it. is there way to use this accessor(getImageAttribute) only for modules method?

答:
You could get rid of the accessor and update the image path inside the modules method.

```<code>public function modules()
{
    return Module::select('id', 'name', 'image')->get()->map(function ($module) {
        $module->image = asset($module->image);
        return $module;
    })->toJson();
}
</code>```

Body:
I want to modify some values of my query result for API call. here's my query

public function modules()
{
    Module::select('id','name','image')->get()->toJson();
}

so I want to modify image value, add full path to it. I added accessor

public function getImageAttribute($image)
{
    return asset($image);
}

and it works fine, but the problem is now it will be affecting this column every time i try to retrieve it. is there way to use this accessor(getImageAttribute) only for modules method?

Body:
You could get rid of the accessor and update the image path inside the modules method.

public function modules()
{
    return Module::select('id', 'name', 'image')->get()->map(function ($module) {
        $module->image = asset($module->image);
        return $module;
    })->toJson();
}


问:
How can I set up different footers for TableSections when using a Custom TableView Renderer
I am using a renderer to allow me to set a custom footer in my TableView. The renderer works but I would like to have the capability to set up different footers for the different table sections. For example one footer for table section 0 and another for table section 1, all the way up to table section 5.

Here's the XAML that I am using:

```<code>           <!-- <local:ExtFooterTableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">-->
                <TableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">
                <TableSection Title="Cards1">
                    <ViewCell Height="50">
                        <Label Text="Hello1" />
                    </ViewCell>
                    <ViewCell Height="50">
                        <Label Text="Hello2" />
                    </ViewCell>
                </TableSection>
                <TableSection Title="Cards2">
                    <TextCell Height="50" Text="Hello"></TextCell>
                </TableSection>

                </TableSection>
        <!--    </local:ExtFooterTableView>-->
            </TableView>
</code>```

and here is the C# class and renderer:

```<code>public class ExtFooterTableView : TableView
{
    public ExtFooterTableView()
    {
    }
}
</code>```

and:

```<code>   using System;
using Japanese;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(ExtFooterTableView), typeof(Japanese.iOS.ExtFooterTableViewRenderer))]
namespace Japanese.iOS
{
    public class ExtFooterTableViewRenderer : TableViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
        {
            base.OnElementChanged(e);
            if (Control == null)
                return;

            var tableView = Control as UITableView;
            var formsTableView = Element as TableView;
            tableView.WeakDelegate = new CustomFooterTableViewModelRenderer(formsTableView);
        }

        private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
        {
            public CustomFooterTableViewModelRenderer(TableView model) : base(model)
            {
            }

            public override UIView GetViewForFooter(UITableView tableView, nint section)
            {
                Debug.WriteLine("xx");
                if (section == 0)
                {
                    return new UILabel()
                    {
                        // Text = TitleForFooter(tableView, section), // or use some other text here
                        Text = "abc",
                        TextAlignment = UITextAlignment.Left
                        // TextAlignment = NSTextAlignment.NSTextAlignmentJustified
                    };
                }
                else
                {
                    return new UILabel()
                    {
                        // Text = TitleForFooter(tableView, section), // or use some other text here
                        Text = "def",
                        TextAlignment = UITextAlignment.Left
                        // TextAlignment = NSTextAlignment.NSTextAlignmentJustified
                    };
                }
            }

        }
    }
}
</code>```

The code works but I would like to find out how I can set up a different footer text for different sections in the XAML. Something like this:

From what I see it looks like the code is partly there TitleForFooter(tableView, section) but I am not sure how to use it and how I could set it up. Note that I am not really looking for a view model solution.  I would be happy to be simply able to specify the section footer text as part of the TableView XAML.

I'd appreciate if anyone could give me some advice on this.

答:
First of all, in order to be able to specify the section footer text in XAML - simplest option would be to create a bindable property in TableSection. But as TableSection is sealed, we can't derive it to define our custom bindable properties.

So, the next option is to create a attached bindable property.

```<code>public class Ex
{
    public static readonly BindableProperty FooterTextProperty =
        BindableProperty.CreateAttached("FooterText", typeof(string), typeof(Ex), defaultValue: default(string));

    public static string GetFooterText(BindableObject view)
    {
        return (string)view.GetValue(FooterTextProperty);
    }

    public static void SetFooterText(BindableObject view, string value)
    {
        view.SetValue(FooterTextProperty, value);
    }
}
</code>```

Next step would be to update renderer to retrieve this value for every section:

```<code>private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
{
    public CustomFooterTableViewModelRenderer(TableView model) : base(model)
    {
    }

    public override UIView GetViewForFooter(UITableView tableView, nint section)
    {
        return new UILabel()
        {
            Text = TitleForFooter(tableView, section), // or use some other text here
            Font = UIFont.SystemFontOfSize(14),
            ShadowColor = Color.White.ToUIColor(),
            ShadowOffset = new CoreGraphics.CGSize(0, 1),
            TextColor = Color.DarkGray.ToUIColor(),
            BackgroundColor = Color.Transparent.ToUIColor(),
            Opaque = false,
            TextAlignment = UITextAlignment.Center
        };
    }

    //Retrieves the footer text for corresponding section through the attached property
    public override string TitleForFooter(UITableView tableView, nint section)
    {
        var tblSection = View.Root[(int)section];
        return Ex.GetFooterText(tblSection);
    }
}
</code>```

Sample Usage

```<code><local:ExtFooterTableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">
    <TableSection Title="Cards1" local:Ex.FooterText="Sample description">
        <ViewCell Height="50">
            <Label Margin="20,0,20,0" Text="Hello1" />
        </ViewCell>
        <ViewCell Height="50">
            <Label Margin="20,0,20,0" Text="Hello2" />
        </ViewCell>
    </TableSection>
    <TableSection  Title="Cards2" local:Ex.FooterText="Disclaimer note">
        <TextCell Height="50" Text="Hello"></TextCell>
    </TableSection>
</local:ExtFooterTableView>
</code>```

Body:
I am using a renderer to allow me to set a custom footer in my TableView. The renderer works but I would like to have the capability to set up different footers for the different table sections. For example one footer for table section 0 and another for table section 1, all the way up to table section 5.

Here's the XAML that I am using:

                <TableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">
                <TableSection Title="Cards1">
                    <ViewCell Height="50">

                    </ViewCell>
                    <ViewCell Height="50">

                    </ViewCell>
                </TableSection>
                <TableSection Title="Cards2">
                    <TextCell Height="50" Text="Hello"></TextCell>
                </TableSection>

                </TableSection>

            </TableView>

and here is the C# class and renderer:

public class ExtFooterTableView : TableView
{
    public ExtFooterTableView()
    {
    }
}

and:

   using System;
using Japanese;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(ExtFooterTableView), typeof(Japanese.iOS.ExtFooterTableViewRenderer))]
namespace Japanese.iOS
{
    public class ExtFooterTableViewRenderer : TableViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
        {
            base.OnElementChanged(e);
            if (Control == null)
                return;

            var tableView = Control as UITableView;
            var formsTableView = Element as TableView;
            tableView.WeakDelegate = new CustomFooterTableViewModelRenderer(formsTableView);
        }

        private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
        {
            public CustomFooterTableViewModelRenderer(TableView model) : base(model)
            {
            }

            public override UIView GetViewForFooter(UITableView tableView, nint section)
            {
                Debug.WriteLine("xx");
                if (section == 0)
                {
                    return new UILabel()
                    {
                        // Text = TitleForFooter(tableView, section), // or use some other text here
                        Text = "abc",
                        TextAlignment = UITextAlignment.Left
                        // TextAlignment = NSTextAlignment.NSTextAlignmentJustified
                    };
                }
                else
                {
                    return new UILabel()
                    {
                        // Text = TitleForFooter(tableView, section), // or use some other text here
                        Text = "def",
                        TextAlignment = UITextAlignment.Left
                        // TextAlignment = NSTextAlignment.NSTextAlignmentJustified
                    };
                }
            }

        }
    }
}

The code works but I would like to find out how I can set up a different footer text for different sections in the XAML. Something like this:

From what I see it looks like the code is partly there TitleForFooter(tableView, section) but I am not sure how to use it and how I could set it up. Note that I am not really looking for a view model solution.  I would be happy to be simply able to specify the section footer text as part of the TableView XAML.

I'd appreciate if anyone could give me some advice on this.

Body:
First of all, in order to be able to specify the section footer text in XAML - simplest option would be to create a bindable property in TableSection. But as TableSection is sealed, we can't derive it to define our custom bindable properties.

So, the next option is to create a attached bindable property.

public class Ex
{
    public static readonly BindableProperty FooterTextProperty =
        BindableProperty.CreateAttached("FooterText", typeof(string), typeof(Ex), defaultValue: default(string));

    public static string GetFooterText(BindableObject view)
    {
        return (string)view.GetValue(FooterTextProperty);
    }

    public static void SetFooterText(BindableObject view, string value)
    {
        view.SetValue(FooterTextProperty, value);
    }
}

Next step would be to update renderer to retrieve this value for every section:

private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
{
    public CustomFooterTableViewModelRenderer(TableView model) : base(model)
    {
    }

    public override UIView GetViewForFooter(UITableView tableView, nint section)
    {
        return new UILabel()
        {
            Text = TitleForFooter(tableView, section), // or use some other text here
            Font = UIFont.SystemFontOfSize(14),
            ShadowColor = Color.White.ToUIColor(),
            ShadowOffset = new CoreGraphics.CGSize(0, 1),
            TextColor = Color.DarkGray.ToUIColor(),
            BackgroundColor = Color.Transparent.ToUIColor(),
            Opaque = false,
            TextAlignment = UITextAlignment.Center
        };
    }

    //Retrieves the footer text for corresponding section through the attached property
    public override string TitleForFooter(UITableView tableView, nint section)
    {
        var tblSection = View.Root[(int)section];
        return Ex.GetFooterText(tblSection);
    }
}

Sample Usage

<local:ExtFooterTableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">
    <TableSection Title="Cards1" local:Ex.FooterText="Sample description">
        <ViewCell Height="50">
            <Label Margin="20,0,20,0" Text="Hello1" />
        </ViewCell>
        <ViewCell Height="50">
            <Label Margin="20,0,20,0" Text="Hello2" />
        </ViewCell>
    </TableSection>
    <TableSection  Title="Cards2" local:Ex.FooterText="Disclaimer note">
        <TextCell Height="50" Text="Hello"></TextCell>
    </TableSection>
</local:ExtFooterTableView>


问:
SSRS -Image not rendering on HTML 4.0 Report(Unauthorization )
I am working on SSRS report. I am accessing report using  web services (using web refrences)
I am using ReportExecutionService class to render report in the html 4.0 format and finaly I attach rendered HTML to my page DIV. Report is rendering very fine in HTML format but the images on that is not rendering properly because of missing authentication for images
 for that  I just replace the src attribute of the img tag in the response returned from the SSRS report execution service with the url to this location below is code for render report:-

```<code> public string Render(string reportDirectory,string reportName,string reportFormat, ParameterValue[]parameters )
        {
            _reportServerExecutionService.ExecutionHeaderValue = new ExecutionHeader();
            _reportServerExecutionService.TrustedUserHeaderValue = new TrustedUserHeader();
            _reportServerExecutionService.LoadReport("/GES-MVC/GES_FWCR",null);
            _reportServerExecutionService.SetExecutionParameters(parameters, "en-us");

            string encoding;
            string mimeType;
            string extension;
            Warning[] warnings;
            string[] streamIds;

            var result = _reportServerExecutionService.Render(reportFormat, @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>", out extension, out encoding, out mimeType, out warnings, out streamIds);
            //Here is logic for image replcaement

            string html = string.Empty;
            html = System.Text.Encoding.Default.GetString(result);
            html = GetReportImages(_reportServerExecutionService, _reportServerExecutionService.ExecutionHeaderValue, _reportServerExecutionService.TrustedUserHeaderValue, reportFormat, streamIds, html);

        return html;

    }
</code>```

and function (code) for image replacement

```<code>   public string GetReportImages(ReportExecutionService _reportServerExecutionService, ExecutionHeader executionHeaderValue, TrustedUserHeader trustedUserHeaderValue, string reportFormat, string[] streamIds, string html)
        {

                if (reportFormat.Equals("HTML4.0") && streamIds.Length > 0)
                {
                    string devInfo;
                    string mimeType;
                    string Encoding;
                    string fileExtension = ".jpg";
                    string SessionId;
                    Byte[] image;

                    foreach (string streamId in streamIds)
                    {
                        SessionId = Guid.NewGuid().ToString().Replace("}", "").Replace("{", "").Replace("-", "");

                        string reportreplacementname = string.Concat(streamId, "_", SessionId, fileExtension);
                        html = html.Replace(streamId, string.Concat(@"Report\GraphFiles\", reportreplacementname));
                        devInfo = "";

                   image= _reportServerExecutionService.RenderStream(reportFormat, streamId, devInfo, out Encoding, out mimeType);

                    System.IO.FileStream stream = System.IO.File.OpenWrite(HttpContext.Current.Request.PhysicalApplicationPath + "Report\\GraphFiles\\" + reportreplacementname);
                    stream.Write(image, 0, image.Length);
                    stream.Close();
                        mimeType = "text/html";
                    }

            }

            return html;

        }
</code>```

but issue is that  image is saved into folder and also src tag is replaced into html ,still image is not display on report Can anybody have solution for this or any related code for same

Thanks In Advance

答:
Below isway I achieve  render report  using reporting services (ReportExecutionSerivce class and webrefrence of SSRS)

```<code> public class ReportManager
    {
        private readonly ReportExecutionService _reportServerExecutionService;

        public ReportManager(string reportServerWsdlUrl, string username, string password, string domain)
        {
            _reportServerExecutionService = new ReportExecutionService
            {
                Url = reportServerWsdlUrl,
                Credentials = new NetworkCredential(username, password)
            };
        }

        public string Render(string reportDirectory, string reportName, string reportFormat, ParameterValue[] parameters)
        {
            _reportServerExecutionService.ExecutionHeaderValue = new ExecutionHeader();
            _reportServerExecutionService.LoadReport("/GES-MVC/"+reportName, null);
            _reportServerExecutionService.SetExecutionParameters(parameters, "en-us");

            string encoding;
            string mimeType;
            string extension;
            Warning[] warnings;
            string[] streamIds;

            var result = _reportServerExecutionService.Render(reportFormat, @"<DeviceInfo><StreamRoot>/</StreamRoot><HTMLFragment>True</HTMLFragment></DeviceInfo>", out extension, out encoding, out mimeType, out warnings, out streamIds);
            //Here is logic for image replcaement

            string html = string.Empty;
            html = System.Text.Encoding.Default.GetString(result);
            html = GetReportImages(_reportServerExecutionService, reportFormat, streamIds, html);

            return html;

        }

        public string GetReportImages(ReportExecutionService _reportServerExecutionService, string reportFormat, string[] streamIds, string html)
        {

            if (reportFormat.Equals("HTML4.0") && streamIds.Length > 0)
            {
                string devInfo;
                string mimeType;
                string Encoding;
                string fileExtension = ".jpg";
                string SessionId;
                Byte[] image;

                foreach (string streamId in streamIds)
                {
                    SessionId = Guid.NewGuid().ToString().Replace("}", "").Replace("{", "").Replace("-", "");

                    string reportreplacementname = string.Concat(streamId, "_", SessionId, fileExtension);
                    html = html.Replace(streamId, string.Concat(@"Report\GraphFiles\", reportreplacementname));

                    devInfo = "";
                    image = _reportServerExecutionService.RenderStream(reportFormat, streamId, devInfo, out Encoding, out mimeType);

                    System.IO.FileStream stream = System.IO.File.OpenWrite(HttpContext.Current.Request.PhysicalApplicationPath + "Report\\GraphFiles\\" + reportreplacementname);
                    stream.Write(image, 0, image.Length);
                    stream.Close();
                    mimeType = "text/html";
                }

            }

            return html;

        }
</code>```

and here I pass required  parameters to class

```<code>string rprwebserviceurl = exceservice;
                string ReportDirName = "GES-MVC";
                string ReportName = "GES_FWCR";
                string RptFormat = "HTML4.0";
                ParameterValue[] parameters = new ParameterValue[5];
                parameters[0] = new ParameterValue();
                parameters[0].Name = "PlantID";
                parameters[0].Value = PlantID;
                parameters[1] = new ParameterValue();
                parameters[1].Name = "FromDateTime";
                parameters[1].Value = Convert.ToString(fromDate); // June
                parameters[2] = new ParameterValue();
                parameters[2].Name = "ToDateTime";
                parameters[2].Value = Convert.ToString(Todate);
                parameters[3] = new ParameterValue();
                parameters[3].Name = "ClientID";
                parameters[3].Value = ClientID;
                parameters[4] = new ParameterValue();
                parameters[4].Name = "SelectedFeeders";
                parameters[4].Value = SelectedFeeders;
                ReportManager rpt = new ReportManager(rprwebserviceurl,RptUserName,RptPassword, "localhost");
                res = rpt.Render(ReportDirName, reportName, RptFormat, parameters);
</code>```

Body:
I am working on SSRS report. I am accessing report using  web services (using web refrences)
I am using ReportExecutionService class to render report in the html 4.0 format and finaly I attach rendered HTML to my page DIV. Report is rendering very fine in HTML format but the images on that is not rendering properly because of missing authentication for images
 for that  I just replace the src attribute of the img tag in the response returned from the SSRS report execution service with the url to this location below is code for render report:-

 public string Render(string reportDirectory,string reportName,string reportFormat, ParameterValue[]parameters )
        {
            _reportServerExecutionService.ExecutionHeaderValue = new ExecutionHeader();
            _reportServerExecutionService.TrustedUserHeaderValue = new TrustedUserHeader();
            _reportServerExecutionService.LoadReport("/GES-MVC/GES_FWCR",null);
            _reportServerExecutionService.SetExecutionParameters(parameters, "en-us");

            string encoding;
            string mimeType;
            string extension;
            Warning[] warnings;
            string[] streamIds;

            var result = _reportServerExecutionService.Render(reportFormat, @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>", out extension, out encoding, out mimeType, out warnings, out streamIds);
            //Here is logic for image replcaement

            string html = string.Empty;
            html = System.Text.Encoding.Default.GetString(result);
            html = GetReportImages(_reportServerExecutionService, _reportServerExecutionService.ExecutionHeaderValue, _reportServerExecutionService.TrustedUserHeaderValue, reportFormat, streamIds, html);

        return html;

    }

and function (code) for image replacement

   public string GetReportImages(ReportExecutionService _reportServerExecutionService, ExecutionHeader executionHeaderValue, TrustedUserHeader trustedUserHeaderValue, string reportFormat, string[] streamIds, string html)
        {

                if (reportFormat.Equals("HTML4.0") && streamIds.Length > 0)
                {
                    string devInfo;
                    string mimeType;
                    string Encoding;
                    string fileExtension = ".jpg";
                    string SessionId;
                    Byte[] image;

                    foreach (string streamId in streamIds)
                    {
                        SessionId = Guid.NewGuid().ToString().Replace("}", "").Replace("{", "").Replace("-", "");

                        string reportreplacementname = string.Concat(streamId, "_", SessionId, fileExtension);
                        html = html.Replace(streamId, string.Concat(@"Report\GraphFiles\", reportreplacementname));
                        devInfo = "";

                   image= _reportServerExecutionService.RenderStream(reportFormat, streamId, devInfo, out Encoding, out mimeType);

                    System.IO.FileStream stream = System.IO.File.OpenWrite(HttpContext.Current.Request.PhysicalApplicationPath + "Report\\GraphFiles\\" + reportreplacementname);
                    stream.Write(image, 0, image.Length);
                    stream.Close();
                        mimeType = "text/html";
                    }

            }

            return html;

        }

but issue is that  image is saved into folder and also src tag is replaced into html ,still image is not display on report Can anybody have solution for this or any related code for same

Thanks In Advance

Body:
Below isway I achieve  render report  using reporting services (ReportExecutionSerivce class and webrefrence of SSRS)

 public class ReportManager
    {
        private readonly ReportExecutionService _reportServerExecutionService;

        public ReportManager(string reportServerWsdlUrl, string username, string password, string domain)
        {
            _reportServerExecutionService = new ReportExecutionService
            {
                Url = reportServerWsdlUrl,
                Credentials = new NetworkCredential(username, password)
            };
        }

        public string Render(string reportDirectory, string reportName, string reportFormat, ParameterValue[] parameters)
        {
            _reportServerExecutionService.ExecutionHeaderValue = new ExecutionHeader();
            _reportServerExecutionService.LoadReport("/GES-MVC/"+reportName, null);
            _reportServerExecutionService.SetExecutionParameters(parameters, "en-us");

            string encoding;
            string mimeType;
            string extension;
            Warning[] warnings;
            string[] streamIds;

            var result = _reportServerExecutionService.Render(reportFormat, @"<DeviceInfo><StreamRoot>/</StreamRoot><HTMLFragment>True</HTMLFragment></DeviceInfo>", out extension, out encoding, out mimeType, out warnings, out streamIds);
            //Here is logic for image replcaement

            string html = string.Empty;
            html = System.Text.Encoding.Default.GetString(result);
            html = GetReportImages(_reportServerExecutionService, reportFormat, streamIds, html);

            return html;

        }

        public string GetReportImages(ReportExecutionService _reportServerExecutionService, string reportFormat, string[] streamIds, string html)
        {

            if (reportFormat.Equals("HTML4.0") && streamIds.Length > 0)
            {
                string devInfo;
                string mimeType;
                string Encoding;
                string fileExtension = ".jpg";
                string SessionId;
                Byte[] image;

                foreach (string streamId in streamIds)
                {
                    SessionId = Guid.NewGuid().ToString().Replace("}", "").Replace("{", "").Replace("-", "");

                    string reportreplacementname = string.Concat(streamId, "_", SessionId, fileExtension);
                    html = html.Replace(streamId, string.Concat(@"Report\GraphFiles\", reportreplacementname));

                    devInfo = "";
                    image = _reportServerExecutionService.RenderStream(reportFormat, streamId, devInfo, out Encoding, out mimeType);

                    System.IO.FileStream stream = System.IO.File.OpenWrite(HttpContext.Current.Request.PhysicalApplicationPath + "Report\\GraphFiles\\" + reportreplacementname);
                    stream.Write(image, 0, image.Length);
                    stream.Close();
                    mimeType = "text/html";
                }

            }

            return html;

        }

and here I pass required  parameters to class

string rprwebserviceurl = exceservice;
                string ReportDirName = "GES-MVC";
                string ReportName = "GES_FWCR";
                string RptFormat = "HTML4.0";
                ParameterValue[] parameters = new ParameterValue[5];
                parameters[0] = new ParameterValue();
                parameters[0].Name = "PlantID";
                parameters[0].Value = PlantID;
                parameters[1] = new ParameterValue();
                parameters[1].Name = "FromDateTime";
                parameters[1].Value = Convert.ToString(fromDate); // June
                parameters[2] = new ParameterValue();
                parameters[2].Name = "ToDateTime";
                parameters[2].Value = Convert.ToString(Todate);
                parameters[3] = new ParameterValue();
                parameters[3].Name = "ClientID";
                parameters[3].Value = ClientID;
                parameters[4] = new ParameterValue();
                parameters[4].Name = "SelectedFeeders";
                parameters[4].Value = SelectedFeeders;
                ReportManager rpt = new ReportManager(rprwebserviceurl,RptUserName,RptPassword, "localhost");
                res = rpt.Render(ReportDirName, reportName, RptFormat, parameters);


问:
Need to test apache poi excel using mockito
I have written a class to create workbook based on passed data. I am now writing mockito tests for testing my method. I am not allowed to use powermock. Following is the code snippet.

```<code>public class TalkDetailsToExcel extends AbstractXlsView {
    private static final ResourceBundle RESOURCE_BUNDLE = MessageResource.getResourceBundle();

    /**
     * Builds the {@link Workbook} containing {@link Talk} details and adds to the {@link Sheet}.
     *
     * @param model               the {@link Map} containing the {@link List} of {@link Talk}.
     * @param workbook            the Excel {@link Workbook} to which {@link Talk} needs to be added.
     * @param httpServletRequest  the {@link HttpServletRequest}
     * @param httpServletResponse the {@link HttpServletResponse}
     * @throws Exception          when adding talk details to workbook.
     */
    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse) throws Exception {
        final String talkListName = "talkList";
        final String fileName = "Talk Details.xls";

        httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        List<Talk> talkList = (List<Talk>) model.get(talkListName);
        Sheet sheet = createAndReturnSheetFromWorkbook(workbook);
        addTalkDetailsToSheet(talkList, sheet);
    }

    /**
     * Creates data cells to the {@link Sheet}.
     *
     * @param talkList the {@link List} of {@link Talk} objects.
     * @param sheet    the {@link Sheet} to which {@link Talk} details need to add.
     */
    @VisibleForTesting
    void addTalkDetailsToSheet(List<Talk> talkList, Sheet sheet) {
        Verifier.verifyNotNull(talkList, RESOURCE_BUNDLE.getString(MessageResource.SHEET_NULL));
        Verifier.verifyNotEmpty(talkList, RESOURCE_BUNDLE.getString(MessageResource.WORKBOOK_NULL));
        Verifier.verifyNotNull(sheet, RESOURCE_BUNDLE.getString(MessageResource.WORKBOOK_NULL));

        int rowCount = 1;
        for (Talk talk : talkList) {
            Row talkRow = sheet.createRow(rowCount++);
            talkRow.createCell(0).setCellValue(talk.getConference().getName());
            talkRow.createCell(1).setCellValue(talk.getTitle());
            talkRow.createCell(2).setCellValue(talk.getSpeaker());
            talkRow.createCell(3).setCellValue(talk.getCernerId());
            talkRow.createCell(4).setCellValue(String.valueOf(talk.getDifficultyLevel()));
            talkRow.createCell(5).setCellValue(talk.getDateTimeStr());
        }
    }

    /**
     * Creates and returns an empty {@link Sheet} containing header {@link Row}.
     *
     * @param workbook       the {@link Workbook} for which {@link Sheet} needs to be created.
     * @return {@link Sheet} containing the header {@link Row}.
     */
    public Sheet createAndReturnSheetFromWorkbook(Workbook workbook) {
        Verifier.verifyNotNull(workbook, RESOURCE_BUNDLE.getString(MessageResource.WORKBOOK_NULL));

        final String sheetName = "Conference Details";
        final String conferenceName = "Conference";
        final String talkTitle = "Talk";
        final String speakerName = "Speaker";
        final String cernerIdOfSpeaker = "Cerner Id";
        final String difficultyLevel = "Difficulty";
        final String dateTimeOfTalk = "Date Time";

        Sheet sheet = workbook.createSheet(sheetName);
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue(conferenceName);
        header.createCell(1).setCellValue(talkTitle);
        header.createCell(2).setCellValue(speakerName);
        header.createCell(3).setCellValue(cernerIdOfSpeaker);
        header.createCell(4).setCellValue(difficultyLevel);
        header.createCell(5).setCellValue(dateTimeOfTalk);
        return sheet;
    }
}
</code>```

Following is the code snippet I have written so far to write junit, I am not able to mock row using createRow. Problem is Row is always null and test throws null pointer exception. Any suggestions are highly appreciated.

```<code>   /**
   * Tests {@link TalkDetailsToExcel#createAndReturnSheetFromWorkbook(Workbook)} returns a {@link
   * Sheet}
   */
  @Test
  public void testCreateAndReturnSheetFromWorkbookReturnsSheet() {
    Workbook mockWorkbook = mock(Workbook.class);
    Sheet mockSheet = mock(Sheet.class);
    Row mockRow = mock(Row.class);
    doReturn(mockSheet).when(mockWorkbook).createSheet();
    doReturn(mockRow).when(mockSheet.createRow(anyInt()));

    Sheet sheet = mockTalkDetailsToExcel.createAndReturnSheetFromWorkbook(mockWorkbook);
  }
</code>```

答:
Using the code you supplied I reproduced a NPE at this line ...

```<code>talkRow.createCell(0).setCellValue(...)
</code>```

... because although a mocked Row was specified this mock was not instructed to return a Cell on invocation of createCell.

This could be mocked as follows:

```<code>when(mockSheet.createRow(anyInt())).thenReturn(mockRow);
when(mockRow.createCell(anyInt())).thenReturn(mockCell);
</code>```

So, the test could be rewritten to:

```<code>Workbook mockWorkbook = mock(Workbook.class);
Sheet mockSheet = mock(Sheet.class);
Row mockRow = mock(Row.class);
Cell mockCell = mock(Cell.class);
when(mockWorkbook.createSheet("Conference Details")).thenReturn(mockSheet);
when(mockSheet.createRow(0)).thenReturn(mockRow);
when(mockSheet.createRow(anyInt())).thenReturn(mockRow);
when(mockRow.createCell(anyInt())).thenReturn(mockCell);

Sheet sheet = mockTalkDetailsToExcel.createAndReturnSheetFromWorkbook(mockWorkbook);
</code>```

This addresses the NPE.

Body:
I have written a class to create workbook based on passed data. I am now writing mockito tests for testing my method. I am not allowed to use powermock. Following is the code snippet.

public class TalkDetailsToExcel extends AbstractXlsView {
    private static final ResourceBundle RESOURCE_BUNDLE = MessageResource.getResourceBundle();

    /**
     * Builds the {@link Workbook} containing {@link Talk} details and adds to the {@link Sheet}.
     *
     * @param model               the {@link Map} containing the {@link List} of {@link Talk}.
     * @param workbook            the Excel {@link Workbook} to which {@link Talk} needs to be added.
     * @param httpServletRequest  the {@link HttpServletRequest}
     * @param httpServletResponse the {@link HttpServletResponse}
     * @throws Exception          when adding talk details to workbook.
     */
    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse) throws Exception {
        final String talkListName = "talkList";
        final String fileName = "Talk Details.xls";

        httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        List<Talk> talkList = (List<Talk>) model.get(talkListName);
        Sheet sheet = createAndReturnSheetFromWorkbook(workbook);
        addTalkDetailsToSheet(talkList, sheet);
    }

    /**
     * Creates data cells to the {@link Sheet}.
     *
     * @param talkList the {@link List} of {@link Talk} objects.
     * @param sheet    the {@link Sheet} to which {@link Talk} details need to add.
     */
    @VisibleForTesting
    void addTalkDetailsToSheet(List<Talk> talkList, Sheet sheet) {
        Verifier.verifyNotNull(talkList, RESOURCE_BUNDLE.getString(MessageResource.SHEET_NULL));
        Verifier.verifyNotEmpty(talkList, RESOURCE_BUNDLE.getString(MessageResource.WORKBOOK_NULL));
        Verifier.verifyNotNull(sheet, RESOURCE_BUNDLE.getString(MessageResource.WORKBOOK_NULL));

        int rowCount = 1;
        for (Talk talk : talkList) {
            Row talkRow = sheet.createRow(rowCount++);
            talkRow.createCell(0).setCellValue(talk.getConference().getName());
            talkRow.createCell(1).setCellValue(talk.getTitle());
            talkRow.createCell(2).setCellValue(talk.getSpeaker());
            talkRow.createCell(3).setCellValue(talk.getCernerId());
            talkRow.createCell(4).setCellValue(String.valueOf(talk.getDifficultyLevel()));
            talkRow.createCell(5).setCellValue(talk.getDateTimeStr());
        }
    }

    /**
     * Creates and returns an empty {@link Sheet} containing header {@link Row}.
     *
     * @param workbook       the {@link Workbook} for which {@link Sheet} needs to be created.
     * @return {@link Sheet} containing the header {@link Row}.
     */
    public Sheet createAndReturnSheetFromWorkbook(Workbook workbook) {
        Verifier.verifyNotNull(workbook, RESOURCE_BUNDLE.getString(MessageResource.WORKBOOK_NULL));

        final String sheetName = "Conference Details";
        final String conferenceName = "Conference";
        final String talkTitle = "Talk";
        final String speakerName = "Speaker";
        final String cernerIdOfSpeaker = "Cerner Id";
        final String difficultyLevel = "Difficulty";
        final String dateTimeOfTalk = "Date Time";

        Sheet sheet = workbook.createSheet(sheetName);
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue(conferenceName);
        header.createCell(1).setCellValue(talkTitle);
        header.createCell(2).setCellValue(speakerName);
        header.createCell(3).setCellValue(cernerIdOfSpeaker);
        header.createCell(4).setCellValue(difficultyLevel);
        header.createCell(5).setCellValue(dateTimeOfTalk);
        return sheet;
    }
}

Following is the code snippet I have written so far to write junit, I am not able to mock row using createRow. Problem is Row is always null and test throws null pointer exception. Any suggestions are highly appreciated.

   /**
   * Tests {@link TalkDetailsToExcel#createAndReturnSheetFromWorkbook(Workbook)} returns a {@link
   * Sheet}
   */
  @Test
  public void testCreateAndReturnSheetFromWorkbookReturnsSheet() {
    Workbook mockWorkbook = mock(Workbook.class);
    Sheet mockSheet = mock(Sheet.class);
    Row mockRow = mock(Row.class);
    doReturn(mockSheet).when(mockWorkbook).createSheet();
    doReturn(mockRow).when(mockSheet.createRow(anyInt()));

    Sheet sheet = mockTalkDetailsToExcel.createAndReturnSheetFromWorkbook(mockWorkbook);
  }

Body:
Using the code you supplied I reproduced a NPE at this line ...

talkRow.createCell(0).setCellValue(...)

... because although a mocked Row was specified this mock was not instructed to return a Cell on invocation of createCell.

This could be mocked as follows:

when(mockSheet.createRow(anyInt())).thenReturn(mockRow);
when(mockRow.createCell(anyInt())).thenReturn(mockCell);

So, the test could be rewritten to:

Workbook mockWorkbook = mock(Workbook.class);
Sheet mockSheet = mock(Sheet.class);
Row mockRow = mock(Row.class);
Cell mockCell = mock(Cell.class);
when(mockWorkbook.createSheet("Conference Details")).thenReturn(mockSheet);
when(mockSheet.createRow(0)).thenReturn(mockRow);
when(mockSheet.createRow(anyInt())).thenReturn(mockRow);
when(mockRow.createCell(anyInt())).thenReturn(mockCell);

Sheet sheet = mockTalkDetailsToExcel.createAndReturnSheetFromWorkbook(mockWorkbook);

This addresses the NPE.


问:
Refresh image URL in ionic 2
I have this HTML syntaks for loop my URL, the URL for get an image from my directory by internet,
but when image changed in my server, the application still showed last image before I update, I was only change image not name.

```<code><ion-card style="margin: auto">
    <ion-card-header class ="head" style="background-color: gray !important">
      <font color="White">{{dt.desc}}</font>
    </ion-card-header>
    <img src= {{dt.name}} >
</ion-card>
</code>```

Whats wrong with this, and how to make image change whenever i change image in server?
In my case the image can replace to new image I've update when I uninstall that apps

答:
Can you use https://ionicframework.com/docs/api/components/refresher/Refresher/.
But you have to retake your data in doRefresh(refresher).</p>

Title: Refresh image URL in ionic 2

Body:
I have this HTML syntaks for loop my URL, the URL for get an image from my directory by internet,
but when image changed in my server, the application still showed last image before I update, I was only change image not name.

<ion-card style="margin: auto">
    <ion-card-header class ="head" style="background-color: gray !important">
      {{dt.desc}}
    </ion-card-header>

</ion-card>

Whats wrong with this, and how to make image change whenever i change image in server?
In my case the image can replace to new image I've update when I uninstall that apps


问:
Hibernate 5.2 encrypt configuration properties
In my application build on Hibernate 5.2.11 there are many hibernate configuration file with username, password and connection url.
I would like to encrypt that data.

My configuration file is like this:

```<code><hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

    <property name="connection.url">jdbc:oracle:localhos</property>
    <property name="connection.username">username</property>
    <property name="connection.password">passowrd123</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">2</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">false</property>

</session-factory>

</hibernate-configuration>
</code>```

Any suggestion?

答:
Use a property placeholder then add your database config to a properties file on the server:

```<code><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>file:${configDir}/database.properties</value>
  </property>
</bean>
</code>```

Then

```<code><property name="connection.url">${url}</property>
<property name="connection.username">${username}</property>
<property name="connection.password">${passowrd}</property>
</code>```

Then your database.properties which is securely on the server will be

```<code>url=jdbc:oracle:localhost
usuername=username
password=passowrd123
</code>```

Then when you start your java app add a system parameter to define the configDir location, for example:

```<code> .... -DconfigDir=/opt/config
</code>```

See examples here

Body:
In my application build on Hibernate 5.2.11 there are many hibernate configuration file with username, password and connection url.
I would like to encrypt that data.

My configuration file is like this:

<hibernate-configuration>

<session-factory>

    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

    <property name="connection.url">jdbc:oracle:localhos</property>
    <property name="connection.username">username</property>
    <property name="connection.password">passowrd123</property>

    <property name="connection.pool_size">2</property>

    <property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>

    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <property name="show_sql">false</property>

</session-factory>

</hibernate-configuration>

Any suggestion?

Body:
Use a property placeholder then add your database config to a properties file on the server:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>file:${configDir}/database.properties</value>
  </property>
</bean>

Then

<property name="connection.url">${url}</property>
<property name="connection.username">${username}</property>
<property name="connection.password">${passowrd}</property>

Then your database.properties which is securely on the server will be

url=jdbc:oracle:localhost
usuername=username
password=passowrd123

Then when you start your java app add a system parameter to define the configDir location, for example:

 .... -DconfigDir=/opt/config

See examples here


问:
How to prevent port timeouts for large remote queries from SQL Server?
I have an unixODBC connection from a linux-based SAP HANA database trying to pull massive amounts of data from another SQL Server 2012 database. Every now and then though I get "Login timeout expired" errors and I also notice via netstat that while the connection reaches "ESTABLISHED" status, it just closes out after about 10 seconds. The issue doesn't happen every time, and I've already done all kinds of due diligence on the network side and found no issues on that end.

Is there anything that can be done on the SQL Server configuration so that the connection doesn't time out?

The current remote query timeout is 600 seconds and remote login time-out is 30 seconds.

I also read in the following link that increasing "Connection timeout" setting in SQL Server helps but how do I change it, it's grayed out.

答:
You are right to note that you need to change the remote query timeout setting to 0.

This link give pretty neat answer to your question. There are ways for doing it via both the SQL Server management Studio, and the command line. However, you need to first login with a user that has the required permissions.


问:
Reduce database log file size
My sql database .mdf file is 130mb and .ldf file is 1300mb. I want to reduce my .ldf file size.
How can I do it and is there any problem occur after deleted data.

Thanks in advance

答:
To start with, do a full backup, a log backup, and then set up scheduled log backups if you haven't done so already. After a few log backups you can shrink the log file and hopefully it won't grow that large again (unless you do some really unusual updates that touch a lot of data over and over again).

See http://msdn.microsoft.com/en-us/library/ms189275.aspx for more info on the different SQL Server recovery modes and backup requirements.

Title: Reduce database log file size


问:
How do I strip down a URL into separate parts in Bash?
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

```<code>URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)
</code>```

答:
Try this too,</p>

```<code>URL="https://example.com/someone/something?test=a"

DOMAIN=$(echo "$URL" | python -c "from urlparse import urlparse;import sys; print urlparse(sys.stdin.read()).hostname")

USER=$(echo "$URL" | python -c "from urlparse import urlparse;import sys; print urlparse(sys.stdin.read()).path.split('/')[1]")

THING=$(echo "$URL" | python -c "from urlparse import urlparse;import sys; print urlparse(sys.stdin.read()).path.split('/')[2]")

QUERYSTRING=$(echo "$URL" | python -c "from urlparse import urlparse;import sys; print urlparse(sys.stdin.read()).query")
</code>```

Body:
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)

Body:
Try this too,

URL="https://example.com/someone/something?test=a"

DOMAIN=$(echo "$URL" | python -c "from urlparse import urlparse;import sys; print urlparse(sys.stdin.read()).hostname")

USER=$(echo "$URL" | python -c "from urlparse import urlparse;import sys; print urlparse(sys.stdin.read()).path.split('/')[1]")

THING=$(echo "$URL" | python -c "from urlparse import urlparse;import sys; print urlparse(sys.stdin.read()).path.split('/')[2]")

QUERYSTRING=$(echo "$URL" | python -c "from urlparse import urlparse;import sys; print urlparse(sys.stdin.read()).query")


问:
Convert ArrayList to Double Array in java
How to Convert ArrayList to Double Array in Java6?

```<code> List lst = new ArrayList();
 double[] dbl=null;
 lst.add(343.34);
 lst.add(432.34);
</code>```

How convert above list to array?

答:
```<code>List<Number> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42);
double[] dbl = lst.stream()
    .map(Number::cast) // Or possibly Double::cast when List lst.
    .mapToDouble(Number::doubleValue)
    .toArray();

List<Double> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42.0);
double[] dbl = lst.stream()
    .mapToDouble(Double::doubleValue)
    .toArray();
</code>```

The mapToDouble transforms an Object holding Stream to a DoubleStream of primitive doubles.

Body:
How to Convert ArrayList to Double Array in Java6?

 List lst = new ArrayList();
 double[] dbl=null;
 lst.add(343.34);
 lst.add(432.34);

How convert above list to array?

Body:
List<Number> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42);
double[] dbl = lst.stream()
    .map(Number::cast) // Or possibly Double::cast when List lst.
    .mapToDouble(Number::doubleValue)
    .toArray();

List<Double> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42.0);
double[] dbl = lst.stream()
    .mapToDouble(Double::doubleValue)
    .toArray();

The mapToDouble transforms an Object holding Stream to a DoubleStream of primitive doubles.


问:
classloader in java is a class itself then who will load the classloader class?
ClassLoader in Java is a class which is used to load class files in Java.

The java.lang.ClassLoader is an abstract class

here my question is does this java.lang.ClassLoader class is any way related to JVM's classloaders(1. Bootstrap class loader 2. Extensions class loader 3. System class loader)?

or this java.lang.ClassLoader is a separate class which can be used to create a custom classloader?

Class loaders are the part of the Java Runtime Environment that dynamically loads Java classes into the Java virtual machine. It is responsible for locating libraries, reading there content and loading the classes contained within the libraries When JVM is started three class loaders are used

Bootstrap class loader

Extensions class loader

System class loader

Bootstrap class loader loads the core java libraries. It is written in native code. The bootstrap class loader is responsible for loading key java classes like java.lang.Object and other runtime code into memory. The runtime classes are packaged inside jre/lib/rt.jar file.

Extensions class loader loads the code in the extension directories. It is implemented by ExtClassLoader class.

System class loader the code found on the java.class.path which map to the system class path variables. It is implemented by AppClassLoader class. All user classes by default are load by the system class loader.

Java ClassLoader are hierarchical and whenever a request is raised to load a class, it delegates it to its parent and in this way uniqueness is maintained in the runtime environment. If the parent class loader doesn’t find the class then the class loader itself tries to load the class.

so that means first System class loader will delegate request to Extensions class loader that will delegate request to Bootstrap class loader here it will search for class if not found then  Extensions class loader  will search for class if not found then  System class loader  will search for class if not found then it throws ClassNotFoundException

does JVM always starts with System class loader for loading class?

correct me if i'm wrong any where

答:
The term “System class loader” is a misnomer. As you stated correctly, it’s responsible for loading the classes from locations of the class path, which are the application classes.

As of Java 8, both, AppClassLoader and ExtClassLoader, are subclasses of java.net.URLClassLoader, which is a subclass of java.security.SecureClassLoader, which is a subclass of java.lang.ClassLoader. All of these classes are loaded by the Bootstrap loader, solving the chicken-and-egg problem.

Each runtime class has a defining class loader. For those classes defined by the Bootstrap loader during startup, the defining class loader is the Bootstrap loader. When the JVM initialization is completed and an attempt to start an application is made, the Application class loader (aka System class loader) will be queried for the main class. The Application class loader will follow the standard delegation model querying the parent first, likewise does the Extension class loader and whichever class loader will create the class will be the class’ defining class loader.

Now, when resolving a class referenced by another class or when Class.forName(String) is invoked, the defining loader of the class containing the reference will be used to resolve the class. So when the Application class loader has loaded your class myapp.foo.Bar and it contains a reference to javax.swing.JButton, its defining class loader, i.e. the Application class loader, will be queried for that class, follow the delegation model to end up with a javax.swing.JButton defined by the Bootstrap loader. So class references within javax.swing.JButton are resolved only through the Bootstrap loader, which implies that javax.swing.JButton can not contain a reference to your myapp.foo.Bar class, as it is not in scope.

So, the JVM does not always starts with “System class loader” for loading a class, but only for resolving class references of classes defined by it (or a child loader) or when being queried explicitly, like when resolving the main class.

There are 3rd party class loaders not strictly following the parent delegation model, but regardless of how and to which loader they delegate, there will be a defining loader for each class (the one returned by getClassLoader()), which will be the one used for resolving references within the class. The JVM ensures that identical symbolic names within one class always resolve to the same runtime class, regardless of how the particular class loader implements lookups.

Note that in Java 9, the Extension class loader has been replaced by the Platform class loader. This class loader may deviate from the simple parent delegation, i.e. it might delegate to the Application class loader for loading application provided modules that supersede a platform provided module. Also, the builtin class loaders are not subclasses of URLClassLoader anymore.


问:
Select all inputs, except elements inside Summernote's div
Summernote's modals have modals with inputs inside.

My JS goes here:

```<code>$('input, select, textarea').on('change',
    function(e){
        var inputs = $('input:text, input[type="radio"]:checked').map(
            function(){
                /* show values */
            }
        ).get();
    }
);
</code>```

Tried to use not() but it doesn't work:

```<code>var inputs = $('input:text, input[type="radio"]:checked')
    .not('div.note-editor > input')
    .map()
    .get();
</code>```

答:
Using not is correct, but you should remove the > as it specifies a direct child, which the input is not. So

```<code>var inputs = $('input:text, input[type="radio"]:checked')
    .not('div.note-editor input')
    .map()
    .get();
</code>```

Body:
Summernote's modals have modals with inputs inside.

My JS goes here:

$('input, select, textarea').on('change',
    function(e){
        var inputs = $('input:text, input[type="radio"]:checked').map(
            function(){
                /* show values */
            }
        ).get();
    }
);

Tried to use not() but it doesn't work:

var inputs = $('input:text, input[type="radio"]:checked')
    .not('div.note-editor > input')
    .map()
    .get();

Body:
Using not is correct, but you should remove the > as it specifies a direct child, which the input is not. So

var inputs = $('input:text, input[type="radio"]:checked')
    .not('div.note-editor input')
    .map()
    .get();


问:
how to join table in grid view in yii2
i want to join my company table name to employee id. here my code in
   employee model

```<code>   public function attributeLabels()
        {
            return [
               'id' => 'ID',
                //'company_id' => 'Company ID',
                'emp_name' => 'Emp Name',
                'emp_email' => 'Emp Email',
                'emp_salery' => 'Emp Salery',
            ];
        }

       public function getCompany()
       {
       return $this->hasOne(Company::className(),['id' => 'company_id']);

       }
</code>```

in index file i use this code

```<code>    <?php PJax::begin();?>
        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                //['class' => 'yii\grid\SerialColumn'],

                //'id',
                [
              'attribute' => 'company_id',
              'value' => 'company.name',
             ],
                'emp_name',
                'emp_email:email',
                'emp_salery',

                ['class' => 'yii\grid\ActionColumn'],
            ],
        ]); ?>
    <?php PJax::end();?></div>
</code>```

in employee search table i use this code

```<code>    public function search($params)
        {
            $query = Employee::find();
          $query->joinWith(['company']);
            // add conditions that should always apply here

            $dataProvider = new ActiveDataProvider([
                'query' => $query,
            ]);

            $this->load($params);

            if (!$this->validate()) {
                // uncomment the following line if you do not want to return any records when validation fails
                 $query->where('0=1');
                return $dataProvider;
            }

            // grid filtering conditions
            $query->andFilterWhere([
                'id' => $this->id,
            ]);

            $query->andFilterWhere(['like', 'company_id', $this->company_id])
                ->andFilterWhere(['like', 'emp_name', $this->emp_name])
                ->andFilterWhere(['like', 'emp_email', $this->emp_email])
                ->andFilterWhere(['like', 'emp_salery', $this->emp_salery])
                ->andFilterWhere(['like', 'Company.name', $this->company_id])
             ->andFilterWhere(['like', 'company.name', $this->company])
    ;

            return $dataProvider;
        }
</code>```

http://localhost/test/web/employee/

is shows in company field (not set)
    pls help me

答:
You should add  a getter eg:getCompanyname()n your base model

```<code>    ......
    public function attributeLabels()
    {
        return [
           'id' => 'ID',
            //'company_id' => 'Company ID',
            'emp_name' => 'Emp Name',
            'emp_email' => 'Emp Email',
            'emp_salery' => 'Emp Salery',
            'companyName' =>  'Company Name')
        ];
    }

   public function getCompany()
   {
   return $this->hasOne(Company::className(),['id' => 'company_id']);

   }
</code>```

You should add  a  getter for company name

```<code>   /*
      Getter for company name

   */
  public function getCommpanyName() {
      return $this->company->name;
  }
</code>```

and in your gridview you should use the new get name (companyName)

```<code>  <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [

            'companyName',

            'emp_name',
            'emp_email:email',
            'emp_salery',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</code>```

see this for more complete samples
http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/

Title: how to join table in grid view in yii2

Body:
i want to join my company table name to employee id. here my code in
   employee model

   public function attributeLabels()
        {
            return [
               'id' => 'ID',
                //'company_id' => 'Company ID',
                'emp_name' => 'Emp Name',
                'emp_email' => 'Emp Email',
                'emp_salery' => 'Emp Salery',
            ];
        }

       public function getCompany()
       {
       return $this->hasOne(Company::className(),['id' => 'company_id']);

       }

in index file i use this code

    <?php PJax::begin();?>
        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                //['class' => 'yii\grid\SerialColumn'],

                //'id',
                [
              'attribute' => 'company_id',
              'value' => 'company.name',
             ],
                'emp_name',
                'emp_email:email',
                'emp_salery',

                ['class' => 'yii\grid\ActionColumn'],
            ],
        ]); ?>
    <?php PJax::end();?>

in employee search table i use this code

    public function search($params)
        {
            $query = Employee::find();
          $query->joinWith(['company']);
            // add conditions that should always apply here

            $dataProvider = new ActiveDataProvider([
                'query' => $query,
            ]);

            $this->load($params);

            if (!$this->validate()) {
                // uncomment the following line if you do not want to return any records when validation fails
                 $query->where('0=1');
                return $dataProvider;
            }

            // grid filtering conditions
            $query->andFilterWhere([
                'id' => $this->id,
            ]);

            $query->andFilterWhere(['like', 'company_id', $this->company_id])
                ->andFilterWhere(['like', 'emp_name', $this->emp_name])
                ->andFilterWhere(['like', 'emp_email', $this->emp_email])
                ->andFilterWhere(['like', 'emp_salery', $this->emp_salery])
                ->andFilterWhere(['like', 'Company.name', $this->company_id])
             ->andFilterWhere(['like', 'company.name', $this->company])
    ;

            return $dataProvider;
        }

http://localhost/test/web/employee/

is shows in company field (not set)
    pls help me

Body:
You should add  a getter eg:getCompanyname()n your base model

    ......
    public function attributeLabels()
    {
        return [
           'id' => 'ID',
            //'company_id' => 'Company ID',
            'emp_name' => 'Emp Name',
            'emp_email' => 'Emp Email',
            'emp_salery' => 'Emp Salery',
            'companyName' =>  'Company Name')
        ];
    }

   public function getCompany()
   {
   return $this->hasOne(Company::className(),['id' => 'company_id']);

   }

You should add  a  getter for company name

   /*
      Getter for company name

   */
  public function getCommpanyName() {
      return $this->company->name;
  }

and in your gridview you should use the new get name (companyName)

  <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [

            'companyName',

            'emp_name',
            'emp_email:email',
            'emp_salery',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

see this for more complete samples
http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/


问:
Missing OnClientClick (or onclick in HTML) for asp:Button if I use Enabled=false
In my page, I have a group of two radio buttons. If click on radio button 2, it will activate a search button. If user click on this search button, it will use jQuery .ajax call to retrieve data and display in a jqGrid.

The search button has to be disabled at start up. By disabled, I mean if user clicks on it, nothing should happen.

As the button is asp button, I use Enabled as:

```<code><asp:Button ID="btnSearch" Text="Search" UseSubmitBehavior="false" runat="server" Enabled="false" OnClientClick="return SearchAccessCode()" />
</code>```

Here is the code for detecting/handling radio button group toggling:

```<code>$('input[name$=radioGroup]').change(function() {
    if ($('input[name$=radioGroup]:checked').val() == "rbFirst") {
        $('#<%=btnSearch.ClientID%>').prop('disabled', true);
    }
    else {
        $('#<%=btnSearch.ClientID%>').prop('disabled', false);
    }
}
</code>```

When I debug my page, after clicking on the second radio button (rbSecond), the Search button is enabled. I click on it and nothing happens! I check the HTML generated and find out it is different from other button. There is no onclick() associated with it!

```<code><input type="button" name="ctl00$MainContent$btnSearch" value="Search" id="MainContent_btnSearch" disabled="disabled" class="aspNetDisabled" />
</code>```

From the web, I know that the Enabled will be transated to disabled in HTML. So I replace the Enabled with disabled.

```<code><asp:Button ID="btnSearch" Text="Search" UseSubmitBehavior="false" runat="server" Disabled="True" OnClientClick="return SearchAccessCode()" />
</code>```

Open up the HTML generated and find out it is same as other asp button. Meaning: it has onclick(). Of course, when I press the Search button, the search function is actually performed!

```<code> <input type="button" name="ctl00$MainContent$btnSearch" value="Search" onclick="return SearchAccessCode();__doPostBack('ctl00$MainContent$btnSearch','')" id="MainContent_btnSearch" Disabled="True" />
</code>```

I just could not help but to ask why. As Javascript can be inserted into an ASP.NET page, if a button is disabled using Enabled="false" (the Microsoft way), I can enable it back using JavaScript. But at this time, I will lose the connection between the button and the function pointed to by onclick()!

答:
This is default behaviour, since the button is disabled anyway and has no function. Re-enabling it, will trigger a PostBack and add the OnClientClick to the button:

```<code><asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:Button ID="btnSearch" Text="Search" UseSubmitBehavior="false" runat="server" Enabled="false" OnClientClick="console.log('btnSearch onClientClickEvent');" />
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:Button ID="Button1" Text="Toggle Search Button" UseSubmitBehavior="false" runat="server" OnClick="Button1_Click" />
</code>```

.cs:

```<code>protected void Button1_Click(object sender, EventArgs e) => btnSearch.Enabled = !btnSearch.Enabled;
</code>```

If you want to keep the OnClientClick event as markup even when the button is disabled you have to use javascript, so the PostBack is not triggered:

```<code>document.getElementById("<%= btnSearch.ClientID %>").disabled = true;
</code>```

Or as you stated, just use the disabled attribute:

```<code><asp:Button ID="btnSearch" Text="Search" UseSubmitBehavior="false" runat="server" disabled OnClientClick="console.log('btnSearch onClientClickEvent');" />
</code>```

Body:
In my page, I have a group of two radio buttons. If click on radio button 2, it will activate a search button. If user click on this search button, it will use jQuery .ajax call to retrieve data and display in a jqGrid.

The search button has to be disabled at start up. By disabled, I mean if user clicks on it, nothing should happen.

As the button is asp button, I use Enabled as:

<asp:Button ID="btnSearch" Text="Search" UseSubmitBehavior="false" runat="server" Enabled="false" OnClientClick="return SearchAccessCode()" />

Here is the code for detecting/handling radio button group toggling:

$('input[name$=radioGroup]').change(function() {
    if ($('input[name$=radioGroup]:checked').val() == "rbFirst") {
        $('#<%=btnSearch.ClientID%>').prop('disabled', true);
    }
    else {
        $('#<%=btnSearch.ClientID%>').prop('disabled', false);
    }
}

When I debug my page, after clicking on the second radio button (rbSecond), the Search button is enabled. I click on it and nothing happens! I check the HTML generated and find out it is different from other button. There is no onclick() associated with it!

<input type="button" name="ctl00$MainContent$btnSearch" value="Search" id="MainContent_btnSearch" disabled="disabled" class="aspNetDisabled" />

From the web, I know that the Enabled will be transated to disabled in HTML. So I replace the Enabled with disabled.

<asp:Button ID="btnSearch" Text="Search" UseSubmitBehavior="false" runat="server" Disabled="True" OnClientClick="return SearchAccessCode()" />

Open up the HTML generated and find out it is same as other asp button. Meaning: it has onclick(). Of course, when I press the Search button, the search function is actually performed!

 <input type="button" name="ctl00$MainContent$btnSearch" value="Search" onclick="return SearchAccessCode();__doPostBack('ctl00$MainContent$btnSearch','')" id="MainContent_btnSearch" Disabled="True" />

I just could not help but to ask why. As Javascript can be inserted into an ASP.NET page, if a button is disabled using Enabled="false" (the Microsoft way), I can enable it back using JavaScript. But at this time, I will lose the connection between the button and the function pointed to by onclick()!

Body:
This is default behaviour, since the button is disabled anyway and has no function. Re-enabling it, will trigger a PostBack and add the OnClientClick to the button:

<asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:Button ID="btnSearch" Text="Search" UseSubmitBehavior="false" runat="server" Enabled="false" OnClientClick="console.log('btnSearch onClientClickEvent');" />
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:Button ID="Button1" Text="Toggle Search Button" UseSubmitBehavior="false" runat="server" OnClick="Button1_Click" />

.cs:

protected void Button1_Click(object sender, EventArgs e) => btnSearch.Enabled = !btnSearch.Enabled;

If you want to keep the OnClientClick event as markup even when the button is disabled you have to use javascript, so the PostBack is not triggered:

document.getElementById("<%= btnSearch.ClientID %>").disabled = true;

Or as you stated, just use the disabled attribute:

<asp:Button ID="btnSearch" Text="Search" UseSubmitBehavior="false" runat="server" disabled OnClientClick="console.log('btnSearch onClientClickEvent');" />


问:
How to fail all tests within "describe" block if first test fail in protractor/jasmine?
I would like to fail whole describe block if first test fail within it?
Is this possible with protractor/jasmine? </p>

答:
You can most probably just use the Jasmine built-in done.fail possibility.

Read about it here

As an example in your question is missing, here the plain example from jasmines introduction page:

```<code>describe("A spec using done.fail", function() {
  var foo = function(x, callBack1, callBack2) {
    if (x) {
      setTimeout(callBack1, 0);
    } else {
      setTimeout(callBack2, 0);
    }
  };

  it("should not call the second callBack", function(done) {
    foo(true,
      done,
      function() {
        done.fail("Second callback has been called");
      }
    );
  });
});
</code>```

Body:
You can most probably just use the Jasmine built-in done.fail possibility.

Read about it here

As an example in your question is missing, here the plain example from jasmines introduction page:

describe("A spec using done.fail", function() {
  var foo = function(x, callBack1, callBack2) {
    if (x) {
      setTimeout(callBack1, 0);
    } else {
      setTimeout(callBack2, 0);
    }
  };

  it("should not call the second callBack", function(done) {
    foo(true,
      done,
      function() {
        done.fail("Second callback has been called");
      }
    );
  });
});