问:
WPF Control and Window issue
Hey all here is a noob question regarding WPF and controls.

I download the project called FluidKit which comes with a hand full of examples for 3D image effects and just image effects in general.

Problem I am having is that I just want 1 type of effect out of all of those but I am unsure how to go about making a new project and copy/paste the FluidKit code to my new project just for that needed effect. I am needing to be able to reproduce this a couple of times in my window and not just once as I currently have.

The code is for the following:

TransitionTester.xaml

Which within that has a few settings like:

Cube (Left to Right)

Cube (Right to Left>

Cube (Top to Bottom)

Cube (Bottom to Top)

Slide (Left to Right)

Slide (Right to Left)

Flip (Left to Right)

Flip (Right to Left)

This TransitionTester.xaml looks to be a UserControl.

So I create a new WPF project and now I have the following forms:

MainWindow.xaml

TransitionTester.xaml

and of course I replace a reference to the fluidkit.dll.

Bow after copy/pasting the code from the fluidKit project to my new project I end up just having 2 errors which is astonishing to me!

The errors are:

Error CS1061  'MainWindow' does not contain a definition for 'SwitchImage' and no extension method 'SwitchImage' accepting a first argument of type 'MainWindow' could be found (are you missing a using directive or an assembly reference?)

Error      The resource "SlideTransition" could not be resolved.

My MainWindow.xaml code looks like this:

```<code><Window x:Class="flipwindow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:flipwindow"
        xmlns:Controls="clr-namespace:FluidKit.Controls;assembly=FluidKit"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Controls:TransitionPresenter x:Name="_transContainer"
                                      MouseLeftButtonDown="SwitchImage"
                                      RestDuration="0:0:3"
                                      IsLooped="True"
                                      Transition="{StaticResource SlideTransition}">
            <Image x:Name="_image1"
                   Source="Images/img1.png"
                   Stretch="Fill" />
            <Image x:Name="_image2"
                   Source="Images/img2.png"
                   Stretch="Fill" />
            <Image x:Name="_image3"
                   Source="Images/img3.png"
                   Stretch="Fill" />
        </Controls:TransitionPresenter>
    </Grid>
</Window>
</code>```

And the code behind that page looks like this:

```<code>namespace flipwindow
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string _backItem = "_image1";
        private string _frontItem = "_image2";

        public MainWindow()
        {
            InitializeComponent();
            Loaded += TransitionTester_Loaded;
            //PlayCube();
        }

        private void TransitionTester_Loaded(object sender, RoutedEventArgs e)
        {
            _transContainer.TransitionCompleted += _transContainer_TransitionCompleted;
        }

        private void _transContainer_TransitionCompleted(object sender, EventArgs e)
        {
            SwapFrontAndBack();
        }

        private void SwapFrontAndBack()
        {
            string temp = _frontItem;
            _frontItem = _backItem;
            _backItem = temp;
        }

        private void PlayCube()
        {
            CubeTransition transition = Resources["CubeTransition"] as CubeTransition;
            //transition.Rotation = Direction.LeftToRight;
            //transition.Rotation = Direction.RightToLeft;
            //transition.Rotation = Direction.TopToBottom;
            transition.Rotation = Direction.BottomToTop;

            _transContainer.Transition = transition;
            _transContainer.ApplyTransition(_frontItem, _backItem);
        }
    }
}
</code>```

The second error listed above show up on this line:

Transition="{StaticResource SlideTransition}">

While I am not sure about the first error and what it's looking for in order for that to be corrected. It seems to maybe be related to the UserControl.Resources that I can not seem to add to my Window:

```<code><UserControl.Resources>
    <Controls:SlideTransition x:Key="SlideTransition" />
    <Controls:CubeTransition x:Key="CubeTransition" Rotation="BottomToTop" />
    <Controls:FlipTransition x:Key="FlipTransition" />
</UserControl.Resources>
</code>```

Layout looks like this:

And my MainWindow.xaml Design looks fine as well:

When comparing it with the original FluidKit window:

So any help to help me fix those 2 errors would be great!

UPDATE 1

答:
First: the MouseLeftButtonDown tag refers to a callback function in your code behind which of course can not be found. So just insert the SwitchImage function as it is in the FluidKit original code in TransitionTester.xaml.cs to the MainWindow class code in the MainWindow.xaml.cs file which should have be created next to your MainWindow.xaml file. (Maybe keep it empty for testing purposes)

Second: Yes, you have to copy the <UserControl.Resources> xml code from the original xaml-File to your file. But you have to replace the tag <UserControl.Resources> by <MainWindow.Resources> as your surrounding tag is <MainWindow>. (The resource named SliceTransition which is referred to later in the code is defined inside this block)

Title: WPF Control and Window issue

Body:
Hey all here is a noob question regarding WPF and controls.

I download the project called FluidKit which comes with a hand full of examples for 3D image effects and just image effects in general.

Problem I am having is that I just want 1 type of effect out of all of those but I am unsure how to go about making a new project and copy/paste the FluidKit code to my new project just for that needed effect. I am needing to be able to reproduce this a couple of times in my window and not just once as I currently have.

The code is for the following:

TransitionTester.xaml

Which within that has a few settings like:

Cube (Left to Right)

Cube (Right to Left>

Cube (Top to Bottom)

Cube (Bottom to Top)

Slide (Left to Right)

Slide (Right to Left)

Flip (Left to Right)

Flip (Right to Left)

This TransitionTester.xaml looks to be a UserControl.

So I create a new WPF project and now I have the following forms:

MainWindow.xaml

TransitionTester.xaml

and of course I replace a reference to the fluidkit.dll.

Bow after copy/pasting the code from the fluidKit project to my new project I end up just having 2 errors which is astonishing to me!

The errors are:

Error CS1061  'MainWindow' does not contain a definition for 'SwitchImage' and no extension method 'SwitchImage' accepting a first argument of type 'MainWindow' could be found (are you missing a using directive or an assembly reference?)

Error      The resource "SlideTransition" could not be resolved.

My MainWindow.xaml code looks like this:

<Window x:Class="flipwindow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:flipwindow"
        xmlns:Controls="clr-namespace:FluidKit.Controls;assembly=FluidKit"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Controls:TransitionPresenter x:Name="_transContainer"
                                      MouseLeftButtonDown="SwitchImage"
                                      RestDuration="0:0:3"
                                      IsLooped="True"
                                      Transition="{StaticResource SlideTransition}">
            <Image x:Name="_image1"
                   Source="Images/img1.png"
                   Stretch="Fill" />
            <Image x:Name="_image2"
                   Source="Images/img2.png"
                   Stretch="Fill" />
            <Image x:Name="_image3"
                   Source="Images/img3.png"
                   Stretch="Fill" />
        </Controls:TransitionPresenter>
    </Grid>
</Window>

And the code behind that page looks like this:

namespace flipwindow
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private string _backItem = "_image1";
        private string _frontItem = "_image2";

        public MainWindow()
        {
            InitializeComponent();
            Loaded += TransitionTester_Loaded;
            //PlayCube();
        }

        private void TransitionTester_Loaded(object sender, RoutedEventArgs e)
        {
            _transContainer.TransitionCompleted += _transContainer_TransitionCompleted;
        }

        private void _transContainer_TransitionCompleted(object sender, EventArgs e)
        {
            SwapFrontAndBack();
        }

        private void SwapFrontAndBack()
        {
            string temp = _frontItem;
            _frontItem = _backItem;
            _backItem = temp;
        }

        private void PlayCube()
        {
            CubeTransition transition = Resources["CubeTransition"] as CubeTransition;
            //transition.Rotation = Direction.LeftToRight;
            //transition.Rotation = Direction.RightToLeft;
            //transition.Rotation = Direction.TopToBottom;
            transition.Rotation = Direction.BottomToTop;

            _transContainer.Transition = transition;
            _transContainer.ApplyTransition(_frontItem, _backItem);
        }
    }
}

The second error listed above show up on this line:

Transition="{StaticResource SlideTransition}">

While I am not sure about the first error and what it's looking for in order for that to be corrected. It seems to maybe be related to the UserControl.Resources that I can not seem to add to my Window:

<UserControl.Resources>
    <Controls:SlideTransition x:Key="SlideTransition" />
    <Controls:CubeTransition x:Key="CubeTransition" Rotation="BottomToTop" />
    <Controls:FlipTransition x:Key="FlipTransition" />
</UserControl.Resources>

Layout looks like this:

And my MainWindow.xaml Design looks fine as well:

When comparing it with the original FluidKit window:

So any help to help me fix those 2 errors would be great!

UPDATE 1


来源: stackexchange

问:
Reactjs POST request through fetch
Hi i am trying reactjs POST request through fetch but getting two error's, I went through all docs but error is not solved.

Errors:

Failed to load http://localhost:8083/students: Response for preflight has invalid HTTP status code 403

Uncaught (in promise) TypeError: Failed to fetch

Here is my Reactjs code:

```<code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

fetch('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>
     <div style={style}>
     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />
     <br/>
     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />
     <br/>
     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />
     <br/>

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />
     <br/>
     <br/>
     <input type="submit" />

     </div>
         </form>

   );
 }

}
</code>```

Even though here my form values also hard-coded.

答:
The error: Response for preflight has invalid HTTP status code 403 means you don't have access to post data to the server. This security policy is called as CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

Here you must have an API server. The server must allow requests from localhost:8083.

To allow such requests, you can add headers to apache configuration files:

I use following configuration in my apache config file:

```<code> Header add Access-Control-Allow-Origin "http://localhost:8083"
    Header add Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Requested-By, Access-Control-Request-Headers,withCredentials"
    Header add Access-Control-Allow-Methods "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
   Header add Access-Control-Allow-Credentials 'true'
</code>```

Edit: To add open your apache configuration file and add the above lines:

```<code><VirtualHost *:80>
    ......
    ......
    ......
    Header add Access-Control-Allow-Origin "http://localhost:8080"
    Header add Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Requested-By, Access-Control-Request-Headers,withCredentials"
    Header add Access-Control-Allow-Methods "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
   Header add Access-Control-Allow-Credentials 'true'
</VirtualHost>
</code>```

The path for the configuration file is: /etc/apache2/sites-available/000-default.conf, which might be different in your case.

ContentLicense: CC BY-SA 3.0

Title: Reactjs POST request through fetch

Body:
Hi i am trying reactjs POST request through fetch but getting two error's, I went through all docs but error is not solved.

Errors:

Failed to load http://localhost:8083/students: Response for preflight has invalid HTTP status code 403

Uncaught (in promise) TypeError: Failed to fetch

Here is my Reactjs code:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

fetch('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>

     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />

     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />

     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />

     <input type="submit" />

         </form>

   );
 }

}

Even though here my form values also hard-coded.

Body:
The error: Response for preflight has invalid HTTP status code 403 means you don't have access to post data to the server. This security policy is called as CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

Here you must have an API server. The server must allow requests from localhost:8083.

To allow such requests, you can add headers to apache configuration files:

I use following configuration in my apache config file:

 Header add Access-Control-Allow-Origin "http://localhost:8083"
    Header add Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Requested-By, Access-Control-Request-Headers,withCredentials"
    Header add Access-Control-Allow-Methods "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
   Header add Access-Control-Allow-Credentials 'true'

Edit: To add open your apache configuration file and add the above lines:

<VirtualHost *:80>
    ......
    ......
    ......
    Header add Access-Control-Allow-Origin "http://localhost:8080"
    Header add Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Requested-By, Access-Control-Request-Headers,withCredentials"
    Header add Access-Control-Allow-Methods "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
   Header add Access-Control-Allow-Credentials 'true'
</VirtualHost>

The path for the configuration file is: /etc/apache2/sites-available/000-default.conf, which might be different in your case.


问:
Http provider Error Ionic 3
I'm getting a error that I have no idea how to fix. I already search for solutions, but they didn't help me.

It's all about make a HTTP request using Ionic Native Http, both GET and POST.

The Error: It's look like I'm not setting the HTTP provider, but in the app.module.ts I'm importing it

```<code>    ERROR Error: Uncaught (in promise): Error: No provider for HTTP!
    Error: No provider for HTTP!
        at injectionError (vendor.js:1590)
        at noProviderError (vendor.js:1628)
        at ReflectiveInjector_._throwOrNull (vendor.js:3129)
        at ReflectiveInjector_._getByKeyDefault (vendor.js:3168)
        at ReflectiveInjector_._getByKey (vendor.js:3100)
        at ReflectiveInjector_.get (vendor.js:2969)
        at AppModuleInjector.get (ng:///AppModule/module.ngfactory.js:240)
        at AppModuleInjector.getInternal (ng:///AppModule/module.ngfactory.js:365)
        at AppModuleInjector.NgModuleInjector.get (vendor.js:3936)
        at resolveDep (vendor.js:11398)
        at injectionError (vendor.js:1590)
        at noProviderError (vendor.js:1628)
        at ReflectiveInjector_._throwOrNull (vendor.js:3129)
        at ReflectiveInjector_._getByKeyDefault (vendor.js:3168)
        at ReflectiveInjector_._getByKey (vendor.js:3100)
        at ReflectiveInjector_.get (vendor.js:2969)
        at AppModuleInjector.get (ng:///AppModule/module.ngfactory.js:240)
        at AppModuleInjector.getInternal (ng:///AppModule/module.ngfactory.js:365)
        at AppModuleInjector.NgModuleInjector.get (vendor.js:3936)
        at resolveDep (vendor.js:11398)
        at c (polyfills.js:3)
        at Object.reject (polyfills.js:3)
        at NavControllerBase._fireError (vendor.js:43003)
        at NavControllerBase._failed (vendor.js:42991)
        at vendor.js:43046
        at t.invoke (polyfills.js:3)
        at Object.onInvoke (vendor.js:4508)
        at t.invoke (polyfills.js:3)
        at r.run (polyfills.js:3)
        at polyfills.js:3
</code>```

The code:

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { CadastroPage } from '../pages/cadastro/cadastro';

import { ApiService } from '../services/api.service';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
    declarations: [
        MyApp,
        HomePage,
        ListPage,
        CadastroPage
    ],
    imports: [
        BrowserModule,
        HttpModule,
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
         entryComponents: [
         MyApp,
         HomePage,
         ListPage,
         CadastroPage
     ],
     providers: [
         ApiService,
         StatusBar,
         SplashScreen,
         {provide: ErrorHandler, useClass: IonicErrorHandler}
     ]
})
export class AppModule {}
</code>```

api.service.ts

```<code>import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http';

@Injectable()
export class ApiService {

    constructor (private http: HTTP) { }

    private apiUrl = '<VALID_URL>';

    get() {
        // Some OK http request here!
    }
}
</code>```

packaje.json

```<code>{
        "name": "app",
        "version": "0.0.1",
        "author": "Ionic Framework",
        "homepage": "http://ionicframework.com/",
        "private": true,
        "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
    },
        "dependencies": {
        "@angular/common": "4.1.3",
        "@angular/compiler": "4.1.3",
        "@angular/compiler-cli": "4.1.3",
        "@angular/core": "4.1.3",
        "@angular/forms": "4.1.3",
        "@angular/http": "4.1.3",
        "@angular/platform-browser": "4.1.3",
        "@angular/platform-browser-dynamic": "4.1.3",
        "@ionic-native/core": "3.12.1",
        "@ionic-native/http": "^4.1.0",
        "@ionic-native/splash-screen": "3.12.1",
        "@ionic-native/status-bar": "3.12.1",
        "@ionic/storage": "2.0.1",
        "cordova-android": "^6.2.3",
        "cordova-plugin-console": "1.0.5",
        "cordova-plugin-device": "1.1.4",
        "cordova-plugin-splashscreen": "~4.0.1",
        "cordova-plugin-statusbar": "2.2.2",
        "cordova-plugin-whitelist": "1.3.1",
        "ionic-angular": "3.5.3",
        "ionic-plugin-keyboard": "~2.2.1",
        "ionicons": "3.0.0",
        "rxjs": "5.4.0",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.12"
    },
        "devDependencies": {
        "@ionic/app-scripts": "2.0.2",
        "@ionic/cli-plugin-cordova": "1.5.0",
        "@ionic/cli-plugin-ionic-angular": "1.4.0",
        "ionic": "3.6.0",
        "typescript": "2.3.4"
    },
        "description": "An Ionic project",
        "cordova": {
            "plugins": {
                "cordova-plugin-console": {},
                "cordova-plugin-device": {},
                "cordova-plugin-splashscreen": {},
                "cordova-plugin-statusbar": {},
                "cordova-plugin-whitelist": {},
                "ionic-plugin-keyboard": {}
            },
            "platforms": [
                "android"
            ]
        }
    }
</code>```

答:
I Had the same error with ionic3. To solve this error, add HTTP in providers</p>

```<code>import { HTTP } from '@ionic-native/http';

...

