问:
jQuery dynamically add script getting body is null
I am writing a jQuery plugin that references another plugin, I dynamically add the reference to that plugin when mine is called:

```<code>var headID = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'js/jquery.genericplugin.js';
document.body.appendChild(script);
</code>```

To call this plugin I use the following in my head tags:

```<code><script type="text/javascript" src="path/to/myplugin.js" />
<script type="text/javascript">
    $(document).ready(function() {
        $('#object').myplugin({
            option1: 1,
            option2: 2
         });
    });
</script>
</code>```

I have tested this successfully on one page, however I'm trying to update another page that was using the code and I keep getting a document body is null error. I'm assuming this is because the body hasn't loaded before my plugin is trying to add the script to it. I changed my page code so that the reference to the plugin is also in the document ready event.

```<code><script type="text/javascript">
    $(document).ready(function() {
        var headID = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'path/to/myplugin.js';
        document.body.appendChild(script);

        $('#object').myplugin({
            option1: 1,
            option2: 2
         });
    });
</script>
</code>```

I no longer get the document body is null error, however I get an error telling me that $('#object').myplugin is not a function
The page is an asp mess, I have verified that I am adding the information in the header of the page...so I'm kind of at a loss. I'm pretty certain I know what is happening, but not why or a solution.

EDIT
Here is what my plugin looks like:

```<code>(function($) {
 var headID = document.getElementsByTagName('head')[0];
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'js/jquery.genericplugin.js';
 document.body.appendChild(script);

 $('.diag-close').live('click', function() {
  $.modal.close();
 });

 $.fn.photomodal = function(options) {

  var defaults = {
   iframeUrl: '',
   imageName: '',
   linkID: '',
   photoID: ''
  };

  var opts = $.extend(defaults, options);

  return this.each(function() {
   $this = $(this);

   $this.click(function() {
    buildModal({
     iframeUrl: opts.iframeUrl,
     photoID: opts.photoID,
     imageName: opts.imageName
    });
   });
  });
 };

 function buildModal(options) {
  var img = new Image();
  img.src = 'http://www.gravatar.com/avatar/' + options.imageName;

  var h = img.height + 310;
  var w = img.width + 110;

  var defaults = {
   bgcolor: '#fff',
   border: '4px solid #3B5998',
   height: h,
   width: w,
   padding: 0,
   top: 15,
   photoID: 'photoThumb'
  };
  var opts = $.extend(defaults, options);
  $.modal('<iframe src="' + opts.iframeUrl + '" height="' + opts.height + '" width="' + opts.width + '" style="border: 0" scrolling="no">', {
   closeHTML: '<img src="x.png" alt="close" style="cursor: pointer; float: right;" />',
   containerCss: {
    'background-color': opts.bgcolor,
    'border': opts.border,
    'height': opts.height + 10,
    'width': opts.width + 20,
    'padding': opts.padding,
    'top': opts.top
   },
   onClose: function(dialog) {
     dialog.data.fadeOut('slow', function() {
      dialog.container.slideUp('slow', function() {
       dialog.overlay.fadeOut('slow', function() {
        $.modal.close();
        if($('#' + opts.photoID).attr('src') != 'undefined')
        {
         var src = $('#' + opts.photoID).attr('src');
         var d = new Date();
         $('#' + opts.photoID).attr('src', src + '&' + d.getTime());
        }
       });
      });
     });
   },
   overlayClose: true,
   autoResize: true
  });
 }
})(jQuery);
</code>```

It is successful on an asp page where the header and footer are being created in asp include files...however if I add it to a page where the header is in the same page it comes back document body is null.

答:
Since you are using jQuery why not use its .getScript() method that accepts a callback for when the script is loaded ?

```<code>$.getScript('path/to/myplugin.js', function(){
     $('#object').myplugin({
            option1: 1,
            option2: 2
      });
});
</code>```

Body:
I am writing a jQuery plugin that references another plugin, I dynamically add the reference to that plugin when mine is called:

var headID = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'js/jquery.genericplugin.js';
document.body.appendChild(script);

To call this plugin I use the following in my head tags:

I have tested this successfully on one page, however I'm trying to update another page that was using the code and I keep getting a document body is null error. I'm assuming this is because the body hasn't loaded before my plugin is trying to add the script to it. I changed my page code so that the reference to the plugin is also in the document ready event.

I no longer get the document body is null error, however I get an error telling me that $('#object').myplugin is not a function
The page is an asp mess, I have verified that I am adding the information in the header of the page...so I'm kind of at a loss. I'm pretty certain I know what is happening, but not why or a solution.

EDIT
Here is what my plugin looks like:

(function($) {
 var headID = document.getElementsByTagName('head')[0];
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'js/jquery.genericplugin.js';
 document.body.appendChild(script);

 $('.diag-close').live('click', function() {
  $.modal.close();
 });

 $.fn.photomodal = function(options) {

  var defaults = {
   iframeUrl: '',
   imageName: '',
   linkID: '',
   photoID: ''
  };

  var opts = $.extend(defaults, options);

  return this.each(function() {
   $this = $(this);

   $this.click(function() {
    buildModal({
     iframeUrl: opts.iframeUrl,
     photoID: opts.photoID,
     imageName: opts.imageName
    });
   });
  });
 };

 function buildModal(options) {
  var img = new Image();
  img.src = 'http://www.gravatar.com/avatar/' + options.imageName;

  var h = img.height + 310;
  var w = img.width + 110;

  var defaults = {
   bgcolor: '#fff',
   border: '4px solid #3B5998',
   height: h,
   width: w,
   padding: 0,
   top: 15,
   photoID: 'photoThumb'
  };
  var opts = $.extend(defaults, options);
  $.modal('', {
   closeHTML: '',
   containerCss: {
    'background-color': opts.bgcolor,
    'border': opts.border,
    'height': opts.height + 10,
    'width': opts.width + 20,
    'padding': opts.padding,
    'top': opts.top
   },
   onClose: function(dialog) {
     dialog.data.fadeOut('slow', function() {
      dialog.container.slideUp('slow', function() {
       dialog.overlay.fadeOut('slow', function() {
        $.modal.close();
        if($('#' + opts.photoID).attr('src') != 'undefined')
        {
         var src = $('#' + opts.photoID).attr('src');
         var d = new Date();
         $('#' + opts.photoID).attr('src', src + '&' + d.getTime());
        }
       });
      });
     });
   },
   overlayClose: true,
   autoResize: true
  });
 }
})(jQuery);

It is successful on an asp page where the header and footer are being created in asp include files...however if I add it to a page where the header is in the same page it comes back document body is null.

Body:
Since you are using jQuery why not use its .getScript() method that accepts a callback for when the script is loaded ?

$.getScript('path/to/myplugin.js', function(){
     $('#object').myplugin({
            option1: 1,
            option2: 2
      });
});


来源: stackexchange

问:
Sum Expression Aggregate Error
I am rewriting this question because Gordon Linoff told me it might come off as rude if I edited my other one -- so this isn't a duplicate, just a correction.

I am trying to write a code that will sum the prices of all the orders that come up when I fill out the query. For example, if I enter the ID range 1-60, I want there to be a sum column created that then sums up all the prices of ID's 1-60.

I thought it would be simple enough to just create a SUM(.....) AS Exp 1, but it tells me that there is a problem with the ID and aggregate function.

I want to be able to see the individual prices, as well as a new column with the sum of all these prices. I plan on adding some more columns of data into the table later on.

My current code looks like this:

```<code>SELECT table.ID, table.Price, SUM(table.Price) AS Exp 1
FROM table
WHERE table.ID BETWEEN StartID AND EndID
</code>```

Thank you for any help

答:
You have a concept error with your aggregate statement. When you run this query, the WHERE clause will evaluate first to exclude all IDs that are not between your user specified start and end points. Then, you missed the GROUP BY clause to tell it what needs to be grouped. Eliminate the table.Price field, otherwise you will be getting unique records for each price which is not what you want.

```<code>SELECT t.ID, SUM(t.Price) AS Price_Summary
FROM table t
WHERE t.ID BETWEEN StartID AND EndID
GROUP BY t.ID
</code>```

Also, aliases will help improve readability.

EDIT

I think this might be what you are trying to get to, but I'm still unclear.

```<code>SELECT t.ID, SUM(t.Price) AS Price_Summary,
    (SELECT SUM(t2.Price) FROM table t2 WHERE t2.ID BETWEEN StartID AND EndID) AS Total_Price
FROM table t
WHERE t.ID BETWEEN StartID AND EndID
GROUP BY t.ID
</code>```

This will give you a result set with all of the IDs, a sum of the price of everything with that ID, and then a total sum. So it would look something like this:

