问:
unable to install signed apk or build apk - showing "App not installed dialog" - "android-P"
I am facing an issue in installing(build or signed) apk in the device showing "App not installed". It's working fine previously, after updating my build tools to "3.1.0" and compile SDK to "android-P" facing this issue,

If I downgrade to "26", showing "drawable-28-alpha" error. Can you please help me with this, tried almost everything.

```<code>**build.gradle**

compileSdkVersion 'android-P'
buildToolsVersion '27.0.3'

defaultConfig {
    applicationId "com.***.******"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 7
    versionName "1.4.2"
    multiDexEnabled true
}

 classpath 'com.android.tools.build:gradle:3.1.0'

**gradle-wrapper:**
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
</code>```

Thanks in advance!

答:
On Android 9 (API 28) try to disable Google Play Protect from play store app.

To disable Google Play Protect. Open "Play Store" application -> tap on Menu button -> select "Play Protect" option -> Click on "Settings" icon -> then disable the option "Scan device for security threats".

Body:
I am facing an issue in installing(build or signed) apk in the device showing "App not installed". It's working fine previously, after updating my build tools to "3.1.0" and compile SDK to "android-P" facing this issue,

If I downgrade to "26", showing "drawable-28-alpha" error. Can you please help me with this, tried almost everything.

**build.gradle**

compileSdkVersion 'android-P'
buildToolsVersion '27.0.3'

defaultConfig {
    applicationId "com.***.******"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 7
    versionName "1.4.2"
    multiDexEnabled true
}

 classpath 'com.android.tools.build:gradle:3.1.0'

**gradle-wrapper:**
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

Thanks in advance!


来源: stackexchange

问:
How to use HTML Agility pack
How do I use the HTML Agility Pack?

My XHTML document is not completely valid. That's why I wanted to use it. How do I use it in my project? My project is in C#.

答:
try this</p>

```<code>string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());

private string ParseHmlBody(string html)
        {
            string body = string.Empty;
            try
            {
                var htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(html);
                var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
                body = htmlBody.OuterHtml;
            }
            catch (Exception ex)
            {

                dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
            }
            return body;
        }
</code>```

OwnerDisplayName: chh

ContentLicense: CC BY-SA 3.0

Title: How to use HTML Agility pack

Body:
try this

string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());

private string ParseHmlBody(string html)
        {
            string body = string.Empty;
            try
            {
                var htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(html);
                var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
                body = htmlBody.OuterHtml;
            }
            catch (Exception ex)
            {

                dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
            }
            return body;
        }

ContentLicense: CC BY-SA 4.0


答: The problem is the ouput in the console itself. If there are multiple similar entries - like the first 10 elements of value 1 in the first row plus the 1 in the second row, it will be grouped as a single entry of 11. You can see that there are multiple if you look to the right of a particular entry.

Title: How to write out n*n Matrix values in JavaScript?

Body:
I'm new to JavaScript, so I decided to try to make a simple n*n Array. When I'm trying to write it out, I get, something starnge back.

var map = [

  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],

  [1, 2, 3, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 3, 1],

  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];

function GoTh() {
  for (var i = 0; i < map.length; i++) {
    for (var j = 0; j < map[i].length; j++) {
      console.log(map[i][j]);
    }
  }
}
GoTh();

I expected it to write all 100 values, but it gives back this:
1 2 3 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 3 1


问:
What is the use of overriding the finalize() method of Object class?
As far as I know , in java if we want to manually call the garbage collector we can do System.gc().

1.What are the operations that we do inside our overriden finalize() method?

2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

答:
1) Any clean up that you want to do on object destruction (if you keep some handles open and nobody has called an explicit close for example). Keep in mind that you don't know when this will happen because the JVM will call the GC and not you.

2) Nope.

Side note, you should not manually call the Garbage Collector, see the answer here, Why do you not explicitly call finalize() or start the garbage collector?


问:
React application caching
I am new to React. I have a React application which recently pushed to Production. There were some frontend fixes and again pushed to production. But it is showing the same page after new build. It is taking from cache. But if i remove cache, it is working.

