问:
vb.net date formatting vs c# datetime formatting
I am doing an Visual Studio vb.net WinForm App.

I am used to work with c#. In C# Datetime DataType I have configured as "dd/MM/yyyy" as is configured in Control Panel and Regedit.

In VB.Net, is different, when I create a Date variable like this

Dim var As New Date
var = DateTime.Now```

Date.Now returns format "mm/dd/yyyy".

So every date format a assign to a variable, VB.Net automatically convert to format "mm/dd/yyyy".

I need Date DataType in VB.Net to be configured as C#. I mean, "dd/MM/yyyy" as it is configured in Control Panel.

Is that possible?

Thanks

答:
I want to work in format dd/MM/yyyy

Actually, you don't. You want to work with dates as DateTime types, because it's most flexible. Storing and working with dates as another type (such as a string in a particular format) in inherently less flexible and more error prone than using the proper type.

This is a perceptual problem; you think about dates in a certain way, and you seem to be demanding the computer represent them in YOUR way, but that's the flaw; you need to work with dates in the way .net does it because it's the best way.

In the same way that you wouldn't think of storing/working your numbers in a string, because "2" + "2" = "22", whereas 2 + 2 = 4, you should store, manipulate and process dates are DateTimes. If you want a particular representation just as the date data is being displayed on screen, THEN you can format it into MM/dd/yy for your american friends, or dd-MM-yyyy for your Europeans

dd= 16 +'/'+ 10 +'/'+ 17
  It should assign 16/10/2017, but it assign 10/16/2017..

Other people have covered this, but whatever class that Date  is, dump it, and use a built in DateTime, maybe like this:

```<code>DateTime d = new DateTime(2017, 10, 16);
</code>```

DateTime has a constructor that takes a year, month and day. Once you have your datetime object you can manipulate it with the AddXXX methods to add 10 days or subtract 15 hours etc. You can do onedate - anotherdate and get a TimeSpan object that will tell you how many minutes, hours, etc are between the two dates.. And so on

But it need it to define in General to all application. I need that Date type defined as dd/MM/yyyy by default.

You can't. .NET will never think of your date in any way other than the way it does internally, it will never process it in any way other than it's programmed to do. You say you know how to format it on the way out to a report.. and you seem to be saying you want to specify that format globally so that every time you, or anyone looks at a date, it's that format. You must appreciate that .net will still treat dates as the way it does internally. You can and should only influence the part of the process that puts the date on screen in some visible form for the user to read.. But really, if you're writing an application that will be used by other people, you shouldn't override the way their system treats dates, within your app..

You should instead just work with dates as dates, .ToString() them onto screen when you need to and let the thread, that is dealing with the conversion,  use whatever culture specific settings it picked up from the user's operating system. This way your app uses dates as dates, and the american using your app sees 10/12/2017 and knows it's the 12th oct, and the european using your app sees 12-10-2017 and knows the same

If you want to force a particular date format during development, set your windows culture settings to the formatting you want. Don't hard code a date format into your app

If I ask for DateTime.Now ,it returns a "MM/dd/yyyy", I need to retrieve a format "dd/MM/YYYY"

No, it doesn't. Datetime.Now returns you a DateTime object of a snapshot of the computer's clock at the time it was called. It represents the date internally as a number, not a string, not in any format etc. When you MessageBox.Show it (or whatever) it's converted to a string text representation and that's what you're seeing as "MM/dd/yyyy" but sure as heck DateTime.Now is not returning you a string like "10/12/2017"

In Main() I add

```<code>    Dim dd As DateTime = DateTime.Now
</code>```

Soo.. Just run me through the logic of the part where you tagged this question as C#, said it was C# and just now you've dumped a load of VB.NET from "your program" into it?

I want a global setting so I get "dd/MM/YYYY" in all my Application, so I do not need to Parse or Cast every time I need it....

Really, think on what I've said about how .NET treats dates. You stores dates as DateTime instances. When you get user input and create user output, those are really the only times you might need to convert from a string representation to a date, but on the input side of things there are controls such as DatePicker that allow the user to choose a date and time, and give you the value they chose, as a DateTime - no strings involved. On the output side; leave it - let the dates display in whatever format the user (including you) has picked in his Windows Region control panel

If you're reading in a text file with dates in a certain format, that's when you'd use DateTime.ParseExact(), to convert that text representation, into a DAteTime.. But you store it in your app memory, in xml files, in database columns etc, as a proper DateTime (or equivalent) datatype, NOT a string

The problem here is not with how .NET thinks about dates, it's with how you're thinking about them/how you think .net thinks about them. Once you're over that part, it'll get much easier

Body:
I am doing an Visual Studio vb.net WinForm App.

I am used to work with c#. In C# Datetime DataType I have configured as "dd/MM/yyyy" as is configured in Control Panel and Regedit.

In VB.Net, is different, when I create a Date variable like this

Dim var As New Date
var = DateTime.Now

Date.Now returns format "mm/dd/yyyy".

So every date format a assign to a variable, VB.Net automatically convert to format "mm/dd/yyyy".

I need Date DataType in VB.Net to be configured as C#. I mean, "dd/MM/yyyy" as it is configured in Control Panel.

Is that possible?

Thanks

Body:
I want to work in format dd/MM/yyyy

Actually, you don't. You want to work with dates as DateTime types, because it's most flexible. Storing and working with dates as another type (such as a string in a particular format) in inherently less flexible and more error prone than using the proper type.

This is a perceptual problem; you think about dates in a certain way, and you seem to be demanding the computer represent them in YOUR way, but that's the flaw; you need to work with dates in the way .net does it because it's the best way.

In the same way that you wouldn't think of storing/working your numbers in a string, because "2" + "2" = "22", whereas 2 + 2 = 4, you should store, manipulate and process dates are DateTimes. If you want a particular representation just as the date data is being displayed on screen, THEN you can format it into MM/dd/yy for your american friends, or dd-MM-yyyy for your Europeans

dd= 16 +'/'+ 10 +'/'+ 17
  It should assign 16/10/2017, but it assign 10/16/2017..

Other people have covered this, but whatever class that Date  is, dump it, and use a built in DateTime, maybe like this:

DateTime d = new DateTime(2017, 10, 16);

DateTime has a constructor that takes a year, month and day. Once you have your datetime object you can manipulate it with the AddXXX methods to add 10 days or subtract 15 hours etc. You can do onedate - anotherdate and get a TimeSpan object that will tell you how many minutes, hours, etc are between the two dates.. And so on

But it need it to define in General to all application. I need that Date type defined as dd/MM/yyyy by default.

You can't. .NET will never think of your date in any way other than the way it does internally, it will never process it in any way other than it's programmed to do. You say you know how to format it on the way out to a report.. and you seem to be saying you want to specify that format globally so that every time you, or anyone looks at a date, it's that format. You must appreciate that .net will still treat dates as the way it does internally. You can and should only influence the part of the process that puts the date on screen in some visible form for the user to read.. But really, if you're writing an application that will be used by other people, you shouldn't override the way their system treats dates, within your app..

You should instead just work with dates as dates, .ToString() them onto screen when you need to and let the thread, that is dealing with the conversion,  use whatever culture specific settings it picked up from the user's operating system. This way your app uses dates as dates, and the american using your app sees 10/12/2017 and knows it's the 12th oct, and the european using your app sees 12-10-2017 and knows the same

If you want to force a particular date format during development, set your windows culture settings to the formatting you want. Don't hard code a date format into your app

If I ask for DateTime.Now ,it returns a "MM/dd/yyyy", I need to retrieve a format "dd/MM/YYYY"

No, it doesn't. Datetime.Now returns you a DateTime object of a snapshot of the computer's clock at the time it was called. It represents the date internally as a number, not a string, not in any format etc. When you MessageBox.Show it (or whatever) it's converted to a string text representation and that's what you're seeing as "MM/dd/yyyy" but sure as heck DateTime.Now is not returning you a string like "10/12/2017"

In Main() I add

    Dim dd As DateTime = DateTime.Now

Soo.. Just run me through the logic of the part where you tagged this question as C#, said it was C# and just now you've dumped a load of VB.NET from "your program" into it?

I want a global setting so I get "dd/MM/YYYY" in all my Application, so I do not need to Parse or Cast every time I need it....

Really, think on what I've said about how .NET treats dates. You stores dates as DateTime instances. When you get user input and create user output, those are really the only times you might need to convert from a string representation to a date, but on the input side of things there are controls such as DatePicker that allow the user to choose a date and time, and give you the value they chose, as a DateTime - no strings involved. On the output side; leave it - let the dates display in whatever format the user (including you) has picked in his Windows Region control panel

If you're reading in a text file with dates in a certain format, that's when you'd use DateTime.ParseExact(), to convert that text representation, into a DAteTime.. But you store it in your app memory, in xml files, in database columns etc, as a proper DateTime (or equivalent) datatype, NOT a string

The problem here is not with how .NET thinks about dates, it's with how you're thinking about them/how you think .net thinks about them. Once you're over that part, it'll get much easier


来源: stackexchange

问:
"None" included in program output... why?
i've searched the forum and found similar questions, but no luck in solving my problem.

My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and i don't know how to fix...

here's the code:

```<code>def encryptLine(line, count):
    headline = line[count:]

    if length(headline) > 0:
        if count == length(line) - 1:
            new = headline
            return new
        elif count <= length(line):
            new = head(tail(headline)) + head(headline)
        new = new + str(encryptLine(line, count+2))
        return new