```<code>ID | Price_Summary | Total_Price
1    10              60
2    30              60
3    20              60
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sum Expression Aggregate Error

Body:
I am rewriting this question because Gordon Linoff told me it might come off as rude if I edited my other one -- so this isn't a duplicate, just a correction.

I am trying to write a code that will sum the prices of all the orders that come up when I fill out the query. For example, if I enter the ID range 1-60, I want there to be a sum column created that then sums up all the prices of ID's 1-60.

I thought it would be simple enough to just create a SUM(.....) AS Exp 1, but it tells me that there is a problem with the ID and aggregate function.

I want to be able to see the individual prices, as well as a new column with the sum of all these prices. I plan on adding some more columns of data into the table later on.

My current code looks like this:

SELECT table.ID, table.Price, SUM(table.Price) AS Exp 1
FROM table
WHERE table.ID BETWEEN StartID AND EndID

Thank you for any help

Body:
You have a concept error with your aggregate statement. When you run this query, the WHERE clause will evaluate first to exclude all IDs that are not between your user specified start and end points. Then, you missed the GROUP BY clause to tell it what needs to be grouped. Eliminate the table.Price field, otherwise you will be getting unique records for each price which is not what you want.

SELECT t.ID, SUM(t.Price) AS Price_Summary
FROM table t
WHERE t.ID BETWEEN StartID AND EndID
GROUP BY t.ID

Also, aliases will help improve readability.

EDIT

I think this might be what you are trying to get to, but I'm still unclear.

SELECT t.ID, SUM(t.Price) AS Price_Summary,
    (SELECT SUM(t2.Price) FROM table t2 WHERE t2.ID BETWEEN StartID AND EndID) AS Total_Price
FROM table t
WHERE t.ID BETWEEN StartID AND EndID
GROUP BY t.ID

This will give you a result set with all of the IDs, a sum of the price of everything with that ID, and then a total sum. So it would look something like this:

ID | Price_Summary | Total_Price
1    10              60
2    30              60
3    20              60


问:
How can I keep my model files from being refreshed when doing an "Update Model from Database"?
I have a project that uses Entity Framework Database First style development. I made some changes to various Model files, and now every time I do an "Update Model from Database" on my EDMX file, those changes get wiped out. I see there is a tab for Refresh and it has my model files listed, but there is no way to tell VS to not refresh these files. What should I do here? Thanks.</p>

答:
Don't write your changes directly to the .edmx classes. Those classes are generated by ef. The generated classes are defined as partial so that you can define your own partial class in a separate physical file to extend the generated functionality.

Here's a good example

https://dotnetcodr.com/2015/02/18/extending-class-definitions-with-partial-classes-in-c-net/

It even states at the top of the generated .cs file

```<code>//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
</code>```

Body:
Don't write your changes directly to the .edmx classes. Those classes are generated by ef. The generated classes are defined as partial so that you can define your own partial class in a separate physical file to extend the generated functionality.

Here's a good example

https://dotnetcodr.com/2015/02/18/extending-class-definitions-with-partial-classes-in-c-net/

It even states at the top of the generated .cs file

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------


问:
Setting up a click listener for an infoWindow in Angular 2
Ok, the case is I'm working in Ionic 3 (which works with Angular 4), and I'm using google maps. Everything is fine to this point, except because I can't set up a click event listener for the infoWindow object.

I wanna execute some code when the user clicks in the infoWindow. Already tried the following:

```<code>google.maps.event.addListener(infowindow, 'click', function(){
    console.log("click");
    this.openPlace(place.id);
});
</code>```

Also tried putting in a div with an id, which I later use with getDocumentById(), and then adding an event listener to that div. Didn't work either. Same trying to put an onclick event in that div, and calling to an Angular function. Nothing works.

What can I do to fix this issue?

Thanks!

答:
https://developers.google.com/maps/documentation/javascript/reference#InfoWindow

InfoWindow object does not broadcast a click event.

This example is from Google's documentation:

```<code>function initMap() {
  var originalMapCenter = new google.maps.LatLng(-25.363882, 131.044922);
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: originalMapCenter
  });

  var infowindow = new google.maps.InfoWindow({
    content: 'Change the zoom level',
    position: originalMapCenter
  });
  infowindow.open(map);

  map.addListener('zoom_changed', function() {
    infowindow.setContent('Zoom: ' + map.getZoom());
  });
}
</code>```

Notice how they are not adding listeners directly to the InfoWindow, but to the map. I can't find a single working example of a click listener bound directly to an InfoWindow.

Body:
Ok, the case is I'm working in Ionic 3 (which works with Angular 4), and I'm using google maps. Everything is fine to this point, except because I can't set up a click event listener for the infoWindow object.

I wanna execute some code when the user clicks in the infoWindow. Already tried the following:

google.maps.event.addListener(infowindow, 'click', function(){
    console.log("click");
    this.openPlace(place.id);
});

Also tried putting in a div with an id, which I later use with getDocumentById(), and then adding an event listener to that div. Didn't work either. Same trying to put an onclick event in that div, and calling to an Angular function. Nothing works.

What can I do to fix this issue?

Thanks!

Body:
https://developers.google.com/maps/documentation/javascript/reference#InfoWindow

InfoWindow object does not broadcast a click event.

This example is from Google's documentation:

function initMap() {
  var originalMapCenter = new google.maps.LatLng(-25.363882, 131.044922);
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: originalMapCenter
  });

  var infowindow = new google.maps.InfoWindow({
    content: 'Change the zoom level',
    position: originalMapCenter
  });
  infowindow.open(map);

  map.addListener('zoom_changed', function() {
    infowindow.setContent('Zoom: ' + map.getZoom());
  });
}

Notice how they are not adding listeners directly to the InfoWindow, but to the map. I can't find a single working example of a click listener bound directly to an InfoWindow.


问:
C# 7:How can I deconstruct an object into a single value using a tuple?
One of the nice new features of C# 7 is the possibility to define deconstructors for classes and assign the deconstructed values directly to a value tuple.

However, in the case that the object is deconstructed into a single value, I can't find a way to assign it to a tuple. Although there is a type for tuples with a single element (ValueTuple<T>), the shorthand syntax using parentheses doesn't work here. The only way I found to access the deconstructor was to call the Deconstruct method directly, but this eliminates its benefit, as I could use any method for this end.

Does anyone know a better way to deconstruct an object into a single value?

Here is my test code:

```<code>class TestClass
{
    private string s;
    private int n;
    public TestClass(string s, int n) => (this.s, this.n) = (s, n);
    public void Deconstruct(out string s) => s = this.s;
    public void Deconstruct(out string s, out int n) => (s, n) = (this.s, this.n);
}

static void Main(string[] args)
{
    var testObject = new TestClass("abc", 3);

    var (s1) = testObject; // sytax error (comma expected)
    ValueTuple<string> t = testObject; // error: "no implicit conversion from TestClass to (string)"
    testObject.Deconstruct(out string s2); // this works
    var (s3, n) = testObject; // no problem

    Console.WriteLine($"{s1} {t.Item1} {s2} {s3} {n}");
    Console.ReadKey();
}
</code>```

答:
Although there is a type for tuples with a single element (ValueTuple<T>), the shorthand syntax using parentheses doesn't work here.

That's correct. The tuple syntax only works for tuples of 2 values or more, so the Deconstruct method with only one out parameter is not very useful. (There is even a ValueTuple type for 0 elements)

The shortest solution is to just ignore the 2nd parameter:

```<code>var (s1, _) = testObject;
</code>```

Edit: based on comments, a little clarification.

As of C# 7, _ is no longer a variable in this situation. It is a new feature called 'discard'.

Even if you have multiple out parameters (and even if they are different types) you can ignore any of them with an underscore:

```<code>var (s1, _, _, _) = testObject;
</code>```

Body:
One of the nice new features of C# 7 is the possibility to define deconstructors for classes and assign the deconstructed values directly to a value tuple.

However, in the case that the object is deconstructed into a single value, I can't find a way to assign it to a tuple. Although there is a type for tuples with a single element (ValueTuple<T>), the shorthand syntax using parentheses doesn't work here. The only way I found to access the deconstructor was to call the Deconstruct method directly, but this eliminates its benefit, as I could use any method for this end.

Does anyone know a better way to deconstruct an object into a single value?

Here is my test code:

class TestClass
{
    private string s;
    private int n;
    public TestClass(string s, int n) => (this.s, this.n) = (s, n);
    public void Deconstruct(out string s) => s = this.s;
    public void Deconstruct(out string s, out int n) => (s, n) = (this.s, this.n);
}

static void Main(string[] args)
{
    var testObject = new TestClass("abc", 3);

    var (s1) = testObject; // sytax error (comma expected)
    ValueTuple<string> t = testObject; // error: "no implicit conversion from TestClass to (string)"
    testObject.Deconstruct(out string s2); // this works
    var (s3, n) = testObject; // no problem

    Console.WriteLine($"{s1} {t.Item1} {s2} {s3} {n}");
    Console.ReadKey();
}

Body:
Although there is a type for tuples with a single element (ValueTuple<T>), the shorthand syntax using parentheses doesn't work here.

That's correct. The tuple syntax only works for tuples of 2 values or more, so the Deconstruct method with only one out parameter is not very useful. (There is even a ValueTuple type for 0 elements)

The shortest solution is to just ignore the 2nd parameter:

var (s1, _) = testObject;

Edit: based on comments, a little clarification.

As of C# 7, _ is no longer a variable in this situation. It is a new feature called 'discard'.

Even if you have multiple out parameters (and even if they are different types) you can ignore any of them with an underscore:

var (s1, _, _, _) = testObject;


问:
Setup a virtual network on Win Server 2012 R2
I would like to get familliar with installing a virtual network on a server that is physical (not virtual) machine running Windows Server 2012 R2. Currently it has only active directory running and it is a domain controller (if it matters).

So, I have read that if I need to add a virtual network on Win 2K12 R2 - I need first to install a Hyper-V role / feature? Is it true, and if it is - do I need a virtual machine to be able to create a virtual network or it could be done independently trough Hyper-V role / feature?

I would like to use that virtual network to connect VPN to it, and then NAT it trough firewall to the server.

Thank you all. All suggestions are welcome!

答:
Yes, it is true that you need to install Hyper-V to add a virtual network.  This can be done either through PowerShell or the "Virtual Switch Manager" window in Hyper-V Manager.  You do not need to create a Virtual Machine to create a Virtual Switch, although the primary use case for Virtual Switches is giving network connections to Virtual Machines.

For detailed instructions on getting started with Hyper-V, I recommend the "Getting Started" guide in the official documentation for Windows Server 2016.  It has pages describing how to create Virtual Machines and Virtual Switches.  For more background on the topic, check out the Windows Server 2016 Virtual Switch Overview page.  While you are on an older operating system, many of the concepts and steps are the identical.

Hopefully that's enough to get you started with your learning.

Past that, I don't completely understand your desired end state with VPN and NAT, so I can't comment on that aspect of the question.  That said, I can say that attaching a Virtual Machine to a Virtual Switch on the physical adapter used by the VPN won't allow the VMs to tunnel out over the VPN.  That said, it looks like a few people got it to work using Fiddler.

Disclosure: I work on the Hyper-V team at Microsoft.


问:
JHipster EntityMapper interface (mapstruct): map a Spring projection interface
I've generated a new project with JHipster v4.6.0 generator and I'm using its EntityMapper interface to do the mapping between domain and DTO objects.

```<code>public interface EntityMapper <D, E> {
    public E toEntity(D dto);
    public D toDto(E entity);
    public List <E> toEntity(List<D> dtoList);
    public List <D> toDto(List<E> entityList);
}
</code>```

I need to use the Spring projection to have a smaller domain and DTO objects, (I don't want all fields of the entity), so I've created an interface with only the getters of the fields I need, and I've created a method in the repository which retrive this interface type (following the Spring reference guide)

```<code>public interface ClienteIdENome {
    Long getId();
    String getNome();
}