providers: [
    StatusBar,
    SplashScreen,
    HTTP,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
]
</code>```

Title: Http provider Error Ionic 3

Body:
I'm getting a error that I have no idea how to fix. I already search for solutions, but they didn't help me.

It's all about make a HTTP request using Ionic Native Http, both GET and POST.

The Error: It's look like I'm not setting the HTTP provider, but in the app.module.ts I'm importing it

    ERROR Error: Uncaught (in promise): Error: No provider for HTTP!
    Error: No provider for HTTP!
        at injectionError (vendor.js:1590)
        at noProviderError (vendor.js:1628)
        at ReflectiveInjector_._throwOrNull (vendor.js:3129)
        at ReflectiveInjector_._getByKeyDefault (vendor.js:3168)
        at ReflectiveInjector_._getByKey (vendor.js:3100)
        at ReflectiveInjector_.get (vendor.js:2969)
        at AppModuleInjector.get (ng:///AppModule/module.ngfactory.js:240)
        at AppModuleInjector.getInternal (ng:///AppModule/module.ngfactory.js:365)
        at AppModuleInjector.NgModuleInjector.get (vendor.js:3936)
        at resolveDep (vendor.js:11398)
        at injectionError (vendor.js:1590)
        at noProviderError (vendor.js:1628)
        at ReflectiveInjector_._throwOrNull (vendor.js:3129)
        at ReflectiveInjector_._getByKeyDefault (vendor.js:3168)
        at ReflectiveInjector_._getByKey (vendor.js:3100)
        at ReflectiveInjector_.get (vendor.js:2969)
        at AppModuleInjector.get (ng:///AppModule/module.ngfactory.js:240)
        at AppModuleInjector.getInternal (ng:///AppModule/module.ngfactory.js:365)
        at AppModuleInjector.NgModuleInjector.get (vendor.js:3936)
        at resolveDep (vendor.js:11398)
        at c (polyfills.js:3)
        at Object.reject (polyfills.js:3)
        at NavControllerBase._fireError (vendor.js:43003)
        at NavControllerBase._failed (vendor.js:42991)
        at vendor.js:43046
        at t.invoke (polyfills.js:3)
        at Object.onInvoke (vendor.js:4508)
        at t.invoke (polyfills.js:3)
        at r.run (polyfills.js:3)
        at polyfills.js:3

The code:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { CadastroPage } from '../pages/cadastro/cadastro';

import { ApiService } from '../services/api.service';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
    declarations: [
        MyApp,
        HomePage,
        ListPage,
        CadastroPage
    ],
    imports: [
        BrowserModule,
        HttpModule,
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
         entryComponents: [
         MyApp,
         HomePage,
         ListPage,
         CadastroPage
     ],
     providers: [
         ApiService,
         StatusBar,
         SplashScreen,
         {provide: ErrorHandler, useClass: IonicErrorHandler}
     ]
})
export class AppModule {}

api.service.ts

import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http';

@Injectable()
export class ApiService {

    constructor (private http: HTTP) { }

    private apiUrl = '<VALID_URL>';

    get() {
        // Some OK http request here!
    }
}

packaje.json

{
        "name": "app",
        "version": "0.0.1",
        "author": "Ionic Framework",
        "homepage": "http://ionicframework.com/",
        "private": true,
        "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
    },
        "dependencies": {
        "@angular/common": "4.1.3",
        "@angular/compiler": "4.1.3",
        "@angular/compiler-cli": "4.1.3",
        "@angular/core": "4.1.3",
        "@angular/forms": "4.1.3",
        "@angular/http": "4.1.3",
        "@angular/platform-browser": "4.1.3",
        "@angular/platform-browser-dynamic": "4.1.3",
        "@ionic-native/core": "3.12.1",
        "@ionic-native/http": "^4.1.0",
        "@ionic-native/splash-screen": "3.12.1",
        "@ionic-native/status-bar": "3.12.1",
        "@ionic/storage": "2.0.1",
        "cordova-android": "^6.2.3",
        "cordova-plugin-console": "1.0.5",
        "cordova-plugin-device": "1.1.4",
        "cordova-plugin-splashscreen": "~4.0.1",
        "cordova-plugin-statusbar": "2.2.2",
        "cordova-plugin-whitelist": "1.3.1",
        "ionic-angular": "3.5.3",
        "ionic-plugin-keyboard": "~2.2.1",
        "ionicons": "3.0.0",
        "rxjs": "5.4.0",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.12"
    },
        "devDependencies": {
        "@ionic/app-scripts": "2.0.2",
        "@ionic/cli-plugin-cordova": "1.5.0",
        "@ionic/cli-plugin-ionic-angular": "1.4.0",
        "ionic": "3.6.0",
        "typescript": "2.3.4"
    },
        "description": "An Ionic project",
        "cordova": {
            "plugins": {
                "cordova-plugin-console": {},
                "cordova-plugin-device": {},
                "cordova-plugin-splashscreen": {},
                "cordova-plugin-statusbar": {},
                "cordova-plugin-whitelist": {},
                "ionic-plugin-keyboard": {}
            },
            "platforms": [
                "android"
            ]
        }
    }

Body:
I Had the same error with ionic3. To solve this error, add HTTP in providers

import { HTTP } from '@ionic-native/http';

...

providers: [
    StatusBar,
    SplashScreen,
    HTTP,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
]


问:
Bootstrap Navbar fixed on top, Container centered vertically
My page is very simple : it is made of a navbar, and two panels.

I am trying to get my navbar fixed on top, and the two panels vertically centered (for any screen size or browsers).

These two panels are placed in a container.

I have been unsuccessful in vertically centering the container so far.

Here is what I have now :

Here is what I want to achieve :

Here is my code :

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <nav class="navbar transparent navbar-static-top">

    <div class="navbar-header">
      <p>Welcome</p>
    </div>

  </nav>

  <div class="container d-flex h-100">

    <div class="row justify-content-center align-self-center">

      <!-- 1st panel -->
      <div class="col-md-4 mb-4" id="panel">

        <div class="panel panel-default1">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel body -->
        </div>
        <!-- panel-default1-->
      </div>
      <!-- col md 4 -->

      <!-- 2nd panel -->

      <div class="col-md-8 col-md-8" id="panel2">

        <div class="panel panel-default2">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel-body -->

        </div>
        <!-- panel-default2-->

      </div>
      <!-- col md 8 -->

    </div>
    <!-- row -->

  </div>
  <!-- container-->

</body></code>```

As you can see from the HTML, I have tried to use Bootstrap's flexbox on container and row, without success.

Please advise a working solution to vertically center my container, except the navbar.

