问:
Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:3.0.5
I want to build a web app using spring boot and react js (followed the tutorial here).
In pom.xml I added:

```<code><plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.0.5</version>
    <executions>
        <execution>
            <id>Copy frontend production build to resources</id>
            <phase>package</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <outputDirectory>${basedir}/target/classes</outputDirectory>
                <resources>
                    <resource>
                        <directory>src/main/app/build/</directory>
                        <filtering>true</filtering>
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

When executing mvn clean package, i get the errors below. Maven version is 3.0.5.

Plugin org.apache.maven.plugins:maven-resources-plugin:3.0.5 or one of
  its dependencies could not be resolved: Failed to read artifact
  descriptor for
  org.apache.maven.plugins:maven-resources-plugin:jar:3.0.5: Failure to
  find org.apache.maven.plugins:maven-resources-plugin:pom:3.0.5 in
  http://repo.maven.apache.org/maven2 was cached in the local
  repository, resolution will not be reattempted until the update
  interval of central has elapsed or updates are forced

EDIT:
I have changed the in maven-resources-plugin tag, the maven version to 3.0.2 but now i get errors on:

```<code><plugin>
    <groupId>com.github.eirslett</groupId>
    <artifactId>frontend-maven-plugin</artifactId>
    <version>1.2</version>
    <executions>
        <execution>
            <id>Install Node and Yarn</id>
            <goals>
                <goal>install-node-and-yarn</goal>
            </goals>
        </execution>

        <execution>
            <id>yarn install</id>
            <goals>
                <goal>yarn</goal>
            </goals>
            <configuration>
                <arguments>install</arguments>
            </configuration>
        </execution>

        <execution>
            <id>Frontend production build</id>
            <phase>package</phase>
            <goals>
                <goal>yarn</goal>
            </goals>
            <configuration>
                <arguments>run build</arguments>
            </configuration>
        </execution>
    </executions>
    <configuration>
        <nodeVersion>v7.2.0</nodeVersion>
        <yarnVersion>v0.18.0</yarnVersion>
        <installDirectory>.mvn</installDirectory>
        <workingDirectory>src/main/app</workingDirectory>
    </configuration>
</plugin>
</code>```

ERROR:

[ERROR] Failed to execute goal
  com.github.eirslett:frontend-maven-plugin:1.2:install-node-and-yarn
  (Install Node and Yarn) on project ema: The plugin
  com.github.eirslett:frontend-maven-plugin:1.2 requires Maven version
  3.1.0 -> [Help 1]

答:
I was facing same problem then i change code        1.5.9.RELEASE it is working now perfectlty </p>

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
</code>```

Body:
I want to build a web app using spring boot and react js (followed the tutorial here).
In pom.xml I added:

<plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.0.5</version>
    <executions>
        <execution>
            <id>Copy frontend production build to resources</id>
            <phase>package</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <outputDirectory>${basedir}/target/classes</outputDirectory>
                <resources>
                    <resource>
                        <directory>src/main/app/build/</directory>
                        <filtering>true</filtering>
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>

When executing mvn clean package, i get the errors below. Maven version is 3.0.5.

Plugin org.apache.maven.plugins:maven-resources-plugin:3.0.5 or one of
  its dependencies could not be resolved: Failed to read artifact
  descriptor for
  org.apache.maven.plugins:maven-resources-plugin:jar:3.0.5: Failure to
  find org.apache.maven.plugins:maven-resources-plugin:pom:3.0.5 in
  http://repo.maven.apache.org/maven2 was cached in the local
  repository, resolution will not be reattempted until the update
  interval of central has elapsed or updates are forced

EDIT:
I have changed the in maven-resources-plugin tag, the maven version to 3.0.2 but now i get errors on:

<plugin>
    <groupId>com.github.eirslett</groupId>
    <artifactId>frontend-maven-plugin</artifactId>
    <version>1.2</version>
    <executions>
        <execution>
            <id>Install Node and Yarn</id>
            <goals>
                <goal>install-node-and-yarn</goal>
            </goals>
        </execution>

        <execution>
            <id>yarn install</id>
            <goals>
                <goal>yarn</goal>
            </goals>
            <configuration>
                <arguments>install</arguments>
            </configuration>
        </execution>

        <execution>
            <id>Frontend production build</id>
            <phase>package</phase>
            <goals>
                <goal>yarn</goal>
            </goals>
            <configuration>
                <arguments>run build</arguments>
            </configuration>
        </execution>
    </executions>
    <configuration>
        <nodeVersion>v7.2.0</nodeVersion>
        <yarnVersion>v0.18.0</yarnVersion>
        <installDirectory>.mvn</installDirectory>
        <workingDirectory>src/main/app</workingDirectory>
    </configuration>
</plugin>

ERROR:

[ERROR] Failed to execute goal
  com.github.eirslett:frontend-maven-plugin:1.2:install-node-and-yarn
  (Install Node and Yarn) on project ema: The plugin
  com.github.eirslett:frontend-maven-plugin:1.2 requires Maven version
  3.1.0 -> [Help 1]

Body:
I was facing same problem then i change code        1.5.9.RELEASE it is working now perfectlty

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>


来源: stackexchange

问:
Hide / Disable default menu in Chrome Custom Tab
I have implemented new Chrome Custom Tab in android, I am using the following code to open

```<code>    String url = "http://www.flipkart.com/";
    int color = Color.BLUE;
    CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
    intentBuilder.setToolbarColor(color);
    intentBuilder.setShowTitle(true);
    CustomTabActivityHelper.openCustomTab(
            this, intentBuilder.build(), Uri.parse(url), new  WebviewFallback());
</code>```

I need to secure my URL or not like to show my URL to User, But there is a option Open in Chrome in default menu, By using this link user can open my URL in browser,By how hide the default menu?

答:
Chrome Custom Tab actually uses Chrome app in user's mobile.

start activity in Chrome app by link, If chrome not installed on the user's mobile, it will use a webView as the default.

In fact, Chrome Custom Tabs is designed to display a web page where the user is sure that the programmer of that software does not have a phishing, Like a bank payment.

Therefore, you must show the options in the toolbar to the user.

ContentLicense: CC BY-SA 3.0

Body:
I have implemented new Chrome Custom Tab in android, I am using the following code to open

    String url = "http://www.flipkart.com/";
    int color = Color.BLUE;
    CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
    intentBuilder.setToolbarColor(color);
    intentBuilder.setShowTitle(true);
    CustomTabActivityHelper.openCustomTab(
            this, intentBuilder.build(), Uri.parse(url), new  WebviewFallback());

I need to secure my URL or not like to show my URL to User, But there is a option Open in Chrome in default menu, By using this link user can open my URL in browser,By how hide the default menu?


问:
EC2 instance termination when operating system practises failure
Im currently learning AWS and getting my hands dirty on EC2 instances. Im wondering how i could auto terminate my instance if the operating system faces any problems such as failures. what code do i add onto the "advanced" section when setting up and configuring an instance?</p>

答:
If you have the ec2 instance running with a role that allows the EC2 terminate instance action then you can run the following on the instance itself. It uses the the EC2 instance metadata to find it's own instance id and the AWS CLI to issue the instance terminate.

```<code>aws ec2 terminate-instances --instance-ids $(curl http://169.254.169.254/latest/meta-data/instance-id/)
</code>```

Alternatively if the instance is started with terminate as it's shutdown behaviour then just a "sudo halt" or "shutdown /s now" will work

Body:
If you have the ec2 instance running with a role that allows the EC2 terminate instance action then you can run the following on the instance itself. It uses the the EC2 instance metadata to find it's own instance id and the AWS CLI to issue the instance terminate.

aws ec2 terminate-instances --instance-ids $(curl http://169.254.169.254/latest/meta-data/instance-id/)

Alternatively if the instance is started with terminate as it's shutdown behaviour then just a "sudo halt" or "shutdown /s now" will work


问:
Pandas Python UnicodeDecodeError
I'm just practicing writing codes for data extraction. I used the following code and it worked before. However, I've recently updated pandas and now it doesn't work and gives me an error.

```<code>import pandas as pd
from pandas_datareader import data
data.DataReader(name = ["MSFT", "GOOG", "AAPL", "YHOO", "AMZN"], data_source = "google",
               start = "2010-01-01", end = "2016-12-31")`
</code>```

Resulting in the following error:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 46626: invalid start byte'
</code>```

I've tried looking online here and used the .encode('utf-8).strip() at the end of each parameters to see if it works but it's not.

答:
This is a known issue which is not yet fixed.

https://github.com/pydata/pandas-datareader/issues/424

Title: Pandas Python UnicodeDecodeError

Body:
I'm just practicing writing codes for data extraction. I used the following code and it worked before. However, I've recently updated pandas and now it doesn't work and gives me an error.