@Repository
public interface ClienteRepository extends JpaRepository<Cliente,Long> {
    ClienteIdENome findById(Long id);
}
</code>```

The query findById retrieve a ClienteIdENome object with only id and nome fields.

Now, I would like to map this object in the following DTO:

```<code>public class ClienteIdENomeDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    @NotNull
    @Size(max = 50)
    private String nome;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
}
</code>```

So, I created the mapper interface:

```<code>@Mapper(componentModel = "spring", uses = {})
public interface ClienteIdENomeMapper extends EntityMapper<ClienteIdENomeDTO, ClienteIdENome> {

}
</code>```

But Eclipse report to me an error in the EntityMapper interface for the method "public E toEntity(D dto)" with the message:

No implementation type is registered for return type it.andrea.ztest01.repository.ClienteIdENome.

Any help?
Thanks a lot

答:
Your ClienteIdENome is not really an entity. I would argue that you don't need to use the EntityMapper, but you need to define a one way mapper. From ClienteIdENome to ClienteIdENomeDTO.

Your mapper needs to look like:

```<code>public interface ClienteIdENomeMapper {
    ClienteIdENomeDTO toDto(ClienteIdENome entity);
    List <ClienteIdENomeDTO> toDto(List<ClienteIdENome> entityList);
}
</code>```

I don't know JHipster, so I can't say what will mean using a mapper different than EntityMapper.

Body:
I've generated a new project with JHipster v4.6.0 generator and I'm using its EntityMapper interface to do the mapping between domain and DTO objects.

public interface EntityMapper <D, E> {
    public E toEntity(D dto);
    public D toDto(E entity);
    public List <E> toEntity(List<D> dtoList);
    public List <D> toDto(List<E> entityList);
}

I need to use the Spring projection to have a smaller domain and DTO objects, (I don't want all fields of the entity), so I've created an interface with only the getters of the fields I need, and I've created a method in the repository which retrive this interface type (following the Spring reference guide)

public interface ClienteIdENome {
    Long getId();
    String getNome();
}

@Repository
public interface ClienteRepository extends JpaRepository<Cliente,Long> {
    ClienteIdENome findById(Long id);
}

The query findById retrieve a ClienteIdENome object with only id and nome fields.

Now, I would like to map this object in the following DTO:

public class ClienteIdENomeDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    @NotNull
    @Size(max = 50)
    private String nome;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
}

So, I created the mapper interface:

@Mapper(componentModel = "spring", uses = {})
public interface ClienteIdENomeMapper extends EntityMapper<ClienteIdENomeDTO, ClienteIdENome> {

}

But Eclipse report to me an error in the EntityMapper interface for the method "public E toEntity(D dto)" with the message:

No implementation type is registered for return type it.andrea.ztest01.repository.ClienteIdENome.

Any help?
Thanks a lot

Body:
Your ClienteIdENome is not really an entity. I would argue that you don't need to use the EntityMapper, but you need to define a one way mapper. From ClienteIdENome to ClienteIdENomeDTO.

Your mapper needs to look like:

public interface ClienteIdENomeMapper {
    ClienteIdENomeDTO toDto(ClienteIdENome entity);
    List <ClienteIdENomeDTO> toDto(List<ClienteIdENome> entityList);
}

I don't know JHipster, so I can't say what will mean using a mapper different than EntityMapper.


问:
Changing the string format of the WPF DatePicker
I need to change the string format of the DatePickerTextBox in the WPF Toolkit DatePicker, to use hyphens instead of slashes for the seperators.

Is there a way to override this default culture or the display string format?

```<code>01-01-2010
</code>```

答:
XAML

```<code> <DatePicker x:Name="datePicker" />
</code>```

C#

```<code>var date = Convert.ToDateTime(datePicker.Text).ToString("yyyy/MM/dd");
</code>```

put what ever format you want in ToString("") for example ToString("dd MMM yyy") and output format will be 7 Jun 2017

ContentLicense: CC BY-SA 2.5

Body:
I need to change the string format of the DatePickerTextBox in the WPF Toolkit DatePicker, to use hyphens instead of slashes for the seperators.

Is there a way to override this default culture or the display string format?

01-01-2010

Body:
XAML

 <DatePicker x:Name="datePicker" />

C#

var date = Convert.ToDateTime(datePicker.Text).ToString("yyyy/MM/dd");

put what ever format you want in ToString("") for example ToString("dd MMM yyy") and output format will be 7 Jun 2017


问:
deleting repetitive columns in unix
I would like to delete multiple repetitive columns from a huge file (about 1 million).
The columns that I want to delete has the same column names: A and others has different unique name. Say:

A B2 A B3

1.1 AA 1.2 AA

2.1 AB 4.3 CT

2.2 AC 6.4 GT

so column headers are A, B2, A, B3,... .
How could I delete the columns named as A's from the data.

答:
I'm not sure I'm understanding your question correctly, but here an (GNU) awk solution to delete all duplicate columns (keeping only the first occurrence):

```<code>#!/usr/bin/awk -f

NR==1 {
    seen[$1] = 1
    cols[0] = 1
    for (i=2; i<=NF; i++) {
        if (!($i in seen)) {
            seen[$i] = 1
            cols[length(cols)] = i
        }
    }
}

{
    for (i=0; i<length(cols); i++)
        printf $(cols[i]) " "
    printf "\n"
}
</code>```

For the first line (NR==1), we find all non-duplicate columns (preserving the order), and for all the other lines, we just print out the columns (fields) we selected before (cols array holds column/field indexes we wish to keep).

```<code>$ ./filter.awk file
A B2 B3
1.1 AA AA
2.1 AB CT
2.2 AC GT
</code>```

Title: deleting repetitive columns in unix

Body:
I'm not sure I'm understanding your question correctly, but here an (GNU) awk solution to delete all duplicate columns (keeping only the first occurrence):

#!/usr/bin/awk -f

NR==1 {
    seen[$1] = 1
    cols[0] = 1
    for (i=2; i<=NF; i++) {
        if (!($i in seen)) {
            seen[$i] = 1
            cols[length(cols)] = i
        }
    }
}

{
    for (i=0; i<length(cols); i++)
        printf $(cols[i]) " "
    printf "\n"
}

For the first line (NR==1), we find all non-duplicate columns (preserving the order), and for all the other lines, we just print out the columns (fields) we selected before (cols array holds column/field indexes we wish to keep).

$ ./filter.awk file
A B2 B3
1.1 AA AA
2.1 AB CT
2.2 AC GT


答:
use:

```<code>jQuery.getScript()
</code>```

or

```<code>$.getScript()
</code>```

to append script and apply it

with this you must remember that plugins has to be added to jQuery object some like that:

```<code>(function($){})(jQuery)
</code>```

Title: jQuery dynamically add script getting body is null

Body:
use:

jQuery.getScript()

or

$.getScript()

to append script and apply it

with this you must remember that plugins has to be added to jQuery object some like that:

(function($){})(jQuery)


问:
R merge multiple files into 1 dataframe and keep all values
I have 6 multiple files, each having only 1 column of names. I want to read all these files and combine them in 1 dataframe so that it looks like this:

```<code>file1  file2  file3  file4  file5  file6
adam   adam   adam   adam   adam   adam
Roy    NA     Roy    Roy    NA     NA
NA     Sam    Sam    NA     NA     NA
</code>```

The colnames of resulting dataframe should represent the actual file names. Let's say that the file I read were named file1.txt, file2.txt and so on..

Any help will be much appreciated.

What I've been trying so far:

```<code>multmerge = function(mypath){
+ filenames=list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
+ datalist = lapply(filenames, function(x){read.csv(file=x,header=F)})
+ Reduce(function(x,y) {merge(x,y, all.x=T)}, datalist)}
> mymergeddata = multmerge("/Path/To/The/Folder/Having/All/Files")
> dim(mymergeddata)
[1] 11508     1
</code>```

As seen here it is combining all values (names) in one column..

答:
Here's one way to do that with rbindlist and dcast from data.table

```<code>library(data.table)
file_list <- list.files("c:/temp/files/",full.names = TRUE)
import_files <- lapply(file_list,read.csv,stringsAsFactors =FALSE)
rbinded_files <- na.omit(rbindlist(import_files,idcol="file"))
dcast(rbinded_files,file1 ~file,fun=max, na.rm=TRUE)

  file1    1    2    3    4    5    6
1  adam adam adam adam adam adam adam
2   Roy  Roy <NA>  Roy  Roy <NA> <NA>
3   Sam <NA>  Sam  Sam <NA> <NA> <NA>
</code>```

You can remove the first column if you want.

Body:
I have 6 multiple files, each having only 1 column of names. I want to read all these files and combine them in 1 dataframe so that it looks like this:

file1  file2  file3  file4  file5  file6
adam   adam   adam   adam   adam   adam
Roy    NA     Roy    Roy    NA     NA
NA     Sam    Sam    NA     NA     NA

The colnames of resulting dataframe should represent the actual file names. Let's say that the file I read were named file1.txt, file2.txt and so on..

Any help will be much appreciated.

What I've been trying so far:

multmerge = function(mypath){
+ filenames=list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
+ datalist = lapply(filenames, function(x){read.csv(file=x,header=F)})
+ Reduce(function(x,y) {merge(x,y, all.x=T)}, datalist)}
> mymergeddata = multmerge("/Path/To/The/Folder/Having/All/Files")
> dim(mymergeddata)
[1] 11508     1

As seen here it is combining all values (names) in one column..

Body:
Here's one way to do that with rbindlist and dcast from data.table

library(data.table)
file_list <- list.files("c:/temp/files/",full.names = TRUE)
import_files <- lapply(file_list,read.csv,stringsAsFactors =FALSE)
rbinded_files <- na.omit(rbindlist(import_files,idcol="file"))
dcast(rbinded_files,file1 ~file,fun=max, na.rm=TRUE)

  file1    1    2    3    4    5    6
1  adam adam adam adam adam adam adam
2   Roy  Roy <NA>  Roy  Roy <NA> <NA>
3   Sam <NA>  Sam  Sam <NA> <NA> <NA>

You can remove the first column if you want.


问:
Rename foldername to filename with bash
I want to rename a file, by using the folder name.

This:

```<code>├── foo01
│   └── bar.png
│   └── bar.txt
├── foo02
│   └── bar.png
│   └── bar.txt
└── foo03
    └── bar.png
    └── bar.txt
</code>```

Should be this:

```<code>├── foo01
│   └── foo01.png
│   └── foo01.txt
├── foo02
│   └── foo02.png
│   └── foo02.txt
└── foo03
    └── foo03.png
    └── foo03.txt