Using react boilerplate (https://github.com/react-boilerplate/react-boilerplate)

I tried searching for Service worker and res.header(cache-control). But nothing seems to be worked.

Below is my webpack prod file

```<code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackPwaManifest = require('webpack-pwa-manifest');
const OfflinePlugin = require('offline-plugin');
const { HashedModuleIdsPlugin } = require('webpack');
const webpack = require('webpack');
const S3Plugin = require('webpack-s3-plugin');
// const TerserPlugin = require('terser-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const config = require('../../app/config');

module.exports = require('./webpack.base.babel')({
  mode: 'production',

  // In production, we skip all hot-reloading stuff
  entry: [
    require.resolve('react-app-polyfill/ie11'),
    path.join(process.cwd(), 'app/app.js'),
  ],

  // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
  output: {
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].chunk.js',
  },

  // optimization: {
  //   minimize: true,
  //   minimizer: [
  //     new TerserPlugin({
  //       terserOptions: {
  //         warnings: false,
  //         compress: {
  //           comparisons: false,
  //         },
  //         parse: {},
  //         mangle: true,
  //         output: {
  //           comments: false,
  //           ascii_only: true,
  //         },
  //       },
  //       parallel: true,
  //       cache: true,
  //       sourceMap: true,
  //     }),
  //   ],
  //   nodeEnv: 'production',
  //   sideEffects: true,
  //   concatenateModules: true,
  //   splitChunks: {
  //     chunks: 'all',
  //     minSize: 30000,
  //     minChunks: 1,
  //     maxAsyncRequests: 5,
  //     maxInitialRequests: 3,
  //     name: true,
  //     cacheGroups: {
  //       commons: {
  //         test: /[\\/]node_modules[\\/]/,
  //         name: 'vendor',
  //         chunks: 'all',
  //       },
  //       main: {
  //         chunks: 'all',
  //         minChunks: 2,
  //         reuseExistingChunk: true,
  //         enforce: true,
  //       },
  //     },
  //   },
  //   runtimeChunk: true,
  // },

  plugins: [
    // Minify and optimize the index.html
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
    }),
    new S3Plugin({
      exclude: /.*\.html$/,
      s3Options: {
        accessKeyId: config.aws.s3.aws_access_key_id,
        secretAccessKey: config.aws.s3.aws_secret_access_key,
        region: 'us-west-2',
      },
      s3UploadOptions: {
        Bucket: config.aws.s3.bucket,
      },
    }),

    // Put it in the end to capture all the HtmlWebpackPlugin's
    // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
    new OfflinePlugin({
      relativePaths: false,
      publicPath: '/',
      appShell: '/',

      // No need to cache .htaccess. See http://mxs.is/googmp,
      // this is applied before any match in `caches` section
      excludes: ['.htaccess'],

      caches: {
        main: [':rest:'],

        // All chunks marked as `additional`, loaded after main section
        // and do not prevent SW to install. Change to `optional` if
        // do not want them to be preloaded at all (cached only when first loaded)
        additional: ['*.chunk.js'],
      },

      // Removes warning for about `additional` section usage
      safeToUseOptionalCaches: true,
      AppCache: false,

      ServiceWorker: {
        events: true,
        publicPath: '/sw.js',
        navigateFallbackURL: '/',
        prefetchRequest: {},
      },
      // Hack
      // This is to skip the warning that OfflinePlugin throws if sw registration is not done
      __tests: {
        ignoreRuntime: true,
      },
    }),

    new CompressionPlugin({
      algorithm: 'gzip',
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8,
    }),

    new WebpackPwaManifest({
      name: 'React Boilerplate',
      short_name: 'React BP',
      description: 'My React Boilerplate-based project!',
      background_color: '#fafafa',
      theme_color: '#b1624d',
      inject: true,
      ios: true,
      icons: [
        {
          src: path.resolve('app/images/icon-512x512.png'),
          sizes: [72, 96, 128, 144, 192, 384, 512],
        },
        {
          src: path.resolve('app/images/icon-512x512.png'),
          sizes: [120, 152, 167, 180],
          ios: true,
        },
      ],
    }),

    new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /en/),

    new HashedModuleIdsPlugin({
      hashFunction: 'sha256',
      hashDigest: 'hex',
      hashDigestLength: 20,
    }),
  ],

  performance: {
    assetFilter: assetFilename =>
      !/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename),
  },
});```
```

答:
Use webpack and use hashing (and append it to file names) to generate the files.

Hence whenever you rebuild the app and deploy it on production those hashed files wont be present in the cache and you wont have the cache problem anymore.

Title: React application caching

Body:
I am new to React. I have a React application which recently pushed to Production. There were some frontend fixes and again pushed to production. But it is showing the same page after new build. It is taking from cache. But if i remove cache, it is working.

Using react boilerplate (https://github.com/react-boilerplate/react-boilerplate)

I tried searching for Service worker and res.header(cache-control). But nothing seems to be worked.

Below is my webpack prod file

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackPwaManifest = require('webpack-pwa-manifest');
const OfflinePlugin = require('offline-plugin');
const { HashedModuleIdsPlugin } = require('webpack');
const webpack = require('webpack');
const S3Plugin = require('webpack-s3-plugin');
// const TerserPlugin = require('terser-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const config = require('../../app/config');

module.exports = require('./webpack.base.babel')({
  mode: 'production',

  // In production, we skip all hot-reloading stuff
  entry: [
    require.resolve('react-app-polyfill/ie11'),
    path.join(process.cwd(), 'app/app.js'),
  ],

  // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
  output: {
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].chunk.js',
  },

  // optimization: {
  //   minimize: true,
  //   minimizer: [
  //     new TerserPlugin({
  //       terserOptions: {
  //         warnings: false,
  //         compress: {
  //           comparisons: false,
  //         },
  //         parse: {},
  //         mangle: true,
  //         output: {
  //           comments: false,
  //           ascii_only: true,
  //         },
  //       },
  //       parallel: true,
  //       cache: true,
  //       sourceMap: true,
  //     }),
  //   ],
  //   nodeEnv: 'production',
  //   sideEffects: true,
  //   concatenateModules: true,
  //   splitChunks: {
  //     chunks: 'all',
  //     minSize: 30000,
  //     minChunks: 1,
  //     maxAsyncRequests: 5,
  //     maxInitialRequests: 3,
  //     name: true,
  //     cacheGroups: {
  //       commons: {
  //         test: /[\\/]node_modules[\\/]/,
  //         name: 'vendor',
  //         chunks: 'all',
  //       },
  //       main: {
  //         chunks: 'all',
  //         minChunks: 2,
  //         reuseExistingChunk: true,
  //         enforce: true,
  //       },
  //     },
  //   },
  //   runtimeChunk: true,
  // },

  plugins: [
    // Minify and optimize the index.html
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
    }),
    new S3Plugin({
      exclude: /.*\.html$/,
      s3Options: {
        accessKeyId: config.aws.s3.aws_access_key_id,
        secretAccessKey: config.aws.s3.aws_secret_access_key,
        region: 'us-west-2',
      },
      s3UploadOptions: {
        Bucket: config.aws.s3.bucket,
      },
    }),

    // Put it in the end to capture all the HtmlWebpackPlugin's
    // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
    new OfflinePlugin({
      relativePaths: false,
      publicPath: '/',
      appShell: '/',

      // No need to cache .htaccess. See http://mxs.is/googmp,
      // this is applied before any match in `caches` section
      excludes: ['.htaccess'],

      caches: {
        main: [':rest:'],

        // All chunks marked as `additional`, loaded after main section
        // and do not prevent SW to install. Change to `optional` if
        // do not want them to be preloaded at all (cached only when first loaded)
        additional: ['*.chunk.js'],
      },

      // Removes warning for about `additional` section usage
      safeToUseOptionalCaches: true,
      AppCache: false,

      ServiceWorker: {
        events: true,
        publicPath: '/sw.js',
        navigateFallbackURL: '/',
        prefetchRequest: {},
      },
      // Hack
      // This is to skip the warning that OfflinePlugin throws if sw registration is not done
      __tests: {
        ignoreRuntime: true,
      },
    }),

    new CompressionPlugin({
      algorithm: 'gzip',
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8,
    }),

    new WebpackPwaManifest({
      name: 'React Boilerplate',
      short_name: 'React BP',
      description: 'My React Boilerplate-based project!',
      background_color: '#fafafa',
      theme_color: '#b1624d',
      inject: true,
      ios: true,
      icons: [
        {
          src: path.resolve('app/images/icon-512x512.png'),
          sizes: [72, 96, 128, 144, 192, 384, 512],
        },
        {
          src: path.resolve('app/images/icon-512x512.png'),
          sizes: [120, 152, 167, 180],
          ios: true,
        },
      ],
    }),

    new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /en/),

    new HashedModuleIdsPlugin({
      hashFunction: 'sha256',
      hashDigest: 'hex',
      hashDigestLength: 20,
    }),
  ],

  performance: {
    assetFilter: assetFilename =>
      !/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename),
  },
});```


问:
How to make http call to an application running inside a kubernetes pod from outside?
I am trying to write a utility which accepts following parameters -

kubernetes service name

spring boot actuator endpoint name (e.g. /actuator/loggers)

This utility should invoke the endpoint on all the pods of this service.

Currently I am obtaining the name of all the pods through service name and iterating over all of them and meeting the requirement by running -

```<code>`kubectl exec $pod -- curl http:\\localhost:8081\actuator\loggers`
</code>```

Though it works, I am looking for a solution where I don't have to do "exec" on the pod as I am not sure of the permission the user may have who runs this utility. Is there any way to make http call to individual pods?

答:
I would run this utility inside the kubernetes cluster, and expose this utility to the developers that need the data. That way you only have to expose this utility, rather than exposing all the pods to allow http calls. I think it's much simpler this way.

There are different ways to expose a Kubernetes Pod to outside the cluster, but I'd recommend using Ingress, which uses a nginx proxy to route traffic coming from outside to your pod.

Body:
I am trying to write a utility which accepts following parameters -

kubernetes service name

spring boot actuator endpoint name (e.g. /actuator/loggers)

This utility should invoke the endpoint on all the pods of this service.

Currently I am obtaining the name of all the pods through service name and iterating over all of them and meeting the requirement by running -

`kubectl exec $pod -- curl http:\\localhost:8081\actuator\loggers`

Though it works, I am looking for a solution where I don't have to do "exec" on the pod as I am not sure of the permission the user may have who runs this utility. Is there any way to make http call to individual pods?


问:
Does @RequestMapping(produces = "application/json;charset=utf-8") block jsonp requests?
I'm trying to debug a problem on production server where there's a method inside a controller that is annotated by:

```<code>@RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
</code>```

And in javascript an ajax call is made to this endpoint:

```<code>$.ajax({
            type: "GET",
            async: true,
            url: "<%=endpointUrl%>",
            dataType: "jsonp",
            success: function(data){
                console.log("success!");
            },
            error: function(xhr, options, error){
                console.log("fail!");
            }
});
</code>```

But in chrome I get warning for Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json.

I thought jsonp is used to 'bypass' same-origin-policy for get requests? Why is it getting blocked?

EDIT: additional info, these headers are set in the endpoint:

```<code>httpResponse.setHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval'");
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
httpResponse.setHeader("X-XSS-Protection", "1");
</code>```

答: Change jsonp to json as your server is returning content type JSON but not jsonp.</p>

Body:
I'm trying to debug a problem on production server where there's a method inside a controller that is annotated by:

@RequestMapping(value = "/endpoint", method = RequestMethod.GET, produces = "application/json;charset=utf-8")

And in javascript an ajax call is made to this endpoint:

$.ajax({
            type: "GET",
            async: true,
            url: "<%=endpointUrl%>",
            dataType: "jsonp",
            success: function(data){
                console.log("success!");
            },
            error: function(xhr, options, error){
                console.log("fail!");
            }
});

But in chrome I get warning for Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json.

I thought jsonp is used to 'bypass' same-origin-policy for get requests? Why is it getting blocked?

EDIT: additional info, these headers are set in the endpoint:

httpResponse.setHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval'");
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
httpResponse.setHeader("X-XSS-Protection", "1");


问:
Why does remove duplicates now throws an error?
I had a script working about a month ago and nothing has changed since. However, when I run the script now, it throws an error. The function I am trying to use is the Remove Duplicates function.

I've tried changing the function in multiple ways thinking that it may be the order, however, I cannot work out how it has broken since nothing has changed since it last worked.

```<code>ActiveSheet.Range("$A$1:$F$8000").RemoveDuplicates 1, xlYes
</code>```

As stated, the expected result is that it removes all the duplicates at the end since the previous part of the script is removing a wide criteria.

Error message:

Data example and the highlight of what should be removed:

Test example which also failed on me which was a lot smaller:

EDIT

Found the issue now... the data was in a separate table within excel so I just copied it out and pasted it as values in a separate sheet.

答: I've added an edit to the question, however I'll post it here to close the question. The table was imported to excel as an XML and had stayed in that format, hence the function wasn't working properly. To fix it, all I had to do was copy all the data and paste it into a separate sheet as values.</p>

Body:
I had a script working about a month ago and nothing has changed since. However, when I run the script now, it throws an error. The function I am trying to use is the Remove Duplicates function.

I've tried changing the function in multiple ways thinking that it may be the order, however, I cannot work out how it has broken since nothing has changed since it last worked.

ActiveSheet.Range("$A$1:$F$8000").RemoveDuplicates 1, xlYes

As stated, the expected result is that it removes all the duplicates at the end since the previous part of the script is removing a wide criteria.

Error message:

Data example and the highlight of what should be removed:

Test example which also failed on me which was a lot smaller:

EDIT

Found the issue now... the data was in a separate table within excel so I just copied it out and pasted it as values in a separate sheet.


问:
How to reference a common properties file from within an osgi bundle properties file?
At the moment, I have a number of features/bundles that refer to a self named properties file. I want to create a number of common properties files, that are included in the individual bundle properties file.

I know that this doesn't work in core Java, but I'm sure I have read somewhere that you can include properties files in Karaf/OSGi/Blueprint, but now I want to do it, I can't find any reference on any of the sites I've been searching for.

What I can't find anywhere is the syntax for how to do it. Can anyone confirm if this is possible, and if so, what the syntax is to do this? Any pointers to suitable documentation would also be welcome.

Thanks!

答:
Assuming you are using blueprint for your bundle:

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.3.0"
           xmlns:camel="http://camel.apache.org/schema/blueprint"
           xsi:schemaLocation="
             http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
             http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd
             http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.3.0 http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.3.0.xsd
             ">
    <cm:property-placeholder persistent-id="my.shared" update-strategy="reload" >
        <cm:default-properties>
            <cm:property name="SOURCE" value="DB" />
            <cm:property name="ENV" value="test" />
        </cm:default-properties>
    </cm:property-placeholder>
</blueprint>
```

<p>For this, you can have a <code>my.shared.cfg</code> (look at the value of the attribute persistent-id in <code>cm:property-placeholder</code> tag) file in <code>${KARAF_HOME}/etc</code> directory.</p>

<p>my.shared.cfg file will have:</p>

```SOURCE=DB
ENV=test
```

<p>Assuming that you would like to use this value to instantiate a bean using from the blueprint, you can do the following:</p>

<pre class="lang-xml prettyprint-override"><code><bean id="myCustomBean" class="com.example.CustomBeanClass">
    <argument value="${SOURCE}" index="0" />
    <argument value="${ENV}" index="1" />
</bean>
</code>```

You can refer here for the information.

Let me know, if this does not help.

Regards,
Cooshal.

Body:
Assuming you are using blueprint for your bundle:

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.3.0"
           xmlns:camel="http://camel.apache.org/schema/blueprint"
           xsi:schemaLocation="
             http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
             http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd
             http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.3.0 http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.3.0.xsd
             ">
    <cm:property-placeholder persistent-id="my.shared" update-strategy="reload" >
        <cm:default-properties>
            <cm:property name="SOURCE" value="DB" />
            <cm:property name="ENV" value="test" />
        </cm:default-properties>
    </cm:property-placeholder>
</blueprint>

For this, you can have a my.shared.cfg (look at the value of the attribute persistent-id in cm:property-placeholder tag) file in ${KARAF_HOME}/etc directory.

my.shared.cfg file will have:

SOURCE=DB
ENV=test

Assuming that you would like to use this value to instantiate a bean using from the blueprint, you can do the following:

<bean id="myCustomBean" class="com.example.CustomBeanClass">
    <argument value="${SOURCE}" index="0" />
    <argument value="${ENV}" index="1" />
</bean>

You can refer here for the information.

Let me know, if this does not help.

Regards,
Cooshal.


问:
Apexcharts remove old data series before render new series
I'm using apex chart for simple data visualization from json output. My charts based on pure javascript and not Vue or other frameworks.

My json (php) backend create two json outputs fro draw the chart as below

JSON 1

```<code>{
    "x": "2019-05-27 16:18:48",
    "y": "100"
},
{
    "x": "2019-05-27 16:25:09",
    "y": "110"
},
</code>```

JSON 2

```<code>{
        "x": "2019-05-27 16:18:48",
        "y": "60"
    },
    {
        "x": "2019-05-27 16:25:09",
        "y": "65"
    },
</code>```

Based on the above two json outputs I retrieve data and draw my graph using the Category paired values method. below is the code responsible for retrieve data and draw the chart.

function for getting json data

```<code>function data_function(){
            $.ajax({
                type: "Get",
                    url: backend,
                    data:{
                        param: "all_a"
                    },
                    async: true,
                    cache: false,
                    success: function(data) {
                        a_data = data;

                        $.ajax({
                        apex_task: "Get",
                            url: backend,
                            data:{
                                param: "all_b"
                            },
                            async: true,
                            cache: false,
                            success: function(data) {
                                    b_data = data;
                                    chart(a_data,b_data);

                            }
                        });
                    }
            });
}
</code>```

function for draw chart

```<code>function draw_chart(a_data,b_data) {
    var options = {

            chart: {
            height: 400,
            type: 'bar',
            stacked: false
            },
            series: [
            {
                name: 'a',
                data: a_data,
            },

            {
                name: 'b',
                data: b_data,
            }],

            yaxis: [
             {
                axisTicks: {
                show: true,
                },
                axisBorder: {
                show: true,
                color: '#008FFB'
                },
                labels: {
                style: {
                    color: '#008FFB',
                }
                }

                    },
            ]
    }

    var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
    chart.render();
}
</code>```

This works fine until I second time render the chart with new data. when I load the different data without reloading the windows chart happen to be laggy and render multiple times with the old incorrect data. sometimes I have to run the data_fnction multiple times to render the chart properly.

How can I fix this? Do I need to use function like appendchart ? how can I use wiht my data_function

答:
You should call the render() method just once in the beginning (even with empty array it should work), then call the updateSeries() method in ajax call to update data of the chart.

```<code>var options = {
  chart: {
    height: 400,
    type: 'bar',
    stacked: false
  },
  series: [],
  yaxis: [{
    axisTicks: {
      show: true,
    },
    axisBorder: {
      show: true,
      color: '#008FFB'
    },
    labels: {
      style: {
        color: '#008FFB',
      }
    }
  }]
}

var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
</code>```

Your ajax call with updateSeries method of the chart

```<code>function data_function() {
  $.ajax({
    type: "Get",
    url: backend,
    data: {
      param: "all_a"
    },
    async: true,
    cache: false,
    success: function (data) {
      a_data = data;

      $.ajax({
        apex_task: "Get",
        url: backend,
        data: {
          param: "all_b"
        },
        async: true,
        cache: false,
        success: function (data) {
          b_data = data;

          chart.updateSeries([{
            name: 'a',
            data: a_data
          }, {
            name: 'b',
            data: b_data
          }])

        }
      });
    }
  });
}
</code>```

Docs for updateSeries

Body:
I'm using apex chart for simple data visualization from json output. My charts based on pure javascript and not Vue or other frameworks.

My json (php) backend create two json outputs fro draw the chart as below

JSON 1

{
    "x": "2019-05-27 16:18:48",
    "y": "100"
},
{
    "x": "2019-05-27 16:25:09",
    "y": "110"
},

JSON 2

{
        "x": "2019-05-27 16:18:48",
        "y": "60"
    },
    {
        "x": "2019-05-27 16:25:09",
        "y": "65"
    },

Based on the above two json outputs I retrieve data and draw my graph using the Category paired values method. below is the code responsible for retrieve data and draw the chart.

function for getting json data

function data_function(){
            $.ajax({
                type: "Get",
                    url: backend,
                    data:{
                        param: "all_a"
                    },
                    async: true,
                    cache: false,
                    success: function(data) {
                        a_data = data;

                        $.ajax({
                        apex_task: "Get",
                            url: backend,
                            data:{
                                param: "all_b"
                            },
                            async: true,
                            cache: false,
                            success: function(data) {
                                    b_data = data;
                                    chart(a_data,b_data);

                            }
                        });
                    }
            });
}

function for draw chart

function draw_chart(a_data,b_data) {
    var options = {

            chart: {
            height: 400,
            type: 'bar',
            stacked: false
            },
            series: [
            {
                name: 'a',
                data: a_data,
            },

            {
                name: 'b',
                data: b_data,
            }],

            yaxis: [
             {
                axisTicks: {
                show: true,
                },
                axisBorder: {
                show: true,
                color: '#008FFB'
                },
                labels: {
                style: {
                    color: '#008FFB',
                }
                }

                    },
            ]
    }

    var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
    chart.render();
}

This works fine until I second time render the chart with new data. when I load the different data without reloading the windows chart happen to be laggy and render multiple times with the old incorrect data. sometimes I have to run the data_fnction multiple times to render the chart properly.

How can I fix this? Do I need to use function like appendchart ? how can I use wiht my data_function

Body:
You should call the render() method just once in the beginning (even with empty array it should work), then call the updateSeries() method in ajax call to update data of the chart.

var options = {
  chart: {
    height: 400,
    type: 'bar',
    stacked: false
  },
  series: [],
  yaxis: [{
    axisTicks: {
      show: true,
    },
    axisBorder: {
      show: true,
      color: '#008FFB'
    },
    labels: {
      style: {
        color: '#008FFB',
      }
    }
  }]
}

var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();

Your ajax call with updateSeries method of the chart

function data_function() {
  $.ajax({
    type: "Get",
    url: backend,
    data: {
      param: "all_a"
    },
    async: true,
    cache: false,
    success: function (data) {
      a_data = data;

      $.ajax({
        apex_task: "Get",
        url: backend,
        data: {
          param: "all_b"
        },
        async: true,
        cache: false,
        success: function (data) {
          b_data = data;

          chart.updateSeries([{
            name: 'a',
            data: a_data
          }, {
            name: 'b',
            data: b_data
          }])

        }
      });
    }
  });
}

Docs for updateSeries


问:
Can any one explain me how the size get allocated in the following case?
I got confused with the size allocation with my gcc compiler, can any one help me how the size get allocated for the following code.

```<code>struct node
{
 int data;
 struct node *next;
};
</code>```

sizeof(struct node) it gives an output as 16.

```<code>struct node
{
 int data;
};
</code>```

sizeof(struct node) it gives an output as 4.

```<code>struct node
{
struct node *next;
};
</code>```

sizeof(struct node) it gives an output as 8.

```<code>struct node
{
int data;
struct node *next;
}*link;
</code>```

sizeof(link) is always 8, even if i add few more elements to structure.

答:
sizeof(link) will always return 8 bytes because that's the size of a pointer in a 64 bits computer.

If you want the size of the structure you need to do sizeof(struct node) as it will give you the size of the actual struct.

And for a linked list type struct I would recomend you something like this

```<code> typedef struct node Node, *pnode;
    struct node{
       //some vars
       pnode next;
    }
</code>```

Then you'll just need to declare it your main or anywhere you as

```<code>pnode list = NULL;

sizeof(Node) //for memory allocation
</code>```

Body:
I got confused with the size allocation with my gcc compiler, can any one help me how the size get allocated for the following code.

struct node
{
 int data;
 struct node *next;
};

sizeof(struct node) it gives an output as 16.

struct node
{
 int data;
};

sizeof(struct node) it gives an output as 4.

struct node
{
struct node *next;
};

sizeof(struct node) it gives an output as 8.

struct node
{
int data;
struct node *next;
}*link;

sizeof(link) is always 8, even if i add few more elements to structure.

Body:
sizeof(link) will always return 8 bytes because that's the size of a pointer in a 64 bits computer.

If you want the size of the structure you need to do sizeof(struct node) as it will give you the size of the actual struct.

And for a linked list type struct I would recomend you something like this

 typedef struct node Node, *pnode;
    struct node{
       //some vars
       pnode next;
    }

Then you'll just need to declare it your main or anywhere you as

pnode list = NULL;

sizeof(Node) //for memory allocation


问:
Need some help positioning a header and sub heading
heres my code: https://codepen.io/anon/pen/dEqJLr#anon-login
heres what I'm trying to do: https://imgur.com/a/NxvyHAC
basically I want the sub header ("helpthistext") to be above my header and I'm not sure how to achieve this..

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
}