print(encryptLine('abcd', 0))
</code>```

the output for 'abcd' is badcNone, which is correct except for the word None. the output for 'abcde' is 'badce', which is correct...

thanks in advance for your help!

答:
None is here because your function return nothing.
There is 1 case where you return nothing it is

if length(headline) <= 0:

In Python, if there is no return to a function and you try to access to a return value, the value will be None.

ContentLicense: CC BY-SA 2.5

Body:
i've searched the forum and found similar questions, but no luck in solving my problem.

My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and i don't know how to fix...

here's the code:

def encryptLine(line, count):
    headline = line[count:]

    if length(headline) > 0:
        if count == length(line) - 1:
            new = headline
            return new
        elif count <= length(line):
            new = head(tail(headline)) + head(headline)
        new = new + str(encryptLine(line, count+2))
        return new

print(encryptLine('abcd', 0))

the output for 'abcd' is badcNone, which is correct except for the word None. the output for 'abcde' is 'badce', which is correct...

thanks in advance for your help!


问:
ios 11 Beta 5 select drop-down list issue
HTML Select drop-down list is not getting dismissed properly on iOS 11 beta 5. Upon closing the drop-down, an empty drop-down with blank options reappears in its place.

Please let me know if anyone else experienced the same issue and if a workaround is available for the same.

Note: It is a hybrid app built for iPad only and this issue is not reproducible on iOS 10 or below.

答:
solution in another thread

This is not a long-term solution, but it works until apple provides a fix.

main points of other answer

Build your app with xcode 8, you can download version 8 of xcode from here, you have to sign in using your apple id.

To be able to build to iOS11 you will have to download xcode 9 (unless you have it) as well, and then copy the 11.0 folder from xCode9/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport and paste it into the same place in xCode8

ContentLicense: CC BY-SA 3.0


问:
Aspnet Boilerplate / Aspnet Zero slow (IoC)
I use the aspnetboilerplate/aspnetzero template for my Multi-Tenant SaaS application with Multi-Database.
This uses CastleWindsor as DI Framework.

I experience very bad performance and I tracked it down with dotTrace - it says that Castle.MicroKernel is the most active code.

My requests take about 5-6 seconds and most of the time passes before it even hits the controller. (while debugging)
I think that resolving all services/controllers is slow. I changed some dependencies (App-Services) from Transient to PerWebRequestLifetime but it didn't affect performance.

Does anyone know, how I can get better performance?

In my Views (_Layout file) I call several different Childactions, that are on Layoutcontroller, this Controller gets following Services injected:

```<code>     public LayoutController(
        IPerSessionCache sessionCache,
        IUserNavigationManager userNavigationManager,
        IMultiTenancyConfig multiTenancyConfig,
        ILanguageManager languageManager,
        ITenancyNameFinder tenancyNameFinder,
        TenantManager tenantManager,
        IUserLinkAppService userLinkAppService,
        UserManager userManager)
</code>```

Actions are

```<code>[ChildActionOnly]
    public PartialViewResult AppHeader()
    {
        var headerModel = new Areas.Mpa.Models.Layout.HeaderViewModel
        {
            LoginInformations = AsyncHelper.RunSync(_sessionCache.GetCurrentLoginInformationsAsync),
            Languages = _languageManager.GetLanguages(),
            CurrentLanguage = _languageManager.CurrentLanguage,
            IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled,
            IsImpersonatedLogin = AbpSession.ImpersonatorUserId.HasValue,
            HasLinkedAccounts = AsyncHelper.RunSync(_userLinkAppService.HasLinkedAccounts)
        };

        return PartialView("~/Views/Layout/_AppHeader.cshtml", headerModel);
    }

[ChildActionOnly]
    public PartialViewResult AppNavbar(string currentPageName = "")
    {
        var sidebarModel = new Areas.Mpa.Models.Layout.NavbarViewModel
        {
            Menu = AsyncHelper.RunSync(() => _userNavigationManager.GetMenuAsync(MeNavigationProvider.MenuName, AbpSession.ToUserIdentifier())),
            CurrentPageName = currentPageName
        };

        return PartialView("_AppNavbar", sidebarModel);
    }
</code>```

and similar ones...But I checked the performance with an empty Layout File but my requests still take way too long

答:
Thanks to Stevens comment:

Make sure your injection constructors are fast. You are probably doing some kind of I/O during object graph construction.

I actually figured out, that this was the problem. One of our Services did I/O in the constructor - which is very slow and results in bad performance of the IoC-Container instantiating it.

Body:
I use the aspnetboilerplate/aspnetzero template for my Multi-Tenant SaaS application with Multi-Database.
This uses CastleWindsor as DI Framework.

I experience very bad performance and I tracked it down with dotTrace - it says that Castle.MicroKernel is the most active code.

My requests take about 5-6 seconds and most of the time passes before it even hits the controller. (while debugging)
I think that resolving all services/controllers is slow. I changed some dependencies (App-Services) from Transient to PerWebRequestLifetime but it didn't affect performance.

Does anyone know, how I can get better performance?

In my Views (_Layout file) I call several different Childactions, that are on Layoutcontroller, this Controller gets following Services injected:

     public LayoutController(
        IPerSessionCache sessionCache,
        IUserNavigationManager userNavigationManager,
        IMultiTenancyConfig multiTenancyConfig,
        ILanguageManager languageManager,
        ITenancyNameFinder tenancyNameFinder,
        TenantManager tenantManager,
        IUserLinkAppService userLinkAppService,
        UserManager userManager)

Actions are

[ChildActionOnly]
    public PartialViewResult AppHeader()
    {
        var headerModel = new Areas.Mpa.Models.Layout.HeaderViewModel
        {
            LoginInformations = AsyncHelper.RunSync(_sessionCache.GetCurrentLoginInformationsAsync),
            Languages = _languageManager.GetLanguages(),
            CurrentLanguage = _languageManager.CurrentLanguage,
            IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled,
            IsImpersonatedLogin = AbpSession.ImpersonatorUserId.HasValue,
            HasLinkedAccounts = AsyncHelper.RunSync(_userLinkAppService.HasLinkedAccounts)
        };

        return PartialView("~/Views/Layout/_AppHeader.cshtml", headerModel);
    }

[ChildActionOnly]
    public PartialViewResult AppNavbar(string currentPageName = "")
    {
        var sidebarModel = new Areas.Mpa.Models.Layout.NavbarViewModel
        {
            Menu = AsyncHelper.RunSync(() => _userNavigationManager.GetMenuAsync(MeNavigationProvider.MenuName, AbpSession.ToUserIdentifier())),
            CurrentPageName = currentPageName
        };

        return PartialView("_AppNavbar", sidebarModel);
    }

and similar ones...But I checked the performance with an empty Layout File but my requests still take way too long


问:
django unable to render form
I'm new to django.
look at the following code in my form.py:

```<code>class ProfileForm(forms.Form):
    name = forms.CharField(label=_("first name"))
    lname = forms.CharField(label=_("last name"))
    phone= forms.CharField(label=_("phone"))
    address = forms.CharField(label=_("address"))

    def categorize_fields(self):
        categorized_fields = [
        [ self.fields["name"], self.fields["lname"]  ] ,
        [ self.fields["phone"], self.fields["address"]  ]
        ]
        return categorized_fields
</code>```

in my form render I have the following code which does not work properly:

```<code>  {% for field_set in form.categorize_fields %}
         {% for field in field_set %}
             {{ field.label }}
             {{ field }}
         {% endfor %}
 {% endfor %}
</code>```

field.label is working correctly but {{ field }} is not showing the HTML rendered and instead is showing this:

```<code><django.forms.fields.CharField object at 0x000012661591CA90>
</code>```

but if I iterate through the main form passed to form_render.html, everything works fine:

```<code>    {% for field in form.visible_fields %}
        {{ field.label_tag }}
        {{ field }}
    {% endfor %}