</code>```

I can't find a way to do this. Can anybody help?

答:
With Perl‘s standalone rename command:

```<code>rename -n 's|([^/]*)/[^/]*\.(.*)$|$1/$1.$2|' */*
</code>```

Output:

```
foo01/bar.png renamed as foo01/foo01.png
foo01/bar.txt renamed as foo01/foo01.txt
foo02/bar.png renamed as foo02/foo02.png
foo02/bar.txt renamed as foo02/foo02.txt
foo03/bar.png renamed as foo03/foo03.png
foo03/bar.txt renamed as foo03/foo03.txt
```

If everything looks okay, remove option -n.

Title: Rename foldername to filename with bash

Body:
I want to rename a file, by using the folder name.

This:

├── foo01
│   └── bar.png
│   └── bar.txt
├── foo02
│   └── bar.png
│   └── bar.txt
└── foo03
    └── bar.png
    └── bar.txt

Should be this:

├── foo01
│   └── foo01.png
│   └── foo01.txt
├── foo02
│   └── foo02.png
│   └── foo02.txt
└── foo03
    └── foo03.png
    └── foo03.txt

I can't find a way to do this. Can anybody help?

Body:
With Perl‘s standalone rename command:

rename -n 's|([^/]*)/[^/]*\.(.*)$|$1/$1.$2|' */*

Output:

foo01/bar.png renamed as foo01/foo01.png
foo01/bar.txt renamed as foo01/foo01.txt
foo02/bar.png renamed as foo02/foo02.png
foo02/bar.txt renamed as foo02/foo02.txt
foo03/bar.png renamed as foo03/foo03.png
foo03/bar.txt renamed as foo03/foo03.txt

If everything looks okay, remove option -n.


问:
Passing a parameter into a an Openquery select statement
I've a query:

```<code>DECLARE @sql2 nvarchar(max), @counts int, @maxdate date;

SELECT @maxdate=isnull(Max(btestDateResultBack),'01/01/1900')
FROM BloodTests
PRINT @maxdate

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs, '
    +CAST(@maxdate AS varchar(20))
    +', count(*) AS Count
    FROM blood_tests
    WHERE btestResult = 1 AND
        btestDateResultBack >'''''
            +convert(varchar(30), @maxdate, 121)
        +''''''

SET @sql2 = 'SELECT * From openquery(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2
</code>```

that returns the DonorIDs and Count columns correctly, but the column with the variable '+CAST(@maxdate AS varchar(20))+' returns the date as an alias to a column (see image below).

Using @maxdate in the WHERE clause works just fine.

How can I use @maxdate in the body of the SELECT statement?

I've seen plenty of answers on how can I use this variable in a WHERE clause, but I haven't seen one discussing adding it to the SELECT statements select list.

Final Working Solution

```<code>DECLARE @sql nvarchar(max)
        ,@sql2 nvarchar(max)
        , @sql3 nvarchar(max)
        , @counts int
        , @bloodtestdonors int
        , @maxdate date;

--Find and delete bloodtests from today
SELECT @maxdate = isnull(Max(btestDateResultBack),'1900-01-01') FROM BloodTests;

PRINT @maxdate;

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
        '''''+CAST(@maxdate AS varchar(30))+''''' AS Date,
        count(*) AS Count FROM blood_tests
        WHERE btestResult = 1 AND
        btestDateResultBack >'''''+convert(varchar(30), @maxdate, 121)+''''''

SET @sql2 = 'SELECT * From OPENQUERY(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2
</code>```

Thanks @bielawski and @Prdp for the help and clarification. I appreciate it. Thanks @stan-shaw for the code formatting.

答:
Use sp_executesql to pass the parameter values to your query

```<code>SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
             @maxdate, count(*) AS Count
             FROM blood_tests WHERE btestResult = 1
             AND btestDateResultBack > @maxdate'

exec sp_executesql @sql2,N'@maxdate date',@maxdate = @maxdate
</code>```

What I don't understand is, how you that values 1982.

ContentLicense: CC BY-SA 4.0

Body:
I've a query:

DECLARE @sql2 nvarchar(max), @counts int, @maxdate date;

SELECT @maxdate=isnull(Max(btestDateResultBack),'01/01/1900')
FROM BloodTests
PRINT @maxdate

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs, '
    +CAST(@maxdate AS varchar(20))
    +', count(*) AS Count
    FROM blood_tests
    WHERE btestResult = 1 AND
        btestDateResultBack >'''''
            +convert(varchar(30), @maxdate, 121)
        +''''''

SET @sql2 = 'SELECT * From openquery(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2

that returns the DonorIDs and Count columns correctly, but the column with the variable '+CAST(@maxdate AS varchar(20))+' returns the date as an alias to a column (see image below).

Using @maxdate in the WHERE clause works just fine.

How can I use @maxdate in the body of the SELECT statement?

I've seen plenty of answers on how can I use this variable in a WHERE clause, but I haven't seen one discussing adding it to the SELECT statements select list.

Final Working Solution

DECLARE @sql nvarchar(max)
        ,@sql2 nvarchar(max)
        , @sql3 nvarchar(max)
        , @counts int
        , @bloodtestdonors int
        , @maxdate date;

--Find and delete bloodtests from today
SELECT @maxdate = isnull(Max(btestDateResultBack),'1900-01-01') FROM BloodTests;

PRINT @maxdate;

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
        '''''+CAST(@maxdate AS varchar(30))+''''' AS Date,
        count(*) AS Count FROM blood_tests
        WHERE btestResult = 1 AND
        btestDateResultBack >'''''+convert(varchar(30), @maxdate, 121)+''''''

SET @sql2 = 'SELECT * From OPENQUERY(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2

Thanks @bielawski and @Prdp for the help and clarification. I appreciate it. Thanks @stan-shaw for the code formatting.

Body:
Use sp_executesql to pass the parameter values to your query

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs,
             @maxdate, count(*) AS Count
             FROM blood_tests WHERE btestResult = 1
             AND btestDateResultBack > @maxdate'

exec sp_executesql @sql2,N'@maxdate date',@maxdate = @maxdate

What I don't understand is, how you that values 1982.


问:
How to handle the Action.submit on an adaptive card with LUIS
How do we do the handle Action.submit when we use the LUIS recognizer in our bot using MS BotFramework?

```<code>var recognizer = new builder.LuisRecognizer(config.LUIS_MODEL_URL);
bot.recognizer(recognizer);

bot.dialog('toolAccess', [
    function (session,args,next) {

           const msg = new builder.Message(session)
                      .addAttachment({
            //adaptive card body here with Action.submit buttons...
           });
           session.send(msg);
    }
]).triggerAction({ matches : 'toolAccess'});
//toolAccess is an intent in my LUIS app.
</code>```

My actions for the adaptive card are:

```<code>"actions": [
                {
                    "type": "Action.Submit",
                    "data": {
                            "type": "okProfileSelection"
                    },
                    "title": "OK"
                },
                {
                    "type": "Action.Submit",
                    "data": {
                            "type": "cancelProfileSelection"
                    },
                    "title": "Cancel"
                }
            ]
</code>```

So the question is how do I handle these OK and Cancel buttons? Should I add another dialog? If so, what should the triggerAction be?

答:
When you setup your bot, use a default handler like this:

```<code>var bot = new builder.UniversalBot(connector, function (session) {

    if (session.message && session.message.value) {
        // A Card's Submit Action obj was received
        processSubmitAction(session, session.message.value);
        return;
    }

    // Display Welcome card with Hotels and Flights search options
    // load Adaptive Card from JSON file
    var card = require('./card-hotels-flights-search.json');

    // send the card with form
    var msg = new builder.Message(session).addAttachment(card);
    session.send(msg);
});
</code>```

For a complete working example check out: BotBuilder-Samples/Node/cards-AdaptiveCards

Body:
How do we do the handle Action.submit when we use the LUIS recognizer in our bot using MS BotFramework?

var recognizer = new builder.LuisRecognizer(config.LUIS_MODEL_URL);
bot.recognizer(recognizer);

bot.dialog('toolAccess', [
    function (session,args,next) {

           const msg = new builder.Message(session)
                      .addAttachment({
            //adaptive card body here with Action.submit buttons...
           });
           session.send(msg);
    }
]).triggerAction({ matches : 'toolAccess'});
//toolAccess is an intent in my LUIS app.

My actions for the adaptive card are:

"actions": [
                {
                    "type": "Action.Submit",
                    "data": {
                            "type": "okProfileSelection"
                    },
                    "title": "OK"
                },
                {
                    "type": "Action.Submit",
                    "data": {
                            "type": "cancelProfileSelection"
                    },
                    "title": "Cancel"
                }
            ]

So the question is how do I handle these OK and Cancel buttons? Should I add another dialog? If so, what should the triggerAction be?

Body:
When you setup your bot, use a default handler like this:

var bot = new builder.UniversalBot(connector, function (session) {

    if (session.message && session.message.value) {
        // A Card's Submit Action obj was received
        processSubmitAction(session, session.message.value);
        return;
    }

    // Display Welcome card with Hotels and Flights search options
    // load Adaptive Card from JSON file
    var card = require('./card-hotels-flights-search.json');

    // send the card with form
    var msg = new builder.Message(session).addAttachment(card);
    session.send(msg);
});

For a complete working example check out: BotBuilder-Samples/Node/cards-AdaptiveCards


问:
Found conflicts between different versions of the same dependent assembly that could not be resolved error

Found conflicts between different versions of the same dependent assembly that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.

It's happened after I'm import Newtonsoft.Json to my  App.Core(Portable) project.

After a look in the output:

There was a conflict between "Microsoft.CSharp, Version=2.0.5.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". (TaskId:90)
2>      "Microsoft.CSharp, Version=2.0.5.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was chosen because it was primary and "Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was not. (TaskId:90)

What I need to do now?

答: Newtonsoft.Json is relying on a newer version of the Microsoft.CSharp assembly than your project is referencing. You can remove the reference to the old library and add the newer one. The newer one may be in your packages directory for your solution, or you may be able to get the NuGet package. In my case, the only reference that depended on the old version of the CSharp library was itself, so there was no harm in doing this.</p>


问:
making a jar file for console
I have a program without a GUI and I use console! So first I read a line from a user from console

BufferedReader userReader = new BufferedReader(new InputStreamReader(System.in));

