问:
hide or show the data based on the dropdown value selected
I am working on angularjs application.
My requirement is to hide or show the data based on the dropdown list value selected. If i choose the option Show from dropdown list, i need to display the tab's data, if user selects 'Hide' from dropdown list, the content inside the tab should not be displayed.Please advice.

One approach i want to follow is ,by default the option should be Show in the dropdown list and the tab data should be available and when user selects hide, the tab content should be hidden or should ot display.
Please advice how to perform the same in angularjs.
Another one i was tring is, right now my select box doesn't show any selected option ,by default i want to make "Show" option selected.Please find the demo here

js code:

```<code>var myApp = angular.module('tabs', [ 'ui.bootstrap']);
myApp.controller('tabsctrl', function ($rootScope,$scope) {
          $rootScope.tabName ='MyTab Name';

    $rootScope.tabValue="tab1Value";
    $scope.applicationData = {};
    $scope.activeModule = "tab1Value";
    $scope.programModules=[{"tabName":"Tab1","tabValue":"tab1Value"},{"tabName":"Tab2","tabValue":"tab2Value"}];
    $scope.loadApplicationData = function(tabVal,tabName){
        $rootScope.tabName =tabName;
        alert("$rootScope.tabName :: "+$rootScope.tabName);
        $rootScope.tabValue=tabVal;
        $scope.activeModule = tabVal;

    };
    $scope.loadApplicationData($scope.activeModule,'Tab1');

});
myApp.controller('chapter',function($scope,$http){
    $scope.modelidchange = function () {
        $scope.id = $scope.selectedValue;

        alert($scope.id)
    }
});
</code>```

答:
You do not need to have two separate controllers, you can easily do this by having a single controller.

just use ng-if as you used to enable the tab based on the scope variable.

```<code> <div ng-if="tabName === 'Tab1'" role="tabpanel" class="tab-pane active" id="tab1">
   <div class="row">
            <div class="col-sm-12">
              <div ng-if="selectedValue ==='show'" class="panel panel-primary">
                <div class="panel-heading">
                  Tab1 data
                </div>This should be shown when user click tab1
              </div>
            </div>
          </div>
   </div>
</code>```

DEMO