</code>```

how can I solve that?
thanks

答:
self.fields contains references to the unbound field objects. If you want access to the actual bound fields, you need to index on self directly:

```<code>categorized_fields = [
    [ self["name"], self["lname"]  ] ,
    [ self["phone"], self["address"]  ]
]
</code>```

However, I do not recommend doing this. Instead, use a third-party library like django-crispy-forms.

Title: django unable to render form

Body:
I'm new to django.
look at the following code in my form.py:

class ProfileForm(forms.Form):
    name = forms.CharField(label=_("first name"))
    lname = forms.CharField(label=_("last name"))
    phone= forms.CharField(label=_("phone"))
    address = forms.CharField(label=_("address"))

    def categorize_fields(self):
        categorized_fields = [
        [ self.fields["name"], self.fields["lname"]  ] ,
        [ self.fields["phone"], self.fields["address"]  ]
        ]
        return categorized_fields

in my form render I have the following code which does not work properly:

  {% for field_set in form.categorize_fields %}
         {% for field in field_set %}
             {{ field.label }}
             {{ field }}
         {% endfor %}
 {% endfor %}

field.label is working correctly but {{ field }} is not showing the HTML rendered and instead is showing this:

<django.forms.fields.CharField object at 0x000012661591CA90>

but if I iterate through the main form passed to form_render.html, everything works fine:

    {% for field in form.visible_fields %}
        {{ field.label_tag }}
        {{ field }}
    {% endfor %}

how can I solve that?
thanks

Body:
self.fields contains references to the unbound field objects. If you want access to the actual bound fields, you need to index on self directly:

categorized_fields = [
    [ self["name"], self["lname"]  ] ,
    [ self["phone"], self["address"]  ]
]

However, I do not recommend doing this. Instead, use a third-party library like django-crispy-forms.


答:
I came up with an answer to the my question. Here there are the lines of codes that if placed in Sandcastle will allow to load the czml file and then add the orientation property through some type of interpolation:

```<code>//Sandcastle_Begin
var terrainProvider = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestVertexNormals : true
});

var viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider : terrainProvider,
baseLayerPicker : false
});

var options = {
    camera : viewer.scene.camera,
    canvas : viewer.scene.canvas
};

Sandcastle.addToolbarMenu([{
    text : 'Lateral avoidance w. real Wx and waypoints (KJFK-LEBL)',
    onselect : function() {

        viewer.camera.flyHome(0);

        viewer.dataSources.add(Cesium.CzmlDataSource.load('./SampleData/interp_turb_data_fromFede_avoid_realistic_w_waypoints.czml')).then(function(ds) {

        var entity = ds.entities.getById('path');

        // viewer.trackedEntity = entity;

        entity.orientation =  new Cesium.VelocityOrientationProperty(entity.position);

        entity.position.setInterpolationOptions({
            interpolationDegree : 1,
            interpolationAlgorithm : Cesium.HermitePolynomialApproximation
          });
    });

    }
}], 'toolbar');

Sandcastle.reset = function() {
    viewer.dataSources.removeAll();
    viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
    viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK;
};
//Sandcastle_End
</code>```

In this way the aircraft will be aligned with the trajectory!

Title: How to add trajectory orientation to CZML file

Body:
I have a czml file representing an aircraft flying a specified path. The file is constructed based on the Sancastle examples provided by Cesiusm (CZML Model + CZML Path).

Here is the CZML variable:

var czml = [{
    "id" : "document",
    "name" : "CZML Path",
    "version" : "1.0",
    "clock": {
        "interval": "2012-08-04T10:00:00Z/2012-08-04T15:00:00Z",
        "currentTime": "2012-08-04T10:00:00Z",
        "multiplier": 10
    }
}, {
    "id" : "path",
    "name" : "path with GPS flight data",
    "description" : "
Hang gliding flight log data from Daniel H. Friedman.
Icon created by Larisa Skosyrska from the Noun Project
",
    "availability" : "2012-08-04T10:00:00Z/2012-08-04T15:00:00Z",
    "path" : {
        "material" : {
            "polylineOutline" : {
                "color" : {
                    "rgba" : [255, 0, 255, 255]
                },
                "outlineColor" : {
                    "rgba" : [0, 255, 255, 255]
                },
                "outlineWidth" : 5
            }
        },
        "width" : 8,
        "leadTime" : 10,
        "trailTime" : 1000,
        "resolution" : 5
    },
    "model": {
        "gltf" : "../../SampleData/models/CesiumAir/Cesium_Air.glb",
        "scale" : 2.0,
        "minimumPixelSize": 128
    },
    "position" : {
        "epoch" : "2012-08-04T10:00:00Z",
        "cartographicDegrees" : [
            0,-122.93797,39.50935,1776,
            10,-122.93822,39.50918,1773,
            20,-122.9385,39.50883,1772,
            30,-122.93855,39.50842,1770,
            40,-122.93868,39.50792,1770,
            50,-122.93877,39.50743,1767,
            60,-122.93862,39.50697,1771,
            70,-122.93828,39.50648,1765,
            80,-122.93818,39.50608,1770,
            90,-122.93783,39.5057,1754,
            100,-122.93777,39.50513,1732,
            110,-122.93793,39.50458,1727,
            120,-122.93815,39.50415,1717,
            130,-122.9382,39.50362,1713,
            140,-122.93818,39.5031,1703,
            150,-122.93812,39.50258,1706,
            160,-122.93792,39.5022,1707,
            170,-122.93775,39.50177,1698,
            180,-122.93745,39.50125,1693,
            190,-122.93723,39.50073,1694,
            200,-122.9373,39.50023,1702
        ]
    }
}];

In order to be able to run the the code I also add the following lines:

var terrainProvider = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestVertexNormals : true
});

var viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider : terrainProvider,
baseLayerPicker : false
});

viewer.dataSources.add(Cesium.CzmlDataSource.load(czml)).then(function(ds) {
viewer.trackedEntity = ds.entities.getById('path');
});

If you run the code you can see how the center point of the aircraft follows the trajectory, however its heading is not aligned with it thus giving a wrong rap presentation of what the flight should look like:

Would you be able to explain how to add the aircraft orientation to the the code without possible changing the initial czml file structure?

Note: I have found the answer to this question but I was not able to implemented to my problem.

Body:
I came up with an answer to the my question. Here there are the lines of codes that if placed in Sandcastle will allow to load the czml file and then add the orientation property through some type of interpolation:

//Sandcastle_Begin
var terrainProvider = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestVertexNormals : true
});

var viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider : terrainProvider,
baseLayerPicker : false
});

var options = {
    camera : viewer.scene.camera,
    canvas : viewer.scene.canvas
};

Sandcastle.addToolbarMenu([{
    text : 'Lateral avoidance w. real Wx and waypoints (KJFK-LEBL)',
    onselect : function() {

        viewer.camera.flyHome(0);

        viewer.dataSources.add(Cesium.CzmlDataSource.load('./SampleData/interp_turb_data_fromFede_avoid_realistic_w_waypoints.czml')).then(function(ds) {

        var entity = ds.entities.getById('path');

        // viewer.trackedEntity = entity;

        entity.orientation =  new Cesium.VelocityOrientationProperty(entity.position);

        entity.position.setInterpolationOptions({
            interpolationDegree : 1,
            interpolationAlgorithm : Cesium.HermitePolynomialApproximation
          });
    });

    }
}], 'toolbar');

Sandcastle.reset = function() {
    viewer.dataSources.removeAll();
    viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
    viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK;
};
//Sandcastle_End

In this way the aircraft will be aligned with the trajectory!


问:
__android_log_print printing with out '/n' newline CR
WHen in native code __android_log_print() is used it prints adds an /n at the end of the text.

I am trying to get the same behavior as printf, where when /n not used it prints the next sting on the same line.

I need to write a data dump so I need to be able to to structure the data.
Now, I know I can store things in a temp buffer but I don't want to do that.

As I am working on an embedded device with an extremely small runtime memory.

答: You should consider whether the __android_log_print() function is appropriate to use for dumping data. It's conventional for logging functions that they output whole lines for each call.


问:
how to create a excel function that returns an array of variable size
I am trying to create a excel function that returns the result of a sql query.
I can do it if the result has size 1x1. However if the result is larger than that, I could not make the code work. Is there a solution for that? I am especially struggling with the fact that in all examples I have found, it is required to select exactly the right number of cells, whereas the result of my sql query could be of any size... and changing through time.

here is what I use so far:

```<code>Public Function getTS(field As String) As String
        Set oConnection = New ADODB.Connection
        Dim oRecordset As ADOR.Recordset
        oConnection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=AISDB;Data Source=mydomainlocation\mydatabase;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;"
        Set oRecordset = oConnection.Execute("select " & field & " from mytable where country = 'China'")
        If oRecordset.EOF Then
            getTS = "n/a"
        Else
            getTS = oRecordset(field)
        End If
    End Function
</code>```

答:
Ahh - sorry, I thought you were writing the function to return values to a vba subroutine. If you want a UDF you'll have to return a variant array and in the spreadsheet enter it as an array formula across the appropriate number of cells. Which means you'll have to know how many rows will be returned in advance.</p>

```<code> Public Function getTS(fieldnames As String) As variant

Set oConnection = New ADODB.Connection
Dim oRecordset As ADOR.Recordset
oConnection.Open....
Set oRecordset = ....
Dim x as long
 dim y as long
 y = 1
redim A(rs.fields.count,1)
do while not rs.eof
 For x = 1 to rs.fields.count
      A(x,y)=rs(x)
  Next x
 Rs.movenext