and then I will write an answer for the user in the console!

System.out.println("Server:"+output);

I want to create a jar file for it ! but how can i show my console in jar file with out using GUI?
please help me thanks.

答:
You need to run your jar file from CLI (command line). Like:

```<code>java -jar yourJar.jar
pause
</code>```

If you want to force this, there are different ways to do this:

a shortcut file to CMD and your jar as an argument

a batch file running your jar using code like mine above

calling it from a batch file manually (as I did above)

Title: making a jar file for console

Body:
You need to run your jar file from CLI (command line). Like:

java -jar yourJar.jar
pause

If you want to force this, there are different ways to do this:

a shortcut file to CMD and your jar as an argument

a batch file running your jar using code like mine above

calling it from a batch file manually (as I did above)


问:
Keep hover-triggered twitter bootstrap popover alive while selecting option from a dropdown inside the popover
I'm trying to put a dropdown list inside the twitter bootstrap popover. The popover should be triggered on link's hover event and remain visible while cursor is inside the popover.

I used a code posted by @vikas devde from here to make it work, and everything works great except selecting an option from a dropdown list.

When trying to select an option, dropdown disappears.

In Firefox there is a chance to select by keyboard arrows, Chrome allows to select but hides the popover on click or on enter, in Safari everything works fine.

Here's a fiddle for illustration.

HTML:

```<code><a id="hover-link" href="#">Hover over me</a>
<form id="form-popover" method="post">
    <label>Select some option here
        <select>
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
        </select>
    </label>
</form>
</code>```

jQuery:

```<code>$(function () {
    $('#hover-link').popover({
                html: true,
                trigger: 'manual',
                placement: 'bottom',
                content: $('#form-popover').html(),
                title: "title"
            }).on("mouseenter", function () {
                var _this = this;
                $(this).popover("show");
                $(this).siblings(".popover").on("mouseleave", function () {
                    setTimeout(function () {
                        $(_this).popover('hide');
                    }, 100);
                });
            }).on("mouseleave", function () {
                var _this = this;
                setTimeout(function () {
                    if (!$(".popover:hover").length) {
                        $(_this).popover('hide');
                    }
                }, 100);
    });
});
</code>```

答:
Apparently, Firefox allows the click event to propagate through to the popover causing the popover to dismiss. So, perhaps this is a simpler, more straightforward approach, since "active" is not a documented function for Bootstrap popovers.</p>

```<code>$(document).on('click','select.popover-specific-select-element',function(event){
    // Hack to make sure the popover stays open when using Firefox.
    event.stopPropagation();
});
</code>```

Body:
I'm trying to put a dropdown list inside the twitter bootstrap popover. The popover should be triggered on link's hover event and remain visible while cursor is inside the popover.

I used a code posted by @vikas devde from here to make it work, and everything works great except selecting an option from a dropdown list.

When trying to select an option, dropdown disappears.

In Firefox there is a chance to select by keyboard arrows, Chrome allows to select but hides the popover on click or on enter, in Safari everything works fine.

Here's a fiddle for illustration.

HTML:

Hover over me
<form id="form-popover" method="post">
    Select some option here
        <select>
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
        </select>

</form>

jQuery:

$(function () {
    $('#hover-link').popover({
                html: true,
                trigger: 'manual',
                placement: 'bottom',
                content: $('#form-popover').html(),
                title: "title"
            }).on("mouseenter", function () {
                var _this = this;
                $(this).popover("show");
                $(this).siblings(".popover").on("mouseleave", function () {
                    setTimeout(function () {
                        $(_this).popover('hide');
                    }, 100);
                });
            }).on("mouseleave", function () {
                var _this = this;
                setTimeout(function () {
                    if (!$(".popover:hover").length) {
                        $(_this).popover('hide');
                    }
                }, 100);
    });
});

Body:
Apparently, Firefox allows the click event to propagate through to the popover causing the popover to dismiss. So, perhaps this is a simpler, more straightforward approach, since "active" is not a documented function for Bootstrap popovers.

$(document).on('click','select.popover-specific-select-element',function(event){
    // Hack to make sure the popover stays open when using Firefox.
    event.stopPropagation();
});


问:
Creating a Visual Studio project from existing funky code structure
I was given the following code structure: there are several subfolders F1, F2, F3, and in each there is are source .cpp files and a folder includes with corresponding .h files. For example

```<code>[F1]
    source1.cpp
    [includes]
        source1.h
[F2]
    source2a.cpp
    source2b.cpp
    [includes]
        source2a.h
        source2b.h
[F3]
    source3.cpp
    [includes]
        source3.h
</code>```

Moreover, e.g. in source3.cpp there may be a line

```<code>#include "source1.h"
</code>```

and not

```<code>#include "F1/source1.h"
</code>```

which I guess is taken care of while compiling using the make file.

I would like to create a C++ project in Visual Studio Community 2017 to use its IDE features, such as IntelliSense, etc. However, due to this funky code structure, all these includes go wrong and Visual Studio does not see the relevant headers. How can I fix this?

答:
From MSDN:

To set this compiler option in the Visual Studio development environment:

Open the project's Property Pages dialog box.

Click the C/C++
  folder.

Click the General property page.

Modify the Additional Include Directories property.

Body:
I was given the following code structure: there are several subfolders F1, F2, F3, and in each there is are source .cpp files and a folder includes with corresponding .h files. For example

[F1]
    source1.cpp
    [includes]
        source1.h
[F2]
    source2a.cpp
    source2b.cpp
    [includes]
        source2a.h
        source2b.h
[F3]
    source3.cpp
    [includes]
        source3.h

Moreover, e.g. in source3.cpp there may be a line

#include "source1.h"

and not

#include "F1/source1.h"

which I guess is taken care of while compiling using the make file.

I would like to create a C++ project in Visual Studio Community 2017 to use its IDE features, such as IntelliSense, etc. However, due to this funky code structure, all these includes go wrong and Visual Studio does not see the relevant headers. How can I fix this?


问:
Change header background color of modal of twitter bootstrap
I am trying to change the background color of modal header of twitter bootstrap using following css code. </p>

```<code>.modal-header
 {
     padding:9px 15px;
     border-bottom:1px solid #eee;
     background-color: #0480be;
 }
 .modal-header .close{margin-top:2px}
 .modal-header h3{margin:0;line-height:30px}
</code>```

<p>But this code makes the corner of the modal header angular. Before using above code corners were round shaped. How can I get round shaped corner of modal header with the above background color ?? Thanks </p>

答:
A little late to the party, but here's another solution.

Simply adjusting the class of the modal to something like alert-danger does work, however it removes the top rounded corners of the modal.

A workaround is to give the element with modal-header an additional class of panel-heading, e.g.

```<code><div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header panel-heading"> <!-- change here -->
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body…</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

Then, to change the heading color you can do something like (assuming you're using jQUery)

```<code>jQuery('.modal-content').addClass('panel-danger')
</code>```

Body:
I am trying to change the background color of modal header of twitter bootstrap using following css code.

.modal-header
 {
     padding:9px 15px;
     border-bottom:1px solid #eee;
     background-color: #0480be;
 }
 .modal-header .close{margin-top:2px}
 .modal-header h3{margin:0;line-height:30px}

But this code makes the corner of the modal header angular. Before using above code corners were round shaped. How can I get round shaped corner of modal header with the above background color ?? Thanks

Body:
A little late to the party, but here's another solution.

Simply adjusting the class of the modal to something like alert-danger does work, however it removes the top rounded corners of the modal.

A workaround is to give the element with modal-header an additional class of panel-heading, e.g.

<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header panel-heading"> <!-- change here -->
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Then, to change the heading color you can do something like (assuming you're using jQUery)

jQuery('.modal-content').addClass('panel-danger')


问:
Visual Basic - start stopwatch for measuring overtime after a given amount of minutes
I'm starting my first steps into Visual Basic and trying to create sort of a stopwatch.

My design is the following:

The idea behind is to create a tool to support a debate. Persons gets a certain time (7 minutes) for presenting their topic and after that time there is room for interactive conversation (Q&A) set to 13 minutes. The idea is that after 7 minutes a buzzer sounds to stop the presenting time and go over to the interactive part. And after 20 minutes a 2nd stopwatch starts with a buzzer and a red flashing background to indicate that session needs to be terminated.

This is what I already got and I'm pretty shure it can be coded otherwise and maybe easier.
I already got it to the first working stopwatch but I don't get the rest working:

```<code>Public Class Form1

    Private Hundredths As Integer = 0
    Private Seconds As Integer = 0
    Private Minutes As Integer = 0
    Private Hours As Integer = 0
    Private OvertimeHundredths As Integer = 0
    Private OvertimeSeconds As Integer = 0
    Private OvertimeMinutes As Integer = 0
    Private OvertimeHours As Integer = 0

    Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
        If Timer1.Enabled Then
            Timer1.Stop()
            StartBtn.Text = "START"
            Return
        End If

        If Not Timer1.Enabled Then
            Timer1.Start()
            StartBtn.Text = "STOP"
            Return
        End If
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Hundredths += 1
        HundredthsTxB.Text = Hundredths.ToString
        SecondsTxB.Text = Seconds.ToString
        MinutesTxB.Text = Minutes.ToString
        HoursTxB.Text = Hours.ToString

        If Hundredths = 10 Then
            Seconds += 1
            Hundredths = 0
        End If

        If Seconds = 60 Then
            Minutes += 1
            Seconds = 0
        End If

        If Minutes = 60 Then
            Hours += 1
            Minutes = 0
        End If

        If Hours = 24 Then
            Timer1.Stop()
        End If
    End Sub

    Private Sub ResetBtn_Click(sender As Object, e As EventArgs) Handles ResetBtn.Click
        Hundredths = 0
        Seconds = 0
        Minutes = 0
        Hours = 0
        HundredthsTxB.Text = Hundredths.ToString
        SecondsTxB.Text = Seconds.ToString
        MinutesTxB.Text = Minutes.ToString
        HoursTxB.Text = Hours.ToString
    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        OvertimeHundredths += 1
        OvertimeHundredthsTxB.Text = OvertimeHundredths.ToString
        OvertimeSecondsTxB.Text = OvertimeSeconds.ToString
        OvertimeMinutesTxB.Text = OvertimeMinutes.ToString
        OvertimeHoursTxB.Text = OvertimeHours.ToString

        If OvertimeHundredths = 10 Then
            OvertimeSeconds += 1
            OvertimeHundredths = 0
        End If

        If OvertimeSeconds = 60 Then
            OvertimeMinutes += 1
            OvertimeSeconds = 0
        End If

        If OvertimeMinutes = 60 Then
            OvertimeHours += 1
            OvertimeMinutes = 0
        End If

        If OvertimeHours = 24 Then
            Timer2.Stop()
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If Timer1.Interval = 2 Then
            Timer2.Start()
        End If
    End Sub