import pandas as pd
from pandas_datareader import data
data.DataReader(name = ["MSFT", "GOOG", "AAPL", "YHOO", "AMZN"], data_source = "google",
               start = "2010-01-01", end = "2016-12-31")`

Resulting in the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 46626: invalid start byte'

I've tried looking online here and used the .encode('utf-8).strip() at the end of each parameters to see if it works but it's not.


问:
an incredible number of tests fail when I add plugins to a Redmine installation
I installed Redmine version 3.4.2.stable onto Ruby 2.3.3, and hit rake test.

Only 3 tests fail, which is pretty good for the first run of a batch of thousands of tests on a new installation.

Then I add a bunch of plugins. Let's just say they are:

```<code>google_analytics_plugin        1.0.0
progressive_projects_list      1.0.0
redmine_agile                  1.4.5
redmine_agreement              0.1.1
redmine_base_deface            0.0.1
redmine_cms                    1.0.1
redmine_contacts               4.1.1
</code>```

Now a lot more tests fail. 215 failures and 1530 errors out of 4225 test cases, to be exact. I'm going to assume that rake test calls rake redmine:plugins:test, but this is still an incredible number of failures.

As an example, one of the errors is:

```<code>MemberTest#test_validate_member_role:
ActiveRecord::StatementInvalid: Mysql2::Error: Incorrect string value: '\xD0\xAD\xD1\x82\xD0\xB8...' for column 'title' at row 1: INSERT INTO `wiki_pages` (`created_on`, `title`, `id`, `wiki_id`, `protected`, `parent_id`) VALUES ('2007-03-07 15:18:07', 'Этика_менеджмента', 10, 1, 0, NULL)
</code>```

It seems someone has switched the language to Russian and not switched it back.

Now my actual question: Does everyone in Redmine-land accept this level of test fragility? I certainly can't be expected to fix every test, submit patches to their maintainers, and then level up my client to use the latest versions of these plugins.

How am I supposed to do TDD with Redmine?

答:
The Redmine project itself maintains its core tests which assumes that its functional integrity is in place, i.e. that there are no plugins present which change functionality. As such, a plain Redmine without any plugins is expected to pass all core tests.

Once you introduce plugins however, things change. Since many plugins hook into or change a lot of internal Redmine functionality (often via monkey patches) in order to provide their functionality, installing them results in various tests of the core Redmine breaking as their assumptions no longer hold true. Since Remdine has only few internal APIs for plugins to hook into, monkey-patches are often the only way for plugins to hook into the core.

Unfortunately though, it is hard (if not impossible) to monkey-patch the core-tests along with the functionality of the plugins to adapt them to the new/changed behavior.

This leads to the current unfortunate situation that almost all Redmine plugins are barely (if at all) tested. Sometimes, you'll have unit tests of the plugin's functionality, but fully-functional integration tests are very rare. When using plugins, you thus can't generally rely on working tests but have to revert to code reviews and manual click-through tests.

I found that when reviewing plugins, the ones that work best have only few monkey patches, try to restrict themselves to stable interfaces or provides hooks where possible, and avoid overriding core functionality of Redmine.

Body:
I installed Redmine version 3.4.2.stable onto Ruby 2.3.3, and hit rake test.

Only 3 tests fail, which is pretty good for the first run of a batch of thousands of tests on a new installation.

Then I add a bunch of plugins. Let's just say they are:

google_analytics_plugin        1.0.0
progressive_projects_list      1.0.0
redmine_agile                  1.4.5
redmine_agreement              0.1.1
redmine_base_deface            0.0.1
redmine_cms                    1.0.1
redmine_contacts               4.1.1

Now a lot more tests fail. 215 failures and 1530 errors out of 4225 test cases, to be exact. I'm going to assume that rake test calls rake redmine:plugins:test, but this is still an incredible number of failures.

As an example, one of the errors is:

MemberTest#test_validate_member_role:
ActiveRecord::StatementInvalid: Mysql2::Error: Incorrect string value: '\xD0\xAD\xD1\x82\xD0\xB8...' for column 'title' at row 1: INSERT INTO `wiki_pages` (`created_on`, `title`, `id`, `wiki_id`, `protected`, `parent_id`) VALUES ('2007-03-07 15:18:07', 'Этика_менеджмента', 10, 1, 0, NULL)

It seems someone has switched the language to Russian and not switched it back.

Now my actual question: Does everyone in Redmine-land accept this level of test fragility? I certainly can't be expected to fix every test, submit patches to their maintainers, and then level up my client to use the latest versions of these plugins.

How am I supposed to do TDD with Redmine?


问:
How to set last recorded value to spinner dropdown?
```<code>String Food;
String[] FoodArray;
Spinner spinFood;
spinFood= (Spinner) findViewById(R.id.spin_food);
FoodArray=getResources().getStringArray(R.array.carray);
spinFood.setAdapter(new
CustomSpinnerAdapter(ChildActivity.this,R.layout.activity_child,FoodArray));