var myApp = angular.module('tabs', ['ui.bootstrap']);
myApp.controller('tabsctrl', function($rootScope, $scope) {
  $rootScope.tabName = 'MyTab Name';
  $rootScope.tabValue = "tab1Value";
  $scope.applicationData = {};
  $scope.selectedValue = 'show';
  $scope.activeModule = "tab1Value";
  $scope.programModules = [{
    "tabName": "Tab1",
    "tabValue": "tab1Value"
  }, {
    "tabName": "Tab2",
    "tabValue": "tab2Value"
  }];
  $scope.loadApplicationData = function(tabVal, tabName) {
    $rootScope.tabName = tabName;
    $rootScope.tabValue = tabVal;
    $scope.activeModule = tabVal;

  };
  $scope.loadApplicationData($scope.activeModule, 'Tab1');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js">
</script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<div ng-app="tabs" ng-controller="tabsctrl">

  Select a Option:
  <select ng-model="selectedValue" ng-change="modelidchange()">
    <option value="show">Show</option>
    <option value="hide">Hide</option>
  </select>
  <br>
  <br>

  <div>
    <div class="top-tabs">
      <!-- Nav tabs -->
      <ul class="nav nav-tabs" role="tablist">
        <li role="presentation" class="{{ pg.tabValue == activeModule? 'active':''}}" ng-repeat="pg in programModules">
          {{pg.tabName}}
        </li>
      </ul>

      <div class="tab-content">
        <div ng-if="tabName === 'Tab1'" role="tabpanel" class="tab-pane active" id="tab1">
          <div class="row">
            <div class="col-sm-12">
              <div ng-if="selectedValue ==='show'" class="panel panel-primary">
                <div class="panel-heading">
                  Tab1 data
                </div>This should be shown when user click tab1
              </div>
            </div>
          </div>
        </div>

        <div ng-if="tabName === 'Tab2'" role="tabpanel" class="tab-pane active" id="tab2">
          <div class="row">
            <div class="col-sm-12">
              <div ng-if="selectedValue ==='show'" class="panel panel-primary">
                <div class="panel-heading">
                  Tab2 data
                </div>This should be shown when user click tab2
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
I am working on angularjs application.
My requirement is to hide or show the data based on the dropdown list value selected. If i choose the option Show from dropdown list, i need to display the tab's data, if user selects 'Hide' from dropdown list, the content inside the tab should not be displayed.Please advice.

One approach i want to follow is ,by default the option should be Show in the dropdown list and the tab data should be available and when user selects hide, the tab content should be hidden or should ot display.
Please advice how to perform the same in angularjs.
Another one i was tring is, right now my select box doesn't show any selected option ,by default i want to make "Show" option selected.Please find the demo here

js code:

var myApp = angular.module('tabs', [ 'ui.bootstrap']);
myApp.controller('tabsctrl', function ($rootScope,$scope) {
          $rootScope.tabName ='MyTab Name';

    $rootScope.tabValue="tab1Value";
    $scope.applicationData = {};
    $scope.activeModule = "tab1Value";
    $scope.programModules=[{"tabName":"Tab1","tabValue":"tab1Value"},{"tabName":"Tab2","tabValue":"tab2Value"}];
    $scope.loadApplicationData = function(tabVal,tabName){
        $rootScope.tabName =tabName;
        alert("$rootScope.tabName :: "+$rootScope.tabName);
        $rootScope.tabValue=tabVal;
        $scope.activeModule = tabVal;

    };
    $scope.loadApplicationData($scope.activeModule,'Tab1');

});
myApp.controller('chapter',function($scope,$http){
    $scope.modelidchange = function () {
        $scope.id = $scope.selectedValue;

        alert($scope.id)
    }
});

Body:
You do not need to have two separate controllers, you can easily do this by having a single controller.

just use ng-if as you used to enable the tab based on the scope variable.

 <div ng-if="tabName === 'Tab1'" role="tabpanel" class="tab-pane active" id="tab1">
   <div class="row">
            <div class="col-sm-12">
              <div ng-if="selectedValue ==='show'" class="panel panel-primary">
                <div class="panel-heading">
                  Tab1 data
                </div>This should be shown when user click tab1
              </div>
            </div>
          </div>
   </div>

DEMO

var myApp = angular.module('tabs', ['ui.bootstrap']);
myApp.controller('tabsctrl', function($rootScope, $scope) {
  $rootScope.tabName = 'MyTab Name';
  $rootScope.tabValue = "tab1Value";
  $scope.applicationData = {};
  $scope.selectedValue = 'show';
  $scope.activeModule = "tab1Value";
  $scope.programModules = [{
    "tabName": "Tab1",
    "tabValue": "tab1Value"
  }, {
    "tabName": "Tab2",
    "tabValue": "tab2Value"
  }];
  $scope.loadApplicationData = function(tabVal, tabName) {
    $rootScope.tabName = tabName;
    $rootScope.tabValue = tabVal;
    $scope.activeModule = tabVal;

  };
  $scope.loadApplicationData($scope.activeModule, 'Tab1');
});

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js">
</script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<div ng-app="tabs" ng-controller="tabsctrl">

  Select a Option:
  <select ng-model="selectedValue" ng-change="modelidchange()">
    <option value="show">Show</option>
    <option value="hide">Hide</option>
  </select>
  <br>
  <br>

  <div>
    <div class="top-tabs">
      <!-- Nav tabs -->
      <ul class="nav nav-tabs" role="tablist">
        <li role="presentation" class="{{ pg.tabValue == activeModule? 'active':''}}" ng-repeat="pg in programModules">
          <a href="javascript:void(0)" ng-click="loadApplicationData(pg.tabValue,pg.tabName)">{{pg.tabName}}</a>
        </li>
      </ul>

      <div class="tab-content">
        <div ng-if="tabName === 'Tab1'" role="tabpanel" class="tab-pane active" id="tab1">
          <div class="row">
            <div class="col-sm-12">
              <div ng-if="selectedValue ==='show'" class="panel panel-primary">
                <div class="panel-heading">
                  Tab1 data
                </div>This should be shown when user click tab1
              </div>
            </div>
          </div>
        </div>

        <div ng-if="tabName === 'Tab2'" role="tabpanel" class="tab-pane active" id="tab2">
          <div class="row">
            <div class="col-sm-12">
              <div ng-if="selectedValue ==='show'" class="panel panel-primary">
                <div class="panel-heading">
                  Tab2 data
                </div>This should be shown when user click tab2
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


来源: stackexchange

答:
You can go ahead and create a Factory to share data. That will be the easiest step. A simple factory will look something link this.

```<code>myApp.factory('Fact', function(){
  return { Field: '' };
});
</code>```

You can use this and update the value of Field whenever you change data. Since you are having two controller I will recommend you to avoid the root scope and use service or factory. Have a look at this answer. Will be helpful.

Share data between AngularJS controllers

ContentLicense: CC BY-SA 3.0

Title: hide or show the data based on the dropdown value selected

Body:
You can go ahead and create a Factory to share data. That will be the easiest step. A simple factory will look something link this.

myApp.factory('Fact', function(){
  return { Field: '' };
});

You can use this and update the value of Field whenever you change data. Since you are having two controller I will recommend you to avoid the root scope and use service or factory. Have a look at this answer. Will be helpful.

Share data between AngularJS controllers


问:
Trying to call function based on clicked ID with this
I am using the Unsplash API to find and download photos.

Just as a model, I have this random photo button that finds a photo and downloads it perfectly.
The download works by creating a link element on the AJAX call and then calling that link element on the button ID click event. Here's the code:

```<code>let randomPhoto = API + 'photos/random/?' + client_id;
var link;

$("#newRB").click(function () {
    $.getJSON(randomPhoto, function (response) {
        console.log(response);
        let randomPhoto2 = response.urls.regular;
        // let randomTitle = response.location.title;
        let download = response.links.download + "?force=true";

        document.getElementById('preview').src = randomPhoto2;
        // document.getElementById('randomTitle').innerHTML = randomTitle;

        // Create a link to be clicked by the download button
        link = document.createElement('a');
        link.href = download;
        link.download = 'Download.jpg';   // The file name suggestion for the user.
        document.body.appendChild(link);

    })
});

$("#downloadRB").click(function () {
    link.click();
})
</code>```

Now, I have created this search bar that searches for 10 photos based off a search term. It then displays all 10 photos at once.

I have created a separate button ID for each button clicked. I proved this by console logging the button ID on the click event.

However, I am unable to call the link.click() function based off the button ID clicked. When clicking, it downloads the last photo in the photo array.

How would I call the specific link() call for that specific photo ID?

Here is the code:

```<code>// Search for Photos

$('form').submit(function (e) {
    e.preventDefault();
    // API Calls
    let input = document.getElementById("search").value;
    let $submitButton = $('#submit');
    let searchPhoto = API + 'search/photos?' + client_id + '&page=1&query=' + input;

    // Ajax part
    $.getJSON(searchPhoto, function (response) {

        // Create beginning of Bootstrap card
        let photoHTML = '<div class="col-12 col-sm-12">';

        // Loop over each response photo, putting it into a unique card
        $.each(response.results, function (i, photo) {
            // Card background
            let photoBackground = photo.urls.regular;
            // Download link
            let download = photo.links.download + "?force=true";
            // Create a link to be clicked by the download button
            link = document.createElement('a');
            link.href = download;
            link.download = 'Download.jpg';   // The file name suggestion for the user.
            document.body.appendChild(link);

            // Add each card element
            photoHTML += '<article class="card animated fadeInLeft text-center">';
            photoHTML += '<img class="card-img-top img-responsive preview" src=' + photoBackground + '/>';
            photoHTML += '<div class="card-block">';
            photoHTML += '<h4 class="card-title" id="randomTitle"></h4>';
            photoHTML += '<button type="button" class="btn btn-outline-primary common_class" id="div' + i + '">Download</button>'; // Create unique ID
            photoHTML += '</article>';

        })
        // End Card
        photoHTML += '</div>';
        // Put each card into a div
        $('#testing').html(photoHTML);

        let currently_clicked_id = '';
        let myID = $(document).on('click', '.common_class', function () {
            currently_clicked_id = $(this).attr('id');
        });

        $(myID).click(function () {
            // Call download link
            link.click();
        });
    })
})
</code>```

答:
Try </p>

```<code>let myID = $("#div" + i);

$(myID).click(function() {
    link.click();
}
</code>```

Body:
I am using the Unsplash API to find and download photos.

Just as a model, I have this random photo button that finds a photo and downloads it perfectly.
The download works by creating a link element on the AJAX call and then calling that link element on the button ID click event. Here's the code:

let randomPhoto = API + 'photos/random/?' + client_id;
var link;

$("#newRB").click(function () {
    $.getJSON(randomPhoto, function (response) {
        console.log(response);
        let randomPhoto2 = response.urls.regular;
        // let randomTitle = response.location.title;
        let download = response.links.download + "?force=true";

        document.getElementById('preview').src = randomPhoto2;
        // document.getElementById('randomTitle').innerHTML = randomTitle;

        // Create a link to be clicked by the download button
        link = document.createElement('a');
        link.href = download;
        link.download = 'Download.jpg';   // The file name suggestion for the user.
        document.body.appendChild(link);

    })
});

$("#downloadRB").click(function () {
    link.click();
})

Now, I have created this search bar that searches for 10 photos based off a search term. It then displays all 10 photos at once.

I have created a separate button ID for each button clicked. I proved this by console logging the button ID on the click event.

However, I am unable to call the link.click() function based off the button ID clicked. When clicking, it downloads the last photo in the photo array.

How would I call the specific link() call for that specific photo ID?

Here is the code:

// Search for Photos

$('form').submit(function (e) {
    e.preventDefault();
    // API Calls
    let input = document.getElementById("search").value;
    let $submitButton = $('#submit');
    let searchPhoto = API + 'search/photos?' + client_id + '&page=1&query=' + input;

    // Ajax part
    $.getJSON(searchPhoto, function (response) {

        // Create beginning of Bootstrap card
        let photoHTML = '
';

        // Loop over each response photo, putting it into a unique card
        $.each(response.results, function (i, photo) {
            // Card background
            let photoBackground = photo.urls.regular;
            // Download link
            let download = photo.links.download + "?force=true";
            // Create a link to be clicked by the download button
            link = document.createElement('a');
            link.href = download;
            link.download = 'Download.jpg';   // The file name suggestion for the user.
            document.body.appendChild(link);

            // Add each card element
            photoHTML += '
';
            photoHTML += '';
            photoHTML += '
';
            photoHTML += '

';
            photoHTML += '<button type="button" class="btn btn-outline-primary common_class" id="div' + i + '">Download</button>'; // Create unique ID
            photoHTML += '
';

        })
        // End Card
        photoHTML += '
';
        // Put each card into a div
        $('#testing').html(photoHTML);

        let currently_clicked_id = '';
        let myID = $(document).on('click', '.common_class', function () {
            currently_clicked_id = $(this).attr('id');
        });

        $(myID).click(function () {
            // Call download link
            link.click();
        });
    })
})

Body:
Try

let myID = $("#div" + i);

$(myID).click(function() {
    link.click();
}


问:
Is there any way for Visual Studio Team Services to track email communication on a bug between developer and user?
We are looking at moving to VSTS from Fogbugz/Kiln for item tracking and source control.

The one issue that I don't see parity in VSTS is that today with Fogbugz, our users can email foo@bar.com and it creates a work item in our system.  Then from that point, whoever is working on that bug can reply from within the system and the system sends the email and the correspondence is tracked along with the work item.  If the user replies, because the subject has "Item:1234" it knows to add the new email to the correspondence for Item 1234, not to create a new work item.

In looking online, it seems most people talk about addins that allow for creating a work item from Outlook, which is quite different from having the system manage the back-and-forth with the user, and allow the user to update the item just by replying to an email.

Does anyone know of a way to achieve this, or an addon/extension that would support this functionality in VSTS?

答:
It is not supported for VSTS, also there isn’t add-in or extension support this.

You can create an outlook add-in to capture ItemSend event and Get/Create/Update/Delete a work item by using VSTS Work Items REST API.


问:
what is the actual use of interface in java?

Possible Duplicates:

  Abstract class and Interface class?

  Java: interface / abstract classes / abstract method

In Java, whatever use of interface is fulfilled by abstract class. I know one advantage of interfaces is that if we implement an interface then we can also extend another class. Is there any other use or advantage of interface in Java?

答: Advantages over an abstract class? except the fact you can implement multiple interfaces but extend only one (abstract or not) class, it's the same as an abstract class that all of it's methods are abstract and public</p>

ContentLicense: CC BY-SA 2.5


问:
Webpack configuration file found but no entry configured
Im trying to organize a webpack 2 template for my personal projects with webpack-dev-server and run it with the npm commands, but i'm getting this error:

Configuration file found but no entry configured.

It's weird because the entry is defined and i tested the resolved route, it's fine, so here is my webpack config, the command to run it and the file to configure the loaders:

webpack.config.dev.js

```<code>const path       = require('path');
const fs         = require('fs');
const configs    = require('./dev-wpk-conf');
const HtmlPlugin = require('html-webpack-plugin');
const Dotenv     = require('dotenv-webpack');
const webpack    = require('webpack');
const dirPath    = fs.realpathSync(process.cwd());

const config = {
  entry: {
    bundle: path.resolve(dirPath, '../src/index.js'),
    vendor: configs.vendor
  },
  output: {
    path: path.resolve(dirPath, '../dist'),
    filename: '[name].[hash].js'
  },
  devServer: {
    port: 3030
  },
  module: {
    rules: [
      configs.jsonLoader,
      configs.babelLoader,
      configs.imgLoader,
      configs.sassLoader
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'] }),
    new HtmlPlugin({ template: './src/index.html' }),
    new Dotenv()
  ]
}
</code>```

dev-wpk-conf.js (the loaders):

```<code>const vendor = [
  'react',
  'react-dom',
  'react-redux',
  'react-router',
  'redux',
  'redux-form',
  'redux-thunk',
  'redux-devtools-extension'
];

const jsonLoader = {
  test: /\.json$/,
  loader: 'json-loader'
};

const babelLoader = {
  test: /\.js$/,
  loader: 'babel-loader',
  exclude: /node_modules/,
  options: {
    presets: ['babel-preset-env', 'react']
  }
};

const imgLoader = {
  test: /\.(jpe?g|png|gif|svg)$/,
  use: [
    { loader: 'url-loader', options: { limit: 40000 } },
    'image-webpack-loader'
  ]
};

const sassLoader = {
  test: /\.(scss|sass)$/,
  use: [
    { loader: 'css-loader' },
    { loader: 'sass-loader' }
  ],
  fallback: 'style-loader'
};

module.exports = {
  vendor,
  jsonLoader,
  babelLoader,
  imgLoader,
  sassLoader
};
</code>```

NPM scripts:

```<code>"clean": "rimraf dist",
"serve": "yarn clean && webpack-dev-server --config ./config/webpack.config.dev.js"
</code>```

The folder structure:

```<code>config/
    dev-wpk-conf.js
    prod-wpk-conf.js
    webpack.config.dev.js
    webpack.config.prod.js
node_modules/
    ...
src/
    index.js
    // the app code
package.json
.env
//rc files
</code>```

So, why exactly i'm getting this error? I'm not an expert but the entry is defined and the resolved path (again) is correct.

Any hint?

答:
You have to export your webpack config in webpack.config.dev.js.

Add this line add the end of your config file.

```<code>module.exports = config;
</code>```

Body:
Im trying to organize a webpack 2 template for my personal projects with webpack-dev-server and run it with the npm commands, but i'm getting this error:

Configuration file found but no entry configured.

It's weird because the entry is defined and i tested the resolved route, it's fine, so here is my webpack config, the command to run it and the file to configure the loaders:

webpack.config.dev.js

const path       = require('path');
const fs         = require('fs');
const configs    = require('./dev-wpk-conf');
const HtmlPlugin = require('html-webpack-plugin');
const Dotenv     = require('dotenv-webpack');
const webpack    = require('webpack');
const dirPath    = fs.realpathSync(process.cwd());

const config = {
  entry: {
    bundle: path.resolve(dirPath, '../src/index.js'),
    vendor: configs.vendor
  },
  output: {
    path: path.resolve(dirPath, '../dist'),
    filename: '[name].[hash].js'
  },
  devServer: {
    port: 3030
  },
  module: {
    rules: [
      configs.jsonLoader,
      configs.babelLoader,
      configs.imgLoader,
      configs.sassLoader
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'] }),
    new HtmlPlugin({ template: './src/index.html' }),
    new Dotenv()
  ]
}

dev-wpk-conf.js (the loaders):

const vendor = [
  'react',
  'react-dom',
  'react-redux',
  'react-router',
  'redux',
  'redux-form',
  'redux-thunk',
  'redux-devtools-extension'
];

const jsonLoader = {
  test: /\.json$/,
  loader: 'json-loader'
};

const babelLoader = {
  test: /\.js$/,
  loader: 'babel-loader',
  exclude: /node_modules/,
  options: {
    presets: ['babel-preset-env', 'react']
  }
};

const imgLoader = {
  test: /\.(jpe?g|png|gif|svg)$/,
  use: [
    { loader: 'url-loader', options: { limit: 40000 } },
    'image-webpack-loader'
  ]
};

const sassLoader = {
  test: /\.(scss|sass)$/,
  use: [
    { loader: 'css-loader' },
    { loader: 'sass-loader' }
  ],
  fallback: 'style-loader'
};

module.exports = {
  vendor,
  jsonLoader,
  babelLoader,
  imgLoader,
  sassLoader
};

NPM scripts:

"clean": "rimraf dist",
"serve": "yarn clean && webpack-dev-server --config ./config/webpack.config.dev.js"

The folder structure:

config/
    dev-wpk-conf.js
    prod-wpk-conf.js
    webpack.config.dev.js
    webpack.config.prod.js
node_modules/
    ...
src/
    index.js
    // the app code
package.json
.env
//rc files

So, why exactly i'm getting this error? I'm not an expert but the entry is defined and the resolved path (again) is correct.

Any hint?

Body:
You have to export your webpack config in webpack.config.dev.js.

Add this line add the end of your config file.

module.exports = config;


问:
ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there
I have a situation very much like the one at Error "ImportError: DLL load failed: %1 is not a valid Win32 application", but the answer there isn't working for me.

My Python code says:

```<code>import cv2
</code>```

But that line throws the error shown in the title of this question.

I have OpenCV installed in C:\lib\opencv on this 64-bit machine. I'm using 64-bit Python.

My PYTHONPATH variable: PYTHONPATH=C:\lib\opencv\build\python\2.7. This folder contains cv2.pyd and that's all.

My PATH variable: Path=%OPENCV_DIR%\bin;... This folder contains 39 DLL files such as opencv_core246d.dll.

OPENCV_DIR has this value: OPENCV_DIR=C:\lib\opencv\build\x64\vc11.

The solution at Error "ImportError: DLL load failed: %1 is not a valid Win32 application" says to add "the new opencv binaries path (C:\opencv\build\bin\Release) to the Windows PATH environment variable". But as shown above, I already have the OpenCV binaries folder (C:\lib\opencv\build\x64\vc11\bin) in my PATH. And my OpenCV installation doesn't have any Release folders (except for an empty one under build/java).

What's going wrong? Can I tell Python to verbosely trace the loading process? Exactly what DLL files is it looking for?

I noticed that, according to http://www.dependencywalker.com/, the cv2.pyd in C:\lib\opencv\build\python\2.7 is 32-bit, whereas the machine and the Python I'm running are 64-bit. Could that be the problem? And if so, where can I find a 64-bit version of cv2.pyd?

答:
I faced the same issue when I uninstalled and reinstalled a different version of 2.7.x of Python on my system using a 32-bit Windows Installer. I got the same error on most of my import statements.

I uninstalled the newly installed Python, downloaded a 64-bit Windows installer, reinstalled Python again, and it worked.

ContentLicense: CC BY-SA 4.0

Body:
I have a situation very much like the one at Error "ImportError: DLL load failed: %1 is not a valid Win32 application", but the answer there isn't working for me.

My Python code says:

import cv2

But that line throws the error shown in the title of this question.

I have OpenCV installed in C:\lib\opencv on this 64-bit machine. I'm using 64-bit Python.

My PYTHONPATH variable: PYTHONPATH=C:\lib\opencv\build\python\2.7. This folder contains cv2.pyd and that's all.

My PATH variable: Path=%OPENCV_DIR%\bin;... This folder contains 39 DLL files such as opencv_core246d.dll.

OPENCV_DIR has this value: OPENCV_DIR=C:\lib\opencv\build\x64\vc11.

The solution at Error "ImportError: DLL load failed: %1 is not a valid Win32 application" says to add "the new opencv binaries path (C:\opencv\build\bin\Release) to the Windows PATH environment variable". But as shown above, I already have the OpenCV binaries folder (C:\lib\opencv\build\x64\vc11\bin) in my PATH. And my OpenCV installation doesn't have any Release folders (except for an empty one under build/java).

What's going wrong? Can I tell Python to verbosely trace the loading process? Exactly what DLL files is it looking for?

I noticed that, according to http://www.dependencywalker.com/, the cv2.pyd in C:\lib\opencv\build\python\2.7 is 32-bit, whereas the machine and the Python I'm running are 64-bit. Could that be the problem? And if so, where can I find a 64-bit version of cv2.pyd?


问:
Is there application Scope in spring?
I saw 'application' scope in the following blog. Is it true?

http://www.concretepage.com/spring/spring-bean-scope-example-using-scope-annotation-and-xml-for-singleton-prototype-request-session-global-session-and-application-scope-with-scoped-proxy

Because, as per my surfing, I got to know spring has only the below 5 scopes. Please correct me if I'm wrong.

Singleton

Prototype

Request

Session

Global Session

答:
There is a section on the official doc which is related to the bean scopes:

7.5 Bean scopes

Basically, they define the next:

singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype
  Scopes a single bean definition to any number of object instances.

request
  Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session
  Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

globalSession
  Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a Portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

application
  Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

websocket
  Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

Furthermore, as Spring 3.0 exists other scope  thread scope but is not registered by default, moreover you could even create your own scope:

As of Spring 3.0, a thread scope is available, but is not registered
  by default. For more information, see the documentation for
  SimpleThreadScope. For instructions on how to register this or any
  another custom scope, see the section called “Using a custom scope”.

There is a section which explains how to define your custom scope:

7.5.5 Custom scopes

Respect to Application scope, they define it as next:

The Spring container creates a new instance of the AppPreferences bean
  by using the appPreferences bean definition once for the entire web
  application. That is, the appPreferences bean is scoped at the
  ServletContext level, stored as a regular ServletContext attribute.

It also explains the difference between a Spring singleton bean:

This is somewhat similar to a Spring singleton bean but differs in two
  important ways: It is a singleton per ServletContext, not per Spring
  'ApplicationContext' (for which there may be several in any given web
  application), and it is actually exposed and therefore visible as a
  ServletContext attribute

So in case you are looking to use with XML:

```<code><bean id="apps" class="com.App" scope="application"/>
</code>```

Or annotation:

```<code>@ApplicationScope
@Component
public class App {
    // ...
}
</code>```

Title: Is there application Scope in spring?

Body:
There is a section on the official doc which is related to the bean scopes:

7.5 Bean scopes

Basically, they define the next:

singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype
  Scopes a single bean definition to any number of object instances.

request
  Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session
  Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

globalSession
  Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a Portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

application
  Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

websocket
  Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

Furthermore, as Spring 3.0 exists other scope  thread scope but is not registered by default, moreover you could even create your own scope:

As of Spring 3.0, a thread scope is available, but is not registered
  by default. For more information, see the documentation for
  SimpleThreadScope. For instructions on how to register this or any
  another custom scope, see the section called “Using a custom scope”.

There is a section which explains how to define your custom scope:

7.5.5 Custom scopes

Respect to Application scope, they define it as next:

The Spring container creates a new instance of the AppPreferences bean
  by using the appPreferences bean definition once for the entire web
  application. That is, the appPreferences bean is scoped at the
  ServletContext level, stored as a regular ServletContext attribute.

It also explains the difference between a Spring singleton bean:

This is somewhat similar to a Spring singleton bean but differs in two
  important ways: It is a singleton per ServletContext, not per Spring
  'ApplicationContext' (for which there may be several in any given web
  application), and it is actually exposed and therefore visible as a
  ServletContext attribute

So in case you are looking to use with XML:

<bean id="apps" class="com.App" scope="application"/>

Or annotation:

@ApplicationScope
@Component
public class App {
    // ...
}


问:
Defining routes within exports vs. above it Node.js
I've come across two different methods of defining routes in Node.js:

Method #1:

```<code>router.get("/", (req, res, next) => {
    res.render("index", { title: "ABC" });
});
module.exports = router;
</code>```

Method #2:

```<code>module.exports = (() => {
    router.get("/", (req, res, next) => {
        res.render("index", { title: "ABC" });
    });
    return router;
})();
</code>```

I was curious, what's the main difference between these two? And, is there a major reason why one method is preferred over the other? Thanks!

答: Method #2 is ES6 syntax with arrow function syntax being used. Both perform the same functionality, only difference is the syntax.</p>

Body:
I've come across two different methods of defining routes in Node.js:

Method #1:

router.get("/", (req, res, next) => {
    res.render("index", { title: "ABC" });
});
module.exports = router;

Method #2:

module.exports = (() => {
    router.get("/", (req, res, next) => {
        res.render("index", { title: "ABC" });
    });
    return router;
})();

I was curious, what's the main difference between these two? And, is there a major reason why one method is preferred over the other? Thanks!


问:
Unable to create or switch to new tab in Selenium Webdriver with JAVA on MAC
I've tried a different options just to open new tab but all of them lead to the same result : sending char "t" to google search field.
The goal in my real test is to switch between tabs in browser, but I am unable even open new one.

Very simple test

```<code>    public class LoginPhp2 {

        @Test
        public void testGoogle() {
            WebDriver driver = new SafariDriver();
            driver.get("https://www.google.com");
            //driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");
            Actions action= new Actions(driver);
           action.keyDown(Keys.COMMAND).sendKeys("t").build().perform();
            //action.keyDown(Keys.COMMAND).sendKeys("t").keyUp(Keys.COMMAND).build().perform();

        }
    }
</code>```

答:
You may use javascript to open a new tab.</p>

```<code>JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open();");
</code>```

Body:
I've tried a different options just to open new tab but all of them lead to the same result : sending char "t" to google search field.
The goal in my real test is to switch between tabs in browser, but I am unable even open new one.

Very simple test

    public class LoginPhp2 {

        @Test
        public void testGoogle() {
            WebDriver driver = new SafariDriver();
            driver.get("https://www.google.com");
            //driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");
            Actions action= new Actions(driver);
           action.keyDown(Keys.COMMAND).sendKeys("t").build().perform();
            //action.keyDown(Keys.COMMAND).sendKeys("t").keyUp(Keys.COMMAND).build().perform();

        }
    }

Body:
You may use javascript to open a new tab.

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open();");


问:
Why would this give me a ClassCastException in Java, while it works well in C++?
Something is driving me crazy.

Assume we have these simple classes

```<code>public class Animal {
public void makeSound() {
    System.out.println("From Animal");
  }
}

public class Dog extends Animal {
public void makeSound() {
    System.out.println("From Dog");
}

public void flip() {
    System.out.println("Flipped");
}

public static void main(String[] args) {
  Animal a= new Animal();
  ((Dog)a).makeSound(); // Gives me an error at runtime.

}
</code>```

C++ code:

```<code>class Animal {
   public:
          virtual void makeSound(){ cout<<" From Animal";}
};

class Dog : public Animal {
    public : void makeSound(){ cout<<" From Dog ";}
             void  flip() { cout<<"Flipped";}
};

 main() {
Animal *a = new Animal();
((Dog*)a)->makeSound(); // returns From animal

  }
</code>```

Why would it generate runtime error in Java, while it would work without a problem in C++ ?

Thank you

答:
Downcasting is only possible (in Java) if at some point in your code you reference the child class e.g.</p>

```<code>Animal a = new Dog();
((Dog)a).makeSound();
</code>```

Body:
Something is driving me crazy.

Assume we have these simple classes

public class Animal {
public void makeSound() {
    System.out.println("From Animal");
  }
}

public class Dog extends Animal {
public void makeSound() {
    System.out.println("From Dog");
}

public void flip() {
    System.out.println("Flipped");
}

public static void main(String[] args) {
  Animal a= new Animal();
  ((Dog)a).makeSound(); // Gives me an error at runtime.

}

C++ code:

class Animal {
   public:
          virtual void makeSound(){ cout<<" From Animal";}
};

class Dog : public Animal {
    public : void makeSound(){ cout<<" From Dog ";}
             void  flip() { cout<<"Flipped";}
};

 main() {
Animal *a = new Animal();
((Dog*)a)->makeSound(); // returns From animal

  }

Why would it generate runtime error in Java, while it would work without a problem in C++ ?

Thank you

Body:
Downcasting is only possible (in Java) if at some point in your code you reference the child class e.g.

Animal a = new Dog();
((Dog)a).makeSound();


问:
Text field in same line HTML
How to make multiple text fields in the same line.

This is my code:

```<code><div class="col-lg-2">
    <div class="form-group">
        <label>Working experience</label>
        <input type="text" class="form-control  " placeholder="Year"/>Year
        <input type="text" class="form-control " placeholder="Month"/>Month
        <input type="text" class="form-control  " placeholder="Day" />Day
    </div>
</div>
</code>```

答:
It's by default. input is inline element.

    Working experience
    <input type="text" class="form-control  " placeholder="Year" />Year
    <input type="text" class="form-control " placeholder="Month" />Month
    <input type="text" class="form-control  " placeholder="Day"

Day

```
</div>
</div>
</p>

<p>In bootstrap you can put all of the fields that you want on a single line within a single form-group</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="form-group">
        <label for="birthday" class="col-xs-3 col-sm-2 control-label">Birthday</label>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="year"/>
        </div>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="month"/>
        </div>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="day"/>
        </div>
    </div></code>```

Title: Text field in same line HTML

Body:
How to make multiple text fields in the same line.

This is my code:

        Working experience
        <input type="text" class="form-control  " placeholder="Year"/>Year
        <input type="text" class="form-control " placeholder="Month"/>Month
        <input type="text" class="form-control  " placeholder="Day" />Day

Body:
It's by default. input is inline element.

<div class="col-lg-2">
  <div class="form-group">
    <label>Working experience</label>
    <input type="text" class="form-control  " placeholder="Year" />Year
    <input type="text" class="form-control " placeholder="Month" />Month
    <input type="text" class="form-control  " placeholder="Day"

Day
  </div>
</div>

In bootstrap you can put all of the fields that you want on a single line within a single form-group

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="form-group">
        <label for="birthday" class="col-xs-3 col-sm-2 control-label">Birthday</label>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="year"/>
        </div>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="month"/>
        </div>
        <div class="col-xs-3">
            <input type="text" class="form-control" placeholder="day"/>
        </div>
    </div>


问:
d3 fill under interpolated line
In the following d3 line chart example, I would like to fill in the the area under the lines with fill color equivalent to line color and a transparency of 50%.

In addition to adding area to the CSS

```<code>.area {
  fill: blue;
  opacity: 0.5
}
</code>```

adding the following to function updateGraph(data)

```<code>    svg.append("path")
   .data([data])
   .attr("class", "area")
   .attr("d", area);
</code>```

and

```<code>var area = d3.svg.area()
    .x(function(d) { return x(d.year); })
    .y0(height)
    .y1(function(d) { return y(d.value); });
</code>```

what is needed for the filled in area to fit under the interpolated line and for fill color to be equivalent to line color?

答:
Actually, you have to create a new selection before the lines' selection (named states), here named stateArea:

```<code>var stateArea = svg.selectAll(".area")
    .data(result, function(d) {
        return d.key
    });

stateArea.enter().append("path")
    .attr("class", "area");

stateArea.transition()
    .style("fill", function(d, i) {
        return d.color = color(d.key);
    })
    .style("opacity", 0.5)
    .attr("id", function(d) {
        return 'tagArea' + d.key.replace(/\s+/g, '');
    })
    .attr("d", function(d) {
        return area(d.values)
    });

stateArea.exit().remove();
</code>```

Here is the updated bl.ocks: http://bl.ocks.org/anonymous/0c80f4f72247dcc8f590aa2d63d40da0

PS: I'm just appending the areas here, you'll have to refactor the code if you want that legend to the left changing the areas as well.

Title: d3 fill under interpolated line

Body:
In the following d3 line chart example, I would like to fill in the the area under the lines with fill color equivalent to line color and a transparency of 50%.

In addition to adding area to the CSS

.area {
  fill: blue;
  opacity: 0.5
}

adding the following to function updateGraph(data)

    svg.append("path")
   .data([data])
   .attr("class", "area")
   .attr("d", area);

and

var area = d3.svg.area()
    .x(function(d) { return x(d.year); })
    .y0(height)
    .y1(function(d) { return y(d.value); });

what is needed for the filled in area to fit under the interpolated line and for fill color to be equivalent to line color?

Body:
Actually, you have to create a new selection before the lines' selection (named states), here named stateArea:

var stateArea = svg.selectAll(".area")
    .data(result, function(d) {
        return d.key
    });

stateArea.enter().append("path")
    .attr("class", "area");

stateArea.transition()
    .style("fill", function(d, i) {
        return d.color = color(d.key);
    })
    .style("opacity", 0.5)
    .attr("id", function(d) {
        return 'tagArea' + d.key.replace(/\s+/g, '');
    })
    .attr("d", function(d) {
        return area(d.values)
    });

stateArea.exit().remove();

Here is the updated bl.ocks: http://bl.ocks.org/anonymous/0c80f4f72247dcc8f590aa2d63d40da0

PS: I'm just appending the areas here, you'll have to refactor the code if you want that legend to the left changing the areas as well.


问:
How to save the state of a button after restarting the app?
So I have a button which changes its image upon clicking. I would like to save the state of the button so that, when user reopens the app again, the button will display it's last state.

Below is my code:-

```<code>- (IBAction)xButtonOnPressed:(id)sender {
    [self.xButtonLabel setImage:[UIImage imageNamed:@"x_did-not-take_marked.png"] forState:UIControlStateSelected];
    [self.xButtonLabel setImage:[UIImage imageNamed:@"x_did-not-take.png"] forState:UIControlStateNormal];

    self.xButtonLabel.selected = !self.xButtonLabel.selected;

}
</code>```

The problem with the code is that, it always goes back to UIControlStateNormal after restarting the app. How can I save the last button state ?

答:
use NSUserDefaults for this.

Objective C:

To store:

```<code>[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"BUTTON_STATE_NORMAL"];
</code>```

To retrieve:

```<code>Bool isNormalState = [[NSUserDefaults standardUserDefaults]
    boolForKey:@"BUTTON_STATE_NORMAL"];

if(isNormalState == true) {
  //Do your thing.
}
</code>```

Additional:

swift 3:

To store:

```<code>UserDefaults.standard.set("Your_button_state", forKey: "Key") //setObject
</code>```

To retrieve:

```<code>UserDefaults.standard.string(forKey: "Key")
</code>```

There are lots of data type in this.Choose how you want to save>:)

Body:
So I have a button which changes its image upon clicking. I would like to save the state of the button so that, when user reopens the app again, the button will display it's last state.

Below is my code:-

- (IBAction)xButtonOnPressed:(id)sender {
    [self.xButtonLabel setImage:[UIImage imageNamed:@"x_did-not-take_marked.png"] forState:UIControlStateSelected];
    [self.xButtonLabel setImage:[UIImage imageNamed:@"x_did-not-take.png"] forState:UIControlStateNormal];

    self.xButtonLabel.selected = !self.xButtonLabel.selected;

}

The problem with the code is that, it always goes back to UIControlStateNormal after restarting the app. How can I save the last button state ?

Body:
use NSUserDefaults for this.

Objective C:

To store:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"BUTTON_STATE_NORMAL"];

To retrieve:

Bool isNormalState = [[NSUserDefaults standardUserDefaults]
    boolForKey:@"BUTTON_STATE_NORMAL"];

if(isNormalState == true) {
  //Do your thing.
}

Additional:

swift 3:

To store:

UserDefaults.standard.set("Your_button_state", forKey: "Key") //setObject

To retrieve:

UserDefaults.standard.string(forKey: "Key")

There are lots of data type in this.Choose how you want to save>:)


问:
Easyadmin One-to-Many: not displaying form
With Easyadmin, Symfony3 and Doctrine I'm trying to display an embedded form for an Article to add Urls to itself.

However, the article form currently does not show the UrlType form, but instead text boxes which - what it seems - expect Ids of the Urls I would like to add.

I found that the following configuration should be working (according to this question):

```<code>       form:
            fields:
                [...]
                - { property: 'urls', type: 'collection', type_options: { entry_type: 'MyVendor\MyBundle\Form\UrlType', by_reference: false }  }
</code>```

Article:

```<code>class Article
{
    [..]

    /**
     * @ORM\OneToMany(targetEntity="Url", mappedBy="article", cascade={"persist", "remove"})
     */
    private $urls;

    public function __construct() {
        $this->urls = new ArrayCollection();
    }

    /**
     * Add url
     *
     * @param Url $url
     *
     * @return Article
     */
    public function addUrl(Url $url)
    {
        $url->setArticle($this);

        $this->urls[] = $url;

        return $this;
    }

    /**
     * Remove url
     *
     * @param Url $url
     */
    public function removeUrl(Url $url)
    {
        $this->urls->removeElement($url);
    }

    /**
     * Get url
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUrls()
    {
        return $this->urls;
    }
}
</code>```

Url:

```<code>class Url
{
   [..]

    /**
     * @var Article
     *
     * @ORM\ManyToOne(targetEntity="Article", inversedBy="urls")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="article_id", referencedColumnName="id")
     * })
     */
    private $article;

    /**
     * Set article
     *
     * @param Article $article
     *
     * @return Url
     */
    public function setArticle(Article $article = null)
    {
        $this->article = $article;

        return $this;
    }

    /**
     * Get article
     *
     * @return Article
     */
    public function getArticle()
    {
        return $this->article;
    }
}
</code>```

UrlType:

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('address', TextType::class);
    $builder->add('description', TextType::class);
}
</code>```

I have checked, double checked and tried so many things in the code and searched google as well as stackoverflow.

How can I display fields to add new URLs to the Article?

答:
Thanks to the friendly folks at EasyAdmin this issue has been resolved. It turns out that despite of using the fully qualified namespace to UrlType in YAML config, the type is overwritten with the Symfony UrlType.

Solution: Rename MyVendor\MyBundle\Form\UrlType to for example MyVendor\MyBundle\Form\UrlEntityType

This looks like a bug in either Symfony or EasyAdmin.

Body:
With Easyadmin, Symfony3 and Doctrine I'm trying to display an embedded form for an Article to add Urls to itself.

However, the article form currently does not show the UrlType form, but instead text boxes which - what it seems - expect Ids of the Urls I would like to add.

I found that the following configuration should be working (according to this question):

       form:
            fields:
                [...]
                - { property: 'urls', type: 'collection', type_options: { entry_type: 'MyVendor\MyBundle\Form\UrlType', by_reference: false }  }

Article:

class Article
{
    [..]

    /**
     * @ORM\OneToMany(targetEntity="Url", mappedBy="article", cascade={"persist", "remove"})
     */
    private $urls;

    public function __construct() {
        $this->urls = new ArrayCollection();
    }

    /**
     * Add url
     *
     * @param Url $url
     *
     * @return Article
     */
    public function addUrl(Url $url)
    {
        $url->setArticle($this);

        $this->urls[] = $url;

        return $this;
    }

    /**
     * Remove url
     *
     * @param Url $url
     */
    public function removeUrl(Url $url)
    {
        $this->urls->removeElement($url);
    }

    /**
     * Get url
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUrls()
    {
        return $this->urls;
    }
}

Url:

class Url
{
   [..]

    /**
     * @var Article
     *
     * @ORM\ManyToOne(targetEntity="Article", inversedBy="urls")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="article_id", referencedColumnName="id")
     * })
     */
    private $article;

    /**
     * Set article
     *
     * @param Article $article
     *
     * @return Url
     */
    public function setArticle(Article $article = null)
    {
        $this->article = $article;

        return $this;
    }

    /**
     * Get article
     *
     * @return Article
     */
    public function getArticle()
    {
        return $this->article;
    }
}

UrlType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('address', TextType::class);
    $builder->add('description', TextType::class);
}

I have checked, double checked and tried so many things in the code and searched google as well as stackoverflow.

How can I display fields to add new URLs to the Article?


问:
Unfortunately App has stopped with no verbose in logcat
I created an app with login activity and wanted to add an splash screen,I have added a java class and layout for the splash screen and bind the layout to the java class and run the app.

It doesn't run it show a dialog that says "unfortunately "my app" has stopped" and no verbose or any error appears in the logcat so i can't find where is the error !!! anyone can help,please??

my java class for splash screen

```<code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

public class Splash extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        Thread myThread=new Thread(){
            @Override
            public void run() {
                try {
                    sleep(2000);
                    Intent in =new Intent(getApplicationContext(),LoginActivity.class);
                    startActivity(in);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        myThread.start();
    }
}
</code>```

logcat after editing :

```<code>/com.google.android.gms.persistent E/InstantApps: DomainFilterImpl: Error while reading domain filter from WHAPI
                                                                              java.util.concurrent.ExecutionException: axvq: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at java.util.concurrent.FutureTask.report(FutureTask.java:93)
                                                                                at java.util.concurrent.FutureTask.get(FutureTask.java:163)
                                                                                at tik.get(:com.google.android.gms:2099)
                                                                                at tmd.a(:com.google.android.gms:347)
                                                                                at tmd.a(:com.google.android.gms:313)
                                                                                at tmd.a(:com.google.android.gms:131)
                                                                                at tmd.b(:com.google.android.gms:101)
                                                                                at tly.b(:com.google.android.gms:38)
                                                                                at com.google.android.gms.instantapps.routing.DomainFilterUpdateChimeraService.a(:com.google.android.gms:74)
                                                                                at rml.run(:com.google.android.gms:261)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                               Caused by: axvq: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at axvm.c(:com.google.android.gms:505)
                                                                                at lgy.a(:com.google.android.gms:168)
                                                                                at thx.b(:com.google.android.gms:7164)
                                                                                at thx.a(:com.google.android.gms:57)
                                                                                at til.call(:com.google.android.gms:1049)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at lmq.run(:com.google.android.gms:450)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                at lra.run(:com.google.android.gms:17)
                                                                                at java.lang.Thread.run(Thread.java:818)
</code>```

manifest file :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="app.com.example.abdelrahman.carcare">

    <!-- To auto-complete the email text field in the login form with the user's emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".CreatNew"
            android:label="@string/title_activity_creat_new">
        </activity>
        <activity android:name=".LoginActivity"
            android:label="@string/app_name"
            ></activity>
    </application>

</manifest>
</code>```

:

答: That's because you can now only see logs from Firebase. Change it to Show only Selected Application

Body:
I created an app with login activity and wanted to add an splash screen,I have added a java class and layout for the splash screen and bind the layout to the java class and run the app.

It doesn't run it show a dialog that says "unfortunately "my app" has stopped" and no verbose or any error appears in the logcat so i can't find where is the error !!! anyone can help,please??

my java class for splash screen

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

public class Splash extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        Thread myThread=new Thread(){
            @Override
            public void run() {
                try {
                    sleep(2000);
                    Intent in =new Intent(getApplicationContext(),LoginActivity.class);
                    startActivity(in);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        myThread.start();
    }
}

logcat after editing :

/com.google.android.gms.persistent E/InstantApps: DomainFilterImpl: Error while reading domain filter from WHAPI
                                                                              java.util.concurrent.ExecutionException: axvq: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at java.util.concurrent.FutureTask.report(FutureTask.java:93)
                                                                                at java.util.concurrent.FutureTask.get(FutureTask.java:163)
                                                                                at tik.get(:com.google.android.gms:2099)
                                                                                at tmd.a(:com.google.android.gms:347)
                                                                                at tmd.a(:com.google.android.gms:313)
                                                                                at tmd.a(:com.google.android.gms:131)
                                                                                at tmd.b(:com.google.android.gms:101)
                                                                                at tly.b(:com.google.android.gms:38)
                                                                                at com.google.android.gms.instantapps.routing.DomainFilterUpdateChimeraService.a(:com.google.android.gms:74)
                                                                                at rml.run(:com.google.android.gms:261)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                               Caused by: axvq: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at axvm.c(:com.google.android.gms:505)
                                                                                at lgy.a(:com.google.android.gms:168)
                                                                                at thx.b(:com.google.android.gms:7164)
                                                                                at thx.a(:com.google.android.gms:57)
                                                                                at til.call(:com.google.android.gms:1049)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at lmq.run(:com.google.android.gms:450)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                at lra.run(:com.google.android.gms:17)
                                                                                at java.lang.Thread.run(Thread.java:818)

manifest file :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="app.com.example.abdelrahman.carcare">

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".CreatNew"
            android:label="@string/title_activity_creat_new">
        </activity>
        <activity android:name=".LoginActivity"
            android:label="@string/app_name"
            ></activity>
    </application>

</manifest>

:


问:
about moving items in selectbox
I am trying to moving the items in a select box by using buttons.. for this i used swapNode().
But it is working only in IE. in chrome not working how to make it to work in chrome
Here is my code</p>

```<code> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title>Moving the options up and down in Multiple select box </title>
 <script type="text/javascript">
 function move(id)
 {

if (id=='up')
{
    var len=    document.f1.selectbox1.options.length;
    if (document.f1.selectbox1[0].selected)
    {
        alert("This is the first record");
        return false;
    }
    var up_id=document.f1.selectbox1.selectedIndex;
    document.f1.selectbox1[up_id].swapNode(document.f1.selectbox1[up_id-1]);
}
if (id=='down')
{
 var len=document.f1.selectbox1.options.length;
    if (document.f1.selectbox1[len-1].selected)
    {
        alert("This is last record");
        return false;
    }
    var down_id=document.f1.selectbox1.selectedIndex;
    document.f1.selectbox1[down_id].swapNode(document.f1.selectbox1[down_id+1]);
}
if (id=='top')
{
    var len=document.f1.selectbox1.options.length;
    if (document.f1.selectbox1[0].selected)
    {
        alert("This is the first record");
        return false;
    }
    var top_id=document.f1.selectbox1.selectedIndex
    for (var j=top_id;j>0 ;j-- )
    {
            document.f1.selectbox1[j].swapNode(document.f1.selectbox1[j-1]);
    }
}
if (id=='bottom')
{
    var len=document.f1.selectbox1.options.length;;
    if(document.f1.selectbox1[len-1].selected)
        {
            alert("This is last record");
            return false;
        }
        var bot_id=document.f1.selectbox1.selectedIndex
        for (var k=bot_id; k<len-1;k++)
        {
                document.f1.selectbox1[k].swapNode(document.f1.selectbox1[k+1]);

        }
}
 }
 </script>
 </head>
 <body>
  <form name="f1">
<select multiple size="20" style="width:30%" name="selectbox1" id="select_box">
<option id="1">First item</option>
<option id="2">Second item</option>
<option id="3">Third item</option>
<option id="4">Fourth item</option>
<option id="4">Fifth item</option>
<option id="4">Sixth item</option>
<option id="4">Seventh item</option>
<option id="4">Eighth item</option>
<option id="4">Ninth item</option>
<option id="4">Tenth item</option>
</select><br>
<input type="button" value="Up" onClick="move('up')">
<input type="button" value="Down" onClick="move('down')">
<input type="button" value="Top" onClick="move('top')">
<input type="button" value="Bottom" onClick="move('bottom')">
  </form>
 </body>
</html>
</code>```

答:
swapNode() is a Microsoft DOM extension and so as a result will not be recognized by browsers other than IE.

I ran your example in FireFox and used FireBug (You should download this plugin and use it in situations like this if you don't already) and sure enough the console was throwing an error that swapNode() was "not a function".

If I were to advise you from here, I would suggest going to lookup a jQuery plugin or something of that sort that achieves this kind functionality. Libraries like jQuery tend to offer cross browser solutions to these sorts of javascript problems and best of all are more often then not open source (so you can have a peek at the code and rework your own implementation if you would like).
http://jquery.com/

Alternatively, you could simply provide the swapNode() function in your code so that other browsers could pick it up. If you plan to go this route, you should be able to find an implementation with a quick Google search. I have provided a link to one such implementation below (I have not reviewed or used this code, use only after reviewing). In my humble opinion however, it is best to avoid solutions that have browser dependency as they are not always future proof and can often result in unforeseen issues.
http://sundberg.it/2006/05/12/swapnode_in_firefox

Good Luck!

Title: about moving items in selectbox

Body:
I am trying to moving the items in a select box by using buttons.. for this i used swapNode().
But it is working only in IE. in chrome not working how to make it to work in chrome
Here is my code

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title>Moving the options up and down in Multiple select box </title>

  <form name="f1">
<select multiple size="20" style="width:30%" name="selectbox1" id="select_box">
<option id="1">First item</option>
<option id="2">Second item</option>
<option id="3">Third item</option>
<option id="4">Fourth item</option>
<option id="4">Fifth item</option>
<option id="4">Sixth item</option>
<option id="4">Seventh item</option>
<option id="4">Eighth item</option>
<option id="4">Ninth item</option>
<option id="4">Tenth item</option>
</select>

<input type="button" value="Up" onClick="move('up')">
<input type="button" value="Down" onClick="move('down')">
<input type="button" value="Top" onClick="move('top')">
<input type="button" value="Bottom" onClick="move('bottom')">
  </form>


问:
replace every second line of my triangle with a blank line for loops
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

```<code>  5

 555

55555
</code>```

This is my code:

```<code> for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}
</code>```

答:
I think that you can just enter one more print statement inside the loop:

```<code> for(int i = 0; i < 5; i++) {

     System.out.println();

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

     for(int k = 0; k <= (i*2); k++) {

         System.out.print("*");
     }
     System.out.println();
}
</code>```

Output

```<code>     *

    ***

   *****

  *******

 *********
</code>```

Body:
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

  5

 555

55555

This is my code:

 for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}

Body:
I think that you can just enter one more print statement inside the loop:

 for(int i = 0; i < 5; i++) {

     System.out.println();

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

     for(int k = 0; k <= (i*2); k++) {

         System.out.print("*");
     }
     System.out.println();
}

Output

     *

    ***

   *****

  *******

 *********


问:
Why doesn't Javascript Dynamic HTML5 Table Not Appear on Page
I am attempting to take quantities of products and multiplying them by the price before inserting these constantly updating values into an HTML table. I am using a forever loop to constantly take input for the sake of the example.</p>

```<code>    <!DOCTYPE html>
    <html>

    <head>
    <meta charset="utf-8">

<script>
<!--
var product1 = 0;
var product2 = 0;
var product3 = 0;
var product4 = 0;
var product5 = 0;
var productNum = 0;
var productNumInt = 0;
var quantitySold = 0;
var quantitySoldInt = 0;

document.write("<table>");
document.write("<tr><th>Product Number</th><th>Quantity Sold</th></tr>");
document.write("<tr><td>1</td><td>$" + product1 + "</td></tr>");
document.write("<tr><td>2</td><td>$" + product2 + "</td></tr>");
document.write("<tr><td>3</td><td>$" + product3 + "</td></tr>");
document.write("<tr><td>4</td><td>$" + product4 + "</td></tr>");
document.write("<tr><td>5</td><td>$" + product5 + "</td></tr>");
document.write("</table>");

while (true) {
  productNum = window.prompt("Please enter the product number");
  quantitySold = window.prompt("Please enter the quantity sold");
  productNumInt = parseInt(productNum);
  quantitySoldInt = parseInt(quantitySold);

  switch (productNumInt) {
    case 1:
      product1 += quantitySoldInt * 2.98;
      break;
    case 2:
      product2 += quantitySoldInt * 4.50;
      break;
    case 3:
      product3 += quantitySoldInt * 9.98;
      break;
    case 4:
      product4 += quantitySoldInt * 4.49;
      break;
    case 5:
      product5 += quantitySoldInt * 6.87;
      break;
  }
}
// -->
</script>
</head>

<body>
</body>

</html>
</code>```

答: As mentioned @vZ10 you need to put the script in the end of the body tag. Also you're prompting user to fill a data after actual render of a table(document.write calls). Try to place  document.write calls after prompt

Body:
I am attempting to take quantities of products and multiplying them by the price before inserting these constantly updating values into an HTML table. I am using a forever loop to constantly take input for the sake of the example.

    <!DOCTYPE html>

    <meta charset="utf-8">


问:
Xamarin.Forms Android System.ObjectModel could not be found
I create the first Xamarin.Forms project using Visual Studio 2017.

The error is The referenced component 'System.ObjectModel' could not be found.. The dll System.ObjectModel.dll is existing in C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\MonoAndroid\v1.0\Facades however it shows Yellow triangle on References.

Replaced by the another dll in C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\MonoAndroid\v1.0\Facades to remove Yellow triangle.

However got another error when compiling:

CS1703    Multiple assemblies with equivalent identity have been
  imported: 'C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework\MonoAndroid\v1.0\Facades\System.ObjectModel.dll'
  and 'C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\MonoAndroid\v1.0\Facades\System.ObjectModel.dll'.
  Remove one of the duplicate
  references.   App2.Android    C:\Users\xxx\documents\visual studio
  2017\Projects\App2\App2\App2.Android\CSC  1   Active

Any idea pls?

答:
Resolved.

Removed the current DLL

Reinstall the package via Nuget


问:
Why SelectMany needs the one of M<S> -> (S -> M<C>) -> (S -> M<C> -> R) -> E<R>?
In the link https://msdn.microsoft.com/en-us/library/bb534631(v=vs.110).aspx, the third signature is

```<code>// M<S> -> (S -> M<C>) -> (S -> M<C> -> R) -> E<R>
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TCollection>> collectionSelector,
    Func<TSource, TCollection, TResult> resultSelector
)
</code>```

Shouldn't the first one which has the signature of the typical Monad bind function M -> (A -> M) -> M be enough? Isn't it easy to merge code in the resultSelector into collectionSelector?

The MSDN document gave an example to show the usage of the method.

```<code>class Program
{
    static void Main(string[] args)
    {
        SelectManyEx3();
    }
    public static void SelectManyEx3()
    {
        PetOwner[] petOwners =
            { new PetOwner { Name="Higa",
                    Pets = new List<string>{ "Scruffy", "Sam" } },
                new PetOwner { Name="Ashkenazi",
                    Pets = new List<string>{ "Walker", "Sugar" } },
                new PetOwner { Name="Price",
                    Pets = new List<string>{ "Scratches", "Diesel" } },
                new PetOwner { Name="Hines",
                    Pets = new List<string>{ "Dusty" } } };

        // Project the pet owner's name and the pet's name.
        var query =
            petOwners
            .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
            .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
            .Select(ownerAndPet =>
                    new
                    {
                        Owner = ownerAndPet.petOwner.Name,
                        Pet = ownerAndPet.petName
                    }
            );

        // Print the results.
        foreach (var obj in query1)
        {
            Console.WriteLine(obj);
        }
    }
}

class PetOwner
{
    public string Name { get; set; }
    public List<string> Pets { get; set; }
}
</code>```

However, the var query = ... can be rewritten using the SelectMany of the first signature as following?

```<code>var query = petOwners.SelectMany(o => o.Pets.Select(p => new { petOwner = o, petName =p}))
</code>```

When will the SelectMany with the third signature be really useful?

答:
The 3rd and 4th overloads of the SelectMany( ) method with the additional “result selector” parameter take a bit more explanation.

The extra selector parameter is trying to help you know and understand the relationship between the parent and child collections. The code is more concise concerned the relationship.

A result selector is an intermediate object available within the scope of the query to give you the information you need, and it’s up to you to decide what data you need in the result selector to help you.

Say you need a result collection that will not only have the full list of Teams that match some criteria in all leagues but need to know what League the teams are in.

For example:

```<code>var teamsAndTheirLeagues = from helper in leagues
    .SelectMany( l => l.Teams, ( league, team )
    => new { league, team } )
    where helper.team.Players.Count > 2
        && helper.league.Teams.Count < 10
    select new { LeagueID = helper.league.ID, Team = helper.team };
</code>```

This syntax gives you extra ability to query both the team and the league in the where clause and you are not "losing" backward connection of the parent-child relationship.

More detailed explanation about selectMany projections can be found here and here

Body:
In the link https://msdn.microsoft.com/en-us/library/bb534631(v=vs.110).aspx, the third signature is

// M<S> -> (S -> M<C>) -> (S -> M<C> -> R) -> E<R>
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TCollection>> collectionSelector,
    Func<TSource, TCollection, TResult> resultSelector
)

Shouldn't the first one which has the signature of the typical Monad bind function M -> (A -> M) -> M be enough? Isn't it easy to merge code in the resultSelector into collectionSelector?

The MSDN document gave an example to show the usage of the method.

class Program
{
    static void Main(string[] args)
    {
        SelectManyEx3();
    }
    public static void SelectManyEx3()
    {
        PetOwner[] petOwners =
            { new PetOwner { Name="Higa",
                    Pets = new List<string>{ "Scruffy", "Sam" } },
                new PetOwner { Name="Ashkenazi",
                    Pets = new List<string>{ "Walker", "Sugar" } },
                new PetOwner { Name="Price",
                    Pets = new List<string>{ "Scratches", "Diesel" } },
                new PetOwner { Name="Hines",
                    Pets = new List<string>{ "Dusty" } } };

        // Project the pet owner's name and the pet's name.
        var query =
            petOwners
            .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
            .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
            .Select(ownerAndPet =>
                    new
                    {
                        Owner = ownerAndPet.petOwner.Name,
                        Pet = ownerAndPet.petName
                    }
            );

        // Print the results.
        foreach (var obj in query1)
        {
            Console.WriteLine(obj);
        }
    }
}

class PetOwner
{
    public string Name { get; set; }
    public List<string> Pets { get; set; }
}

However, the var query = ... can be rewritten using the SelectMany of the first signature as following?

var query = petOwners.SelectMany(o => o.Pets.Select(p => new { petOwner = o, petName =p}))

When will the SelectMany with the third signature be really useful?

Body:
The 3rd and 4th overloads of the SelectMany( ) method with the additional “result selector” parameter take a bit more explanation.

The extra selector parameter is trying to help you know and understand the relationship between the parent and child collections. The code is more concise concerned the relationship.

A result selector is an intermediate object available within the scope of the query to give you the information you need, and it’s up to you to decide what data you need in the result selector to help you.

Say you need a result collection that will not only have the full list of Teams that match some criteria in all leagues but need to know what League the teams are in.

For example:

var teamsAndTheirLeagues = from helper in leagues
    .SelectMany( l => l.Teams, ( league, team )
    => new { league, team } )
    where helper.team.Players.Count > 2
        && helper.league.Teams.Count < 10
    select new { LeagueID = helper.league.ID, Team = helper.team };

This syntax gives you extra ability to query both the team and the league in the where clause and you are not "losing" backward connection of the parent-child relationship.

More detailed explanation about selectMany projections can be found here and here


问:
Dynamically Change WCF Service URL in ASP.NET MVC
I have one solution in which I have 2 projects with:

ASP.NET MVC Application to consume wcf services.

5 WCF services.

I have added one web service reference in the project 1. Now, I need to use different services based on the user e.g.

User Type 1: Only allow to consume Service 1.

User Type 2: Only allow to consume Service 2.
etc.

I have Service URL's like localhost:6227/Service1.svc, localhost:6227/Service2.svc etc.

I have stored all service URL's in the db and I need to change URL for each user type to consume his allowed service only without adding more end points and only change URL from the backend based on user type. I need relevant link or code to solve this problem.

Edit

In Web Config
I have added just this endpoint in the mvc application and I don't want to use web config to change address in here but I want to change address in the code for each user type while application is running.

```<code><client>
      <endpoint address="http://localhost:6227/Service1.svc"
        binding="customBinding" bindingConfiguration="CustomBinding_IService1"
        contract="Service1.IService1" name="CustomBinding_IService1" />
    </client>
</code>```

答:
if i completely realize your question you need dynamic soap service calling. maybe something like this:</p>

```<code>private void CallService()
{
    var myBinding = new BasicHttpBinding();
    myBinding.Security.Mode = BasicHttpSecurityMode.None;
    var myEndpointAddress = new EndpointAddress("your url depend on user type");
    var client = new ClientService1(myBinding, myEndpointAddress);
    var outpiut = client.someCall();
    client.close();
}
</code>```

Body:
I have one solution in which I have 2 projects with:

ASP.NET MVC Application to consume wcf services.

5 WCF services.

I have added one web service reference in the project 1. Now, I need to use different services based on the user e.g.

User Type 1: Only allow to consume Service 1.

User Type 2: Only allow to consume Service 2.
etc.

I have Service URL's like localhost:6227/Service1.svc, localhost:6227/Service2.svc etc.

I have stored all service URL's in the db and I need to change URL for each user type to consume his allowed service only without adding more end points and only change URL from the backend based on user type. I need relevant link or code to solve this problem.

Edit

In Web Config
I have added just this endpoint in the mvc application and I don't want to use web config to change address in here but I want to change address in the code for each user type while application is running.

<client>
      <endpoint address="http://localhost:6227/Service1.svc"
        binding="customBinding" bindingConfiguration="CustomBinding_IService1"
        contract="Service1.IService1" name="CustomBinding_IService1" />
    </client>

Body:
if i completely realize your question you need dynamic soap service calling. maybe something like this:

private void CallService()
{
    var myBinding = new BasicHttpBinding();
    myBinding.Security.Mode = BasicHttpSecurityMode.None;
    var myEndpointAddress = new EndpointAddress("your url depend on user type");
    var client = new ClientService1(myBinding, myEndpointAddress);
    var outpiut = client.someCall();
    client.close();
}


问:
Angular2 Reactive Form Post HTTP
i am new on using angular2. i just dont know how to send http form. i use the reactive form format.

this is my html

```<code><form novalidate [formGroup]="form" (ngSubmit)="onSubmit(form)">
  <div class="form-group">
    <input formControlName="categoryname" type="text" class="form-control" placeholder="Category" >
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
<p>Form: {{ form.value | json }}</p>
<p>Form status: {{ form.status }}</p>
<p> {{error}}</p>
</code>```

and this is my component

```<code>import { Component } from '@angular/core';
import {Category} from './category';
import {CategoryService} from '../service/category.service';
import {FormBuilder, FormGroup, FormControl} from '@angular/forms';
import {Subscription} from 'rxjs';
import { ActivatedRoute, Params} from '@angular/router';

@Component({
    selector: 'registration',
    templateUrl:'./registration.html',
    styleUrls:['./registration.css'],
    providers: [CategoryService]
})

export class AppRegistration {

    categoryname: any;
    response: string;

    form: FormGroup;
    constructor(private categoryserv: CategoryService, public fb: FormBuilder) {
        this.form = this.fb.group({
            categoryname: '',
        });
    }

    onSubmit() {
        console.log(this.form.value, this.form.valid);
    }
}
</code>```

and this is my service

```<code>import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Rx';

import {Category} from '../app-registration/category';

@Injectable()
export class CategoryService {
    private urlcategory = "http://localhost:8080/create-category";
    constructor(private http: Http){ }

}
</code>```

This my category model

```<code>export class Category {
   categoryname: string;
   constructor() {
   }
}
</code>```

my service code is not complete yet . yes because that is my question.
how to make service code and get the value of the form and send to the API link based on my model Category code.

I have been confused for three days and i still dont get any answer yet. please help me guys :(

答:
In your service make function for the http post with body that contains the value to be passed

```<code> @Injectable()
    export class CategoryService {
        private urlcategory = "http://localhost:8080/create-category";
        constructor(private http: Http){
       senddata(data : any)
         var body = JSON.stringify(data);
                var headers = new Headers();
                headers.append('Content-Type', 'application/json');
                return this.http.post(this.urlcategory, body, { headers: headers }).map((data: Response) => data.json()).catch(this.handleError);
     }

    }
</code>```

In your component call the service and pass the form data

```<code> onSubmit() {
            this.categoryserv.senddata(this.form.value.categoryname).subscribe(data=>{
       console.log(data);
    })
        }
</code>```

Title: Angular2 Reactive Form Post HTTP

Body:
i am new on using angular2. i just dont know how to send http form. i use the reactive form format.

this is my html

<form novalidate [formGroup]="form" (ngSubmit)="onSubmit(form)">

    <input formControlName="categoryname" type="text" class="form-control" placeholder="Category" >

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

Form: {{ form.value | json }}

Form status: {{ form.status }}

 {{error}}

and this is my component

import { Component } from '@angular/core';
import {Category} from './category';
import {CategoryService} from '../service/category.service';
import {FormBuilder, FormGroup, FormControl} from '@angular/forms';
import {Subscription} from 'rxjs';
import { ActivatedRoute, Params} from '@angular/router';

@Component({
    selector: 'registration',
    templateUrl:'./registration.html',
    styleUrls:['./registration.css'],
    providers: [CategoryService]
})

export class AppRegistration {

    categoryname: any;
    response: string;

    form: FormGroup;
    constructor(private categoryserv: CategoryService, public fb: FormBuilder) {
        this.form = this.fb.group({
            categoryname: '',
        });
    }

    onSubmit() {
        console.log(this.form.value, this.form.valid);
    }
}

and this is my service

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Rx';

import {Category} from '../app-registration/category';

@Injectable()
export class CategoryService {
    private urlcategory = "http://localhost:8080/create-category";
    constructor(private http: Http){ }

}

This my category model

export class Category {
   categoryname: string;
   constructor() {
   }
}

my service code is not complete yet . yes because that is my question.
how to make service code and get the value of the form and send to the API link based on my model Category code.

I have been confused for three days and i still dont get any answer yet. please help me guys :(

Body:
In your service make function for the http post with body that contains the value to be passed

 @Injectable()
    export class CategoryService {
        private urlcategory = "http://localhost:8080/create-category";
        constructor(private http: Http){
       senddata(data : any)
         var body = JSON.stringify(data);
                var headers = new Headers();
                headers.append('Content-Type', 'application/json');
                return this.http.post(this.urlcategory, body, { headers: headers }).map((data: Response) => data.json()).catch(this.handleError);
     }

    }

In your component call the service and pass the form data

 onSubmit() {
            this.categoryserv.senddata(this.form.value.categoryname).subscribe(data=>{
       console.log(data);
    })
        }


答:
Say you have a button called button:

```<code>UIButton *button;

// get nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// save selected state
[defaults setBool:button.selected forKey:@"myButtonState"];
</code>```

Then later, after the app launches again...

```<code>// restore the selected state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
button.selected = [defaults boolForKey:@"myButtonState"];
</code>```

Title: How to save the state of a button after restarting the app?

Body:
Say you have a button called button:

UIButton *button;

// get nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// save selected state
[defaults setBool:button.selected forKey:@"myButtonState"];

Then later, after the app launches again...

// restore the selected state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
button.selected = [defaults boolForKey:@"myButtonState"];


答:
Your example does not work fine; it's behavior is undefined.

C++ has several different types of cast operations.  The one you've used here is a C-style cast (technically it ends up doing a static_cast).  C-style casts don't do any runtime type checking.  It's up to the programmer to make sure the types involved make sense.  If you want runtime type checking, use dynamic_cast.  When using dynamic_cast with pointers, the cast will fail and return nullptr if the object isn't actually an instance of the type being cast to.  When using references it will throw std::bad_cast.

```<code>class Animal {
public:
    virtual void makeSound() { std::cout << "From Animal\n"; }
};

class Dog : public Animal {
public:
    void makeSound() { std::cout << "From Dog\n"; }
};

int main() {
    Animal *a = new Animal();
    Dog* d = dynamic_cast<Dog*>(a);
    if (d == nullptr) {
        std::cout << "cast failed\n";
    } else {
        d->makeSound();
    }
}
</code>```

Live example

Title: Why would this give me a ClassCastException in Java, while it works well in C++?

Body:
Something is driving me crazy.

Assume we have these simple classes

public class Animal {
public void makeSound() {
    System.out.println("From Animal");
  }
}

public class Dog extends Animal {
public void makeSound() {
    System.out.println("From Dog");
}

public void flip() {
    System.out.println("Flipped");
}

public static void main(String[] args) {
  Animal a= new Animal();
  ((Dog)a).makeSound(); // Gives me an error at runtime.

}

C++ code:

class Animal {
   public:
          virtual void makeSound(){ cout<<" From Animal";}
};

class Dog : public Animal {
    public : void makeSound(){ cout<<" From Dog ";}
             void  flip() { cout<<"Flipped";}
};

 main() {
Animal *a = new Animal();
((Dog*)a)->makeSound(); // returns From animal

  }

Why would it generate runtime error in Java, while it would work without a problem in C++ ?

Thank you

Body:
Your example does not work fine; it's behavior is undefined.

C++ has several different types of cast operations.  The one you've used here is a C-style cast (technically it ends up doing a static_cast).  C-style casts don't do any runtime type checking.  It's up to the programmer to make sure the types involved make sense.  If you want runtime type checking, use dynamic_cast.  When using dynamic_cast with pointers, the cast will fail and return nullptr if the object isn't actually an instance of the type being cast to.  When using references it will throw std::bad_cast.

class Animal {
public:
    virtual void makeSound() { std::cout << "From Animal\n"; }
};

class Dog : public Animal {
public:
    void makeSound() { std::cout << "From Dog\n"; }
};

int main() {
    Animal *a = new Animal();
    Dog* d = dynamic_cast<Dog*>(a);
    if (d == nullptr) {
        std::cout << "cast failed\n";
    } else {
        d->makeSound();
    }
}

Live example