End Class
</code>```

So any help is welcome. Also I'm keen on learning on how other guru's are thinking and coding.

答:
Instead of using timers, I would use a Stopwatch. This way there is less messing around adding numbers etc. The code below accomplishes what you want apart from sounding a buzzer as I'm presuming you want to implement it your own. It looks worse than it is, but seems to work ok. See code comments for a little explanation

```<code>Public Class Form1

    Private PresentationTimer As New Stopwatch
    Private InteractiveTimer As New Stopwatch
    Private PresentationMinutes As Integer
    Private InteractiveMinutes As Integer

    'When this timer is enabled, it keeps track of the two stopwatches and checks
    'that they're within the alloted time.
    '
    'When the presentation timer has expired, that one is stopped and the interactive
    'timer is started
    '
    'When the interactive timer has expired, the timer for background flashing starts.
    'To stop the flashing, click the reset button on the form
    Private Sub UiUpdateTimer_Tick(sender As Object, e As EventArgs) Handles uiUpdateTimer.Tick
        UpdateUI()
        If PresentationTimer.IsRunning And IsTimeExpired(PresentationTimer, PresentationMinutes) Then
            PresentationTimer.Stop()
            InteractiveTimer.Start()
            'add code here for buzzer to show end of presentation time
        End If
        If InteractiveTimer.IsRunning And IsTimeExpired(InteractiveTimer, InteractiveMinutes) Then
            InteractiveTimer.Stop()
            BackgroundFlashTimer.Enabled = True
            'add code here for buzzer to show end of interactive time
            StartBtn.Text = "START"
        End If

    End Sub

    'checks if the timer passed as a parameter is expired by comparing
    'the number of elapsed minutes with the number of minutes passed in
    'the second parameter
    Private Function IsTimeExpired(tmr As Stopwatch, mins As Integer) As Boolean
        If tmr.Elapsed.Minutes >= mins Then
            Return True
        Else
            Return False
        End If
    End Function

    'simply updates all the textboxes with the stopwatch values.
    Private Sub UpdateUI()
        HundredthsTxB.Text = Int(PresentationTimer.Elapsed.Milliseconds / 10).ToString
        SecondsTxB.Text = PresentationTimer.Elapsed.Seconds.ToString
        MinutesTxB.Text = PresentationTimer.Elapsed.Minutes.ToString
        HoursTxB.Text = PresentationTimer.Elapsed.Hours.ToString
        OvertimeHundredthsTxB.Text = Int(InteractiveTimer.Elapsed.Milliseconds / 10).ToString
        OvertimeSecondsTxB.Text = InteractiveTimer.Elapsed.Seconds.ToString
        OvertimeMinutesTxB.Text = InteractiveTimer.Elapsed.Minutes.ToString
        overtimeHoursTxB.Text = InteractiveTimer.Elapsed.Hours.ToString
    End Sub

    Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
        'if either timer is running, stop them both and exit this sub
        If PresentationTimer.IsRunning Or InteractiveTimer.IsRunning Then
            PresentationTimer.Stop()
            InteractiveTimer.Stop()
            StartBtn.Text = "START"
            uiUpdateTimer.Enabled = False
            Exit Sub
        End If

        'if the presentation timer hasn't run yet, check if the minutes values are
        'valid and start it
        If PresentationTimer.ElapsedMilliseconds = 0 Then
            PresentationMinutes = CInt(Val(PresentationMinutesTxB.Text))
            InteractiveMinutes = CInt(Val(InteractiveMinutesTxB.Text))
            'if the minutes values are't valid show messagebox and exit this sub
            If PresentationMinutes = 0 Or InteractiveMinutes = 0 Then
                MessageBox.Show("Please enter valid Presentation and Interactive times.")
                Exit Sub
            End If
            'if minutes values are ok start the presentation timer
            uiUpdateTimer.Enabled = True
            PresentationTimer.Start()
            StartBtn.Text = "STOP"
            Exit Sub
        End If

        'if the presentation timer has been running, but is currently stopped,
        'continue the timer and exit this sub
        If Not PresentationTimer.IsRunning And PresentationTimer.ElapsedMilliseconds > 0 Then
            uiUpdateTimer.Enabled = True
            PresentationTimer.Start()
            StartBtn.Text = "STOP"
            Exit Sub
        End If

        'if the interactive timer has been running,but is currently stopped,
        'continue the timer and exit this sub
        If Not InteractiveTimer.IsRunning And InteractiveTimer.ElapsedMilliseconds > 0 Then
            uiUpdateTimer.Enabled = True
            InteractiveTimer.Start()
            StartBtn.Text = "STOP"
            Exit Sub
        End If

    End Sub

    Private Sub ResetBtn_Click(sender As Object, e As EventArgs) Handles ResetBtn.Click
        PresentationTimer.Reset()
        InteractiveTimer.Reset()
        uiUpdateTimer.Enabled = False
        StartBtn.Enabled = True
        StartBtn.Text = "START"
        UpdateUI()
        BackgroundFlashTimer.Enabled = False
        Me.BackColor = defaultBackColor
    End Sub

    Private Sub BackgroundFlashTimer_Tick(sender As Object, e As EventArgs) Handles BackgroundFlashTimer.Tick
        StartBtn.Enabled = False
        If Me.BackColor = DefaultBackColor Then
            Me.BackColor = Color.Red
        Else
            Me.BackColor = DefaultBackColor
        End If
        Me.Update()
    End Sub

End Class
</code>```

Body:
I'm starting my first steps into Visual Basic and trying to create sort of a stopwatch.

My design is the following:

The idea behind is to create a tool to support a debate. Persons gets a certain time (7 minutes) for presenting their topic and after that time there is room for interactive conversation (Q&A) set to 13 minutes. The idea is that after 7 minutes a buzzer sounds to stop the presenting time and go over to the interactive part. And after 20 minutes a 2nd stopwatch starts with a buzzer and a red flashing background to indicate that session needs to be terminated.

This is what I already got and I'm pretty shure it can be coded otherwise and maybe easier.
I already got it to the first working stopwatch but I don't get the rest working:

Public Class Form1

    Private Hundredths As Integer = 0
    Private Seconds As Integer = 0
    Private Minutes As Integer = 0
    Private Hours As Integer = 0
    Private OvertimeHundredths As Integer = 0
    Private OvertimeSeconds As Integer = 0
    Private OvertimeMinutes As Integer = 0
    Private OvertimeHours As Integer = 0

    Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
        If Timer1.Enabled Then
            Timer1.Stop()
            StartBtn.Text = "START"
            Return
        End If

        If Not Timer1.Enabled Then
            Timer1.Start()
            StartBtn.Text = "STOP"
            Return
        End If
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Hundredths += 1
        HundredthsTxB.Text = Hundredths.ToString
        SecondsTxB.Text = Seconds.ToString
        MinutesTxB.Text = Minutes.ToString
        HoursTxB.Text = Hours.ToString

        If Hundredths = 10 Then
            Seconds += 1
            Hundredths = 0
        End If

        If Seconds = 60 Then
            Minutes += 1
            Seconds = 0
        End If

        If Minutes = 60 Then
            Hours += 1
            Minutes = 0
        End If

        If Hours = 24 Then
            Timer1.Stop()
        End If
    End Sub

    Private Sub ResetBtn_Click(sender As Object, e As EventArgs) Handles ResetBtn.Click
        Hundredths = 0
        Seconds = 0
        Minutes = 0
        Hours = 0
        HundredthsTxB.Text = Hundredths.ToString
        SecondsTxB.Text = Seconds.ToString
        MinutesTxB.Text = Minutes.ToString
        HoursTxB.Text = Hours.ToString
    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        OvertimeHundredths += 1
        OvertimeHundredthsTxB.Text = OvertimeHundredths.ToString
        OvertimeSecondsTxB.Text = OvertimeSeconds.ToString
        OvertimeMinutesTxB.Text = OvertimeMinutes.ToString
        OvertimeHoursTxB.Text = OvertimeHours.ToString

        If OvertimeHundredths = 10 Then
            OvertimeSeconds += 1
            OvertimeHundredths = 0
        End If

        If OvertimeSeconds = 60 Then
            OvertimeMinutes += 1
            OvertimeSeconds = 0
        End If

        If OvertimeMinutes = 60 Then
            OvertimeHours += 1
            OvertimeMinutes = 0
        End If

        If OvertimeHours = 24 Then
            Timer2.Stop()
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If Timer1.Interval = 2 Then
            Timer2.Start()
        End If
    End Sub

End Class

So any help is welcome. Also I'm keen on learning on how other guru's are thinking and coding.

Body:
Instead of using timers, I would use a Stopwatch. This way there is less messing around adding numbers etc. The code below accomplishes what you want apart from sounding a buzzer as I'm presuming you want to implement it your own. It looks worse than it is, but seems to work ok. See code comments for a little explanation

Public Class Form1

    Private PresentationTimer As New Stopwatch
    Private InteractiveTimer As New Stopwatch
    Private PresentationMinutes As Integer
    Private InteractiveMinutes As Integer

    'When this timer is enabled, it keeps track of the two stopwatches and checks
    'that they're within the alloted time.
    '
    'When the presentation timer has expired, that one is stopped and the interactive
    'timer is started
    '
    'When the interactive timer has expired, the timer for background flashing starts.
    'To stop the flashing, click the reset button on the form
    Private Sub UiUpdateTimer_Tick(sender As Object, e As EventArgs) Handles uiUpdateTimer.Tick
        UpdateUI()
        If PresentationTimer.IsRunning And IsTimeExpired(PresentationTimer, PresentationMinutes) Then
            PresentationTimer.Stop()
            InteractiveTimer.Start()
            'add code here for buzzer to show end of presentation time
        End If
        If InteractiveTimer.IsRunning And IsTimeExpired(InteractiveTimer, InteractiveMinutes) Then
            InteractiveTimer.Stop()
            BackgroundFlashTimer.Enabled = True
            'add code here for buzzer to show end of interactive time
            StartBtn.Text = "START"
        End If

    End Sub

    'checks if the timer passed as a parameter is expired by comparing
    'the number of elapsed minutes with the number of minutes passed in
    'the second parameter
    Private Function IsTimeExpired(tmr As Stopwatch, mins As Integer) As Boolean
        If tmr.Elapsed.Minutes >= mins Then
            Return True
        Else
            Return False
        End If
    End Function

    'simply updates all the textboxes with the stopwatch values.
    Private Sub UpdateUI()
        HundredthsTxB.Text = Int(PresentationTimer.Elapsed.Milliseconds / 10).ToString
        SecondsTxB.Text = PresentationTimer.Elapsed.Seconds.ToString
        MinutesTxB.Text = PresentationTimer.Elapsed.Minutes.ToString
        HoursTxB.Text = PresentationTimer.Elapsed.Hours.ToString
        OvertimeHundredthsTxB.Text = Int(InteractiveTimer.Elapsed.Milliseconds / 10).ToString
        OvertimeSecondsTxB.Text = InteractiveTimer.Elapsed.Seconds.ToString
        OvertimeMinutesTxB.Text = InteractiveTimer.Elapsed.Minutes.ToString
        overtimeHoursTxB.Text = InteractiveTimer.Elapsed.Hours.ToString
    End Sub

    Private Sub StartBtn_Click(sender As Object, e As EventArgs) Handles StartBtn.Click
        'if either timer is running, stop them both and exit this sub
        If PresentationTimer.IsRunning Or InteractiveTimer.IsRunning Then
            PresentationTimer.Stop()
            InteractiveTimer.Stop()
            StartBtn.Text = "START"
            uiUpdateTimer.Enabled = False
            Exit Sub
        End If

        'if the presentation timer hasn't run yet, check if the minutes values are
        'valid and start it
        If PresentationTimer.ElapsedMilliseconds = 0 Then
            PresentationMinutes = CInt(Val(PresentationMinutesTxB.Text))
            InteractiveMinutes = CInt(Val(InteractiveMinutesTxB.Text))
            'if the minutes values are't valid show messagebox and exit this sub
            If PresentationMinutes = 0 Or InteractiveMinutes = 0 Then
                MessageBox.Show("Please enter valid Presentation and Interactive times.")
                Exit Sub
            End If
            'if minutes values are ok start the presentation timer
            uiUpdateTimer.Enabled = True
            PresentationTimer.Start()
            StartBtn.Text = "STOP"
            Exit Sub
        End If

        'if the presentation timer has been running, but is currently stopped,
        'continue the timer and exit this sub
        If Not PresentationTimer.IsRunning And PresentationTimer.ElapsedMilliseconds > 0 Then
            uiUpdateTimer.Enabled = True
            PresentationTimer.Start()
            StartBtn.Text = "STOP"
            Exit Sub
        End If

        'if the interactive timer has been running,but is currently stopped,
        'continue the timer and exit this sub
        If Not InteractiveTimer.IsRunning And InteractiveTimer.ElapsedMilliseconds > 0 Then
            uiUpdateTimer.Enabled = True
            InteractiveTimer.Start()
            StartBtn.Text = "STOP"
            Exit Sub
        End If

    End Sub

    Private Sub ResetBtn_Click(sender As Object, e As EventArgs) Handles ResetBtn.Click
        PresentationTimer.Reset()
        InteractiveTimer.Reset()
        uiUpdateTimer.Enabled = False
        StartBtn.Enabled = True
        StartBtn.Text = "START"
        UpdateUI()
        BackgroundFlashTimer.Enabled = False
        Me.BackColor = defaultBackColor
    End Sub

    Private Sub BackgroundFlashTimer_Tick(sender As Object, e As EventArgs) Handles BackgroundFlashTimer.Tick
        StartBtn.Enabled = False
        If Me.BackColor = DefaultBackColor Then
            Me.BackColor = Color.Red
        Else
            Me.BackColor = DefaultBackColor
        End If
        Me.Update()
    End Sub

End Class


问:
Spacing on AppBarLayout
Spacing on AppBarLayout and incomplete app bar title

on geny motion virtual mobile is ok

on all my mobiles problem

problem screenshot:

on virtual mobile ok screenshot:

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        app:tabMode="fixed"
        android:layoutDirection="rtl"
        app:tabGravity="fill"
        android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</LinearLayout>
</code>```