spinFood.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int
        position, long id) {

            if(position==1){
                Food=getString(R.string.textYes);
            }
            else if (position==2){
                Food=getString(R.string.textNo);
            }
            else {
               Food="0";
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
</code>```

i tried a lot  but didn't get the answer,
 please help me.

the spinner should be set to a last recorded value which comes from the database, by default.

答:
```<code> String compareValue;
                ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.array, android.R.layout.simple_spinner_item);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinFood.setAdapter(new CustomSpinnerAdapter(
                        getApplicationContext().this, R.layout.yourlayout,
                        compareValue));
                if (!compareValue.equals(null)) {
                    int spinnerPosition = adapter.getPosition(compareValue);
                    spinFood.setSelection(spinnerPosition);
                }
</code>```

take your last recorded value i.e compareValue from sqlite database and set that value to ArrayAdapter and check for the null condition.

ContentLicense: CC BY-SA 4.0

Body:
String Food;
String[] FoodArray;
Spinner spinFood;
spinFood= (Spinner) findViewById(R.id.spin_food);
FoodArray=getResources().getStringArray(R.array.carray);
spinFood.setAdapter(new
CustomSpinnerAdapter(ChildActivity.this,R.layout.activity_child,FoodArray));

spinFood.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int
        position, long id) {

            if(position==1){
                Food=getString(R.string.textYes);
            }
            else if (position==2){
                Food=getString(R.string.textNo);
            }
            else {
               Food="0";
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

i tried a lot  but didn't get the answer,
 please help me.

the spinner should be set to a last recorded value which comes from the database, by default.

Body:
 String compareValue;
                ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.array, android.R.layout.simple_spinner_item);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinFood.setAdapter(new CustomSpinnerAdapter(
                        getApplicationContext().this, R.layout.yourlayout,
                        compareValue));
                if (!compareValue.equals(null)) {
                    int spinnerPosition = adapter.getPosition(compareValue);
                    spinFood.setSelection(spinnerPosition);
                }

take your last recorded value i.e compareValue from sqlite database and set that value to ArrayAdapter and check for the null condition.


问:
Flask TypeError 'is not JSON serializable' - nested dictionary
i am using Flask as framework for my server, and while returning a response i get the following error:

```<code>> Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Python27\lib\site-packages\flask_restful\__init__.py", line 480, in wrapper
    resp = resource(*args, **kwargs)
  File "C:\Python27\lib\site-packages\flask\views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "C:\Python27\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request
    resp = meth(*args, **kwargs)
  File "rest.py", line 27, in get
    return jsonify(**solution)
  File "C:\Python27\lib\site-packages\flask\json.py", line 263, in jsonify
    (dumps(data, indent=indent, separators=separators), '\n'),
  File "C:\Python27\lib\site-packages\flask\json.py", line 123, in dumps
    rv = _json.dumps(obj, **kwargs)
  File "C:\Python27\lib\json\__init__.py", line 251, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 209, in encode
    chunks = list(chunks)
  File "C:\Python27\lib\json\encoder.py", line 434, in _iterencode
    for chunk in _iterencode_dict(o, _current_indent_level):
  File "C:\Python27\lib\json\encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 442, in _iterencode
    o = _default(o)
  File "C:\Python27\lib\site-packages\flask\json.py", line 80, in default
    return _json.JSONEncoder.default(self, o)
  File "C:\Python27\lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: {'origin': u'porto', 'dest': u'lisboa', 'price': '31', 'date': '2017-12-23', 'url': u'https://www.google.pt/flights/#search;f=opo;t=lis;d=2017-12-23;r=2017-12-24'} is not JSON serializable
</code>```

i have the following function:

```<code>from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_cors import CORS, cross_origin
from json import dumps
import flights
import solveProblem

app = Flask(__name__)
api = Api(app)
CORS(app)

class Flights(Resource):
    def get(self, data):
        print 'received data from client: ' + data
        solution = solveProblem.solve(data)
        print 'got the solution from the script! \nSOLUTION: \n'
        print solution
        return jsonify(solution)

api.add_resource(Flights, '/flights/<string:data>')

if __name__ == '__main__':
    app.run()
</code>```

while debugging the problem, i found the following solutions which did not work:

1) return solution instead of {'solution': solution}

2) do jsonify(solution)

3) do jsonify(**solution)

none of the above worked for me;
i wonder why this happens, when i am trying to return a valid dictionary:

```<code>{'flights': [[{'origin': u'porto', 'dest': u'lisboa', 'price': '31', 'date': '2017-12-23', 'url': u'https://www.google.pt/flights/#search;f=opo;t=lis;d=2017-12-23;r=2017-12-24'}]], 'cost': '31'}
</code>```

any help is appreciated.
Thanks

答:
I had the same problem with a 3 level Nested Dictionary; it was valid, json serializable and via command line json.dumps had no issue. However, Flask did not want to output it: "TypeError", not json serializable. The only difference is that I am using Python 3.5.

So I made a copy of it as a string (that on command line was json serializable!) and passed to Flask output, it worked.

Try to pass the nested json as

eval(str(solution))

and see the error. It's not a definitive solution but more a workaround.

Hope it helps.

Body:
i am using Flask as framework for my server, and while returning a response i get the following error:

> Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Python27\lib\site-packages\flask_restful\__init__.py", line 480, in wrapper
    resp = resource(*args, **kwargs)
  File "C:\Python27\lib\site-packages\flask\views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "C:\Python27\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request
    resp = meth(*args, **kwargs)
  File "rest.py", line 27, in get
    return jsonify(**solution)
  File "C:\Python27\lib\site-packages\flask\json.py", line 263, in jsonify
    (dumps(data, indent=indent, separators=separators), '\n'),
  File "C:\Python27\lib\site-packages\flask\json.py", line 123, in dumps
    rv = _json.dumps(obj, **kwargs)
  File "C:\Python27\lib\json\__init__.py", line 251, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 209, in encode
    chunks = list(chunks)
  File "C:\Python27\lib\json\encoder.py", line 434, in _iterencode
    for chunk in _iterencode_dict(o, _current_indent_level):
  File "C:\Python27\lib\json\encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 442, in _iterencode
    o = _default(o)
  File "C:\Python27\lib\site-packages\flask\json.py", line 80, in default
    return _json.JSONEncoder.default(self, o)
  File "C:\Python27\lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: {'origin': u'porto', 'dest': u'lisboa', 'price': '31', 'date': '2017-12-23', 'url': u'https://www.google.pt/flights/#search;f=opo;t=lis;d=2017-12-23;r=2017-12-24'} is not JSON serializable

i have the following function:

from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_cors import CORS, cross_origin
from json import dumps
import flights
import solveProblem

app = Flask(__name__)
api = Api(app)
CORS(app)

class Flights(Resource):
    def get(self, data):
        print 'received data from client: ' + data
        solution = solveProblem.solve(data)
        print 'got the solution from the script! \nSOLUTION: \n'
        print solution
        return jsonify(solution)

api.add_resource(Flights, '/flights/<string:data>')

if __name__ == '__main__':
    app.run()

while debugging the problem, i found the following solutions which did not work:

1) return solution instead of {'solution': solution}

2) do jsonify(solution)

3) do jsonify(**solution)

none of the above worked for me;
i wonder why this happens, when i am trying to return a valid dictionary:

{'flights': [[{'origin': u'porto', 'dest': u'lisboa', 'price': '31', 'date': '2017-12-23', 'url': u'https://www.google.pt/flights/#search;f=opo;t=lis;d=2017-12-23;r=2017-12-24'}]], 'cost': '31'}

any help is appreciated.
Thanks


问:
Android Gradle Plugin 3.0.1 versionNameSuffix overriding with flavors dimensions
I have several flavors with 2 dimensions:

```<code>    flavorDimensions "buildType", "serverType"

    prod {
        dimension "serverType"
        versionNameSuffix "-prod"
    }

    development {
        dimension "buildType"
    }

    googlePlay {
        dimension "buildType"
        versionNameSuffix "-play"
        versionName "1.1"
    }
</code>```

I want googlePlay flavor to override versionNameSuffix of prod flavor but it just appends suffixes to the final version name so I have version name like '1.1-prod-play' but I want it to be like '1.1-play'.

Could someone help me to achieve this?

答:
Solution is to override versionName like this:

```<code>    prod {
        dimension "serverType"
        versionName globalConfig.androidVersionName + "-prod"
    }

    development {
        dimension "buildType"
    }

    googlePlay {
        dimension "buildType"
        versionName globalConfig.androidVersionName
    }
</code>```

Where globalConfig.androidVersionName is defined by me variable with version name.

Body:
I have several flavors with 2 dimensions:

    flavorDimensions "buildType", "serverType"

    prod {
        dimension "serverType"
        versionNameSuffix "-prod"
    }

    development {
        dimension "buildType"
    }

    googlePlay {
        dimension "buildType"
        versionNameSuffix "-play"
        versionName "1.1"
    }

I want googlePlay flavor to override versionNameSuffix of prod flavor but it just appends suffixes to the final version name so I have version name like '1.1-prod-play' but I want it to be like '1.1-play'.

Could someone help me to achieve this?

Body:
Solution is to override versionName like this:

    prod {
        dimension "serverType"
        versionName globalConfig.androidVersionName + "-prod"
    }

    development {
        dimension "buildType"
    }

    googlePlay {
        dimension "buildType"
        versionName globalConfig.androidVersionName
    }

Where globalConfig.androidVersionName is defined by me variable with version name.


问:
Scrollable dropdown menu in element ui framework
How does one implement scrollable dropdown menu using element ui framework? I have many items I need to populate the dropdown with.</p>

答: When using the select-tag, a scrollbar is added automatically when to many elements are inside.</p>


问:
Trigger change event to trigger backbone event
I am prefilling a form (generated from an external script). Using Jquery: $("#first_name_1").val("test");

When submitting the form it says that my input field is empty ..

After some research:

onchange only fires when the user types into the input and then the input loses focus.

I tried every event (everything !): $("#first_name_1").trigger("change"), etc. ..

After some hours I saw that my form is validated with an external script using Backbone.js ... Its minified crap but I now I am here :

```<code>        return n.addHandler([{
        selector: "[contenteditable]",
        updateMethod: "html",
        events: ["input", "change"]
    }, {
        selector: "input",
        events: ["propertychange", "input", "change"],
        update: function (e, t) {
            console.log("88");
            e.val(t);
        },
        getVal: function (e) {
            console.log("99");
            console.log(e);
            return e.val();
        }
</code>```

UPDATE -> Link to the external Backbone.js script

The application is only logging "99" when I type manually some data in the input field. But not when I use Jquery val() function...

So How do I trigger this event in my external backbone file ??

Many thanks for any help ...

PS: I have not any experience in Backbone.js
My application is a Spring Boot App. Frontend: Html, Semantic UI, Jquery, Thymeleaf.

UPDATE

I have answered my own answer ..

答:
Ok I have received some code from externs wich works now:

Instead of

```<code>function preFillForm(){
    var gegevens = {'first_name_1':'test2 ','last_name_2':'test2 ','e-mail_address_3':'test2@test.com '};
    for(var id in gegevens){
            $("#" + id).val(gegevens[id]);
            $("#" + id).trigger("change");
    }
}
</code>```

I needed to do

```<code>function preFillForm(){
    var gegevens = [[${gegevens}]];
    for(var id in gegevens){
        var input = $("#" + id)[0];
        input.value = gegevens[id];
        if ("createEvent" in document) {
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("change", true, true);
            input.dispatchEvent(evt);
        }
        else {
            input.fireEvent("onchange");
        }
    }
}
</code>```

I do not really understand the difference but I'm glad it's working now.

Body:
I am prefilling a form (generated from an external script). Using Jquery: $("#first_name_1").val("test");

When submitting the form it says that my input field is empty ..

After some research:

onchange only fires when the user types into the input and then the input loses focus.

I tried every event (everything !): $("#first_name_1").trigger("change"), etc. ..

After some hours I saw that my form is validated with an external script using Backbone.js ... Its minified crap but I now I am here :

        return n.addHandler([{
        selector: "[contenteditable]",
        updateMethod: "html",
        events: ["input", "change"]
    }, {
        selector: "input",
        events: ["propertychange", "input", "change"],
        update: function (e, t) {
            console.log("88");
            e.val(t);
        },
        getVal: function (e) {
            console.log("99");
            console.log(e);
            return e.val();
        }

UPDATE -> Link to the external Backbone.js script

The application is only logging "99" when I type manually some data in the input field. But not when I use Jquery val() function...

So How do I trigger this event in my external backbone file ??

Many thanks for any help ...

PS: I have not any experience in Backbone.js
My application is a Spring Boot App. Frontend: Html, Semantic UI, Jquery, Thymeleaf.

UPDATE

I have answered my own answer ..

Body:
Ok I have received some code from externs wich works now:

Instead of

function preFillForm(){
    var gegevens = {'first_name_1':'test2 ','last_name_2':'test2 ','e-mail_address_3':'test2@test.com '};
    for(var id in gegevens){
            $("#" + id).val(gegevens[id]);
            $("#" + id).trigger("change");
    }
}

I needed to do

function preFillForm(){
    var gegevens = [[${gegevens}]];
    for(var id in gegevens){
        var input = $("#" + id)[0];
        input.value = gegevens[id];
        if ("createEvent" in document) {
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("change", true, true);
            input.dispatchEvent(evt);
        }
        else {
            input.fireEvent("onchange");
        }
    }
}

I do not really understand the difference but I'm glad it's working now.


问:
2 Where and 1 Group by Condition LINQ C#
I need to fetch the result of the List by using 2 Where Conditions and GroupBy Condition.

The Query which worked to achive part of the solution is

```<code> var errorQuery = AgentOpList.Where(x => x.LastError != "")
                             .GroupBy(x => x.LastError.Substring(0, 30)).ToArray();
</code>```

But now, i should also include another condition in the list, so the condition is
    x.Status != "FINISHED"
So the final query which i tried was

```<code>var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
                            .GroupBy(x => x.LastError.Substring(0, 30)).ToArray();
</code>```

However, it throws me the error

Index and length must refer to a location within the string. Parameter
  name: length

I know the reason for this error. However, i would like to know the solution.

答:
Make sure Substring never receives a string shorter than 30 characters by padding it with trailing spaces:

```<code>var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
   .GroupBy(x => x.LastError.PadRight(30, ' ').Substring(0, 30)).ToArray();
</code>```

(Assuming this is LINQ to objects as SQL's SUBSTRING wouldn't throw an exception).

Body:
I need to fetch the result of the List by using 2 Where Conditions and GroupBy Condition.

The Query which worked to achive part of the solution is

 var errorQuery = AgentOpList.Where(x => x.LastError != "")
                             .GroupBy(x => x.LastError.Substring(0, 30)).ToArray();

But now, i should also include another condition in the list, so the condition is
    x.Status != "FINISHED"
So the final query which i tried was

var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
                            .GroupBy(x => x.LastError.Substring(0, 30)).ToArray();

However, it throws me the error

Index and length must refer to a location within the string. Parameter
  name: length

I know the reason for this error. However, i would like to know the solution.

Body:
Make sure Substring never receives a string shorter than 30 characters by padding it with trailing spaces:

var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
   .GroupBy(x => x.LastError.PadRight(30, ' ').Substring(0, 30)).ToArray();

(Assuming this is LINQ to objects as SQL's SUBSTRING wouldn't throw an exception).


问:
How to implement interactive remote notifications in iOS Objective-c
I am new in Objective-c. I want to create a interactive remote notification which have two action, one is call 'OK' and another is called 'VIEW'. When user receive notification through APNS that time if user click 'OK' the notification have to be dismiss and if user click 'VIEW' that time open a particular page of my app. That's it.

I have go through many web documents and grab some concept of notification payload. But I am not able to implement this step wise. Can any one assist me, how can I implement this functionality. And please anyone don't mark as a duplicate question. Thanks

答:
Note: I have use my own constants here for category like KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID use your at that place

Register for push

```<code>- (void) registerPushNotification {

    UIUserNotificationType  type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge |  UIUserNotificationTypeSound;
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:type categories:[NSSet setWithObjects:[self createActionNotificationsSettingForApproveBID],[self createActionNotificationsSettingForCancelingRequest ], nil]];
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    [[UIApplication sharedApplication] registerForRemoteNotifications];

}

- (UIMutableUserNotificationCategory *) createActionNotificationsSettingForApproveBID {

    UIMutableUserNotificationAction *actionApproveBID = [[UIMutableUserNotificationAction alloc]  init];
    [actionApproveBID setIdentifier:KNotificatoin_IDENTIFER_ACTION_APPROVEBID];
    actionApproveBID.activationMode = UIUserNotificationActivationModeForeground;
    actionApproveBID.title = @"Approve";
    actionApproveBID.authenticationRequired = true;
    [actionApproveBID setDestructive: false];

    UIMutableUserNotificationAction *actionCancelDialog = [[UIMutableUserNotificationAction alloc]  init];
    [actionCancelDialog setIdentifier:KNotificatoin_IDENTIFER_ACTION_DETAILS];
    actionCancelDialog.activationMode = UIUserNotificationActivationModeForeground;
    actionCancelDialog.title = @"Details";
    actionCancelDialog.authenticationRequired = true;
    [actionCancelDialog setDestructive: false];

    UIMutableUserNotificationCategory *cateogoryApproveBID = [[UIMutableUserNotificationCategory alloc] init];
    cateogoryApproveBID.identifier = KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID;
    [cateogoryApproveBID setActions:@[actionApproveBID,actionCancelDialog] forContext:UIUserNotificationActionContextDefault];
    [cateogoryApproveBID setActions:@[actionApproveBID,actionCancelDialog] forContext:UIUserNotificationActionContextMinimal];

    return cateogoryApproveBID;
}

- (UIMutableUserNotificationCategory *) createActionNotificationsSettingForCancelingRequest {

    UIMutableUserNotificationAction *actionGetMoreBids = [[UIMutableUserNotificationAction alloc]  init];
    [actionGetMoreBids setIdentifier:KNotificatoin_IDENTIFER_ACTION_APPROVEBID];
    actionGetMoreBids.activationMode = UIUserNotificationActivationModeForeground;
    actionGetMoreBids.title = @"Get more bids";
    actionGetMoreBids.authenticationRequired = true;
    [actionGetMoreBids setDestructive: false];

    UIMutableUserNotificationAction *actionEditRequest = [[UIMutableUserNotificationAction alloc]  init];
    [actionEditRequest setIdentifier:KNotificatoin_IDENTIFER_ACTION_EDIT_REQUEST];
    actionEditRequest.activationMode = UIUserNotificationActivationModeForeground;
    actionEditRequest.title = @"Edit request";
    actionEditRequest.authenticationRequired = true;
    [actionEditRequest setDestructive: false];

    UIMutableUserNotificationCategory *categoryCancelRequest = [[UIMutableUserNotificationCategory alloc] init];
    categoryCancelRequest.identifier = KNotificatoin_IDENTIFER_ACTION_MORE_BIDS;
    [categoryCancelRequest setActions:@[actionGetMoreBids,actionEditRequest] forContext:UIUserNotificationActionContextDefault];
    [categoryCancelRequest setActions:@[actionGetMoreBids,actionEditRequest] forContext:UIUserNotificationActionContextMinimal];

    return categoryCancelRequest;
}
</code>```

How you will handle actions  ?

```<code>- (void) application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
    NSLog(@" APPLICATION STATUS %ld",(long)[UIApplication sharedApplication].applicationState);

    if ([[[userInfo objectForKey:@"aps"] objectForKey:kCategory] isEqualToString:KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID]){
        if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_APPROVEBID]) {
            NSMutableDictionary *dictData = [NSMutableDictionary dictionaryWithDictionary:userInfo];
            [dictData setObject:@17 forKey:kType];

            if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
                [self saveDictionaryForPushActiveState:dictData];
            } else {
                [self navigatateAsPerPush:dictData allowInActiveState:NO];
            }
        }
        else if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_DETAILS]) {
            NSLog(@"You chose action 2.");
            if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
                [self saveDictionaryForPushActiveState:userInfo];
            } else {
                [self navigatateAsPerPush:userInfo allowInActiveState:NO];
            }
        }
    } else  if ([[[userInfo objectForKey:@"aps"] objectForKey:kCategory] isEqualToString:KNotificatoin_IDENTIFIER_NOTIFICATION_REQUEST]){

        NSMutableDictionary *dictData = [NSMutableDictionary dictionaryWithDictionary:userInfo];

        if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_EDIT_REQUEST]) {
            NSLog(@"You chose action 1.");
            [dictData setObject:@16 forKey:kType];
            if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
                [self saveDictionaryForPushActiveState:dictData];
            } else {
                [self navigatateAsPerPush:dictData allowInActiveState:NO];
            }

        }
        else if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_MORE_BIDS]) {
            NSLog(@"You chose action 2.");
            if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
                [self saveDictionaryForPushActiveState:dictData];
            } else {
                [self navigatateAsPerPush:dictData allowInActiveState:NO];
            }

        }

    }

    if (completionHandler) {
        completionHandler();
    }
}
</code>```

Hope it is helpful to you

Body:
Note: I have use my own constants here for category like KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID use your at that place

Register for push

- (void) registerPushNotification {

    UIUserNotificationType  type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge |  UIUserNotificationTypeSound;
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:type categories:[NSSet setWithObjects:[self createActionNotificationsSettingForApproveBID],[self createActionNotificationsSettingForCancelingRequest ], nil]];
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    [[UIApplication sharedApplication] registerForRemoteNotifications];

}

- (UIMutableUserNotificationCategory *) createActionNotificationsSettingForApproveBID {

    UIMutableUserNotificationAction *actionApproveBID = [[UIMutableUserNotificationAction alloc]  init];
    [actionApproveBID setIdentifier:KNotificatoin_IDENTIFER_ACTION_APPROVEBID];
    actionApproveBID.activationMode = UIUserNotificationActivationModeForeground;
    actionApproveBID.title = @"Approve";
    actionApproveBID.authenticationRequired = true;
    [actionApproveBID setDestructive: false];

    UIMutableUserNotificationAction *actionCancelDialog = [[UIMutableUserNotificationAction alloc]  init];
    [actionCancelDialog setIdentifier:KNotificatoin_IDENTIFER_ACTION_DETAILS];
    actionCancelDialog.activationMode = UIUserNotificationActivationModeForeground;
    actionCancelDialog.title = @"Details";
    actionCancelDialog.authenticationRequired = true;
    [actionCancelDialog setDestructive: false];

    UIMutableUserNotificationCategory *cateogoryApproveBID = [[UIMutableUserNotificationCategory alloc] init];
    cateogoryApproveBID.identifier = KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID;
    [cateogoryApproveBID setActions:@[actionApproveBID,actionCancelDialog] forContext:UIUserNotificationActionContextDefault];
    [cateogoryApproveBID setActions:@[actionApproveBID,actionCancelDialog] forContext:UIUserNotificationActionContextMinimal];

    return cateogoryApproveBID;
}

- (UIMutableUserNotificationCategory *) createActionNotificationsSettingForCancelingRequest {

    UIMutableUserNotificationAction *actionGetMoreBids = [[UIMutableUserNotificationAction alloc]  init];
    [actionGetMoreBids setIdentifier:KNotificatoin_IDENTIFER_ACTION_APPROVEBID];
    actionGetMoreBids.activationMode = UIUserNotificationActivationModeForeground;
    actionGetMoreBids.title = @"Get more bids";
    actionGetMoreBids.authenticationRequired = true;
    [actionGetMoreBids setDestructive: false];

    UIMutableUserNotificationAction *actionEditRequest = [[UIMutableUserNotificationAction alloc]  init];
    [actionEditRequest setIdentifier:KNotificatoin_IDENTIFER_ACTION_EDIT_REQUEST];
    actionEditRequest.activationMode = UIUserNotificationActivationModeForeground;
    actionEditRequest.title = @"Edit request";
    actionEditRequest.authenticationRequired = true;
    [actionEditRequest setDestructive: false];

    UIMutableUserNotificationCategory *categoryCancelRequest = [[UIMutableUserNotificationCategory alloc] init];
    categoryCancelRequest.identifier = KNotificatoin_IDENTIFER_ACTION_MORE_BIDS;
    [categoryCancelRequest setActions:@[actionGetMoreBids,actionEditRequest] forContext:UIUserNotificationActionContextDefault];
    [categoryCancelRequest setActions:@[actionGetMoreBids,actionEditRequest] forContext:UIUserNotificationActionContextMinimal];

    return categoryCancelRequest;
}

How you will handle actions  ?

- (void) application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
    NSLog(@" APPLICATION STATUS %ld",(long)[UIApplication sharedApplication].applicationState);

    if ([[[userInfo objectForKey:@"aps"] objectForKey:kCategory] isEqualToString:KNotificatoin_IDENTIFIER_CATEGORY_NEW_BID]){
        if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_APPROVEBID]) {
            NSMutableDictionary *dictData = [NSMutableDictionary dictionaryWithDictionary:userInfo];
            [dictData setObject:@17 forKey:kType];

            if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
                [self saveDictionaryForPushActiveState:dictData];
            } else {
                [self navigatateAsPerPush:dictData allowInActiveState:NO];
            }
        }
        else if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_DETAILS]) {
            NSLog(@"You chose action 2.");
            if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
                [self saveDictionaryForPushActiveState:userInfo];
            } else {
                [self navigatateAsPerPush:userInfo allowInActiveState:NO];
            }
        }
    } else  if ([[[userInfo objectForKey:@"aps"] objectForKey:kCategory] isEqualToString:KNotificatoin_IDENTIFIER_NOTIFICATION_REQUEST]){

        NSMutableDictionary *dictData = [NSMutableDictionary dictionaryWithDictionary:userInfo];

        if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_EDIT_REQUEST]) {
            NSLog(@"You chose action 1.");
            [dictData setObject:@16 forKey:kType];
            if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
                [self saveDictionaryForPushActiveState:dictData];
            } else {
                [self navigatateAsPerPush:dictData allowInActiveState:NO];
            }

        }
        else if ([identifier isEqualToString:KNotificatoin_IDENTIFER_ACTION_MORE_BIDS]) {
            NSLog(@"You chose action 2.");
            if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive || self.isApplicationIsInActiveState) {
                [self saveDictionaryForPushActiveState:dictData];
            } else {
                [self navigatateAsPerPush:dictData allowInActiveState:NO];
            }

        }

    }

    if (completionHandler) {
        completionHandler();
    }
}

Hope it is helpful to you


问:
iTunes Store operation failed ERROR ITMS-90534 "invalid toolchain" on XCode 9.2
I got some issue while distributing my new build since the new XCode 9.2 update.

Please help me to solve.

答:
Have you checked the following link, if not, check once.

Xcode 9.2 Upload to App Store fails with description length and invalid toolchain errors

And also this I got someone posted following reply other query.

I heard few people faced this too. Apple has just released the Xcode 9.2 update and might not have updated iTunes connect to accept builds from it yet. It might be resolved soon in a couple of hours or days.

So, check with Apple Team regarding this issue instead of waiting for submission till fix this issue by Apple.


问:
Function on ngFor loop is called too many times
I have a checkbox component in a loop that makes a call to the controller to see if it's checked on initial load.  The list that it's looping through is only three items long but the function is being called 24 times.

HTML :

```<code>       <div class="MhSearchForm__Checkboxes">
        <div *ngFor="let propertyStatus of propertyStatuses" class="ml-3">
          <app-mh-check-box [option]="propertyStatus" [checked]="isChecked(propertyStatus)" (action)="statusSelected($event)"></app-mh-check-box>
        </div>
      </div>