答:
try this

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
  background:red;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
  background:green;
}
.navbar-header{
    float: none;
    padding: 20px;
    background:black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<body>

  <nav class="navbar transparent navbar-static-top text-center">

    <div class="navbar-header">
      <p>Welcome</p>
    </div>

  </nav>

  <div class="container">

    <div class="row">

      <!-- 1st panel -->
      <div class="col-md-4 mb-4" id="panel">

        <div class="panel panel-default1">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel body -->
        </div>
        <!-- panel-default1-->
      </div>
      <!-- col md 4 -->

      <!-- 2nd panel -->

      <div class="col-md-8 col-md-8" id="panel2">

        <div class="panel panel-default2">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel-body -->

        </div>
        <!-- panel-default2-->

      </div>
      <!-- col md 8 -->

    </div>
    <!-- row -->

  </div>
  <!-- container-->

</body></code>```

Body:
My page is very simple : it is made of a navbar, and two panels.

I am trying to get my navbar fixed on top, and the two panels vertically centered (for any screen size or browsers).

These two panels are placed in a container.

I have been unsuccessful in vertically centering the container so far.

Here is what I have now :

Here is what I want to achieve :

Here is my code :

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}

Welcome

Blablabla

Blablabla

As you can see from the HTML, I have tried to use Bootstrap's flexbox on container and row, without success.

Please advise a working solution to vertically center my container, except the navbar.

Body:
try this

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
  background:red;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
  background:green;
}
.navbar-header{
    float: none;
    padding: 20px;
    background:black;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<body>

  <nav class="navbar transparent navbar-static-top text-center">

    <div class="navbar-header">
      <p>Welcome</p>
    </div>

  </nav>

  <div class="container">

    <div class="row">

      <!-- 1st panel -->
      <div class="col-md-4 mb-4" id="panel">

        <div class="panel panel-default1">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel body -->
        </div>
        <!-- panel-default1-->
      </div>
      <!-- col md 4 -->

      <!-- 2nd panel -->

      <div class="col-md-8 col-md-8" id="panel2">

        <div class="panel panel-default2">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel-body -->

        </div>
        <!-- panel-default2-->

      </div>
      <!-- col md 8 -->

    </div>
    <!-- row -->

  </div>
  <!-- container-->

</body>


问:
Debugging django-allauth Social Network Login Failure
When using django-allauth to do an OAuth login via a social provider, sometimes it fails with the error page "Social Network Login Failure".  There is no log output containing more information.  There is a feature request for this log output (https://github.com/pennersr/django-allauth/issues/1120) but it has been open for over a year.  In the mean time, how do I get more information to debug this error?</p>

答:
When I was testing locally, my problem was two fold:
First, I had to make sure that I started the server using

```<code>python manage.py runserver localhost:8000
</code>```

Then, in the admin page I had to make sure the Sites table had an entry for localhost:8000, e.g. at

```<code>http://localhost:8000/en/admin/sites/site/
</code>```

The gotcha for me was that I'd had multiple attempts at this and the result was the the ID for my localhost:8000 Sites table entry had become greater than 1. You'll notice in the allauth documentation that is says to to have SITE_ID = 1 in the settings.py but if you inadvertently create a different ID for the entry, you'll have to either alter the database entry's ID or change SITE_ID value.

The other issue I had (unrelated to the poster's issue) was that I also had old registrations url template include interfering with the allauth ones.

Body:
When I was testing locally, my problem was two fold:
First, I had to make sure that I started the server using

python manage.py runserver localhost:8000

Then, in the admin page I had to make sure the Sites table had an entry for localhost:8000, e.g. at

http://localhost:8000/en/admin/sites/site/

The gotcha for me was that I'd had multiple attempts at this and the result was the the ID for my localhost:8000 Sites table entry had become greater than 1. You'll notice in the allauth documentation that is says to to have SITE_ID = 1 in the settings.py but if you inadvertently create a different ID for the entry, you'll have to either alter the database entry's ID or change SITE_ID value.

The other issue I had (unrelated to the poster's issue) was that I also had old registrations url template include interfering with the allauth ones.


问:
jQuery: resetting .animated divs position
I am using the following code to expand and center on div on :hover

```<code>    $(document).ready(function(){

    //animation on hover

        $('#sliding_grid li').hover(function() {
          $(this).addClass('highlight');
        }, function() {
          //$(this).removeClass('highlight');
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });
</code>```

My problem is two things:

1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut.  To see a working demo, go here:

http://jsfiddle.net/kTFvj/1/

2) The z-index (see here: http://jsfiddle.net/kTFvj/1/) is not affecting the :hovered grid elements.  Not sure why.

答:
You can use jQuerys .data method to store the original values and retrieve them on mouseout

I have made a modification to your original code that might work like you wish.. it uses .data and also updates the z-index so the active element is always on top

http://jsfiddle.net/kTFvj/2/

ContentLicense: CC BY-SA 2.5

Body:
I am using the following code to expand and center on div on :hover

    $(document).ready(function(){

    //animation on hover

        $('#sliding_grid li').hover(function() {
          $(this).addClass('highlight');
        }, function() {
          //$(this).removeClass('highlight');
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });

My problem is two things:

1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut.  To see a working demo, go here:

http://jsfiddle.net/kTFvj/1/

2) The z-index (see here: http://jsfiddle.net/kTFvj/1/) is not affecting the :hovered grid elements.  Not sure why.


问:
Xamarin.Android Projects failed to deploy in visual studio emulator for android
I'm using visual studio 2015 update 1 with windows 10 build 10586 TH1.

also I'm using Xamarin Version 4.0.1.96.

I have created a blank Xamarin.Forms app. It deploys to Windows Phone emulators without any issue. But unable to deploy to Android Emulators.

When I start android project Android Emulator launched successfully but visual studio freeze at this step.

I've tried a lot of android emulator profiles but cannot solve the problem.

This problem only exists for Emulators and project successfully deployed on physical android device.

I have the same issue with Xamarin.Android projects.

Here is all of the text in output window:

1>Starting deploy 4.5" KitKat (4.4) HDPI Phone ...

1>Starting emulator 4.5" KitKat (4.4) HDPI Phone ...

1>Validating emulator arguments...

1>Determining if emulator is already running...

1>Preparing virtual machine...

1>Launching emulator...

1>Emulator launched successfully

Thank you in advance for your help.

答:
I had the same issue. After a long struggle i fixed it.

Sol 1 :

Check with the registry as mentioned by others.

```<code> **HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools**
</code>```

Sol 2 :

In my case there is no android-SDK tool found in registry. So you have to add the registry manually here "**HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node**"

you can add it by right click on **Wow6432Node** => **New** => **key**.

Set Key name as **"Android SDK Tools"**then right click on **Android SDK Tools** =>**New** => **String Value**

Set Name as **Path** for newly added string. Then right click on **Path** => **Modify..**

Copy the Android SDK Tools path from program files and paste in Value Data.

Now the registry is created manually. You can debug the project via emulator.

Note : Don't forgot to restart the system.

Body:
I had the same issue. After a long struggle i fixed it.

Sol 1 :

Check with the registry as mentioned by others.

 **HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools**

Sol 2 :

In my case there is no android-SDK tool found in registry. So you have to add the registry manually here "**HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node**"

you can add it by right click on **Wow6432Node** => **New** => **key**.

Set Key name as **"Android SDK Tools"**then right click on **Android SDK Tools** =>**New** => **String Value**

Set Name as **Path** for newly added string. Then right click on **Path** => **Modify..**

Copy the Android SDK Tools path from program files and paste in Value Data.

Now the registry is created manually. You can debug the project via emulator.

Note : Don't forgot to restart the system.


问:
maven jaxb plugin, java packages generated has mis-match with XSD namespace
Background: I am trying to convert WSDL/XSD to Java classes

Issue: package names generated is mismatching with the namespace. Last part of number namespace is missing, below 02 is missing from package

XSD has - xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.02"

Java class generated - package iso.std.iso._20022.tech.xsd.pain_001_001;

Steps Taken:

I tried with 2 maven plugin, both gave me same results.

org.jvnet.jaxb2.maven2
maven-jaxb2-plugin

org.codehaus.mojo
jaxb2-maven-plugin

答:
This works as designed. See Section D.5.2 of the JAXB Specification.

Step 2 says:

Remove the trailing file type, one of .?? or .??? or .html.

Apparently, .02 is considered to be the "trailing file type" here and is removed.

Consider using bindings to specify the target package.


问:
Select rows which do not have duplicates
I have following SQL table:

```<code>+--------------+
| Account      |
+--------------+
|    11100011  |
|    11100012  |
|    11100013  |
|    11100014  |
|    11100011  |
|    11100012  |
|    11100015  |
+--------------+
</code>```

What I need is to make a select query with rows that do not have any duplicates in this table (i.e. removing both duplicated rows), so query result will look like this

```<code>+--------------+
| Account      |
+--------------+
|    11100013  |
|    11100014  |
|    11100015  |
+--------------+
</code>```

How can I do this in tsql?

答:
Try this,    </p>

```<code>select * from table_name group by account having count(*)<=1;
</code>```

Body:
I have following SQL table:

+--------------+
| Account      |
+--------------+
|    11100011  |
|    11100012  |
|    11100013  |
|    11100014  |
|    11100011  |
|    11100012  |
|    11100015  |
+--------------+

What I need is to make a select query with rows that do not have any duplicates in this table (i.e. removing both duplicated rows), so query result will look like this

+--------------+
| Account      |
+--------------+
|    11100013  |
|    11100014  |
|    11100015  |
+--------------+

How can I do this in tsql?

Body:
Try this,

select * from table_name group by account having count(*)<=1;


问:
How to write java script confirm popup box in spring MVC controller?
I am writing a file uploading program in spring mvc 3

This is my controller class

```<code>        package com.fss;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Controller
public class FileController {
 @Autowired
   ServletContext context;
 private static final String PATH="D:\\fdirct";

 public int isDuplicate(String file)
 {
     int i=0;
     File f = new File(PATH);
        String[] listOfFiles = f.list();

           for (int k = 0; k < listOfFiles.length; k++) {
                 if( file.equals(listOfFiles[k]))
                 {
                     i=1;
                 }
             }
                 return i;
 }

@RequestMapping("/toupload")
 public ModelAndView uploadFile(){
    return new ModelAndView("fileUpload");
 }

//uploading if not existing file
 @RequestMapping(value="savefile",method=RequestMethod.POST)
public ModelAndView uploadFile( @RequestParam CommonsMultipartFile file) throws Exception{

     int c=0;
     byte[] bytes = file.getBytes();
     String filename = file.getOriginalFilename();
      String message ="";
      String x="";

      if(file.isEmpty())
      {
          message="please select a file to upload ";
          ModelAndView mav=new ModelAndView("fileUpload","message",message);
          return mav;

      }
      else
      {
      //to check whether the file already exists
      c=isDuplicate(filename);

      if(c==1)
      {
           x="crosscheck";
      }
      else if(c==0)
      {
          x="fileUpload";
      }
      ModelAndView mav=new ModelAndView(x);

      //if file already exists
           if(c==1)
           {
              bytes.toString();
              String filecontent=new String(bytes);

                 mav.addObject("filename",filename);
                 mav.addObject("filecontent",filecontent);
                 mav.addObject("1",c);
        message="File already exists !! Do you want me to overwrite it ?";

                }

           //if file doesn't exists
           else if(c==0)
           {
                 File f1=new File(PATH + File.separator + filename);
                 FileOutputStream fos=new FileOutputStream(f1);
                 BufferedOutputStream bos =new BufferedOutputStream(fos);
                    bos.write(bytes);
                    bos.flush();
                    bos.close();
                    message="File successfully uploaded ";
           }
            mav.addObject("message", message);
            return mav;
      }

         }

 //crosschecking if exisitng file

 @RequestMapping(value="/saveagain",method = RequestMethod.POST)
 public ModelAndView fileUploading2(@ModelAttribute("choice") Choice choice) throws IOException{

     String ch="";
     String m="";
     ch=choice.getChoice();
     if(ch.equalsIgnoreCase("no"))
     {
         m="Upload suspended as requested by user ";
     }
     else if(ch.equalsIgnoreCase("yes"))
     {
        //System.out.println("In case of YES ");
         String filename=choice.getFname();
         String content=choice.getFcontent();

         File f1=new File(PATH+File.separator+filename);
         FileWriter fw=new FileWriter(f1);
         fw.write(content);
         fw.close();
        m ="File successfully uploaded by overwriting the existing file !";
     }

    return new ModelAndView("crosscheck","m",m);
 }
}
</code>```

In above code, i am checking if the file being uploaded is an existing file. If not, i am uploading the file. If it is an existing file, i am redirecting the control to a jsp page, asking the user to overwrite the file , and collecting the user choice in a html form.

jsp pages i used

fileUpload.jsp

```<code><%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>File Upload Example</title>
</head>
<body style="background-color:powderblue;color:Tomato">
<br>
<br>
<center><form:form action="savefile" method = "POST" modelAttribute = "fileUpload"
         enctype = "multipart/form-data">
         Please select a file to upload :
         <input type = "file" name = "file" /><br><br><br>
         <input type = "submit" value = "upload" />
         <input type = "reset" value = "Reset" />
      </form:form></center>
      <br>
      <br>
      <br>
      <center><b> ${message} </b></center>
      <br>
     <center> <a href="view">View files</a><br><br>
       <a href="uploadxml">Upload xml as text file</a>  <br><br>
<a href="uploadcsv">Upload CSV as text file</a>  <br><br>
<a href="uploadxls">Upload excel as text file</a>  <br><br>
<a href="deletefiles">Delete multiple files</a>
   </center>
   </body>
</html>
</code>```

crosscheck.jsp

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body style="background-color:powderblue;color:Tomato">
<center><form method="POST" action="saveagain">

   <center><h3>${message}(Say yes\no)</h3></center>
   <br>

          <input type="text" name="choice">
            <br><br>
            <input type="hidden" name="fname" value="${filename}">

              <input type="hidden" name="fcontent" value="${filecontent}">
     <input type="submit" value="submit" /> </form></center>
<br>
<br>
<center><b>${m}</b></center>
<br><br>
<center><a href="toupload">Click me to upload a file</a>  <br><br>
<a href="uploadxml">Upload xml as text file</a>  <br><br>
<a href="uploadcsv">Upload CSV as text file</a>  <br><br>
<a href="uploadxls">Upload excel as text file</a>  <br><br>
<a href="view">View files</a><br><br>
<a href="deletefiles">Delete multiple files</a></center>
</body>
</html>
</code>```

Instead of using a html form to know user's choice , how to use a javascript confirmation box ? In that if user selects OK, file should be overwritten else "Uploading suspended" message should be displayed. How and where to write the confirmation box ?

This is my bean class

```<code>  package com.fss;

    public class Choice {
    private boolean choice;
    private String fname;
    private String fcontent;

    public boolean isChoice() {
        return choice;
    }

    public void setChoice(boolean choice) {
        this.choice = choice;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getFcontent() {
        return fcontent;
    }

    public void setFcontent(String fcontent) {
        this.fcontent = fcontent;
    }

    }
</code>```

I am including my jsp page.

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function getChoice(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    return k;
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<center><form method="POST" action="saveagain">
<h3>${message} </h3>
            <br> <br>
<input type="hidden" name="fname" value="${filename}">
<input type="hidden" name="fcontent" value="${filecontent}"> <br><br>
 <input type="button" value="Overwrite ?" onclick="choice=getChoice()"/>
<input type="submit" value="Submit ?"></form></center>
<br>
<br>
<center><b>${m}</b></center>
<br><br>
<center><a href="toupload">Click me to upload a file</a>  <br><br>
<a href="uploadxml">Upload xml as text file</a>  <br><br>
<a href="uploadcsv">Upload CSV as text file</a>  <br><br>
<a href="uploadxls">Upload excel as text file</a>  <br><br>
<a href="view">View files</a><br><br>
<a href="deletefiles">Delete multiple files</a></center>
</body>
</html>
</code>```

How to set the bean variable "choice" to the result of the Confirm popup ?

答:
Try this

function myFunction() {
    var a = confirm("Press a button!");
    console.log(a)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="myFunction()">Try it</button></code>```

Body:
I am writing a file uploading program in spring mvc 3

This is my controller class

        package com.fss;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Controller
public class FileController {
 @Autowired
   ServletContext context;
 private static final String PATH="D:\\fdirct";

 public int isDuplicate(String file)
 {
     int i=0;
     File f = new File(PATH);
        String[] listOfFiles = f.list();

           for (int k = 0; k < listOfFiles.length; k++) {
                 if( file.equals(listOfFiles[k]))
                 {
                     i=1;
                 }
             }
                 return i;
 }

@RequestMapping("/toupload")
 public ModelAndView uploadFile(){
    return new ModelAndView("fileUpload");
 }

//uploading if not existing file
 @RequestMapping(value="savefile",method=RequestMethod.POST)
public ModelAndView uploadFile( @RequestParam CommonsMultipartFile file) throws Exception{

     int c=0;
     byte[] bytes = file.getBytes();
     String filename = file.getOriginalFilename();
      String message ="";
      String x="";

      if(file.isEmpty())
      {
          message="please select a file to upload ";
          ModelAndView mav=new ModelAndView("fileUpload","message",message);
          return mav;

      }
      else
      {
      //to check whether the file already exists
      c=isDuplicate(filename);

      if(c==1)
      {
           x="crosscheck";
      }
      else if(c==0)
      {
          x="fileUpload";
      }
      ModelAndView mav=new ModelAndView(x);

      //if file already exists
           if(c==1)
           {
              bytes.toString();
              String filecontent=new String(bytes);

                 mav.addObject("filename",filename);
                 mav.addObject("filecontent",filecontent);
                 mav.addObject("1",c);
        message="File already exists !! Do you want me to overwrite it ?";

                }

           //if file doesn't exists
           else if(c==0)
           {
                 File f1=new File(PATH + File.separator + filename);
                 FileOutputStream fos=new FileOutputStream(f1);
                 BufferedOutputStream bos =new BufferedOutputStream(fos);
                    bos.write(bytes);
                    bos.flush();
                    bos.close();
                    message="File successfully uploaded ";
           }
            mav.addObject("message", message);
            return mav;
      }

         }

 //crosschecking if exisitng file

 @RequestMapping(value="/saveagain",method = RequestMethod.POST)
 public ModelAndView fileUploading2(@ModelAttribute("choice") Choice choice) throws IOException{

     String ch="";
     String m="";
     ch=choice.getChoice();
     if(ch.equalsIgnoreCase("no"))
     {
         m="Upload suspended as requested by user ";
     }
     else if(ch.equalsIgnoreCase("yes"))
     {
        //System.out.println("In case of YES ");
         String filename=choice.getFname();
         String content=choice.getFcontent();

         File f1=new File(PATH+File.separator+filename);
         FileWriter fw=new FileWriter(f1);
         fw.write(content);
         fw.close();
        m ="File successfully uploaded by overwriting the existing file !";
     }

    return new ModelAndView("crosscheck","m",m);
 }
}

In above code, i am checking if the file being uploaded is an existing file. If not, i am uploading the file. If it is an existing file, i am redirecting the control to a jsp page, asking the user to overwrite the file , and collecting the user choice in a html form.

jsp pages i used

fileUpload.jsp

<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>File Upload Example</title>

<form:form action="savefile" method = "POST" modelAttribute = "fileUpload"
         enctype = "multipart/form-data">
         Please select a file to upload :
         <input type = "file" name = "file" />

         <input type = "submit" value = "upload" />
         <input type = "reset" value = "Reset" />
      </form:form>

       ${message}

      View files

       Upload xml as text file

Upload CSV as text file

Upload excel as text file

Delete multiple files

crosscheck.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form method="POST" action="saveagain">

${message}(Say yes\no)

          <input type="text" name="choice">

            <input type="hidden" name="fname" value="${filename}">

              <input type="hidden" name="fcontent" value="${filecontent}">
     <input type="submit" value="submit" /> </form>

${m}

Click me to upload a file

Upload xml as text file

Upload CSV as text file

Upload excel as text file

View files

Delete multiple files

Instead of using a html form to know user's choice , how to use a javascript confirmation box ? In that if user selects OK, file should be overwritten else "Uploading suspended" message should be displayed. How and where to write the confirmation box ?

This is my bean class

  package com.fss;

    public class Choice {
    private boolean choice;
    private String fname;
    private String fcontent;

    public boolean isChoice() {
        return choice;
    }

    public void setChoice(boolean choice) {
        this.choice = choice;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getFcontent() {
        return fcontent;
    }

    public void setFcontent(String fcontent) {
        this.fcontent = fcontent;
    }

    }

I am including my jsp page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form method="POST" action="saveagain">

${message}

<input type="hidden" name="fname" value="${filename}">
<input type="hidden" name="fcontent" value="${filecontent}">

 <input type="button" value="Overwrite ?" onclick="choice=getChoice()"/>
<input type="submit" value="Submit ?"></form>

${m}

Click me to upload a file

Upload xml as text file

Upload CSV as text file

Upload excel as text file

View files

Delete multiple files

How to set the bean variable "choice" to the result of the Confirm popup ?

Body:
Try this

function myFunction() {
    var a = confirm("Press a button!");
    console.log(a)
}

<button onclick="myFunction()">Try it</button>


问:
Opencart 2: Which method does admin --> index.php?route=api/order/add&token=xxx point to?
Where does:

admin --> index.php?route=api/order/add&token=xxx point to?

Which controller file, method will this call?

答: index.php?route=api/order/add&token=xxx points to   catalog\controller\api</p>


问:
Attributed String
a text that has some part with yellow backgroundI need some padding to left and right of yellow colored text and need the label "3" to be center..I am using attributed text for it.can anyone help me on this.Below is the code i am using.Attaching screenshot as well.</p>

```<code>string CardTileText = "3 Shared Documents";
NSAttributedString decoratedText = CardTileText.GetAttributedStringFromHtml("#ffe601","3");

  public static NSAttributedString GetAttributedStringFromHtml(this string source, UIColor color, string identifier)
        {
            var atts = new UIStringAttributes();
            UIFont newConnFont = UIFont.FromName("NotoSans-Bold", 16);
            NSRange range = GetRangeFor(source, identifier);
            NSNumber offset = 5;

            NSMutableParagraphStyle para = new NSMutableParagraphStyle
            {
                Alignment = UITextAlignment.Left
            };
            NSMutableAttributedString attributedString = new NSMutableAttributedString(source, atts);
            attributedString.AddAttribute(UIStringAttributeKey.BackgroundColor, color, range);
            attributedString.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Black, range);
            attributedString.AddAttribute(UIStringAttributeKey.Font, newConnFont, range);
            attributedString.AddAttribute(UIStringAttributeKey.KerningAdjustment, offset, range);
            attributedString.AddAttribute(UIStringAttributeKey.ParagraphStyle, para, range);

            return attributedString;
        }

        static NSRange GetRangeFor(string source, string substring)
        {
            var range = new NSRange
            {
                Location = source.IndexOf(substring, StringComparison.Ordinal),
                Length = substring.Length
            };
            return range;
        }
</code>```

答:
I'm afraid the only solution is that set offset(which is used on KerningAdjustment) with a proper value.

Here is the comparison

offset = 0.5

offset = 10

Title: Attributed String

Body:
a text that has some part with yellow backgroundI need some padding to left and right of yellow colored text and need the label "3" to be center..I am using attributed text for it.can anyone help me on this.Below is the code i am using.Attaching screenshot as well.

string CardTileText = "3 Shared Documents";
NSAttributedString decoratedText = CardTileText.GetAttributedStringFromHtml("#ffe601","3");

  public static NSAttributedString GetAttributedStringFromHtml(this string source, UIColor color, string identifier)
        {
            var atts = new UIStringAttributes();
            UIFont newConnFont = UIFont.FromName("NotoSans-Bold", 16);
            NSRange range = GetRangeFor(source, identifier);
            NSNumber offset = 5;

            NSMutableParagraphStyle para = new NSMutableParagraphStyle
            {
                Alignment = UITextAlignment.Left
            };
            NSMutableAttributedString attributedString = new NSMutableAttributedString(source, atts);
            attributedString.AddAttribute(UIStringAttributeKey.BackgroundColor, color, range);
            attributedString.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Black, range);
            attributedString.AddAttribute(UIStringAttributeKey.Font, newConnFont, range);
            attributedString.AddAttribute(UIStringAttributeKey.KerningAdjustment, offset, range);
            attributedString.AddAttribute(UIStringAttributeKey.ParagraphStyle, para, range);

            return attributedString;
        }

        static NSRange GetRangeFor(string source, string substring)
        {
            var range = new NSRange
            {
                Location = source.IndexOf(substring, StringComparison.Ordinal),
                Length = substring.Length
            };
            return range;
        }


问:
0 results in MS Access totals query (w. COUNT) after applying criteria
A query I am working on is showing a rather interesting behaviour that I couldn't debug so far.
This is the query before it gets buggy:

QryCount

```<code>SELECT EmpId, [Open/Close], Count([Open/Close]) AS Occurences, Attribute1, Market, Tier, Attribute2, MtSWeek
FROM qrySource
WHERE (Venue="NewYork") AND (Type="TypeA")
GROUP BY EmpId, [Open/Close], Attribute1, Market, Tier, Attribute2, MtSWeek;
</code>```

The query gives precisely the results that I would expect it to:

```<code>#01542 | Open   | 5 | Call | English | Tier1 | Complain | 01/01/2017
#01542 | Closed | 2 | Call | English | Tier2 | ProdInfo | 01/01/2017
#01542 | Open   | 7 | Mail | English | Tier1 | ProdInfo | 08/01/2017
etc...
</code>```

But as a matter of fact in doing so it provides more records than needed at a subsequent step thereby creating cartesians.

qrySource.[Open/Close] is a string type field with possible attributes (you guessed) "open", "Closed" and null and it is actually provided by a mapping table at the creation stage of qrySource (not sure, but maybe this helps).

Now, the error comes in when I try to limit qryCount only to records where Open/Close = "Open".
I tried both using WHERE and HAVING to no avail. The query would result in 0 records, which is not what I would like to see.
I thought that maybe it is because "open" is a reserved term, but even by changing it to "D_open" in the source table didn't fix the issue.
Also tried to filter for the desired records in a subsequent query

```<code>SELECT *
FROM QryCount
WHERE [Open/Close] ="D_Open"
</code>```

But nothing, still 0 records found.

I am suspicious it might be somehow related to some inherent proprieties of the COUNT function but not sure. Any help would be appreciated.

答:
Everyone who participated, thank you and apologies for providing you with insufficient/confusing information. I recon the question could have been drafted better.

Anyhow, I found that the problem was apparently caused by the "/" in the Open/Closed field name. As soon as I removed it from the field name in the original mapping table the query performed as expected.

Body:
A query I am working on is showing a rather interesting behaviour that I couldn't debug so far.
This is the query before it gets buggy:

QryCount

SELECT EmpId, [Open/Close], Count([Open/Close]) AS Occurences, Attribute1, Market, Tier, Attribute2, MtSWeek
FROM qrySource
WHERE (Venue="NewYork") AND (Type="TypeA")
GROUP BY EmpId, [Open/Close], Attribute1, Market, Tier, Attribute2, MtSWeek;

The query gives precisely the results that I would expect it to:

#01542 | Open   | 5 | Call | English | Tier1 | Complain | 01/01/2017
#01542 | Closed | 2 | Call | English | Tier2 | ProdInfo | 01/01/2017
#01542 | Open   | 7 | Mail | English | Tier1 | ProdInfo | 08/01/2017
etc...

But as a matter of fact in doing so it provides more records than needed at a subsequent step thereby creating cartesians.

qrySource.[Open/Close] is a string type field with possible attributes (you guessed) "open", "Closed" and null and it is actually provided by a mapping table at the creation stage of qrySource (not sure, but maybe this helps).

Now, the error comes in when I try to limit qryCount only to records where Open/Close = "Open".
I tried both using WHERE and HAVING to no avail. The query would result in 0 records, which is not what I would like to see.
I thought that maybe it is because "open" is a reserved term, but even by changing it to "D_open" in the source table didn't fix the issue.
Also tried to filter for the desired records in a subsequent query

SELECT *
FROM QryCount
WHERE [Open/Close] ="D_Open"

But nothing, still 0 records found.

I am suspicious it might be somehow related to some inherent proprieties of the COUNT function but not sure. Any help would be appreciated.


问:
Is there a JavaScript MVC (micro-)framework?
Are there any client-side JavaScript MVC (micro-)frameworks?

I have a rather complicated HTML form, and it would benefit from the MVC pattern.

I imagine a good solution would provide the following:

Model and View update the Controller when values change (Observer pattern)

Populate the model from the form data when the page loads

Populate the form from the model when the model changes

Ajax, comet, JSONP and all that jazz are serious overkill.

答: Maverick is a small JavaScript MVC framework — http://maverick.round.ee</p>

OwnerDisplayName: nicholaides

LastEditorDisplayName: nicholaides


问:
Subtract two columns of in ruby
I Have a Table User

```<code>Id Name    offered  used

1  John     10       8
2  michel   2        2
</code>```

Sql Query

```<code>select offered-used from Users where id=1

result = 2
</code>```

I required the same query in ruby

答:
If you are using Active Record you can do this:</p>

```<code>> user = User.find(1)
> user_offered = user.offered
  result will be 10
> user_used = user.used
  result will be 8
> output = user_offered - user_used
  will result 2
</code>```

Title: Subtract two columns of in ruby

Body:
I Have a Table User

Id Name    offered  used

1  John     10       8
2  michel   2        2

Sql Query

select offered-used from Users where id=1

result = 2

I required the same query in ruby

Body:
If you are using Active Record you can do this:

> user = User.find(1)
> user_offered = user.offered
  result will be 10
> user_used = user.used
  result will be 8
> output = user_offered - user_used
  will result 2


问:
VBA - Unable to close excel
I'm new to VBA, I had this simple code that cause some cells to be mandatory and highlight the cells if they are empty when the workbook is opened. However, I'm unable to close my excel with the codes I have. Can anyone please tell me why?</p>

```<code>Private Sub Workbook_BeforeClose(Cancel As Boolean)
        If Cells(2, 6).Value = "" Then
            MsgBox "Cell F2 requires user input", vbInformation, "Please filled up the mandatory cells"
        ElseIf Cells(2, 9).Value = "" Then
            MsgBox "Cell I2 requires user input", vbInformation, "Please filled up the mandatory cells"
        ElseIf Cells(4, 4).Value = "" Then
            MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells"
        End If
        Cancel = True
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
        If Cells(2, 6).Value = "" Then
            MsgBox "Cell F2 requires user input", vbInformation, "Please filled up the mandatory cells"
        ElseIf Cells(2, 9).Value = "" Then
            MsgBox "Cell I2 requires user input", vbInformation, "Please filled up the mandatory cells"
        ElseIf Cells(4, 4).Value = "" Then
            MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells"
        End If
        Cancel = True
End Sub

    Private Sub Workbook_Open()
    If Cells(2, 6).Value = "" Then
            Range("F2").Interior.ColorIndex = 6
    ElseIf Cells(2, 9).Value = "" Then
            Range("I2").Interior.ColorIndex = 6
    ElseIf Cells(4, 4).Value = "" Then
            Range("D4").Interior.ColorIndex = 6
    End If
End Sub
</code>```

答:
the cancel = true at the end of the sub cancels the exit process, so the workbook stays open

try this

```<code>Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim aaa As Variant
    For Each aaa In Array("F2", "I2", "D4")
        If Range(aaa).Value = "" Then
            MsgBox "Cell " & aaa & " requires user input", vbInformation, "Please filled up the mandatory cells"
            Cancel = True
            Exit Sub
        End If
    Next aaa
    Cancel = False
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim aaa As Variant
    For Each aaa In Array("F2", "I2", "D4")
        If Range(aaa).Value = "" Then
            MsgBox "Cell " & aaa & " requires user input", vbInformation, "Please filled up the mandatory cells"
            Cancel = True
            Exit Sub
        End If
    Next aaa
    Cancel = False
End Sub

Private Sub Workbook_Open()
    Dim aaa As Variant
    For Each aaa In Array("F2", "I2", "D4")
        If Range(aaa).Value = "" Then Range(aaa).Interior.ColorIndex = 6
    Next aaa
End Sub
</code>```

Title: VBA - Unable to close excel

Body:
I'm new to VBA, I had this simple code that cause some cells to be mandatory and highlight the cells if they are empty when the workbook is opened. However, I'm unable to close my excel with the codes I have. Can anyone please tell me why?

Private Sub Workbook_BeforeClose(Cancel As Boolean)
        If Cells(2, 6).Value = "" Then
            MsgBox "Cell F2 requires user input", vbInformation, "Please filled up the mandatory cells"
        ElseIf Cells(2, 9).Value = "" Then
            MsgBox "Cell I2 requires user input", vbInformation, "Please filled up the mandatory cells"
        ElseIf Cells(4, 4).Value = "" Then
            MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells"
        End If
        Cancel = True
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
        If Cells(2, 6).Value = "" Then
            MsgBox "Cell F2 requires user input", vbInformation, "Please filled up the mandatory cells"
        ElseIf Cells(2, 9).Value = "" Then
            MsgBox "Cell I2 requires user input", vbInformation, "Please filled up the mandatory cells"
        ElseIf Cells(4, 4).Value = "" Then
            MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells"
        End If
        Cancel = True
End Sub

    Private Sub Workbook_Open()
    If Cells(2, 6).Value = "" Then
            Range("F2").Interior.ColorIndex = 6
    ElseIf Cells(2, 9).Value = "" Then
            Range("I2").Interior.ColorIndex = 6
    ElseIf Cells(4, 4).Value = "" Then
            Range("D4").Interior.ColorIndex = 6
    End If
End Sub

Body:
the cancel = true at the end of the sub cancels the exit process, so the workbook stays open

try this

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim aaa As Variant
    For Each aaa In Array("F2", "I2", "D4")
        If Range(aaa).Value = "" Then
            MsgBox "Cell " & aaa & " requires user input", vbInformation, "Please filled up the mandatory cells"
            Cancel = True
            Exit Sub
        End If
    Next aaa
    Cancel = False
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim aaa As Variant
    For Each aaa In Array("F2", "I2", "D4")
        If Range(aaa).Value = "" Then
            MsgBox "Cell " & aaa & " requires user input", vbInformation, "Please filled up the mandatory cells"
            Cancel = True
            Exit Sub
        End If
    Next aaa
    Cancel = False
End Sub

Private Sub Workbook_Open()
    Dim aaa As Variant
    For Each aaa In Array("F2", "I2", "D4")
        If Range(aaa).Value = "" Then Range(aaa).Interior.ColorIndex = 6
    Next aaa
End Sub


答:
1-  Response for preflight has invalid HTTP status code 403, means that you need to send the authorization token in header (it's commented out)

2- Uncaught (in promise) TypeError: Failed to fetch means the the server is not sending a respose with JSON format then  response.json() is throwing an exception.

Title: Reactjs POST request through fetch

Body:
Hi i am trying reactjs POST request through fetch but getting two error's, I went through all docs but error is not solved.

Errors:

Failed to load http://localhost:8083/students: Response for preflight has invalid HTTP status code 403

Uncaught (in promise) TypeError: Failed to fetch

Here is my Reactjs code:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

fetch('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>

     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />

     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />

     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />

     <input type="submit" />

         </form>

   );
 }

}

Even though here my form values also hard-coded.


问:
Finite loop in Go routine
I am trying to execute two or more go routine synchronously after finish the topic

goroutines order of execution

And I write some code to test the go routines' behaviour
(I treat it like a queue, BTW the go concurrency tutorial page not really help me)

```<code>package main

import (
        "fmt"
        "sync"
)

const size = 10
var vChan chan int = make(chan int, size)

func justSend(wg *sync.WaitGroup) {
        defer wg.Done()
        for i := 1; i <= 10; i++ {
                vChan <- i
        }
}

func justPrint(wg *sync.WaitGroup) {
        defer wg.Done()
        v := <- vChan
        fmt.Printf("%4d ", v);
}

func main() {
        wg := new(sync.WaitGroup)

        go func() {
                wg.Add(1)
                go justSend(wg)
                wg.Wait()
                wg.Add(size)
                go justPrint(wg)
                wg.Wait()
                close(vChan)
        }()
}
</code>```

But it print nothing, should we design a go routine always have a infinite loop in there or we can't get it work properly?

(The piece of code is prepared for my real problem on building multiple websocket connection and testing our API server's response, so...I think passing bunch of channel which has same type between different function is quite annoying, so I set it globally)

答:
No, don't use  infinite loop.
Synchronization is better done with channels or the facilities of the sync package.  The main() is a goroutine too (main one), so if main exits before other goroutines, your task remains unfinished.
One way is to use sync.WaitGroup to wait for other goroutines to finish (see examples 1,2 and 3). Another way is using channels to wait for other goroutines to finish (see examples 4 and 5). I provide some examples so you may choose which one fits to your case:

1- One tx and multi rx (leave channel open), Try this:

```<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    go tx()
    wg.Add(20)
    for i := 1; i <= 20; i++ {
        go rx()
    }
    wg.Wait()
}

func tx() {
    for i := 1; i <= 20; i++ {
        vChan <- i
    }
}

func rx() {
    defer wg.Done()
    fmt.Println(<-vChan)
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)
</code>```

2- One tx and one rx (leave channel open), Try this:

```<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    go tx()
    wg.Add(1)
    go rx()
    wg.Wait()
}

func tx() {
    for i := 1; i <= 20; i++ {
        vChan <- i
    }
}

func rx() {
    defer wg.Done()
    for i := 1; i <= 20; i++ {
        fmt.Println(<-vChan)
    }
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)
</code>```

3- Closing channel to signal end of tx, Try this:

```<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    go tx()
    wg.Add(1)
    go rx()
    wg.Wait()
}

func tx() {
    for i := 1; i <= 5; i++ {
        vChan <- i
    }
    close(vChan)
}

func rx() {
    defer wg.Done()
    for v := range vChan {
        fmt.Println(v)
    }
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)
</code>```

4- Closing channel to signal end of tx, using main goroutine for rx, try this:

```<code>package main

import (
    "fmt"
)

func main() {
    go tx()
    for v := range vChan {
        fmt.Println(v)
    }
}

func tx() {
    for i := 1; i <= 20; i++ {
        vChan <- i
    }
    close(vChan)
}

var vChan = make(chan int, 10)
</code>```

5- Using quit channel, try this:

```<code>package main

import (
    "fmt"
)

func main() {
    go tx()
    go rx()
    <-quit
}
func rx() {
    for v := range vChan {
        fmt.Println(v)
    }
    quit <- struct{}{}
}
func tx() {
    for i := 10; i <= 15; i++ {
        vChan <- i
    }
    close(vChan)
}

var quit = make(chan struct{}, 1)
var vChan = make(chan int, 10)
</code>```

output:

```<code>10
11
12
13
14
15
</code>```

6- Multi tx multi rx, try this:

```<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    wg.Add(5)
    for i := 1; i <= 5; i++ {
        go tx()
        go rx()
    }
    wg.Wait()
}

var n = 10

func tx() {
    vChan <- n
    n++
}

func rx() {
    defer wg.Done()
    fmt.Println(<-vChan)
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)
</code>```

7- Multi tx and one rx, try this:

```<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go tx()
    }

    go rx()
    wg.Wait()
}

func rx() {
    for {
        fmt.Println(<-vChan)
        wg.Done()
    }
}

var n = 20

func tx() {
    vChan <- n
    n++
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)
</code>```

I hope this helps.

Title: Finite loop in Go routine

Body:
I am trying to execute two or more go routine synchronously after finish the topic

goroutines order of execution

And I write some code to test the go routines' behaviour
(I treat it like a queue, BTW the go concurrency tutorial page not really help me)

package main

import (
        "fmt"
        "sync"
)

const size = 10
var vChan chan int = make(chan int, size)

func justSend(wg *sync.WaitGroup) {
        defer wg.Done()
        for i := 1; i <= 10; i++ {
                vChan <- i
        }
}

func justPrint(wg *sync.WaitGroup) {
        defer wg.Done()
        v := <- vChan
        fmt.Printf("%4d ", v);
}

func main() {
        wg := new(sync.WaitGroup)

        go func() {
                wg.Add(1)
                go justSend(wg)
                wg.Wait()
                wg.Add(size)
                go justPrint(wg)
                wg.Wait()
                close(vChan)
        }()
}

But it print nothing, should we design a go routine always have a infinite loop in there or we can't get it work properly?

(The piece of code is prepared for my real problem on building multiple websocket connection and testing our API server's response, so...I think passing bunch of channel which has same type between different function is quite annoying, so I set it globally)

Body:
No, don't use  infinite loop.
Synchronization is better done with channels or the facilities of the sync package.  The main() is a goroutine too (main one), so if main exits before other goroutines, your task remains unfinished.
One way is to use sync.WaitGroup to wait for other goroutines to finish (see examples 1,2 and 3). Another way is using channels to wait for other goroutines to finish (see examples 4 and 5). I provide some examples so you may choose which one fits to your case:

1- One tx and multi rx (leave channel open), Try this:

package main

import (
    "fmt"
    "sync"
)

func main() {
    go tx()
    wg.Add(20)
    for i := 1; i <= 20; i++ {
        go rx()
    }
    wg.Wait()
}

func tx() {
    for i := 1; i <= 20; i++ {
        vChan <- i
    }
}

func rx() {
    defer wg.Done()
    fmt.Println(<-vChan)
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)

2- One tx and one rx (leave channel open), Try this:

package main

import (
    "fmt"
    "sync"
)

func main() {
    go tx()
    wg.Add(1)
    go rx()
    wg.Wait()
}

func tx() {
    for i := 1; i <= 20; i++ {
        vChan <- i
    }
}

func rx() {
    defer wg.Done()
    for i := 1; i <= 20; i++ {
        fmt.Println(<-vChan)
    }
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)

3- Closing channel to signal end of tx, Try this:

package main

import (
    "fmt"
    "sync"
)

func main() {
    go tx()
    wg.Add(1)
    go rx()
    wg.Wait()
}

func tx() {
    for i := 1; i <= 5; i++ {
        vChan <- i
    }
    close(vChan)
}

func rx() {
    defer wg.Done()
    for v := range vChan {
        fmt.Println(v)
    }
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)

4- Closing channel to signal end of tx, using main goroutine for rx, try this:

package main

import (
    "fmt"
)

func main() {
    go tx()
    for v := range vChan {
        fmt.Println(v)
    }
}

func tx() {
    for i := 1; i <= 20; i++ {
        vChan <- i
    }
    close(vChan)
}

var vChan = make(chan int, 10)

5- Using quit channel, try this:

package main

import (
    "fmt"
)

func main() {
    go tx()
    go rx()
    <-quit
}
func rx() {
    for v := range vChan {
        fmt.Println(v)
    }
    quit <- struct{}{}
}
func tx() {
    for i := 10; i <= 15; i++ {
        vChan <- i
    }
    close(vChan)
}

var quit = make(chan struct{}, 1)
var vChan = make(chan int, 10)

output:

10
11
12
13
14
15

6- Multi tx multi rx, try this:

package main

import (
    "fmt"
    "sync"
)

func main() {
    wg.Add(5)
    for i := 1; i <= 5; i++ {
        go tx()
        go rx()
    }
    wg.Wait()
}

var n = 10

func tx() {
    vChan <- n
    n++
}

func rx() {
    defer wg.Done()
    fmt.Println(<-vChan)
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)

7- Multi tx and one rx, try this:

package main

import (
    "fmt"
    "sync"
)

func main() {
    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go tx()
    }

    go rx()
    wg.Wait()
}

func rx() {
    for {
        fmt.Println(<-vChan)
        wg.Done()
    }
}

var n = 20

func tx() {
    vChan <- n
    n++
}

var wg sync.WaitGroup

var vChan = make(chan int, 10)

I hope this helps.


问:
MyBase (base) Object Property not showing actual value in the debugger
So I get a paniced IM from a coworker saying this if statement is skipping when

```<code>If true Then
    DoSomething
End IF
</code>```

The actual code being

```<code>If MyBase.IsDirty Then
    DoSomething
End IF
</code>```

C# Version

```<code>if(base.IsDirty)
{
    DoSomething();
}
</code>```

My first question to them was well the If statement isn't magically broken so are you sure MyBase.IsDirty is actually true? They responded 'Yes OF COURSE!'. Upon asking them how they determined this they said they were putting a breakpoint at the line and hovering over MyBase.IsDirty to see what the value was and that they had also done ?MyBase.IsDirty in the immediate window. My initial thought and what I am thinking to still be correct is due to the way that base classes function that it wasn't actually showing the value at in those cases (at least the correct one) so I suggested doing

Dim dirty As Boolean = MyBase.IsDirty

Then running the code again, which showed as I guessed that dirty was actually false.

Now why is this the case? As far as I can tell it has something to do with the way that MyBase is implemented but I want specifics so I can have a 100% answer to this.

Edit

Right so MyBase.IsDirty is a Boolean

The Get is done as Follows:

```<code><Browsable(False)> _
    Public Overridable ReadOnly Property IsDirty() As Boolean Implements IEditableBusinessObject.IsDirty
      Get
        Return IsSelfDirty OrElse (_fieldManager IsNot Nothing AndAlso FieldManager.IsDirty())
      End Get
    End Property
</code>```

Where

```<code><Browsable(False)> _
    Public Overridable ReadOnly Property IsSelfDirty() As Boolean Implements IEditableBusinessObject.IsSelfDirty
      Get
        Return _isDirty
      End Get
    End Property
</code>```

And

_isDirty is Initialized as true

(Field Manager is a non issue for this case).

I should note that this is all taken from CSLA 3.5.3.0

Another Edit

I'm calling MyBase.IsDirty because that is the way that Rocky Lhotka shows it being done in his books on CSLA.

答:
The debugger can't evaluate expressions using the base (or MyBase in VB) keyword correctly because the debugging API doesn't support non virtual calls. It returns the value a virtual call to the getter returns instead of the one the getter in the base class returns. So the effect you're observing is a debugger problem.

I guess you overrode the property in the derived class and return false there, and that's what the debugger shows. The compiled code itself will handle the base. call correctly.

The MSDN blog entry "Debugger won't properly evaluate C#s base keyword" describes this problem in detail

Body:
So I get a paniced IM from a coworker saying this if statement is skipping when

If true Then
    DoSomething
End IF

The actual code being

If MyBase.IsDirty Then
    DoSomething
End IF

C# Version

if(base.IsDirty)
{
    DoSomething();
}

My first question to them was well the If statement isn't magically broken so are you sure MyBase.IsDirty is actually true? They responded 'Yes OF COURSE!'. Upon asking them how they determined this they said they were putting a breakpoint at the line and hovering over MyBase.IsDirty to see what the value was and that they had also done ?MyBase.IsDirty in the immediate window. My initial thought and what I am thinking to still be correct is due to the way that base classes function that it wasn't actually showing the value at in those cases (at least the correct one) so I suggested doing

Dim dirty As Boolean = MyBase.IsDirty

Then running the code again, which showed as I guessed that dirty was actually false.

Now why is this the case? As far as I can tell it has something to do with the way that MyBase is implemented but I want specifics so I can have a 100% answer to this.

Edit

Right so MyBase.IsDirty is a Boolean

The Get is done as Follows:

<Browsable(False)> _
    Public Overridable ReadOnly Property IsDirty() As Boolean Implements IEditableBusinessObject.IsDirty
      Get
        Return IsSelfDirty OrElse (_fieldManager IsNot Nothing AndAlso FieldManager.IsDirty())
      End Get
    End Property

Where

<Browsable(False)> _
    Public Overridable ReadOnly Property IsSelfDirty() As Boolean Implements IEditableBusinessObject.IsSelfDirty
      Get
        Return _isDirty
      End Get
    End Property

And

_isDirty is Initialized as true

(Field Manager is a non issue for this case).

I should note that this is all taken from CSLA 3.5.3.0

Another Edit

I'm calling MyBase.IsDirty because that is the way that Rocky Lhotka shows it being done in his books on CSLA.


问:
How remove .php extension from codeigniter?
My link show this:

```<code>http://localhost/project/index.php
</code>```

I want this:

```<code>http://localhost/project/
</code>```

Do not display extension

答:
CodeIgniter provide Routing rules/URI Routing for this.

You can achive this by adding variable to $route array in

/application/config/routes.php file

```<code>$old_path = 'home/about'; // no need to add .php to about

$new_path='home/about'; //or about or any other name you want

$route[$new_path] =$old_path;
</code>```

Now you can visit page by only

http://localhost/project/home/about

For more details :-

https://www.codeigniter.com/user_guide/general/routing.html?highlight=route

Body:
My link show this:

http://localhost/project/index.php

I want this:

http://localhost/project/

Do not display extension

Body:
CodeIgniter provide Routing rules/URI Routing for this.

You can achive this by adding variable to $route array in

/application/config/routes.php file

$old_path = 'home/about'; // no need to add .php to about

$new_path='home/about'; //or about or any other name you want

$route[$new_path] =$old_path;

Now you can visit page by only

http://localhost/project/home/about

For more details :-

https://www.codeigniter.com/user_guide/general/routing.html?highlight=route


问:
can not understand the result of np.where(array1==array2)
I have a code below:

```<code>import numpy as np
a=np.array([[0., 4., 1.0],[2., 3., 2.0]])
argm=a.argmax(axis=0)
m=a[argm,np.arange(3)]
print (np.where(a == m))
</code>```

I can not understand the result:

```<code>(array([0, 1, 1], dtype=int64), array([1, 0, 2], dtype=int64))
</code>```

anyone can explain it?
thank you very much!!

答:
Your a and m arrays look like this:

```<code>In [2]: a
Out[2]:
array([[ 0.,  4.,  1.],
       [ 2.,  3.,  2.]])

In [5]: m
Out[5]: array([ 2.,  4.,  2.])
</code>```

This is the result of a == m:

```<code>In [7]: a == m
Out[7]:
array([[False,  True, False],
       [ True, False,  True]], dtype=bool)
</code>```

You can think of the result of np.where(a==m) as returning pairs of coordinates: the first True it located is in row 0 (as seen in the first returned array), column 1 (per the second one), as you can verify for yourself. The second one is in row 1, column 0. Likewise for the third one.

Is that clear enough?

You may also want to look at the docs for numpy.nonzero, which is what numpy.where collapses to when given a single argument.

Body:
I have a code below:

import numpy as np
a=np.array([[0., 4., 1.0],[2., 3., 2.0]])
argm=a.argmax(axis=0)
m=a[argm,np.arange(3)]
print (np.where(a == m))

I can not understand the result:

(array([0, 1, 1], dtype=int64), array([1, 0, 2], dtype=int64))

anyone can explain it?
thank you very much!!

Body:
Your a and m arrays look like this:

In [2]: a
Out[2]:
array([[ 0.,  4.,  1.],
       [ 2.,  3.,  2.]])

In [5]: m
Out[5]: array([ 2.,  4.,  2.])

This is the result of a == m:

In [7]: a == m
Out[7]:
array([[False,  True, False],
       [ True, False,  True]], dtype=bool)

You can think of the result of np.where(a==m) as returning pairs of coordinates: the first True it located is in row 0 (as seen in the first returned array), column 1 (per the second one), as you can verify for yourself. The second one is in row 1, column 0. Likewise for the third one.

Is that clear enough?

You may also want to look at the docs for numpy.nonzero, which is what numpy.where collapses to when given a single argument.