y = y+1
Redim preserve A(rs.fields.count,y+1)
Loop
rs.close
GetTS = A()
End Function
</code>```

Body:
I am trying to create a excel function that returns the result of a sql query.
I can do it if the result has size 1x1. However if the result is larger than that, I could not make the code work. Is there a solution for that? I am especially struggling with the fact that in all examples I have found, it is required to select exactly the right number of cells, whereas the result of my sql query could be of any size... and changing through time.

here is what I use so far:

Public Function getTS(field As String) As String
        Set oConnection = New ADODB.Connection
        Dim oRecordset As ADOR.Recordset
        oConnection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=AISDB;Data Source=mydomainlocation\mydatabase;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;"
        Set oRecordset = oConnection.Execute("select " & field & " from mytable where country = 'China'")
        If oRecordset.EOF Then
            getTS = "n/a"
        Else
            getTS = oRecordset(field)
        End If
    End Function

Body:
Ahh - sorry, I thought you were writing the function to return values to a vba subroutine. If you want a UDF you'll have to return a variant array and in the spreadsheet enter it as an array formula across the appropriate number of cells. Which means you'll have to know how many rows will be returned in advance.

 Public Function getTS(fieldnames As String) As variant

Set oConnection = New ADODB.Connection
Dim oRecordset As ADOR.Recordset
oConnection.Open....
Set oRecordset = ....
Dim x as long
 dim y as long
 y = 1
redim A(rs.fields.count,1)
do while not rs.eof
 For x = 1 to rs.fields.count
      A(x,y)=rs(x)
  Next x
 Rs.movenext
y = y+1
Redim preserve A(rs.fields.count,y+1)
Loop
rs.close
GetTS = A()
End Function


问:
Including carriage returns in PHP regex
How do I rewrite the following regex expression to include carriage returns and spaces?

```<code>mysql_query\("(.*)"\)
</code>```

It should match the following types of data.

String with carriage returns:

```<code>$result = my_mysql_query("
SELECT foo, bar
FROM mytable
ORDER BY name");
</code>```

String with some carriage returns:

```<code>$result = my_mysql_query("SELECT foo, bar
FROM mytable
ORDER BY name");
</code>```

String with no carriage returns:

```<code>$result = my_mysql_query("SELECT foo, bar FROM mytable ORDER BY name");
</code>```

答:
If you use PCRE (used by PHP's preg_*() functions), use the s modifier so . matches carriage returns and newlines:

```<code>/mysql_query\("(.*)"\)/s
</code>```

Title: Including carriage returns in PHP regex

Body:
How do I rewrite the following regex expression to include carriage returns and spaces?

mysql_query\("(.*)"\)

It should match the following types of data.

String with carriage returns:

$result = my_mysql_query("
SELECT foo, bar
FROM mytable
ORDER BY name");

String with some carriage returns:

$result = my_mysql_query("SELECT foo, bar
FROM mytable
ORDER BY name");

String with no carriage returns:

$result = my_mysql_query("SELECT foo, bar FROM mytable ORDER BY name");

Body:
If you use PCRE (used by PHP's preg_*() functions), use the s modifier so . matches carriage returns and newlines:

/mysql_query\("(.*)"\)/s


问:
Dynamically add element beside inputs
Let's say I have 10 different input fields, each of them has an ID.

<input id="blue">
<input id="pink">
<input id="red">

```

<p>Next to these input fields, I want to create an <code><a></code> element whose <code>href</code> attribute should dynamically include the ID of the button right next to it:</p>

<pre class="lang-html prettyprint-override"><code><input id="blue">
<a/>

<input id="pink">
href="mylink.com/pink"><a/>

<input id="red">
href="mylink.com/red"><a/>
</code>```

This is the simple code I am working with:

$('input').prepend('href="mylink.com/'+ID of the element next to this a tag+'/'');```

答:
Pure js approach

https://jsfiddle.net/r5thro2w/

```<code><input id="blue">
<input id="pink">
<input id="red">

window.onload = addAnchors();

function addAnchors() {
   let allInputs = document.getElementsByTagName("input");
   for(i=0;i<allInputs.length;i++) {
    let anchorTag = document.createElement('a');
    anchorTag.setAttribute('href',allInputs[i].getAttribute("id"));
    anchorTag.innerHTML = allInputs[i].getAttribute("id");
    allInputs[i].insertAdjacentElement("afterend", anchorTag);
   }
}
</code>```

Title: Dynamically add element beside inputs

Body:
Let's say I have 10 different input fields, each of them has an ID.

<input id="blue">
<input id="pink">
<input id="red">

Next to these input fields, I want to create an  element whose href attribute should dynamically include the ID of the button right next to it:

<input id="blue">

<input id="pink">

<input id="red">

This is the simple code I am working with:

$('input').prepend('<a href="mylink.com/'+ID of the element next to this a tag+'/'');

Body:
Pure js approach

https://jsfiddle.net/r5thro2w/

<input id="blue">
<input id="pink">
<input id="red">

window.onload = addAnchors();

function addAnchors() {
   let allInputs = document.getElementsByTagName("input");
   for(i=0;i<allInputs.length;i++) {
    let anchorTag = document.createElement('a');
    anchorTag.setAttribute('href',allInputs[i].getAttribute("id"));
    anchorTag.innerHTML = allInputs[i].getAttribute("id");
    allInputs[i].insertAdjacentElement("afterend", anchorTag);
   }
}


问:
Xamarin Forms - Error MT2002: Failed to resolve UIKit.UIEdgeInsets
I am working on a Xamarin.Forms project and I am getting the following error after I updated my Xamarin.Forms version to 2.4.0.74863.

```<code>/Users/UserName/Official/Projects/ProjectFolder/ProjectName/iOS/MTOUCH: Error MT2002: Failed to resolve "UIKit.UIEdgeInsets UIKit.UIView::get_SafeAreaInsets()" reference from "Xamarin.iOS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065" (MT2002) (ProjectName.iOS)
</code>```

How can I resolve this?
I have XCode 8.2.1, Xamarin Studio 6.1.2.44 installed in my machine.

I tried to change the link mode to 'Don't Link' (although its not preferable) but it gives different problems.

答:
Besides updating Xcode (to 9.x) you must set the Deployment Target to iOS 9.0 in the Info.plist file.

This is because SafeAreaInsets is only available in iOS 9 and up (as SushiHangover pointed out in the comments).

This will however mean that your app will only work on devices that run iOS 9.0 and up.

Body:
I am working on a Xamarin.Forms project and I am getting the following error after I updated my Xamarin.Forms version to 2.4.0.74863.

/Users/UserName/Official/Projects/ProjectFolder/ProjectName/iOS/MTOUCH: Error MT2002: Failed to resolve "UIKit.UIEdgeInsets UIKit.UIView::get_SafeAreaInsets()" reference from "Xamarin.iOS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065" (MT2002) (ProjectName.iOS)

How can I resolve this?
I have XCode 8.2.1, Xamarin Studio 6.1.2.44 installed in my machine.

I tried to change the link mode to 'Don't Link' (although its not preferable) but it gives different problems.


问:
How to set checkbox value to checked in zend framework 2?
I am wondering how to set the checkbox value of a zend form element to 'checked'?
I went in my Debug-11-condition so I would expect to see an active arrow in my box. Unfortunately the box remains empty.</p>

```<code>$room = $this->getRoomTable()->getRoom($roomId);
$roomForm->bind($room);
$lightOneValue = $room->getLighsone();
if ($lightOneValue == "100"){
    Debug::dump('11');
    $roomForm->get('lightone')->setChecked(true);
} else { ...
</code>```

答: $this->formCheckbox instead of $this->formInput was the point in my case, as Nykac pointed out above.</p>

Body:
I am wondering how to set the checkbox value of a zend form element to 'checked'?
I went in my Debug-11-condition so I would expect to see an active arrow in my box. Unfortunately the box remains empty.

$room = $this->getRoomTable()->getRoom($roomId);
$roomForm->bind($room);
$lightOneValue = $room->getLighsone();
if ($lightOneValue == "100"){
    Debug::dump('11');
    $roomForm->get('lightone')->setChecked(true);
} else { ...


问:
angular 5 material MatTableDataSource
I updated from angular 4.4.6 and material beta 19 to angular 5 and material 5.0.0-rc0

The application compiles correctly, but executing on Chrome I get

"Uncaught Error: Unexpected value 'MatTable DataSource' imported by the module 'Material Modules'. Please add a @NgModule annotation."

Other material components work correctly, mat-icon, mat-card-content, mat-tab-group, mat-dialog-xxx ...

Could you help me?

答: I had similar issue after upgrading to Angular 5, updating all the dependency like typescript, corejs , angular-cli etc to latest version solved the problem.</p>

Title: angular 5 material MatTableDataSource


问:
How to change a tabLayout clickable background color?
I know clickable background's can made a selector xml. But it's giving me following error(app:tabBackground):

Caused by: android.content.res.Resources$NotFoundException: File res/color/tab_selector.xml from drawable resource ID #0x7f050062

My Layout:

```<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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.khash.copytimejava.MainActivity"
    android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabBackground="@color/tab_selector"
            app:tabTextColor="@android:color/white"
            app:tabTextAppearance="@style/TabLayoutTextStyle"
            app:tabSelectedTextColor="@android:color/white"/>

        <FrameLayout
            android:id="@+id/frame_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>
</code>```

My tab selector xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorBlueWithAlpha" android:state_selected="true"></item>
    <item android:color="@color/colorBlueWithAlpha" android:state_pressed="true"></item>
    <item android:color="@color/colorPrimary"></item>
</selector>
</code>```

When i change

```<code>app:tabBackground="@color/tab_selector"
</code>```

to

```<code>app:tabBackground="@android:color/colorPrimary"
</code>```

it's working correctly.

Why it's giving me .Resources$NotFoundException?

Error Log after moved it drawable folder(and named tab_color):

```<code>FATAL EXCEPTION: main Process: com.example.khash.time, PID: 31922
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khash.time/com.example.khash.time.MainActivity}: android.content.res.Resources$NotFoundException: File res/drawable/tab_color.xml from drawable resource ID #0x7f070075
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/tab_color.xml from drawable resource ID #0x7f070075
    at android.content.res.Resources.loadDrawable(Resources.java:3457)
    at android.content.res.Resources.getDrawable(Resources.java:1897)
    at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:353)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
    at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
    at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1518)
    at android.support.design.widget.TabLayout.createTabView(TabLayout.java:932)
    at android.support.design.widget.TabLayout.newTab(TabLayout.java:569)
    at com.example.khash.time.MainActivity.setupTabLayout(MainActivity.java:44)
    at com.example.khash.time.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:5605)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: <item> tag requires a 'drawable' attribute or child tag defining a drawable
    at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:181)
    at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:990)
    at android.graphics.drawable.Drawable.createFromXml(Drawable.java:930)
    at android.content.res.Resources.loadDrawable(Resources.java:3453)
    at android.content.res.Resources.getDrawable(Resources.java:1897)
    at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:353)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
    at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
    at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1518)
    at android.support.design.widget.TabLayout.createTabView(TabLayout.java:932)         at android.support.design.widget.TabLayout.newTab(TabLayout.java:569)
    at com.example.khash.time.MainActivity.setupTabLayout(MainActivity.java:44)
    at com.example.khash.time.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:5605)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