</code>```

JS:

```<code>  isChecked(status) {
   console.log(status);
  }
</code>```

答:
You should read about angular life-cycle hooks, It is amazing how angular keeps track of everything like, view initializing, after view init, before view, doCheck etc.

Angular Life Cycle Hooks

Hope that Helps !

Body:
I have a checkbox component in a loop that makes a call to the controller to see if it's checked on initial load.  The list that it's looping through is only three items long but the function is being called 24 times.

HTML :

          <app-mh-check-box [option]="propertyStatus" [checked]="isChecked(propertyStatus)" (action)="statusSelected($event)"></app-mh-check-box>

JS:

  isChecked(status) {
   console.log(status);
  }


问:
How nested FETCH JOIN works on Hibernate using JpaRepository and @Query annotation?
I have the following problem (pseudo-java-code):

Let me a class A,B,C with the following relationships:

```<code>@Entity
@Table(name = "A")
public class A {

  @OneToMany(mappedBy = "a")
  private B b;

}

@Entity
@Table(name = "B")
public class B {

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "a_id")
  private A a;

  @OneToOne(mappedBy = "b", fetch = FetchType.LAZY)
  private C c;

}

@Entity
@Table(name = "C")
public class C {

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "b_id")
  private B b;

}
</code>```

I'm using JpaRepository with @Query annotation and I implemented the following query:

```<code>@Query("SELECT DISTINCT(a) FROM A a "
        + "LEFT JOIN FETCH a.b as b"
        + "WHERE a.id = :id ")