.newtest {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="newtest">
  <span class="sub-head">helpthistext</span>
  <h1 class="main-head">title one & another one</h1>
</div></code>```

答:
Please add the flex direction to the newtest.</p>

```<code>.newtest {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 75%;
      flex-direction: column;
}
</code>```

Body:
heres my code: https://codepen.io/anon/pen/dEqJLr#anon-login
heres what I'm trying to do: https://imgur.com/a/NxvyHAC
basically I want the sub header ("helpthistext") to be above my header and I'm not sure how to achieve this..

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
}

.newtest {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75%;
}

  helpthistext

title one & another one

Body:
Please add the flex direction to the newtest.

.newtest {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 75%;
      flex-direction: column;
}


问:
What element values should i select in order to click the element
Here is the html code snippet:

```<code><div autoid="" buttondecorator="" class="ideas-card _ngcontent-zty-5 collapsed-card" aria-label="Find new keywords" aria-expanded="false" aria-describedby="F7C56A74-5C67-4B02-B3E2-AFD3DFBA318B--0" aria-hidden="false" id="F49F12F8-6C5C-4567-AAD9-6C76A52FD801--0" tabindex="0" role="button" aria-disabled="false"></div>
</code>```

From the above snippet code its is a card element and using selenium python I am trying to click that element.

My code is:

```<code>find_new = browser.find_element_by_xpath("//div[@aria-label='Find new keywords']").click()
</code>```

Is there any other methods to select that element?

The error message I am getting is :

```<code>element not interactable
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.16299 x86_64)
</code>```

答:
You might need to wait for the element to become clickable before clicking on it. Use WebDriverWait and Expected Conditions:

```<code>from selenium.webdriver.support import expected_conditions