Looks like android.support.design.widget.TabLayout does not support a color state list as a background.

From the source code:

```<code>if (mTabBackgroundResId != 0) {
    ViewCompat.setBackground(this, AppCompatResources.getDrawable(context, mTabBackgroundResId));
}
</code>```

You may be able to use a StateListDrawable to achieve this by replacing the android:color in your selector with an android:drawable.

Body:
I know clickable background's can made a selector xml. But it's giving me following error(app:tabBackground):

Caused by: android.content.res.Resources$NotFoundException: File res/color/tab_selector.xml from drawable resource ID #0x7f050062

My Layout:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.khash.copytimejava.MainActivity"
    android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabBackground="@color/tab_selector"
            app:tabTextColor="@android:color/white"
            app:tabTextAppearance="@style/TabLayoutTextStyle"
            app:tabSelectedTextColor="@android:color/white"/>

        <FrameLayout
            android:id="@+id/frame_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>

My tab selector xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorBlueWithAlpha" android:state_selected="true"></item>
    <item android:color="@color/colorBlueWithAlpha" android:state_pressed="true"></item>
    <item android:color="@color/colorPrimary"></item>
</selector>

When i change

app:tabBackground="@color/tab_selector"

to

app:tabBackground="@android:color/colorPrimary"

it's working correctly.

Why it's giving me .Resources$NotFoundException?

Error Log after moved it drawable folder(and named tab_color):

FATAL EXCEPTION: main Process: com.example.khash.time, PID: 31922
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khash.time/com.example.khash.time.MainActivity}: android.content.res.Resources$NotFoundException: File res/drawable/tab_color.xml from drawable resource ID #0x7f070075
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/tab_color.xml from drawable resource ID #0x7f070075
    at android.content.res.Resources.loadDrawable(Resources.java:3457)
    at android.content.res.Resources.getDrawable(Resources.java:1897)
    at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:353)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
    at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
    at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1518)
    at android.support.design.widget.TabLayout.createTabView(TabLayout.java:932)
    at android.support.design.widget.TabLayout.newTab(TabLayout.java:569)
    at com.example.khash.time.MainActivity.setupTabLayout(MainActivity.java:44)
    at com.example.khash.time.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:5605)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: <item> tag requires a 'drawable' attribute or child tag defining a drawable
    at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:181)
    at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:990)
    at android.graphics.drawable.Drawable.createFromXml(Drawable.java:930)
    at android.content.res.Resources.loadDrawable(Resources.java:3453)
    at android.content.res.Resources.getDrawable(Resources.java:1897)
    at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:353)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
    at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
    at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1518)
    at android.support.design.widget.TabLayout.createTabView(TabLayout.java:932)         at android.support.design.widget.TabLayout.newTab(TabLayout.java:569)
    at com.example.khash.time.MainActivity.setupTabLayout(MainActivity.java:44)
    at com.example.khash.time.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:5605)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)

Body:
Looks like android.support.design.widget.TabLayout does not support a color state list as a background.

From the source code:

if (mTabBackgroundResId != 0) {
    ViewCompat.setBackground(this, AppCompatResources.getDrawable(context, mTabBackgroundResId));
}

You may be able to use a StateListDrawable to achieve this by replacing the android:color in your selector with an android:drawable.


问:
When I compile .c file it always creates .exe file with name 'a'
I use GCC compiler to compile and run C program on CMD.
When I compile C program using command gcc hello.c it creates an executable file file with name a.exe but when I use IDE it uses the name same as .c file as hello.exe.
Is it possible to create .exe file name same as .c file on CMD?

答:
Just tell GCC the output name you want.</p>

```<code>gcc hello.c -o hello
</code>```

Body:
Just tell GCC the output name you want.

gcc hello.c -o hello


问:
Display image in cell.imageView.image using URL
I'm trying to display image once it's been processed.
Here's my code.

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "foodList", for: indexPath)
        let dict = itemsArray?[indexPath.row]

        cell.textLabel?.text = dict?["food_name"] as? String
        var URLz = dict?["image_url"] as! String
        Alamofire.request(URLz).response{ response in
            if let data = response.data{
                let image = UIImage(data:data)
                cell.imageView?.image = image
            }else{
                print("Data is nil.")
            }
        }

        return cell;
    }
</code>```

When I do the following; nothing gets displayed but table rows.

答:
It's not trivial to download and show image in tableviewcell, you need to check if the cell is visible before assigning the image to the imageview.

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "foodList", for: indexPath)
            .............
            cell.imageView?.image = UIImage(named: "placeholder.png") //or nil
            if let dict = dict, imageURL = dict["image_url"] as? String {
                Alamofire.request(imageURL).response { response in
                    if let data = response.data, let image = UIImage(data: data) {
                        DispatchQueue.main.async {
                            if let cell = tableView.cellForRow(at: indexPath) {
                                 cell.imageView?.image = image
                            }
                        }
                    } else {
                        print("Data is nil.")
                    }
                }
            }
            return cell
    }
</code>```

Better option would be to use third party libraries like Kingfisher which uses UIImageView extension to download and cache images from the network. It would as simple as below

```<code>let url = URL(string: imageURL)!
cell.imageView.kf.setImage(with: url, placeholder: nil)
</code>```

Body:
I'm trying to display image once it's been processed.
Here's my code.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "foodList", for: indexPath)
        let dict = itemsArray?[indexPath.row]

        cell.textLabel?.text = dict?["food_name"] as? String
        var URLz = dict?["image_url"] as! String
        Alamofire.request(URLz).response{ response in
            if let data = response.data{
                let image = UIImage(data:data)
                cell.imageView?.image = image
            }else{
                print("Data is nil.")
            }
        }

        return cell;
    }

When I do the following; nothing gets displayed but table rows.

Body:
It's not trivial to download and show image in tableviewcell, you need to check if the cell is visible before assigning the image to the imageview.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "foodList", for: indexPath)
            .............
            cell.imageView?.image = UIImage(named: "placeholder.png") //or nil
            if let dict = dict, imageURL = dict["image_url"] as? String {
                Alamofire.request(imageURL).response { response in
                    if let data = response.data, let image = UIImage(data: data) {
                        DispatchQueue.main.async {
                            if let cell = tableView.cellForRow(at: indexPath) {
                                 cell.imageView?.image = image
                            }
                        }
                    } else {
                        print("Data is nil.")
                    }
                }
            }
            return cell
    }

Better option would be to use third party libraries like Kingfisher which uses UIImageView extension to download and cache images from the network. It would as simple as below