A findById(@Param("id") Integer id);
</code>```

I want retrieve the informations about class A and B, but not C.
Somehow (I don't know why) the query try to retrive also the relation between B and C.
And then, with hibernate, start the lazy invocation for retrieving C.

Naturally, if I fetch also the relation between B and C (adding LEFT JOIN FETCH b.c as c) that's not happen.

My question is, why? Why I'm forced to fetch all nested relations and not only the ones which I need?

thank you.
Carmelo

答:
Nullable @OneToOne relation are always eager fetched as explained in this post
Making a OneToOne-relation lazy

Unconstrained (nullable) one-to-one association is the only one that
  can not be proxied without bytecode instrumentation. The reason for
  this is that owner entity MUST know whether association property
  should contain a proxy object or NULL and it can't determine that by
  looking at its base table's columns due to one-to-one normally being
  mapped via shared PK, so it has to be eagerly fetched anyway making
  proxy pointless.

Body:
I have the following problem (pseudo-java-code):

Let me a class A,B,C with the following relationships:

@Entity
@Table(name = "A")
public class A {

  @OneToMany(mappedBy = "a")
  private B b;

}

@Entity
@Table(name = "B")
public class B {

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "a_id")
  private A a;

  @OneToOne(mappedBy = "b", fetch = FetchType.LAZY)
  private C c;

}

@Entity
@Table(name = "C")
public class C {

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "b_id")
  private B b;

}

I'm using JpaRepository with @Query annotation and I implemented the following query:

@Query("SELECT DISTINCT(a) FROM A a "
        + "LEFT JOIN FETCH a.b as b"
        + "WHERE a.id = :id ")
A findById(@Param("id") Integer id);

I want retrieve the informations about class A and B, but not C.
Somehow (I don't know why) the query try to retrive also the relation between B and C.
And then, with hibernate, start the lazy invocation for retrieving C.

Naturally, if I fetch also the relation between B and C (adding LEFT JOIN FETCH b.c as c) that's not happen.

My question is, why? Why I'm forced to fetch all nested relations and not only the ones which I need?

thank you.
Carmelo


问:
Issue with JavaScript recursive function
I have an object with nested objects. I need to get all the keys and values from all the sub objects into one array.

So I'm trying to do it with a recursive function, but I guess I'm doing something wrong...

The object :

```<code>var jsonobj = {

  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "enterprise": {
    "parameters": {
      "company": "foo",
      "companyID": "12345678912345",
      "address": "adress principale",
     }
   },
  "contacts": [],
   "requirements": []
 }
</code>```

Here is the function :

```<code>  function check(arr){
      var val = '';
      $.each(arr, function(k, v) {
          if (typeof v == "object" && v.length !== 0) {
              val = check(v);
          }
      });

      return val;
 }
</code>```

And this is the function using it :

```<code>function rec_res(obj_res) {
    var foo=[];
    $.each(jsonobj, function(k, v) {
        if (typeof v == "object" && v.length !== 0) {
            g = check(jsonobj); // calling the function
            foo.push(g);
        } else {
            foo.push(v);
        }
    });
    console.log(foo);
};
</code>```

Expected output:

```<code> [foo:{
  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "company": "foo",
  "companyID": "12345678912345",
  "address": "adress principale",
 }]
</code>```

Fiddle

答:
You can create recursive function with Object.keys() and reduce() methods.

var jsonobj = {
  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "enterprise": {
    "parameters": {
      "company": "foo",
      "companyID": "12345678912345",
      "address": "adress principale",
    }
  },
  "contacts": [],
  "requirements": []
}

function rec_res(obj) {
  return Object.keys(obj).reduce((r, e) => {
    if(typeof obj[e] == 'object') Object.assign(r, rec_res(obj[e]))
    else r[e] = obj[e];
    return r;
  }, {})
}

console.log(rec_res(jsonobj))```

Body:
I have an object with nested objects. I need to get all the keys and values from all the sub objects into one array.

So I'm trying to do it with a recursive function, but I guess I'm doing something wrong...

The object :

var jsonobj = {

  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "enterprise": {
    "parameters": {
      "company": "foo",
      "companyID": "12345678912345",
      "address": "adress principale",
     }
   },
  "contacts": [],
   "requirements": []
 }

Here is the function :

  function check(arr){
      var val = '';
      $.each(arr, function(k, v) {
          if (typeof v == "object" && v.length !== 0) {
              val = check(v);
          }
      });

      return val;
 }

And this is the function using it :

function rec_res(obj_res) {
    var foo=[];
    $.each(jsonobj, function(k, v) {
        if (typeof v == "object" && v.length !== 0) {
            g = check(jsonobj); // calling the function
            foo.push(g);
        } else {
            foo.push(v);
        }
    });
    console.log(foo);
};

Expected output:

 [foo:{
  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "company": "foo",
  "companyID": "12345678912345",
  "address": "adress principale",
 }]

Fiddle


问:
Text inside div wont center
Problem Statement : Center alignment not happening

Relevant code:

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="innhold">
  <div id="tekst"> text </div>
</div></code>```

any help would be appreciated.

答:
You can use text-align:center; to center text.

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
  text-align: center;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="innhold">
  <div id="tekst"> text </div>
</div></code>```

Title: Text inside div wont center

Body:
Problem Statement : Center alignment not happening

Relevant code:

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}

 text

any help would be appreciated.

Body:
You can use text-align:center; to center text.

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
  text-align: center;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}

<div id="innhold">
  <div id="tekst"> text </div>
</div>


问:
How to set tomcat springboot project upload file path?

I have a springboot project. Use WAR package, on the remote tomcat server webapps directory. ROOT is the WAR project, which has two folders, WEB-INF and META-INF.As shown below

Now there is a problem, I upload files on the project root directory 'upload-dir' directory (you can see the upload-dir position in the figure below). Not in the WAR package, and not on the remote server. Where should I create this new directory on the remote server?

I use Files.createDirectories to to create folders.

答:
For this you can create a folder path   say /home/upload_dir.

Now upload the files through your app to this folder using absolute path in app. Create a CONTEXT PATH for this upload dir path in server.xml file as shown below.

```<code><Context
  docBase="/home/upload_dir"
  path="/uploads"
  reloadable="true"
/>
</code>```

I assume you are uploading some images to this folder. Now you can show images in your application by using the url Eg: localhost:8080/uploads/imageName

For prodcution you can create HOST with some sub domain in server.xml and access the uploaded file with the specified URL (For eg: img.facebook.com/image)

Body:
For this you can create a folder path   say /home/upload_dir.

Now upload the files through your app to this folder using absolute path in app. Create a CONTEXT PATH for this upload dir path in server.xml file as shown below.

<Context
  docBase="/home/upload_dir"
  path="/uploads"
  reloadable="true"
/>

I assume you are uploading some images to this folder. Now you can show images in your application by using the url Eg: localhost:8080/uploads/imageName