find_new = WebDriverWait(driver, 20).until(
 expected_conditions.presence_of_element_located((By.XPATH, "//div[@aria-label='Find new keywords']")).click()
</code>```

Another trick you might try is using JavaScript Executor:

```<code>find_new = browser.find_element_by_xpath("//div[@aria-label='Find new keywords']")
browser.execute_script("arguments[0].click();", find_new)
</code>```

Body:
Here is the html code snippet:

From the above snippet code its is a card element and using selenium python I am trying to click that element.

My code is:

find_new = browser.find_element_by_xpath("//div[@aria-label='Find new keywords']").click()

Is there any other methods to select that element?

The error message I am getting is :

element not interactable
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.16299 x86_64)

Body:
You might need to wait for the element to become clickable before clicking on it. Use WebDriverWait and Expected Conditions:

from selenium.webdriver.support import expected_conditions

find_new = WebDriverWait(driver, 20).until(
 expected_conditions.presence_of_element_located((By.XPATH, "//div[@aria-label='Find new keywords']")).click()

Another trick you might try is using JavaScript Executor:

find_new = browser.find_element_by_xpath("//div[@aria-label='Find new keywords']")
browser.execute_script("arguments[0].click();", find_new)


问:
0.625rem isn't a valid CSS value
I'm compiling my stylesheets with Laravel Mix.

When I add the following variable:

```<code>$font-size-micro: $font-size-base * .625;
</code>```

The $font-base: 1rem so this should render a 10px font-size but I get this error: 0.625rem isn't a valid CSS value.

Anyone with this error?

答:
Just wrap your calculation in parenthesis like:

```<code>$font-size-micro: ($font-size-base * 0.625);
</code>```

Consider the following SCSS;

```<code>.xyz {

  $font-size-base: 1rem;
  $font-size-micro: ($font-size-base * 0.625);

  font-size: $font-size-micro;
}
</code>```

It should produce the CSS as:

```<code>@charset "UTF-8";
.xyz {
  font-size: 0.625rem ;
}
</code>```

Title: 0.625rem isn't a valid CSS value

Body:
I'm compiling my stylesheets with Laravel Mix.

When I add the following variable:

$font-size-micro: $font-size-base * .625;

The $font-base: 1rem so this should render a 10px font-size but I get this error: 0.625rem isn't a valid CSS value.

Anyone with this error?

Body:
Just wrap your calculation in parenthesis like:

$font-size-micro: ($font-size-base * 0.625);

Consider the following SCSS;

.xyz {

  $font-size-base: 1rem;
  $font-size-micro: ($font-size-base * 0.625);

  font-size: $font-size-micro;
}

It should produce the CSS as:

@charset "UTF-8";
.xyz {
  font-size: 0.625rem ;
}


问:
How to detect which scrolling child of NestedScrollView was scrolled?
I have a parent NestedScrollView that contains 2 recycler views. One scrolls horizontally and the other one scrolls vertically. How can I detect which one was scrolled? Below is my xml layout.

I can't extract my recyclerviews from NestedScrollView because this nested scroll view is being used inside a coordinator layout so I must keep my recyclerviews inside the NestedScrollview.

```<code><androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:overScrollMode="never"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollableContent"
        android:paddingTop="24dp"
        android:clipToPadding="false">

        <TextView
            style="@style/GatewayLabel"
            android:id="@+id/privateGatewaysLabel"
            android:text="@string/private_gateways_label"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/privateGatewaysRecycler"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:paddingEnd="20dp"
            android:paddingStart="20dp"
            android:clipToPadding="false"
            android:overScrollMode="never"
            android:layout_marginTop="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/privateGatewaysLabel" />

        <TextView
            android:id="@+id/sharedGatewayLabel"
            style="@style/GatewayLabel"
            android:layout_marginTop="16dp"
            android:text="@string/shared_gateways_label"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/privateGatewaysRecycler" />

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/sharedGatewaysRecycler"
            android:overScrollMode="never"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@id/sharedGatewayLabel" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</code>```

答:
You can check by adding this observer to ur nested scrollview object  then you can act upon

scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                Rect scrollBounds = new Rect();
                scrollView.getHitRect(scrollBounds);
                if (yourViews.getLocalVisibleRect(scrollBounds)) {  //ditect if your views visibilty is in bound or not the

                } else {

                }

            }
        });```
</div>
</div>
</p>

<p>For your Recyclerviews scroll smoothness, you can use</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> YourRecylerview.setNestedScrollingEnabled(false);</code>```