let url = URL(string: imageURL)!
cell.imageView.kf.setImage(with: url, placeholder: nil)


问:
Validating a swagger
I am trying to validate swagger files (as part of my gradle build actually).
I have tried using swagger-parser, but while that works and gives an error if the swagger doesn't parse at all, it doesn't seem to catch issues the way http://editor.swagger.io/#/ does. (which is what I'm looking for)

Surely this is a common enough problem that there must be a way to do this already?

What I've tried:

build.gradle:

```<code>     compile("io.swagger:swagger-parser:1.0.31")
</code>```

A simple swagger with some obvious issues:

```<code>swagger: '2.0'
info:
  description: 'This is a sample server Petstore server.'
  version: 1.0.0
  title: Swagger Petstore
  termsOfService: http://swagger.io/terms/
  contact:
    email: apiteam@swagger.io
  license:
    name: Apache 2.0
    url: http://www.apache.org/licenses/LICENSE-2.0.html
host: petstore.swagger.io
basePath: /v2
paths:
  /pet:
    post:
      tags:
      - pet
      summary: Add a new pet to the store
      description: ''
      operationId: addPet
      parameters:
      - in: body
        name: body
        description: Pet object that needs to be added to the store
        required: true
        schema:
          type: '#/definitions/Pet'
      responses:
        '405':
          description: Invalid input
      security:
      - petstore_auth:
        - write:pets
        - read:pets
definitions:
  Category:
    type: petObject
    properties:
      id:
        type: integer
        format: int64
      name:
        type: string
    xml:
      name: Category
  Pet:
    type: object
    required:
    - name
    - photoUrls
    properties:
      id:
        type: integer
        format: int64
      category:
        $ref: '#/definitions/Category'
      name:
        type: string
        example: doggie
    xml:
      name: Pet
</code>```

And a simple class to test it (with the intent to move this to gradle eventually) :

```<code>class SwaggerTest {

public static void main(String[] args) {
  SwaggerTest st = new SwaggerTest();
  st.validate();
}

private void validate() {
    try {

      String content = new String(Files.readAllBytes(Paths.get("petstore.yml")));
      SwaggerParser swaggerParser = new SwaggerParser();
      SwaggerDeserializationResult result = swaggerParser.readWithInfo(content);
      swaggerParser.parse(content);

        Swagger swagger = result.getSwagger();
        if (swagger == null) {
            System.out.println("Unable to validate swagger");
        }else {
          System.out.println("Read the swagger");
        }
        List<String> messageList = result.getMessages();
        for(String message: messageList) {
            System.out.println(message);
        }

    } catch(Exception e) {
        System.out.println("Error!! "+ e.getMessage());
    }
}
}
</code>```

The above swagger has multiple issues, as you can see in http://editor.swagger.io/ however, swagger-parser doesnt tell me about them.

答:
I was running Swagger 2.0 with your file without any additional dependencies. It works without any errors, here is implementation:</p>

```<code>Swagger20Parser swaggerParser = new Swagger20Parser();
</code>```

Title: Validating a swagger

Body:
I am trying to validate swagger files (as part of my gradle build actually).
I have tried using swagger-parser, but while that works and gives an error if the swagger doesn't parse at all, it doesn't seem to catch issues the way http://editor.swagger.io/#/ does. (which is what I'm looking for)

Surely this is a common enough problem that there must be a way to do this already?

What I've tried:

build.gradle:

     compile("io.swagger:swagger-parser:1.0.31")

A simple swagger with some obvious issues:

swagger: '2.0'
info:
  description: 'This is a sample server Petstore server.'
  version: 1.0.0
  title: Swagger Petstore
  termsOfService: http://swagger.io/terms/
  contact:
    email: apiteam@swagger.io
  license:
    name: Apache 2.0
    url: http://www.apache.org/licenses/LICENSE-2.0.html
host: petstore.swagger.io
basePath: /v2
paths:
  /pet:
    post:
      tags:
      - pet
      summary: Add a new pet to the store
      description: ''
      operationId: addPet
      parameters:
      - in: body
        name: body
        description: Pet object that needs to be added to the store
        required: true
        schema:
          type: '#/definitions/Pet'
      responses:
        '405':
          description: Invalid input
      security:
      - petstore_auth:
        - write:pets
        - read:pets
definitions:
  Category:
    type: petObject
    properties:
      id:
        type: integer
        format: int64
      name:
        type: string
    xml:
      name: Category
  Pet:
    type: object
    required:
    - name
    - photoUrls
    properties:
      id:
        type: integer
        format: int64
      category:
        $ref: '#/definitions/Category'
      name:
        type: string
        example: doggie
    xml:
      name: Pet

And a simple class to test it (with the intent to move this to gradle eventually) :

class SwaggerTest {

public static void main(String[] args) {
  SwaggerTest st = new SwaggerTest();
  st.validate();
}

private void validate() {
    try {

      String content = new String(Files.readAllBytes(Paths.get("petstore.yml")));
      SwaggerParser swaggerParser = new SwaggerParser();
      SwaggerDeserializationResult result = swaggerParser.readWithInfo(content);
      swaggerParser.parse(content);

        Swagger swagger = result.getSwagger();
        if (swagger == null) {
            System.out.println("Unable to validate swagger");
        }else {
          System.out.println("Read the swagger");
        }
        List<String> messageList = result.getMessages();
        for(String message: messageList) {
            System.out.println(message);
        }

    } catch(Exception e) {
        System.out.println("Error!! "+ e.getMessage());
    }
}
}

The above swagger has multiple issues, as you can see in http://editor.swagger.io/ however, swagger-parser doesnt tell me about them.

Body:
I was running Swagger 2.0 with your file without any additional dependencies. It works without any errors, here is implementation:

Swagger20Parser swaggerParser = new Swagger20Parser();


问:
Why is my AJAX request in Wordpress not working
I am trying to use an external AJAX page to do something with PHP that inserts into my SQL database. I have tried to import a Wordpress class which is not working.

```<code>function accept_request(friend_id, user_id, status){
    $.ajax({
            type:'POST',
            url: myAjax.theme_dir +'callbacks/friend_action.php',
            data:{'friend_id':friend_id, 'user_id':user_id, 'status':status},
            success: function(data){
                alert(data);
                //location.reload();
             }
            });
          }
</code>```

and the php code is

```<code>//require_once($_SERVER['DOCUMENT_ROOT']."/choice/wp-load.php");
require_once("C:/xampp/htdocs/choice/wp-load.php");
global $wpdb;
$friend_id=$_POST['friend_id'];
$user_id=$_POST['user_id'];
$status=$_POST['status'];

if($status=="D"){
    $wpdb->query("delete from Friends_list where user_id='".$user_id."' and Friend_id='".$friend_id."'");
}
else{
    echo $friend_id.$user_id.$status;
    $wpdb->query("Update Friends_list set status='".$status."' where user_id='".$user_id."' and Friend_id='".$friend_id."'");
}
</code>```

答:
You need to use a standard guide to implement ajax in wordpress.
You need to do following

Make proper ajax call

Create function to handle the request

Add function to hook

Create success/error or other handlers as needed

Body:
I am trying to use an external AJAX page to do something with PHP that inserts into my SQL database. I have tried to import a Wordpress class which is not working.

function accept_request(friend_id, user_id, status){
    $.ajax({
            type:'POST',
            url: myAjax.theme_dir +'callbacks/friend_action.php',
            data:{'friend_id':friend_id, 'user_id':user_id, 'status':status},
            success: function(data){
                alert(data);
                //location.reload();
             }
            });
          }

and the php code is

//require_once($_SERVER['DOCUMENT_ROOT']."/choice/wp-load.php");
require_once("C:/xampp/htdocs/choice/wp-load.php");
global $wpdb;
$friend_id=$_POST['friend_id'];
$user_id=$_POST['user_id'];
$status=$_POST['status'];

if($status=="D"){
    $wpdb->query("delete from Friends_list where user_id='".$user_id."' and Friend_id='".$friend_id."'");
}
else{
    echo $friend_id.$user_id.$status;
    $wpdb->query("Update Friends_list set status='".$status."' where user_id='".$user_id."' and Friend_id='".$friend_id."'");
}


问:
Xcode 9 - "Fixed Width Constraints May Cause Clipping" and Other Localization Warnings
I downloaded the new Xcode and in Interface Builder I'm having a ton of problems with warnings that say things like:

Fixed Width Constraints May Cause Clipping

It looks like this:

I do have localization for several languages and I understand the warning that in another language a label's size may change, but my app doesn't have this problem. I ran and tested it in Xcode 8 yesterday, it was fine. I don't want to spend hours and hours adding pointless new constraints.

Any suggested solutions?

答:
Swift 4 , Xcode 9.1 :

About this issue, I think your object don't know what it's the correct center position in the context of it's  superview, and using remove, greater than or other leading/trealing settings most of times don't work correctly. First, you must check the correct constraints of your superview.

If your superview/s are correctly setted, you can try to "explain" to your object what is the correct position in the view by setting the "horizontally in Container" constraint:


问:
Break up a SQL Server 2008 query into batches
I'm trying to prepare some data for deletion by a 3rd party, and unfortunately they can only process data in batches of 2000 records.  I have 100k records and may need to divide-and-export this data several more times, so I'd like to automate the process somehow.

Is there a reasonably easy way to do this using SQL Server 2008?  I'm not running a complex query -- it's not too far off from SELECT PKID FROM Sometable ORDER BY PKID -- and while I can probably do this using a cursor, I'd like to know if there's a better way.

答:
You could work out the ranges in a while @@ROWCOUNT loop to target the rows required. It may work better than ROW_NUMBER() which would have to keep numbering from the start.</p>

```<code>declare @startid int
declare @endid int

-- get one range, these are efficient as they go over the PKID key by range
select top(1) @startid = pkid from sometable order by pkid  -- 1 key visited
select top(2000) @endid = pkid from sometable order by pkid  -- 2000 keys visited
-- note: top 2000 may end up with the 514th id if that is the last one

while @@ROWCOUNT > 0
begin
    insert otherdb.dbo.backupcopy
    select * from sometable
    where pkid between @startid and @endid

    select top(1) @startid = pkid from sometable
    WHERE pkid > @endid -- binary locate
    order by pkid

    select top(2000) @endid = pkid from sometable
    WHERE pkid > @endid -- binary locate, then forward range lookup, max 2000 keys
    order by pkid
end
</code>```

Body:
You could work out the ranges in a while @@ROWCOUNT loop to target the rows required. It may work better than ROW_NUMBER() which would have to keep numbering from the start.

declare @startid int
declare @endid int

-- get one range, these are efficient as they go over the PKID key by range
select top(1) @startid = pkid from sometable order by pkid  -- 1 key visited
select top(2000) @endid = pkid from sometable order by pkid  -- 2000 keys visited
-- note: top 2000 may end up with the 514th id if that is the last one

while @@ROWCOUNT > 0
begin
    insert otherdb.dbo.backupcopy
    select * from sometable
    where pkid between @startid and @endid

    select top(1) @startid = pkid from sometable
    WHERE pkid > @endid -- binary locate
    order by pkid

    select top(2000) @endid = pkid from sometable
    WHERE pkid > @endid -- binary locate, then forward range lookup, max 2000 keys
    order by pkid
end


问:
WebSphere MQ High Connection Count Issue
As per our configuration, we have WAS version is 8.5.5.1, IBM MQ version 7.5.0.3. We are using 2 channels to connect to WMQ, one with MAXINST set to 250 and one with 500. SHARECNV is set to 10 for both. Now we have an upper limit of making maximum 1600 connections in a queue manager but we end up crossing that limit after 3-4 days of continuous running of WAS Server.

I want to understand how parameters on WAS side affect this count. We are using Queue Connection Factory and Act Spec for making the connections and we have 23 of each of them. Out of these for 22 the settings in Act Spec and QCF are kept default like max server sessions=10, max connection in connection pool=10, max sessions in session pool set to 10. This services have quite low tps of around 15-20 request per minute. All 22 of them use same channel to connect to queue manager with MAXINST set to 250. 1 gets quite high load with peak of 80 requests per second(aprox 40 per server) for which max server sessions=40, max connection in connection pool=40, max sessions in session pool is set to 10.Connection Timeout, Reap Time, Unused Timeout and Aged timeout values are kept default for all.

With these settings we end up making around 1200 connection on the channel used by 22 services and around 500 for the other channel after 2-3 days of continuous running. These build up over a period of time.
Now I want to tune these settings so that we don't end up crossing the connection count limit and also don't end up having no connections available.
So I have a few questions:

What is a better option from performance point of view- reducing max connections in connection pool or max sessions in sessions pool. What should be the ideal values for the load mentioned earlier.

What should be the ideal value for Unused Timeout for Connection Pool and Session Pool which is set to 30 mins by default. If we reduce it to say 5 mins, what implications could it have on performance of failure to get the connections.

Is there some setting that can be done at WMQ side so that the  idle/unused connections are closed or this can happen only from the client side.

DISCINT parameter value is set to zero and HBINT to 300. What should be the ideal value.

I ran below command to view the connections

```<code>echo "DIS CONN(*) TYPE(*) CONNAME CHANNEL OBJNAME OBJTYPE" | mqsc -e -m     QM-p width=1000 | grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS="," 'function printValues() { if ("CHANNEL" in p) { print p["CHANNEL"], p["CURSHCNV"], p["CONNAME"],p["CHSTADA"],p["CHSTATI"],p["LSTMSGDA"],p["LSTMSGTI"],p["OBJNAME"],p["OBJTYPE"],p["ASTATE"] } } /^\w+:/ { printValues(); delete p; next } { p[$1] = $2 } END { printValues() }' | grep MYCHANNEL

MYCHANNEL,,10.215.161.65,,,,,,,NONE
MYCHANNEL,,10.215.161.65,,,,,,,SUSPENDED
    MYCHANNEL,,10.215.161.65,,,,,MYQUEUE01,QUEUE,ACTIVE
</code>```

I can see a lot of connection in None and suspended state which do not have any OBJNAME or OBJTYPE associated.
I have tried simulating the issue in Test and same thing happens and these connections keeps on increasing as we keep in hitting requests. Can someone tell me why these connections are getting created. Also it looks like these connections will never be used by the application.

This is how connection are made and closed in the application:
We have an abstrack bean class which is extended by all MDB's

```<code>@MessageDriven(activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })
public class TrackBeanV2 extends AbstractServiceBean implements MessageListener {//code}
</code>```

The abstrack bean handles creation and closing of connections in following manner:

```<code>public abstract class AbstractServiceBean {

@Resource(name = "myQCF", type = QueueConnectionFactory.class, shareable = true, description = "Reply Connection Factory")
private ConnectionFactory replyCF;

@PostConstruct
private void postConstruct() {
        replyConnection = replyCF.createConnection();

    }  catch (JMSException e) {
        throw new RuntimeException("Failed to create JMS Connection");
    }

}
@PreDestroy
private void preDestroy() {
    try {
        replyConnection.close();
    } catch (JMSException e) {
        throw new RuntimeException("Failed to close JMS connection", e);
    }
}

private void sendResponseMessage(String outputMessageText, String jmsMessageID , Destination replyDestination) {
    TextMessage replyMessage = null;
    try {
        createSession();
        createProducer();
        replyMessage = createReplyMessage(outputMessageText , jmsMessageID);
        sendReply(replyMessage, replyDestination);
        closeProducer();
        closeSession();
    } catch (JMSException exp) {
        handleException(exp);
    }
}
private void createSession() throws JMSException{
    replySession = replyConnection.createSession(true, 0);
}`
private void createProducer() throws JMSException{
    replyProducer = replySession.createProducer(null);
}

private void closeSession() throws JMSException {
    if (replySession != null) {
        replySession.close();
    }
}