For prodcution you can create HOST with some sub domain in server.xml and access the uploaded file with the specified URL (For eg: img.facebook.com/image)


问:
CS0188 Error in Structure
Take a look at this code.

```<code>public struct Customer
{
    private int _id;
    private string _name;

    public int Id
    {
        get { return this._id; }
        set { this._id = value; }
    }

    public Customer(int Id, string Name)
    {
        this.Id = Id; // Error - CS0188: The 'this' object cannot be used before all of its fields are assigned to.
        this._name = Name;
    }
}
</code>```

`
Why do I get this error on the above line.

Now look at this code.

```<code>public struct Customer
{
    private string _name;
    public int Id { get; set; }

    public Customer(int Id, string Name)
    {
        this.Id = Id; // No error recieved.
        this._name = Name;
    }
}
</code>```

In the above code I implemented Id as an Auto-Implemented property.
This time I don't get any errors. Why?

Just to make it clear following link does not have my answer.

Compilation error. Using properties with struct

答:
Under C# 5, both methods should generate an error. From Automatically Implemented Properties:

This restriction also means that definite assignment of struct types with auto-implemented properties can only be achieved using the standard constructor of the struct, since assigning to the property itself requires the struct to be definitely assigned. This means that user-defined constructors must call the default constructor.

However, C# 6 introduced read-only auto-implemented properties and introduced this language (whilst removing the above language):

a getter-only auto-property can also be assigned to in the body of a constructor of the enclosing class. Such an assignment assigns directly to the readonly backing field of the property.

I suspect that they changed all assignments for Automatically Implemented Properties (not just for readonly) in constructors to assign to the backing field rather than use the accessor. This is known to be "safe" since the accessor doesn't contain any custom code - unlike the situation in your first example where the set accessor could do anything, including leaking the not-definitely-assigned this outside of the current struct.

Title: CS0188 Error in Structure

Body:
Take a look at this code.

public struct Customer
{
    private int _id;
    private string _name;

    public int Id
    {
        get { return this._id; }
        set { this._id = value; }
    }

    public Customer(int Id, string Name)
    {
        this.Id = Id; // Error - CS0188: The 'this' object cannot be used before all of its fields are assigned to.
        this._name = Name;
    }
}

`
Why do I get this error on the above line.

Now look at this code.

public struct Customer
{
    private string _name;
    public int Id { get; set; }

    public Customer(int Id, string Name)
    {
        this.Id = Id; // No error recieved.
        this._name = Name;
    }
}

In the above code I implemented Id as an Auto-Implemented property.
This time I don't get any errors. Why?

Just to make it clear following link does not have my answer.

Compilation error. Using properties with struct


问:
int max = ~0; What does it mean?
int max = ~0;

What does it mean?

答:
The ~ operator is the unary bitwise complement operator which computes the bitwise complement. This means that it reverses all the bits in its argument (0s become 1s and 1s become 0s). Thus,

```<code>int max = ~0;
</code>```

which is setting max to the negation of the 32-bit value 0000 0000 0000 0000 0000 0000 0000 0000 resulting in 1111 1111 1111 1111 1111 1111 1111 1111. As we are storing this result in an Int32, this is the same as -1.

Whether or not it is better to say

```<code>int max = ~0;
</code>```

or

```<code>int max = -1;
</code>```

depends on the context. If the point of max is to have a number all of whose bits are 1 I would choose the former. If the point of max is to compute the maximum of a list of non-negative integers, I would choose the latter (well, I'd prefer int max = Int32.MinValue; and even more so, I'd just prefer int max = list.Max();).

ContentLicense: CC BY-SA 2.5

Title: int max = ~0; What does it mean?

Body:
int max = ~0;

What does it mean?

Body:
The ~ operator is the unary bitwise complement operator which computes the bitwise complement. This means that it reverses all the bits in its argument (0s become 1s and 1s become 0s). Thus,

int max = ~0;

which is setting max to the negation of the 32-bit value 0000 0000 0000 0000 0000 0000 0000 0000 resulting in 1111 1111 1111 1111 1111 1111 1111 1111. As we are storing this result in an Int32, this is the same as -1.

Whether or not it is better to say

int max = ~0;

or

int max = -1;

depends on the context. If the point of max is to have a number all of whose bits are 1 I would choose the former. If the point of max is to compute the maximum of a list of non-negative integers, I would choose the latter (well, I'd prefer int max = Int32.MinValue; and even more so, I'd just prefer int max = list.Max();).


问:
EmberJS - Passing Query Params from Controller to Nested Route
I currently have a form with multiple inputs. These inputs are used to populate query params. On the controller for this route a Submit action registers the query param inputs and uses transitionToRoute to load a nested route displaying information that the query returns.

Here is the relevant part of the controller:

```<code>import Controller from '@ember/controller';

export default Controller.extend({

  queryParams: ['dateFrom', 'dateTo', 'unitNumber', 'customerName'],
  dateFrom: null,
  dateTo: null,
  unitNumber: null,
  customerName: null,

actions: {
    submitQuery() {
      switch (module) {
        case 'Option 1 List':
          this.transitionToRoute('reports.option1', {
            queryParams: {
              dateFrom: this.get('dateFrom'),
              dateTo: this.get('dateTo'),
              unitNumber: this.get('unitNumber'),
             customerName: this.get('customerName'),
          },
      })

          break;
}
</code>```

Here is the route that is nested:

```<code>import Route from '@ember/routing/route';

export default Route.extend({
  queryParams: {
  dateFrom: { as: 'meddateFrom',
refreshModel:true},
  dateTo: { as: 'meddateTo', refreshModel:true},
  unitNumber: { as: 'medunitNumber', refreshModel:true},
  customerName: { as: 'medcustomerName', refreshModel:true},
},

  model(params) {

      return this.get('store').query('option1api', params)

      },

});
</code>```

I must be doing something very wrong here because this produces some awful behaviour. I end up with double the query params in the URL string. I also end up with bad param updating behaviour which affects my ability to re-run the queries when the inputs change.

If I do not include the queryParams object in the nested route the
query does not fire and nothing is produced.

If I do not alias the queryParams in the nested route I receive
errors telling me that I can not have duplicate Key values in
multiple controllers.

I tried to uses paramsFor instead of the above queryParams and could
not produce a result.

I am also unable to press the Submit button again to launch a fresh query. I assume this is because I am attempting to transition to a route that is already loaded.

I considered moving the queryParams from the controller to the parent route (reports.js) but as I understand it, I need the controller to set the queryParams in the first instance.

This question seemed to be very similar but unfortunately there isn't much of an answer available.

Can anyone spot my big mistake or point me in the right direction? The documentation available at the EmberJS guides hasn't helped my current understanding.

答:
I managed to resolve this myself by changing my approach.

Instead of handling the query params on the controller as per my question, I moved them to the parent route with a {refreshModel:true} option.

In the nested route I added the following:

```<code>let dateFrom = this.paramsFor('reports').dateFrom
let dateTo = this.paramsFor('reports').dateTo
let unitNumber = this.paramsFor('reports').unitNumber
let customerName = this.paramsFor('reports').customerName

let hash = {dateFrom, dateTo, unitNumber, customerName}

return this.get('store').query('mymodel', hash)
</code>```

This confirmed that my subroute was able to read the queryparams and I could then use the variables to construct a hash for my model query.

I don't know if the above is best practice but it got me up and running with a live refresh for my subroute.

Body:
I currently have a form with multiple inputs. These inputs are used to populate query params. On the controller for this route a Submit action registers the query param inputs and uses transitionToRoute to load a nested route displaying information that the query returns.

Here is the relevant part of the controller:

import Controller from '@ember/controller';