Body:
I have a parent NestedScrollView that contains 2 recycler views. One scrolls horizontally and the other one scrolls vertically. How can I detect which one was scrolled? Below is my xml layout.

I can't extract my recyclerviews from NestedScrollView because this nested scroll view is being used inside a coordinator layout so I must keep my recyclerviews inside the NestedScrollview.

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:overScrollMode="never"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollableContent"
        android:paddingTop="24dp"
        android:clipToPadding="false">

        <TextView
            style="@style/GatewayLabel"
            android:id="@+id/privateGatewaysLabel"
            android:text="@string/private_gateways_label"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/privateGatewaysRecycler"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:paddingEnd="20dp"
            android:paddingStart="20dp"
            android:clipToPadding="false"
            android:overScrollMode="never"
            android:layout_marginTop="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/privateGatewaysLabel" />

        <TextView
            android:id="@+id/sharedGatewayLabel"
            style="@style/GatewayLabel"
            android:layout_marginTop="16dp"
            android:text="@string/shared_gateways_label"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/privateGatewaysRecycler" />

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/sharedGatewaysRecycler"
            android:overScrollMode="never"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@id/sharedGatewayLabel" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>

Body:
You can check by adding this observer to ur nested scrollview object  then you can act upon

scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                Rect scrollBounds = new Rect();
                scrollView.getHitRect(scrollBounds);
                if (yourViews.getLocalVisibleRect(scrollBounds)) {  //ditect if your views visibilty is in bound or not the

                } else {

                }

            }
        });