private void closeProducer() throws JMSException{
    if (replyProducer != null) {
        replyProducer.close();
    }
}
private void sendReply(TextMessage replyMessage, Destination replyDestination) throws JMSException {
    logMessages(replyMessage.getText(), "RESPONSE MESSAGE");
    replyProducer.send(replyDestination, replyMessage);
}
</code>```

I have not added other methods of the class which marshalling/unmarshalling and other stuff.

答:
We had a similar problem where the connection count used to reach its limit once the application was kept active for hours.

Our catch was to call disconnect() of the queue manager post enqueue or dequeue rather than close(). So make sure your finally block looks something like this.

```<code>finally
{
    queue.close();
    qMgr.disconnect();     //rather than qMgr.close();
}
</code>```

Body:
As per our configuration, we have WAS version is 8.5.5.1, IBM MQ version 7.5.0.3. We are using 2 channels to connect to WMQ, one with MAXINST set to 250 and one with 500. SHARECNV is set to 10 for both. Now we have an upper limit of making maximum 1600 connections in a queue manager but we end up crossing that limit after 3-4 days of continuous running of WAS Server.

I want to understand how parameters on WAS side affect this count. We are using Queue Connection Factory and Act Spec for making the connections and we have 23 of each of them. Out of these for 22 the settings in Act Spec and QCF are kept default like max server sessions=10, max connection in connection pool=10, max sessions in session pool set to 10. This services have quite low tps of around 15-20 request per minute. All 22 of them use same channel to connect to queue manager with MAXINST set to 250. 1 gets quite high load with peak of 80 requests per second(aprox 40 per server) for which max server sessions=40, max connection in connection pool=40, max sessions in session pool is set to 10.Connection Timeout, Reap Time, Unused Timeout and Aged timeout values are kept default for all.

With these settings we end up making around 1200 connection on the channel used by 22 services and around 500 for the other channel after 2-3 days of continuous running. These build up over a period of time.
Now I want to tune these settings so that we don't end up crossing the connection count limit and also don't end up having no connections available.
So I have a few questions:

What is a better option from performance point of view- reducing max connections in connection pool or max sessions in sessions pool. What should be the ideal values for the load mentioned earlier.

What should be the ideal value for Unused Timeout for Connection Pool and Session Pool which is set to 30 mins by default. If we reduce it to say 5 mins, what implications could it have on performance of failure to get the connections.

Is there some setting that can be done at WMQ side so that the  idle/unused connections are closed or this can happen only from the client side.

DISCINT parameter value is set to zero and HBINT to 300. What should be the ideal value.

I ran below command to view the connections

echo "DIS CONN(*) TYPE(*) CONNAME CHANNEL OBJNAME OBJTYPE" | mqsc -e -m     QM-p width=1000 | grep -o '^\w\+:\|\w\+[(][^)]\+[)]' | awk -F '[()]' -v OFS="," 'function printValues() { if ("CHANNEL" in p) { print p["CHANNEL"], p["CURSHCNV"], p["CONNAME"],p["CHSTADA"],p["CHSTATI"],p["LSTMSGDA"],p["LSTMSGTI"],p["OBJNAME"],p["OBJTYPE"],p["ASTATE"] } } /^\w+:/ { printValues(); delete p; next } { p[$1] = $2 } END { printValues() }' | grep MYCHANNEL

MYCHANNEL,,10.215.161.65,,,,,,,NONE
MYCHANNEL,,10.215.161.65,,,,,,,SUSPENDED
    MYCHANNEL,,10.215.161.65,,,,,MYQUEUE01,QUEUE,ACTIVE

I can see a lot of connection in None and suspended state which do not have any OBJNAME or OBJTYPE associated.
I have tried simulating the issue in Test and same thing happens and these connections keeps on increasing as we keep in hitting requests. Can someone tell me why these connections are getting created. Also it looks like these connections will never be used by the application.

This is how connection are made and closed in the application:
We have an abstrack bean class which is extended by all MDB's

@MessageDriven(activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })
public class TrackBeanV2 extends AbstractServiceBean implements MessageListener {//code}

The abstrack bean handles creation and closing of connections in following manner:

public abstract class AbstractServiceBean {

@Resource(name = "myQCF", type = QueueConnectionFactory.class, shareable = true, description = "Reply Connection Factory")
private ConnectionFactory replyCF;

@PostConstruct
private void postConstruct() {
        replyConnection = replyCF.createConnection();

    }  catch (JMSException e) {
        throw new RuntimeException("Failed to create JMS Connection");
    }

}
@PreDestroy
private void preDestroy() {
    try {
        replyConnection.close();
    } catch (JMSException e) {
        throw new RuntimeException("Failed to close JMS connection", e);
    }
}

private void sendResponseMessage(String outputMessageText, String jmsMessageID , Destination replyDestination) {
    TextMessage replyMessage = null;
    try {
        createSession();
        createProducer();
        replyMessage = createReplyMessage(outputMessageText , jmsMessageID);
        sendReply(replyMessage, replyDestination);
        closeProducer();
        closeSession();
    } catch (JMSException exp) {
        handleException(exp);
    }
}
private void createSession() throws JMSException{
    replySession = replyConnection.createSession(true, 0);
}`
private void createProducer() throws JMSException{
    replyProducer = replySession.createProducer(null);
}

private void closeSession() throws JMSException {
    if (replySession != null) {
        replySession.close();
    }
}

private void closeProducer() throws JMSException{
    if (replyProducer != null) {
        replyProducer.close();
    }
}
private void sendReply(TextMessage replyMessage, Destination replyDestination) throws JMSException {
    logMessages(replyMessage.getText(), "RESPONSE MESSAGE");
    replyProducer.send(replyDestination, replyMessage);
}

I have not added other methods of the class which marshalling/unmarshalling and other stuff.

Body:
We had a similar problem where the connection count used to reach its limit once the application was kept active for hours.

Our catch was to call disconnect() of the queue manager post enqueue or dequeue rather than close(). So make sure your finally block looks something like this.

finally
{
    queue.close();
    qMgr.disconnect();     //rather than qMgr.close();
}


问:
Adding padding to
 in CSS is making the content not move with consistent line-height
My predicament is this. I have a list, a simple cart, login, user registration list. I want to move the list up by adding padding. But I cannot with out the list adding line height. What is the way around this? See examples below. This list is in the header.

Before:

.content{
  border: 2px solid #000;
}

li {
 list-style-type: none;
 font-size: 10px;
 direction: right;
 text-align: right;
 padding-bottom: 20px;
 line-height: 1;
 display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <ul>
    <li>Cart</li>
    <li>Login</li>
    <li>Customer Registration</li>
  </ul>
</div></code>```

After:

答:
Try This:

```<code>ul {
    margin-top: 0;
}
</code>```

ul {
  margin-top: 0;
}

li {
  list-style-type: none;
  font-size: 10px;
  direction: right;
  text-align: right;
  padding-bottom: 20px;
  line-height: 1;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Cart</li>
  <li>Login</li>
  <li>Customer Registration</li>
</ul</code>```

Title: Adding padding to <li> in CSS is making the content not move with consistent line-height

Body:
My predicament is this. I have a list, a simple cart, login, user registration list. I want to move the list up by adding padding. But I cannot with out the list adding line height. What is the way around this? See examples below. This list is in the header.

Before:

.content{
  border: 2px solid #000;
}

li {
 list-style-type: none;
 font-size: 10px;
 direction: right;
 text-align: right;
 padding-bottom: 20px;
 line-height: 1;
 display: block;
}

Cart

Login

Customer Registration

After:

Body:
Try This:

ul {
    margin-top: 0;
}

ul {
  margin-top: 0;
}

li {
  list-style-type: none;
  font-size: 10px;
  direction: right;
  text-align: right;
  padding-bottom: 20px;
  line-height: 1;
  display: block;
}

<ul>
  <li><a href="#">Cart</a></li>
  <li><a href="#">Login</a></li>
  <li><a href="#">Customer Registration</a></li>
</ul


问:
Failed to show selected image from gallery in android
I want to choose image from gallery and load or show it in the activity. But the code is not working properly. It can only select image from the phone gallery but doesn't show the selected image. Checking the logcat got these errors.I'm providing the java file, xml file and manifest below.

```<code>11-15 16:31:23.795 18921-18921/com.example.emma.gallaryview E/MultiWindowProxy: getServiceInstance failed!
11-15 16:31:34.970 18921-18921/com.example.emma.gallaryview E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20171114_202150.jpg: open failed: EACCES (Permission denied)
</code>```

java file

```<code>    public class MainActivity extends AppCompatActivity {
    private static int RESULT_LOAD_IMG = 1;
    String imgDecodableString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                ImageView imgView = (ImageView) findViewById(R.id.imgView);
                // Set the Image in ImageView after decoding the String
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgDecodableString));

            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }

    }

}
</code>```

The xml file

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ImageView>

    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:onClick="loadImagefromGallery"
        android:text="Load Picture" >
    </Button>

</LinearLayout>
</code>```

and manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.emma.gallaryview">
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-feature android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.autofocus"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
</code>```

答:
On Android 6+ you have to add code to ask the user of your app to confirm the permissions you requested in manifest.

Google for runtime permissions.

Further your code is much to complicated. You should just open an input stream for the obtained uri and then let bitmap factory decode from the steam.

```<code>InputStream is = getContentResolver().openInputStream(data.getData());
</code>```

Then use

```<code>BitmapFactory.decodeStream(is).
</code>```

Finally: dont be surprised if decodeStream returns null on a lot of devices. Well as decodeFile would.

Body:
I want to choose image from gallery and load or show it in the activity. But the code is not working properly. It can only select image from the phone gallery but doesn't show the selected image. Checking the logcat got these errors.I'm providing the java file, xml file and manifest below.

11-15 16:31:23.795 18921-18921/com.example.emma.gallaryview E/MultiWindowProxy: getServiceInstance failed!
11-15 16:31:34.970 18921-18921/com.example.emma.gallaryview E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20171114_202150.jpg: open failed: EACCES (Permission denied)

java file

    public class MainActivity extends AppCompatActivity {
    private static int RESULT_LOAD_IMG = 1;
    String imgDecodableString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                ImageView imgView = (ImageView) findViewById(R.id.imgView);
                // Set the Image in ImageView after decoding the String
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgDecodableString));

            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }

    }

}

The xml file

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ImageView>

    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:onClick="loadImagefromGallery"
        android:text="Load Picture" >
    </Button>

</LinearLayout>

and manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.emma.gallaryview">
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-feature android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.autofocus"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Body:
On Android 6+ you have to add code to ask the user of your app to confirm the permissions you requested in manifest.

Google for runtime permissions.

Further your code is much to complicated. You should just open an input stream for the obtained uri and then let bitmap factory decode from the steam.

InputStream is = getContentResolver().openInputStream(data.getData());

Then use

BitmapFactory.decodeStream(is).

Finally: dont be surprised if decodeStream returns null on a lot of devices. Well as decodeFile would.