export default Controller.extend({

  queryParams: ['dateFrom', 'dateTo', 'unitNumber', 'customerName'],
  dateFrom: null,
  dateTo: null,
  unitNumber: null,
  customerName: null,

actions: {
    submitQuery() {
      switch (module) {
        case 'Option 1 List':
          this.transitionToRoute('reports.option1', {
            queryParams: {
              dateFrom: this.get('dateFrom'),
              dateTo: this.get('dateTo'),
              unitNumber: this.get('unitNumber'),
             customerName: this.get('customerName'),
          },
      })

          break;
}

Here is the route that is nested:

import Route from '@ember/routing/route';

export default Route.extend({
  queryParams: {
  dateFrom: { as: 'meddateFrom',
refreshModel:true},
  dateTo: { as: 'meddateTo', refreshModel:true},
  unitNumber: { as: 'medunitNumber', refreshModel:true},
  customerName: { as: 'medcustomerName', refreshModel:true},
},

  model(params) {

      return this.get('store').query('option1api', params)

      },

});

I must be doing something very wrong here because this produces some awful behaviour. I end up with double the query params in the URL string. I also end up with bad param updating behaviour which affects my ability to re-run the queries when the inputs change.

If I do not include the queryParams object in the nested route the
query does not fire and nothing is produced.

If I do not alias the queryParams in the nested route I receive
errors telling me that I can not have duplicate Key values in
multiple controllers.

I tried to uses paramsFor instead of the above queryParams and could
not produce a result.

I am also unable to press the Submit button again to launch a fresh query. I assume this is because I am attempting to transition to a route that is already loaded.

I considered moving the queryParams from the controller to the parent route (reports.js) but as I understand it, I need the controller to set the queryParams in the first instance.

This question seemed to be very similar but unfortunately there isn't much of an answer available.

Can anyone spot my big mistake or point me in the right direction? The documentation available at the EmberJS guides hasn't helped my current understanding.

Body:
I managed to resolve this myself by changing my approach.

Instead of handling the query params on the controller as per my question, I moved them to the parent route with a {refreshModel:true} option.

In the nested route I added the following:

let dateFrom = this.paramsFor('reports').dateFrom
let dateTo = this.paramsFor('reports').dateTo
let unitNumber = this.paramsFor('reports').unitNumber
let customerName = this.paramsFor('reports').customerName

let hash = {dateFrom, dateTo, unitNumber, customerName}

return this.get('store').query('mymodel', hash)

This confirmed that my subroute was able to read the queryparams and I could then use the variables to construct a hash for my model query.

I don't know if the above is best practice but it got me up and running with a live refresh for my subroute.


问:
TCP error code 10060:A connection attemp failed bcos the connection party didnot properly respnod after period of time, or established connection fail
We have a Framework 4.x WCF Service which is in turn hosted in a Windows Service using Net.Tcp Binding. When calling WCF service from client machine run properly. If we turn on Window firewall then it gives error as

```<code>****"Error 10060 - Could not connect to net.tcp://1xx.xxx.xxx.xxx:9098/MyService/.
The connection attemp lasted for a time span of 00:00:21. TCP error code 10060: A connection attemp failed because the connection party didnot properly respnod after a period of time, or established connection failed because connected host has failed to respond 19x.xxx.xxx.xxx:9098."****
</code>```

I open port 9098 with Inbound and Outbound rule on machine where WCF service is hosted. And also open 808 port from client machine. Still we get this error.

答:
Was facing the same problem

Following config saved my day

Now it did not say time out until 5 min

Server Side

```<code><system.serviceModel>
<diagnostics>
  <messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true" />
</diagnostics>
<bindings>
  <netTcpBinding>
    <binding name="meritBasicBinding" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
             closeTimeout="00:05:00" openTimeout="00:05:00" sendTimeout="00:05:00" receiveTimeout="00:05:00">
      <readerQuotas maxDepth="128" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
      <reliableSession ordered="true" inactivityTimeout="00:05:00" enabled="false"/>
      <security mode="Transport">
        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
      </security>
    </binding>
  </netTcpBinding>
</bindings>
<services>
  <service name="Merit.Services.Reporting" behaviorConfiguration="mexBehaviour">
    <endpoint address="Reporting" binding="netTcpBinding" behaviorConfiguration="meritEndPointBehaviour" bindingConfiguration="meritBasicBinding" contract="Merit.Services.IReporting"></endpoint>
    <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"></endpoint>
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp://Localhost:8090/"/>
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="mexBehaviour">
      <serviceMetadata httpGetEnabled="false"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="meritEndPointBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </endpointBehaviors>
</behaviors>
</code>```

Client Side

```<code><system.serviceModel>
<bindings>
  <netTcpBinding>
    <binding name="meritBasicBinding" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" listenBacklog="2147483647"
             closeTimeout="00:05:00" openTimeout="00:05:00" sendTimeout="00:05:00" receiveTimeout="00:05:00">
      <readerQuotas maxDepth="128" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
      <security mode="Transport">
        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
      </security>
    </binding>
  </netTcpBinding>
</bindings>
<client>
  <endpoint address="net.tcp://Localhost:8090/Reporting" binding="netTcpBinding"
    bindingConfiguration="meritBasicBinding" behaviorConfiguration="meritEndPointBehaviour" contract="MeritReportingService.IReporting"
    name="NetTcpBinding_IReporting">
    <identity>
      <servicePrincipalName value="host/SERVER DOMAIN ADDRESS(usually picked automatically)" />
    </identity>
  </endpoint>
</client>
<behaviors>
  <endpointBehaviors>
    <behavior name="meritEndPointBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </endpointBehaviors>
</behaviors>
</code>```

Body:
We have a Framework 4.x WCF Service which is in turn hosted in a Windows Service using Net.Tcp Binding. When calling WCF service from client machine run properly. If we turn on Window firewall then it gives error as

****"Error 10060 - Could not connect to net.tcp://1xx.xxx.xxx.xxx:9098/MyService/.
The connection attemp lasted for a time span of 00:00:21. TCP error code 10060: A connection attemp failed because the connection party didnot properly respnod after a period of time, or established connection failed because connected host has failed to respond 19x.xxx.xxx.xxx:9098."****

I open port 9098 with Inbound and Outbound rule on machine where WCF service is hosted. And also open 808 port from client machine. Still we get this error.

Body:
Was facing the same problem

Following config saved my day

Now it did not say time out until 5 min

Server Side

<system.serviceModel>
<diagnostics>
  <messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true" />
</diagnostics>
<bindings>
  <netTcpBinding>
    <binding name="meritBasicBinding" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
             closeTimeout="00:05:00" openTimeout="00:05:00" sendTimeout="00:05:00" receiveTimeout="00:05:00">
      <readerQuotas maxDepth="128" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
      <reliableSession ordered="true" inactivityTimeout="00:05:00" enabled="false"/>
      <security mode="Transport">
        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
      </security>
    </binding>
  </netTcpBinding>
</bindings>
<services>
  <service name="Merit.Services.Reporting" behaviorConfiguration="mexBehaviour">
    <endpoint address="Reporting" binding="netTcpBinding" behaviorConfiguration="meritEndPointBehaviour" bindingConfiguration="meritBasicBinding" contract="Merit.Services.IReporting"></endpoint>
    <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"></endpoint>
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp://Localhost:8090/"/>
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="mexBehaviour">
      <serviceMetadata httpGetEnabled="false"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="meritEndPointBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </endpointBehaviors>
</behaviors>

Client Side

<system.serviceModel>
<bindings>
  <netTcpBinding>
    <binding name="meritBasicBinding" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" listenBacklog="2147483647"
             closeTimeout="00:05:00" openTimeout="00:05:00" sendTimeout="00:05:00" receiveTimeout="00:05:00">
      <readerQuotas maxDepth="128" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
      <security mode="Transport">
        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
      </security>
    </binding>
  </netTcpBinding>
</bindings>
<client>
  <endpoint address="net.tcp://Localhost:8090/Reporting" binding="netTcpBinding"
    bindingConfiguration="meritBasicBinding" behaviorConfiguration="meritEndPointBehaviour" contract="MeritReportingService.IReporting"
    name="NetTcpBinding_IReporting">
    <identity>
      <servicePrincipalName value="host/SERVER DOMAIN ADDRESS(usually picked automatically)" />
    </identity>
  </endpoint>
</client>
<behaviors>
  <endpointBehaviors>
    <behavior name="meritEndPointBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </endpointBehaviors>
</behaviors>


问:
Center vertically a div in Bootstrap 4
I want to center automatically a div on my paga using bootstrap 3 but I cannot achieve it. I got an image (with a fixed responsive height) and I want the text to be centered (horizontally and verticaly)

I've made a bootly : https://www.bootply.com/4AyZFwlOdE

答:
.vcenter {
   display: inline-block;
   vertical-align: middle;
   float: none;
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}
.image {
    height:500px;
    background:yellow;
  }
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image">
  <div class="container">
      <div class="row">
          <div class="col-xs-6 col-md-8 col-lg-10 vcenter">
            <div style="text-align:center; height:3em;border:1px solid #F00">Small</div>
          </div>
      </div>
    </div>
  </div></code>```

Title: Center vertically a div in Bootstrap 4

Body:
.vcenter {
   display: inline-block;
   vertical-align: middle;
   float: none;
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}
.image {
    height:500px;
    background:yellow;
  }

<div class="image">
  <div class="container">
      <div class="row">
          <div class="col-xs-6 col-md-8 col-lg-10 vcenter">
            <div style="text-align:center; height:3em;border:1px solid #F00">Small</div>
          </div>
      </div>
    </div>
  </div>


问:
I want to push element in to array
I want to get all input field which have value have this format

```<code>"name": [{
  "id": 3,
  "qty": 2
}, {
  "id": 4,
  "qty": 5
}]
</code>```

My script

```<code>$("#qty-"+item.id).keyup(function(){
                            var qty = $("#qty-"+item.id).val();
                            var price = $("#price-"+item.id).val();
                            var ids = $("#ids-"+item.id).val();
                            var total = qty * price;
                            $("#amount-"+item.id).val(total);
                            var obj={};
                            var name = [];
                            obj.id = ids;
                            obj.qty = qty;
                            name.push(obj);
                            console.log(name);
                            /* Sum of Total of all amount */
                                var add = 0;
                                $(".amount").each(function() {
                                    add += Number($(this).val());
                                });
                                console.log(add);
                                $("#aproxTotal").text("Aprox Total is : " + add);
                            /* Sum of Total of all amount */
                        });
</code>```

In console i got only last enter value only in this way

output

```<code>0:
id:"14"
qty:"1"
</code>```

How to get all filed only have value. If i use each function it will show all even empty field also

My HTML given Below

```<code>    <div id="price-calculation-view">
   <div id="price_calculation">
      <div class="col-lg-2 main"><input type="text" value="Newspaper" readonly="" class="form-control"></div>
      <div class="col-lg-2 main"><input type="text" name="price" id="price-3" value="9" readonly="" class="form-control" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-2 main"><input type="text" value="" name="qty" id="qty-3" class="form-control qty" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-2 main"><input type="text" name="amount" id="amount-3" value="" readonly="" class="form-control amount" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-3 main"><input type="text" name="id" id="ids-3" value="3" readonly="" class="form-control"></div>
   </div>
   <div id="price_calculation">
      <div class="col-lg-2 main"><input type="text" value="Cardboards (flattened)" readonly="" class="form-control"></div>
      <div class="col-lg-2 main"><input type="text" name="price" id="price-4" value="5" readonly="" class="form-control" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-2 main"><input type="text" value="" name="qty" id="qty-4" class="form-control qty" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-2 main"><input type="text" name="amount" id="amount-4" value="" readonly="" class="form-control amount" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-3 main"><input type="text" name="id" id="ids-4" value="4" readonly="" class="form-control"></div>
   </div>
   <div id="price_calculation">
      <div class="col-lg-2 main"><input type="text" value="Glass Bottles (Unbroken)" readonly="" class="form-control"></div>
      <div class="col-lg-2 main"><input type="text" name="price" id="price-5" value="0.4" readonly="" class="form-control" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-2 main"><input type="text" value="" name="qty" id="qty-5" class="form-control qty" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-2 main"><input type="text" name="amount" id="amount-5" value="" readonly="" class="form-control amount" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-3 main"><input type="text" name="id" id="ids-5" value="5" readonly="" class="form-control"></div>
   </div>
   <div id="price_calculation">
      <div class="col-lg-2 main"><input type="text" value="Plastic bottles" readonly="" class="form-control"></div>
      <div class="col-lg-2 main"><input type="text" name="price" id="price-6" value="11" readonly="" class="form-control" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-2 main"><input type="text" value="" name="qty" id="qty-6" class="form-control qty" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-2 main"><input type="text" name="amount" id="amount-6" value="" readonly="" class="form-control amount" onkeypress="return isNumber(event)"></div>
      <div class="col-lg-3 main"><input type="text" name="id" id="ids-6" value="6" readonly="" class="form-control"></div>
   </div>

</div>
</code>```

Values are comming from api dynamically How to achieve this ??

答:
The problem is your var holding hash array is not global, so everytime you do var name = [] it resets it.

Put var name = [] outside keyup function.

```<code>var name = [];

$("#qty-"+item.id).keyup(function(){
                        var qty = $("#qty-"+item.id).val();
                        var price = $("#price-"+item.id).val();
                        var ids = $("#ids-"+item.id).val();
                        var total = qty * price;
                        $("#amount-"+item.id).val(total);
                        var obj={};
                        obj.id = ids;
                        obj.qty = qty;
                        name.push(obj);
                        console.log(name);
                        /* Sum of Total of all amount */
                            var add = 0;
                            $(".amount").each(function() {
                                add += Number($(this).val());
                            });
                            console.log(add);
                            $("#aproxTotal").text("Aprox Total is : " + add);
                        /* Sum of Total of all amount */
                    });
</code>```

See the fiddle, you just need to adapt it! https://jsfiddle.net/zqxn5gzf/

Title: I want to push element in to array

Body:
I want to get all input field which have value have this format

"name": [{
  "id": 3,
  "qty": 2
}, {
  "id": 4,
  "qty": 5
}]

My script

$("#qty-"+item.id).keyup(function(){
                            var qty = $("#qty-"+item.id).val();
                            var price = $("#price-"+item.id).val();
                            var ids = $("#ids-"+item.id).val();
                            var total = qty * price;
                            $("#amount-"+item.id).val(total);
                            var obj={};
                            var name = [];
                            obj.id = ids;
                            obj.qty = qty;
                            name.push(obj);
                            console.log(name);
                            /* Sum of Total of all amount */
                                var add = 0;
                                $(".amount").each(function() {
                                    add += Number($(this).val());
                                });
                                console.log(add);
                                $("#aproxTotal").text("Aprox Total is : " + add);
                            /* Sum of Total of all amount */
                        });

In console i got only last enter value only in this way

output

0:
id:"14"
qty:"1"

How to get all filed only have value. If i use each function it will show all even empty field also

My HTML given Below

<input type="text" value="Newspaper" readonly="" class="form-control">

<input type="text" name="price" id="price-3" value="9" readonly="" class="form-control" onkeypress="return isNumber(event)">

<input type="text" value="" name="qty" id="qty-3" class="form-control qty" onkeypress="return isNumber(event)">

<input type="text" name="amount" id="amount-3" value="" readonly="" class="form-control amount" onkeypress="return isNumber(event)">

<input type="text" name="id" id="ids-3" value="3" readonly="" class="form-control">

<input type="text" value="Cardboards (flattened)" readonly="" class="form-control">

<input type="text" name="price" id="price-4" value="5" readonly="" class="form-control" onkeypress="return isNumber(event)">

<input type="text" value="" name="qty" id="qty-4" class="form-control qty" onkeypress="return isNumber(event)">

<input type="text" name="amount" id="amount-4" value="" readonly="" class="form-control amount" onkeypress="return isNumber(event)">

<input type="text" name="id" id="ids-4" value="4" readonly="" class="form-control">

<input type="text" value="Glass Bottles (Unbroken)" readonly="" class="form-control">

<input type="text" name="price" id="price-5" value="0.4" readonly="" class="form-control" onkeypress="return isNumber(event)">

<input type="text" value="" name="qty" id="qty-5" class="form-control qty" onkeypress="return isNumber(event)">

<input type="text" name="amount" id="amount-5" value="" readonly="" class="form-control amount" onkeypress="return isNumber(event)">

<input type="text" name="id" id="ids-5" value="5" readonly="" class="form-control">

<input type="text" value="Plastic bottles" readonly="" class="form-control">

<input type="text" name="price" id="price-6" value="11" readonly="" class="form-control" onkeypress="return isNumber(event)">

<input type="text" value="" name="qty" id="qty-6" class="form-control qty" onkeypress="return isNumber(event)">

<input type="text" name="amount" id="amount-6" value="" readonly="" class="form-control amount" onkeypress="return isNumber(event)">

<input type="text" name="id" id="ids-6" value="6" readonly="" class="form-control">

Values are comming from api dynamically How to achieve this ??

Body:
The problem is your var holding hash array is not global, so everytime you do var name = [] it resets it.

Put var name = [] outside keyup function.

var name = [];

$("#qty-"+item.id).keyup(function(){
                        var qty = $("#qty-"+item.id).val();
                        var price = $("#price-"+item.id).val();
                        var ids = $("#ids-"+item.id).val();
                        var total = qty * price;
                        $("#amount-"+item.id).val(total);
                        var obj={};
                        obj.id = ids;
                        obj.qty = qty;
                        name.push(obj);
                        console.log(name);
                        /* Sum of Total of all amount */
                            var add = 0;
                            $(".amount").each(function() {
                                add += Number($(this).val());
                            });
                            console.log(add);
                            $("#aproxTotal").text("Aprox Total is : " + add);
                        /* Sum of Total of all amount */
                    });

See the fiddle, you just need to adapt it! https://jsfiddle.net/zqxn5gzf/


问:
Dockerized tomcat is not starting
I am new to docker and I have tried following some tutorials and documentation on USING DOCKER TO EFFICIENTLY CREATE MULTIPLE TOMCAT INSTANCES, but am having trouble getting the service to run via the docker run command.

I have a docker file with the following coding below

```<code>FROM ubuntu:precise
MAINTAINER Quinten Krijger < qkrijger [at] gmail {dot} com>

RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list

RUN apt-get update && apt-get -y install python-software-properties

RUN add-apt-repository ppa:webupd8team/java

RUN apt-get update && apt-get -y upgrade

RUN echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections

RUN apt-get -y install oracle-java7-installer && apt-get clean

RUN update-alternatives --display java

RUN echo "JAVA_HOME=/usr/lib/jvm/java-7-oracle" >> /etc/environment
</code>```

When I build using the command

```<code>docker build -t quintenk/jdk7-oracle .
</code>```

it shows the build is successful.

In the another dockerfile, I try to create create other images based on it

I have another docker in a different path with the following commands

```<code>FROM quintenk/jdk7-oracle

MAINTAINER Quinten Krijger "qkrijger@gmail.com"

RUN apt-get -y install tomcat7

RUN echo "JAVA_HOME=/usr/lib/jvm/java-7-oracle" >> /etc/default/tomcat7

EXPOSE 8080

CMD service tomcat7 start && tail -f /var/lib/tomcat7/logs/catalina.out
</code>```

I use the following command to run the docker file

```<code>docker run -d quintenk/tomcat7
</code>```

But it shows as tomcat instance fail

```<code>* Starting Tomcat servlet engine tomcat7

...fail!
</code>```

If I give the command

```<code>docker ps
</code>```

also there is no instance running on my machine

I'm obviously doing something wrong and I'm getting the behaviour on my OSX

答:
I have faced this issue. Finally, I am able to run the tomcat.Follow below steps.

Step-1: open terminal Ctrl+Alt+t

Step-2: then on terminal go inside the running container, type commands

```<code>     sudo docker exec -it containerID /bin/bash
</code>```

Now to check tomcat is running or not, type your container IP address followed by colon(:) 8080 port on the browser. like 172.17.0.2:8080.

Hope it helps!!

Title: Dockerized tomcat is not starting

Body:
I am new to docker and I have tried following some tutorials and documentation on USING DOCKER TO EFFICIENTLY CREATE MULTIPLE TOMCAT INSTANCES, but am having trouble getting the service to run via the docker run command.

I have a docker file with the following coding below

FROM ubuntu:precise
MAINTAINER Quinten Krijger < qkrijger [at] gmail {dot} com>

RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list

RUN apt-get update && apt-get -y install python-software-properties

RUN add-apt-repository ppa:webupd8team/java

RUN apt-get update && apt-get -y upgrade

RUN echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections

RUN apt-get -y install oracle-java7-installer && apt-get clean

RUN update-alternatives --display java

RUN echo "JAVA_HOME=/usr/lib/jvm/java-7-oracle" >> /etc/environment

When I build using the command

docker build -t quintenk/jdk7-oracle .

it shows the build is successful.

In the another dockerfile, I try to create create other images based on it

I have another docker in a different path with the following commands

FROM quintenk/jdk7-oracle

MAINTAINER Quinten Krijger "qkrijger@gmail.com"

RUN apt-get -y install tomcat7

RUN echo "JAVA_HOME=/usr/lib/jvm/java-7-oracle" >> /etc/default/tomcat7

EXPOSE 8080

CMD service tomcat7 start && tail -f /var/lib/tomcat7/logs/catalina.out

I use the following command to run the docker file

docker run -d quintenk/tomcat7

But it shows as tomcat instance fail

* Starting Tomcat servlet engine tomcat7

...fail!

If I give the command

docker ps

also there is no instance running on my machine

I'm obviously doing something wrong and I'm getting the behaviour on my OSX

Body:
I have faced this issue. Finally, I am able to run the tomcat.Follow below steps.

Step-1: open terminal Ctrl+Alt+t

Step-2: then on terminal go inside the running container, type commands

     sudo docker exec -it containerID /bin/bash

Now to check tomcat is running or not, type your container IP address followed by colon(:) 8080 port on the browser. like 172.17.0.2:8080.

Hope it helps!!