答:
Try changing the style of the main activity (the one causing the issues) in the manifest, that should do it. You can check the default values when you create a new project using the "Basic Activity" template.

In this case since your layout contains a toolbar you should use the default theme (or a custom one to the same effect): android:theme="@style/AppTheme.NoActionBar". Notice that I´m using the default values of the template. The style you need should be something like this:

```<code><style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

This would be the manifest entry:

```<code><activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</code>```

BTW, just in case you havent done it, consider testing with the same API level in all devices (virtual and physical) to get consistent test results.

Hope it helps!

Title: Spacing on AppBarLayout

Body:
Spacing on AppBarLayout and incomplete app bar title

on geny motion virtual mobile is ok

on all my mobiles problem

problem screenshot:

on virtual mobile ok screenshot:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        app:tabMode="fixed"
        android:layoutDirection="rtl"
        app:tabGravity="fill"
        android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</LinearLayout>

Body:
Try changing the style of the main activity (the one causing the issues) in the manifest, that should do it. You can check the default values when you create a new project using the "Basic Activity" template.

In this case since your layout contains a toolbar you should use the default theme (or a custom one to the same effect): android:theme="@style/AppTheme.NoActionBar". Notice that I´m using the default values of the template. The style you need should be something like this:

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

This would be the manifest entry:

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

BTW, just in case you havent done it, consider testing with the same API level in all devices (virtual and physical) to get consistent test results.

Hope it helps!


问:
How to make Responsive button with Bootstrap
I'm Trying to have submit button center the page.
my code in html is:

```<code><div class="container-fluid">
<div class="row" style="margin-right:0;margin-left:0">

<form method="POST"
      action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
    {{csrf_field()}}

    <button type="submit" class="btn btn-primary submit">Submit</button>
</form>
</div>
</code>```

I give the submit button center in desktop but this button Not at the center in mobile!what can I do to centered button in mobile?

答:
For this the CSS should be

```<code>submit {
    display:block; /*setting the display to block(auto margin only work's on
    this case)*/
    margin: auto; /*centering*/
    width: 8%; /*choosing the width*/
}
</code>```

Body:
I'm Trying to have submit button center the page.
my code in html is:

<form method="POST"
      action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
    {{csrf_field()}}

    <button type="submit" class="btn btn-primary submit">Submit</button>
</form>

I give the submit button center in desktop but this button Not at the center in mobile!what can I do to centered button in mobile?

Body:
For this the CSS should be

submit {
    display:block; /*setting the display to block(auto margin only work's on
    this case)*/
    margin: auto; /*centering*/
    width: 8%; /*choosing the width*/
}


问:
Radio button not inline
I have 3 radio button with css property of  margin-top: -27px; This cause the 2 radio button to move above the main label header where as the other 1 i correct as it is beside the radio button label and beneath the main label of radio button. How do I limit or force the other 2 radio button not exceeding certain limit and stay same height line with the 3rd radio button. </p>

答:
It's hard to understand what you're talking about completely. As the others pointed out, you need to post your code if you want the best help.

However, if you want to try and align the 3 radio buttons, you could wrap them in a div and set the individual elements to inline.

So here would be your elements:

```<code><div class="wrapper">
    <input type="radio" class="inline-button">
    <input type="radio" class="inline-button">
    <input type="radio" class="inline-button">
</div>
</code>```

And you could style them like this:

```<code>.wrapper {
    width: auto;
    height: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: row;
}
.inline-button {
    display:inline-flex;
}
</code>```

Title: Radio button not inline

Body:
It's hard to understand what you're talking about completely. As the others pointed out, you need to post your code if you want the best help.

However, if you want to try and align the 3 radio buttons, you could wrap them in a div and set the individual elements to inline.

So here would be your elements:

<div class="wrapper">
    <input type="radio" class="inline-button">
    <input type="radio" class="inline-button">
    <input type="radio" class="inline-button">
</div>

And you could style them like this:

.wrapper {
    width: auto;
    height: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: row;
}
.inline-button {
    display:inline-flex;
}


问:
Is there a React shorthand for passing props?
I am tired of doing this all the time:

```<code><Elem x={x} y={y} z={z} />
<Elem x={this.props.x} y={this.props.y} z={this.props.z} />
</code>```

Is there a way I can get something like this to work?

```<code><Elem x, y, z />
</code>```

or

```<code><Elem {x, y, z} />
</code>```

答:
it should be noted that this only works for objects. for example:</p>

```<code>this.props = {
  x: 'foo',
  y: 'bar',
  z: 'baz',
}

const {
  x,
  ...allOtherProps
} = this.props

<Elem { ...allOtherProps } /> // works (allOtherProps is an object)
<Elem { ...x } /> // does not work (x is not an object)
<Elem x={ x } /> // works
</code>```

Body:
I am tired of doing this all the time:

<Elem x={x} y={y} z={z} />
<Elem x={this.props.x} y={this.props.y} z={this.props.z} />

Is there a way I can get something like this to work?

<Elem x, y, z />

or

<Elem {x, y, z} />

Body:
it should be noted that this only works for objects. for example:

this.props = {
  x: 'foo',
  y: 'bar',
  z: 'baz',
}

const {
  x,
  ...allOtherProps
} = this.props

<Elem { ...allOtherProps } /> // works (allOtherProps is an object)
<Elem { ...x } /> // does not work (x is not an object)
<Elem x={ x } /> // works


问:
Get specific attributes from an ActiveRecord model
Let's say that I have a User model with attributes :id, :first_name, :last_name, and :email. In my application, guest users shouldn't see User's email and last_name. I know how to select specific values if I want a list of users but I don't know how I can get specific attributes of a specific user like

```<code>User.find_by(id: 5).select(:id, :first_name).
</code>```

One solution to that is to user

```<code>User.find_by(id: 5).attributes.slice('id', 'first_name')
</code>```

but then I get a hash instead of an AR record. I could do

```<code>User.select(:id, :first_name).find_by(id: 1)
</code>```

but the thing that I don't know which filters I should filter since I need to know the user first.

Could you help me?

答:
This will works as well

User.select(:id, :first_name).find(5)

Body:
Let's say that I have a User model with attributes :id, :first_name, :last_name, and :email. In my application, guest users shouldn't see User's email and last_name. I know how to select specific values if I want a list of users but I don't know how I can get specific attributes of a specific user like

User.find_by(id: 5).select(:id, :first_name).

One solution to that is to user

User.find_by(id: 5).attributes.slice('id', 'first_name')

but then I get a hash instead of an AR record. I could do

User.select(:id, :first_name).find_by(id: 1)

but the thing that I don't know which filters I should filter since I need to know the user first.

Could you help me?


问:
How to specify region name in AWS S3 Java API?
I am using AWS Java API for S3. The access key, secret key, bucket name, and region name are all provided to my application as environment variables.

I am not sure how to set the region name...I'm currently getting the AmazonS3Client

```<code>return new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey))
</code>```

Can someone please tell me how to set the region name?

答:
Notice that if you have the region as a string, you can do this:

```<code>Regions regions = Regions.fromName('us-west-1');
</code>```

And you can create a credentials provider in a variety of ways, including this:

```<code>AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(
        new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY));