For your Recyclerviews scroll smoothness, you can use

 YourRecylerview.setNestedScrollingEnabled(false);


问:
Single instance problem of ngx-bootstrap modal
I have developed three different components from ngx-bootstrap modal
1. Modal 2. iFrame modal 3. Alertbox modal

I just pass the template in these component and they render it.

But the problem comes when I use any two in single template. Which share same instance. So when I hide one modal, then other modal Output hidden also triggers.

I think this is due to the same BsModalService service utilization.
So any solution for this?

```<code><app-new-modal (hidden)="onModalHidden()">
<div heading>Heading</div>
</app-new-modal>
<app-iframe-modal #iframe (hidden)="onIframeHidden()">
<div heading>Heading</div>
</app-iframe-modal>
</code>```

答:
Try instantiating a service respective to that particular component. Since you are subscribing to the modal close and emitting the event, this seems to call on all scenarios irrespective of that particular component. Hope this helps :)</p>

```<code>@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css'],
  providers: [BsModalService]
})

---------------------------------------------------------

@Component({
  selector: 'app-alertbox',
  templateUrl: './alertbox.component.html',
  styleUrls: ['./alertbox.component.css'],
  providers: [BsModalService]
})
</code>```

Body:
I have developed three different components from ngx-bootstrap modal
1. Modal 2. iFrame modal 3. Alertbox modal