</code>```

and then (for whatever builder you're doing), you can do this:

```<code>AmazonSNS snsClient = AmazonSNSClientBuilder.standard()
    .withRegion(region)
    .withCredentials(credentialsProvider)
    .build();
</code>```

Body:
I am using AWS Java API for S3. The access key, secret key, bucket name, and region name are all provided to my application as environment variables.

I am not sure how to set the region name...I'm currently getting the AmazonS3Client

return new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey))

Can someone please tell me how to set the region name?

Body:
Notice that if you have the region as a string, you can do this:

Regions regions = Regions.fromName('us-west-1');

And you can create a credentials provider in a variety of ways, including this:

AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(
        new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY));

and then (for whatever builder you're doing), you can do this:

AmazonSNS snsClient = AmazonSNSClientBuilder.standard()
    .withRegion(region)
    .withCredentials(credentialsProvider)
    .build();


问:
Validation that excludes itself on update action if fields have not changed
I have a table called rents that hold a start and end date. I have then created a validation so that no new rents cant overlap existing rents start and end dates.

The thing is, when i click on a rent to update it and if i don't change any fields and click update. It trys to validate on itself and say that its overlapping an existing record. ( The existing record its referring to is it itself.)

The thing im trying to do is, how can i have my validation exclude itself. This is how my validation looks like.

```<code>def should_not_overlap_rental_periods
  errors.add(:start_date, "can't overlap other rental periods") if self.rents.where("end_date <= ? and start_date >= ?", self.end_date.strftime("%Y-%m-%d"), self.start_date.strftime("%Y-%m-%d")).count > 0 unless self.rents.blank?
end
</code>```

答:
You need to check up on ActiveModel's Dirty Checking module. You can check on attributes if they have changed and branch your logic accordingly.

http://railsapi.com/doc/rails-v3.0.1/classes/ActiveModel/Dirty.html

Body:
I have a table called rents that hold a start and end date. I have then created a validation so that no new rents cant overlap existing rents start and end dates.

The thing is, when i click on a rent to update it and if i don't change any fields and click update. It trys to validate on itself and say that its overlapping an existing record. ( The existing record its referring to is it itself.)

The thing im trying to do is, how can i have my validation exclude itself. This is how my validation looks like.

def should_not_overlap_rental_periods
  errors.add(:start_date, "can't overlap other rental periods") if self.rents.where("end_date <= ? and start_date >= ?", self.end_date.strftime("%Y-%m-%d"), self.start_date.strftime("%Y-%m-%d")).count > 0 unless self.rents.blank?
end


问:
QBWC: "Index Out Of Range" in do_authenticate()
I'm using QuickBooks WebConnector 2.2.0.71 and my WCF web service (on .NET 4.6.1). After pressing "Update selected" in WebConnector serverVersion and clientVersion requests successfully processed, but authenticate failed:

```<code>20170705.06:31:00 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : *** Calling authenticate() with following parameters:<userName="username"><password=<MaskedForSecurity>
20170705.06:31:00 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : QBWC1012: Authentication failed due to following error message.
Index Out Of Range.
More info:
StackTrace =    в QBWebConnector.WebService.do_authenticate(String& ticket, String& companyFileName)
Source = QBWebConnector
</code>```

Response of my WCF service (from WCF Test Client):

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body>
    <authenticateResponse xmlns="http://developer.intuit.com/">
      <authenticateResult xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:string>a3f10876-e027-419d-8dd8-3752a852ddae</a:string>
        <a:string>nvu</a:string>
        <a:string>3</a:string>
        <a:string>60</a:string>
        <a:string>60</a:string>
      </authenticateResult>
    </authenticateResponse>
  </s:Body>
</s:Envelope>
</code>```

Docs says "Your callback must return A string array with 4 possible elements. The first element contains either NONE or NVU (invalid user) or BUSY., or empty
string, or a string that is the QB company file name." but in samples first element is guid token, so I send array of 5 elements.

Same error occured when I send not an array, but int value, so I guess - maybe something wrong with my xml?

答:
Solved by adding [XmlSerializerFormat] to IService, so responce become

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <authenticateResponse xmlns="http://developer.intuit.com/">
      <authenticateResult>
        <string>d0297d33-859d-4259-a598-5fbf328bac3b</string>
        <string>nvu</string>
        <string>3</string>
        <string>60</string>
      </authenticateResult>
    </authenticateResponse>
  </s:Body>
</s:Envelope>
</code>```

Body:
I'm using QuickBooks WebConnector 2.2.0.71 and my WCF web service (on .NET 4.6.1). After pressing "Update selected" in WebConnector serverVersion and clientVersion requests successfully processed, but authenticate failed:

20170705.06:31:00 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : *** Calling authenticate() with following parameters:<userName="username"><password=<MaskedForSecurity>
20170705.06:31:00 UTC   : QBWebConnector.SOAPWebService.do_authenticate() : QBWC1012: Authentication failed due to following error message.
Index Out Of Range.
More info:
StackTrace =    в QBWebConnector.WebService.do_authenticate(String& ticket, String& companyFileName)
Source = QBWebConnector

Response of my WCF service (from WCF Test Client):

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body>
    <authenticateResponse xmlns="http://developer.intuit.com/">
      <authenticateResult xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        a3f10876-e027-419d-8dd8-3752a852ddae
        nvu
        3
        60
        60
      </authenticateResult>
    </authenticateResponse>
  </s:Body>
</s:Envelope>

Docs says "Your callback must return A string array with 4 possible elements. The first element contains either NONE or NVU (invalid user) or BUSY., or empty
string, or a string that is the QB company file name." but in samples first element is guid token, so I send array of 5 elements.

Same error occured when I send not an array, but int value, so I guess - maybe something wrong with my xml?

Body:
Solved by adding [XmlSerializerFormat] to IService, so responce become

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <authenticateResponse xmlns="http://developer.intuit.com/">
      <authenticateResult>
        <string>d0297d33-859d-4259-a598-5fbf328bac3b</string>
        <string>nvu</string>
        <string>3</string>
        <string>60</string>
      </authenticateResult>
    </authenticateResponse>
  </s:Body>
</s:Envelope>


问:
Post-processing the heatmap in python or ImageMagick
How could I make this heatmap look more clear without the blurred effect. How could I sharpen it Python (or ImageMagick)? also, how could I get a pixel-grid on the background?

Here is what I used to get the current image:

```<code>maxsize = (1030, 2056)
for i in range(1,334,1):
    img = Image.open('C:Desktop/Img/image'+'_'+ str(i)+'.png')
    img = img.resize(maxsize, Image.BICUBIC)
    img.save('C:/Desktop/Res/img'+'_'+ str(i)+'.png', dpi = (7040,7040))
</code>```

I also tried in ImageMagick (but that did not help much, atleast looking visually):

```<code>magick img_244.png -sharpen 0x3 out.png
</code>```

Thank you very much in advance,

答:
In ImageMagick (and also OpenCV/python) you can use kmeans to process your image. I have a bash unix shell script for ImageMagick that does that.

```<code>kmeans -n 7 -m 5 g4Zwf.png result7.png
</code>```

where n is the number of colors and m is the maximum number of iterations.

Then you can use my script, grid, to draw lines (or use ImageMagick directly) to draw lines. Using my script, grid with 100 pixel spacing gives:

```<code>grid -s 100,100 -c white result7.png result7g100.png
</code>```

My scripts are at http://www.fmwconcepts.com/imagemagick/index.html

For OpenCV/Python, see http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_ml/py_kmeans/py_kmeans_opencv/py_kmeans_opencv.html and How to write lines and grid on image in Python?

OpenCV/Python also has expectation maximization that may perform better on your color processing than kmeans. See https://en.wikipedia.org/wiki/Expectation–maximization_algorithm
and
Maximum likelihood pixel classification in python opencv

Body:
How could I make this heatmap look more clear without the blurred effect. How could I sharpen it Python (or ImageMagick)? also, how could I get a pixel-grid on the background?

Here is what I used to get the current image:

maxsize = (1030, 2056)
for i in range(1,334,1):
    img = Image.open('C:Desktop/Img/image'+'_'+ str(i)+'.png')
    img = img.resize(maxsize, Image.BICUBIC)
    img.save('C:/Desktop/Res/img'+'_'+ str(i)+'.png', dpi = (7040,7040))

I also tried in ImageMagick (but that did not help much, atleast looking visually):

magick img_244.png -sharpen 0x3 out.png

Thank you very much in advance,

Body:
In ImageMagick (and also OpenCV/python) you can use kmeans to process your image. I have a bash unix shell script for ImageMagick that does that.

kmeans -n 7 -m 5 g4Zwf.png result7.png

where n is the number of colors and m is the maximum number of iterations.

Then you can use my script, grid, to draw lines (or use ImageMagick directly) to draw lines. Using my script, grid with 100 pixel spacing gives:

grid -s 100,100 -c white result7.png result7g100.png

My scripts are at http://www.fmwconcepts.com/imagemagick/index.html

For OpenCV/Python, see http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_ml/py_kmeans/py_kmeans_opencv/py_kmeans_opencv.html and How to write lines and grid on image in Python?

OpenCV/Python also has expectation maximization that may perform better on your color processing than kmeans. See https://en.wikipedia.org/wiki/Expectation–maximization_algorithm
and
Maximum likelihood pixel classification in python opencv