I just pass the template in these component and they render it.

But the problem comes when I use any two in single template. Which share same instance. So when I hide one modal, then other modal Output hidden also triggers.

I think this is due to the same BsModalService service utilization.
So any solution for this?

<app-new-modal (hidden)="onModalHidden()">

Heading

</app-new-modal>
<app-iframe-modal #iframe (hidden)="onIframeHidden()">

Heading

</app-iframe-modal>

Body:
Try instantiating a service respective to that particular component. Since you are subscribing to the modal close and emitting the event, this seems to call on all scenarios irrespective of that particular component. Hope this helps :)

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css'],
  providers: [BsModalService]
})

---------------------------------------------------------

@Component({
  selector: 'app-alertbox',
  templateUrl: './alertbox.component.html',
  styleUrls: ['./alertbox.component.css'],
  providers: [BsModalService]
})


问:
How to prevent android layer drawable shapes (e.g. circle) from scaling
I try to create a simple illustration using XML layer-list drawable.

I have two shapes, a circle and a rectangle

I want a circle not to scale.

The following is the layout:

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

    <ImageView
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/shape5"
        android:layout_gravity="center"
        android:scaleType="center"
        />
</LinearLayout>
</code>```

And this is the shape5.xml drawable

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:top="0dp" android:left="0dp">
        <shape android:shape="rectangle" android:scaleType="center">
            <stroke android:width="2dp" android:color="@android:color/holo_red_light" />
            <size android:width="200dp" android:height="100dp"/>
        </shape>
    </item>

    <item android:top="10dp" android:left="10dp">
        <shape android:shape="oval" android:gravity="center" android:scaleType="center" >
            <stroke android:width="2dp" android:color="@android:color/holo_blue_light" />
            <corners android:radius="10dp" />
            <size android:width="20dp" android:height="20dp"/>

        </shape>
    </item>
</layer-list>
</code>```

The resulting drawing looks like this:

it is clear that item android:top does the work, but nothing prevents shape from scaling. size width does not work, android:scaleType="center" does not work either.

I looked quickly at LayerDrawable.java implementation. Seems like behind the scenes an inset is created from item attributes. So I guess by calculating those I can achieve the result, I want. Is that the only way?

Update:

As per this answer, I knew that manipulating item's android:top, android:left etc, I can create a virtual inset that will scale my "shapes" as I want them.
I checked this, and it is correct. So it is a workaround. I however am sorely disappointed with how counter-intuitive it is. I still hope someone can point me to a simple way to disable scaling.

Update:
As per this Google Android documentation page, setting ImageView scaleType should have prevented scaling. Apparently in my case it did not work. Something is missing.

答:
Put your shape drawable into the layer-list and put android:gravity="center" in the item tag. For example, I have several TextViews in LinearLayout and their size is determined by weight, so these views are not perfect squares.

In TextView I define background: android:background="@drawable/button_selector"

Selector is defined as following:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/btn_pressed" />
    <item android:state_pressed="false" android:drawable="@android:color/transparent"/>
</selector>
</code>```

Drawable:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:gravity="center">
    <shape
            android:shape="oval">
        <stroke
                android:width="@dimen/mat2"
                android:color="@color/dodger_blue"/>
        <size
                android:width="@dimen/mat70"
                android:height="@dimen/mat70"/>
    </shape>
</item>
</layer-list>
</code>```

Body:
I try to create a simple illustration using XML layer-list drawable.

I have two shapes, a circle and a rectangle

I want a circle not to scale.

The following is the layout:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

    <ImageView
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/shape5"
        android:layout_gravity="center"
        android:scaleType="center"
        />
</LinearLayout>

And this is the shape5.xml drawable

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:top="0dp" android:left="0dp">
        <shape android:shape="rectangle" android:scaleType="center">
            <stroke android:width="2dp" android:color="@android:color/holo_red_light" />
            <size android:width="200dp" android:height="100dp"/>
        </shape>
    </item>

    <item android:top="10dp" android:left="10dp">
        <shape android:shape="oval" android:gravity="center" android:scaleType="center" >
            <stroke android:width="2dp" android:color="@android:color/holo_blue_light" />
            <corners android:radius="10dp" />
            <size android:width="20dp" android:height="20dp"/>

        </shape>
    </item>
</layer-list>

The resulting drawing looks like this:

it is clear that item android:top does the work, but nothing prevents shape from scaling. size width does not work, android:scaleType="center" does not work either.

I looked quickly at LayerDrawable.java implementation. Seems like behind the scenes an inset is created from item attributes. So I guess by calculating those I can achieve the result, I want. Is that the only way?

Update:

As per this answer, I knew that manipulating item's android:top, android:left etc, I can create a virtual inset that will scale my "shapes" as I want them.
I checked this, and it is correct. So it is a workaround. I however am sorely disappointed with how counter-intuitive it is. I still hope someone can point me to a simple way to disable scaling.

Update:
As per this Google Android documentation page, setting ImageView scaleType should have prevented scaling. Apparently in my case it did not work. Something is missing.

Body:
Put your shape drawable into the layer-list and put android:gravity="center" in the item tag. For example, I have several TextViews in LinearLayout and their size is determined by weight, so these views are not perfect squares.

In TextView I define background: android:background="@drawable/button_selector"

Selector is defined as following:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/btn_pressed" />
    <item android:state_pressed="false" android:drawable="@android:color/transparent"/>
</selector>

Drawable:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:gravity="center">
    <shape
            android:shape="oval">
        <stroke
                android:width="@dimen/mat2"
                android:color="@color/dodger_blue"/>
        <size
                android:width="@dimen/mat70"
                android:height="@dimen/mat70"/>
    </shape>
</item>
</layer-list>