问:
How to call Cordova plugin using Angular without Ionic
I built a PWA in Angular 6 and was intending to use the Google Maps API for geolocation purposes.  However, I soon realized that the geolocation services in a PWA only work when the user is interacting with the UI to deliberately request their location.  My app is supposed to track the user's location in the background as they drive around, however.  So when they lock the screen or go to a different application it should still track them.  For the record, this is a private application and users are fully aware that they are being tracked.  As a result, I converted the PWA to a hybrid app using Cordova.  Everything works so far with what I had already (emulation is fine, etc), but I can't seem to figure out how to add the geolocation piece.  I have installed this plugin, which appears to be installed and available.  All of the examples I have seen use Ionic (which I don't need at this point) and are for the scenario where the user clicks a button to get their location, but I need it where the geolocation stuff is in a service and starts running in the background after they are logged in.  I can't seem to find something that shows how to do this.  Here's what I was thinking I should do:

(this isn't complete, I just pasted the example code from GitHub here and intend to fill it in with "stuff" when I know it's actually being called)

_services/geolocation.service.ts:

```<code>import { Injectable } from '@angular/core';
import { Component, ViewChild } from '@angular/core';

declare var cordova: any;

@Injectable()
export class GeolocationService {
  startBackgroundGeolocation() {
    console.log("Geolocation service called...");
    cordova.plugins.BackgroundGeolocation.configure({
      locationProvider: cordova.plugins.BackgroundGeolocation.ACTIVITY_PROVIDER,
      desiredAccuracy: cordova.plugins.BackgroundGeolocation.HIGH_ACCURACY,
      stationaryRadius: 50,
      distanceFilter: 50,
      notificationTitle: 'Background tracking',
      notificationText: 'enabled',
      debug: true,
      interval: 10000,
      fastestInterval: 5000,
      activitiesInterval: 10000,
      url: 'http://192.168.0.3:3000/location',
      httpHeaders: {
        'X-FOO': 'bar'
      },
      // customize post properties
      postTemplate: {
        lat: '@latitude',
        lon: '@longitude',
        foo: 'bar' // you can also add your own properties
      }
    });

    cordova.plugins.BackgroundGeolocation.on('location', function(location) {
      // handle your locations here
      // to perform long running operation on iOS
      // you need to create background task
      cordova.plugins.BackgroundGeolocation.startTask(function(taskKey) {
        // execute long running task
        // eg. ajax post location
        // IMPORTANT: task has to be ended by endTask
        cordova.plugins.BackgroundGeolocation.endTask(taskKey);
      });
    });

    cordova.plugins.BackgroundGeolocation.on('stationary', function(stationaryLocation) {
      // handle stationary locations here
    });

    cordova.plugins.BackgroundGeolocation.on('error', function(error) {
      console.log('[ERROR] cordova.plugins.BackgroundGeolocation error:', error.code, error.message);
    });

    cordova.plugins.BackgroundGeolocation.on('start', function() {
      console.log('[INFO] cordova.plugins.BackgroundGeolocation service has been started');
    });

    cordova.plugins.BackgroundGeolocation.on('stop', function() {
      console.log('[INFO] cordova.plugins.BackgroundGeolocation service has been stopped');
    });

    cordova.plugins.BackgroundGeolocation.on('authorization', function(status) {
      console.log('[INFO] cordova.plugins.BackgroundGeolocation authorization status: ' + status);
      if (status !== cordova.plugins.BackgroundGeolocation.AUTHORIZED) {
        // we need to set delay or otherwise alert may not be shown
        setTimeout(function() {
          var showSettings = confirm('App requires location tracking permission. Would you like to open app settings?');
          if (showSettings) {
            return cordova.plugins.BackgroundGeolocation.showAppSettings();
          }
        }, 1000);
      }
    });

    cordova.plugins.BackgroundGeolocation.on('background', function() {
      console.log('[INFO] App is in background');
      // you can also reconfigure service (changes will be applied immediately)
      cordova.plugins.BackgroundGeolocation.configure({ debug: true });
    });

    cordova.plugins.BackgroundGeolocation.on('foreground', function() {
      console.log('[INFO] App is in foreground');
      cordova.plugins.BackgroundGeolocation.configure({ debug: false });
    });

    cordova.plugins.BackgroundGeolocation.on('abort_requested', function() {
      console.log('[INFO] Server responded with 285 Updates Not Required');
      cordova.plugins.BackgroundGeolocation.stop();
      // Here we can decide whether we want stop the updates or not.
      // If you've configured the server to return 285, then it means the server does not require further update.
      // So the normal thing to do here would be to `cordova.plugins.BackgroundGeolocation.stop()`.
      // But you might be counting on it to receive location updates in the UI, so you could just reconfigure and set `url` to null.
    });

    cordova.plugins.BackgroundGeolocation.on('http_authorization', () => {
      console.log('[INFO] App needs to authorize the http requests');
    });

    cordova.plugins.BackgroundGeolocation.checkStatus(function(status) {
      console.log('[INFO] cordova.plugins.BackgroundGeolocation service is running', status.isRunning);
      console.log('[INFO] cordova.plugins.BackgroundGeolocation services enabled', status.locationServicesEnabled);
      console.log('[INFO] cordova.plugins.BackgroundGeolocation auth status: ' + status.authorization);

      // you don't need to check status before start (this is just the example)
      if (!status.isRunning) {
        cordova.plugins.BackgroundGeolocation.start(); //triggers start on start event
      }
    });

    // you can also just start without checking for status
    // cordova.plugins.BackgroundGeolocation.start();

    // Don't forget to remove listeners at some point!
    // cordova.plugins.BackgroundGeolocation.events.forEach(function(event) {
    //   return cordova.plugins.BackgroundGeolocation.removeAllListeners(event);
    // });
  }

}
</code>```

Then from app.component:

```<code>    import { Component, OnInit } from '@angular/core';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import {
      transition,
      trigger,
      query,
      style,
      animate,
      group,
      animateChild
    } from '@angular/animations';
    import { GeolocationService } from './_services/geolocation.service';

    declare const device;

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      animations: [
        trigger('routeAnimation', [
          transition('* => *', [
            query(
              ':enter',
              [style({ opacity: 0 })],
              { optional: true }
            ),
            query(
              ':leave',
               [style({ opacity: 1 }), animate('0.3s', style({ opacity: 0 }))],
              { optional: true }
            ),
            query(
              ':enter',
              [style({ opacity: 0 }), animate('0.3s', style({ opacity: 1 }))],
              { optional: true }
            )
          ])
        ])
      ]
    })

    export class AppComponent implements OnInit{
      title = 'HLD Phlebotomist App';

  constructor(private geolocationService: GeolocationService) { }

      ngOnInit() {
        document.addEventListener("deviceready", function() {
          this.geolocationService.startBackgroundGeolocation();
          alert(device.platform);
        }, false);
      }
    }
</code>```

However, when I run this in an android emulator, I get "Uncaught TypeError: Cannot read property 'startBackgroundGeolocation' of undefined".  No idea why.  Can someone help me understand the structure here?  I think my problem is that I don't totally understand how to "call" the Cordova plugin.

答:
I'm writing this here because I struggled to find these answers in a single place and pieced them together from various blog posts and stackoverflow posts all of which seemed incomplete some how.

(1) Very Important Bootstrapping

A source of continual bugs and head ache turned out to be that in certain conditions Angular and the core App would be bootstrapped before the mobile device (both android and iOS) were ready to provide access to system resources like the camera. This was something that I danced around with until finally adding SSO as a first step in our app made me confront the problem in more than 75% of loading scenarios

The solution here is pretty straight forward in the main.ts of your angular application add a javascript document.addEventListener that waits for cordova to say the device is ready before bootstrapping angular.

```<code>document.addEventListener('deviceready', bootstrap, false);
</code>```

We have actually taken this one step further by adding a conditional block that injects the cordova script tag only when we turn it on in our environment variable. This made it easier to test non cordova features using ng serve in our test environment.

```<code>const bootstrap = () => platformBrowserDynamic().bootstrapModule(AppModule).catch(e => console.error(e));
const bootstrapCordova = () => {
  /** Dynamically load cordova JS **/
  console.log('bootstrapped cordova');

  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'cordova.js';

  document.head.appendChild(script);

  if (script['readyState']) {
    // IE 2018 and earlier (?). They're migrating to using Chromium under the hood, so this may change
    script['onreadystatechange'] = () => {
      if (script['readyState'] === "loaded" || script['readyState'] === "complete") {
        document.addEventListener('deviceready', bootstrap, false);

      }
    };
  } else {
    // All other browsers
    document.addEventListener('deviceready', bootstrap, false);
  }
};
environment.cordova ? bootstrapCordova() : bootstrap();
</code>```

(2) Recognizing typings

Since cordova and its plugins aren't bootstrapped as part of Angular it self we need to add cordova typings to our Angular project. While it is possible to write code without this using "window" functions in a particular way we found that important the typings solved lots of problems. Thankfully someone has contributed typescript typings to almost every single core cordova plugin. We tried just installing these typings in a types file but found that angular would grumble at compile time about having types but no library. For the record we don't feel like the following method should work but time and again they were the only replicable steps that got angular to stop grumbling.

First, we maintain our angular app in a separate filespace from cordova we then write the app to the www folder when ever we run ng build --prod. this means that our cordova app and our angular app each have a unique package.json to manage npm dependencies. in order to get access to cordova typings in angular we need to add cordova and all of the plugins we are using to the package.json of our angular project.

```<code>"cordova": "latest",
"cordova-plugin-camera": "latest",
"cordova-plugin-inappbrowser": "latest"
</code>```

Second - once you have installed these dependencies we need to generate a typings file for our project. its worth noting that the "typings" package is deprecated in npm in favor of "@types" . however we weren't able to figure out how to accomplish the end result we wanted with "@types" so for now we are using "typings"

```<code>npm install –g typings
typings search cordova
typings install dt~cordova --global --save
</code>```

This will generate a typings folder where ever you run the command so we recommend doing that in the root of your angular project. Once this is in place add the types file to your tsconfig.app.json and you are good to start coding.

```<code>"types": [
  "./typings/globals/cordova"
]
</code>```

Third - file level import

in our research we saw lots of ways to implement typings at a code level but only one worked in our project. Logic would dictate that we should be able to do a simple:

```<code>import {*} from 'typings/globals/cordova'
</code>```

and while our ide was fine with this ng build --prod was not. instead we reference the typings file in the following way:

```<code>/// <reference path="../../../../typings/globals/cordova/index.d.ts" />
</code>```

once we had done this we were able to benefit from full intellisense in our IDE.

```<code>export class SplashComponent implements AfterViewInit, OnDestroy {
  private browser: InAppBrowser;
  private cordova: Cordova;

  constructor(private route: Router) {
    this.cordova = window['cordova']
this.browser = this.cordova.InAppBrowser;
  }

  ngAfterViewInit(){
      this.currentBrowser = this.browser.open('https://www.google.com', '_blank', 'location=yes');
}

}
</code>```

(3) Building cordova

If you haven't seen it anywhere else know that the best way to handle any remaining issues you encounter with builds in cordova is to remove you platform and add it again.

```<code>cordova platform rm android
cordova platform add android
</code>```

Using this workflow we were able to eliminate almost 100% of the runtime errors we experienced with our app and performance of our app skyrocketed.

Hopefully if you are having these issues you find this post helpful since its all the things I wish existed.

Notes:
The proper Angular way to handle the "window" elements of this code is to use an injection token. I haven't included it here because this was a long post. I may update it later to include this.

Body:
I built a PWA in Angular 6 and was intending to use the Google Maps API for geolocation purposes.  However, I soon realized that the geolocation services in a PWA only work when the user is interacting with the UI to deliberately request their location.  My app is supposed to track the user's location in the background as they drive around, however.  So when they lock the screen or go to a different application it should still track them.  For the record, this is a private application and users are fully aware that they are being tracked.  As a result, I converted the PWA to a hybrid app using Cordova.  Everything works so far with what I had already (emulation is fine, etc), but I can't seem to figure out how to add the geolocation piece.  I have installed this plugin, which appears to be installed and available.  All of the examples I have seen use Ionic (which I don't need at this point) and are for the scenario where the user clicks a button to get their location, but I need it where the geolocation stuff is in a service and starts running in the background after they are logged in.  I can't seem to find something that shows how to do this.  Here's what I was thinking I should do:

(this isn't complete, I just pasted the example code from GitHub here and intend to fill it in with "stuff" when I know it's actually being called)

_services/geolocation.service.ts:

import { Injectable } from '@angular/core';
import { Component, ViewChild } from '@angular/core';

declare var cordova: any;

@Injectable()
export class GeolocationService {
  startBackgroundGeolocation() {
    console.log("Geolocation service called...");
    cordova.plugins.BackgroundGeolocation.configure({
      locationProvider: cordova.plugins.BackgroundGeolocation.ACTIVITY_PROVIDER,
      desiredAccuracy: cordova.plugins.BackgroundGeolocation.HIGH_ACCURACY,
      stationaryRadius: 50,
      distanceFilter: 50,
      notificationTitle: 'Background tracking',
      notificationText: 'enabled',
      debug: true,
      interval: 10000,
      fastestInterval: 5000,
      activitiesInterval: 10000,
      url: 'http://192.168.0.3:3000/location',
      httpHeaders: {
        'X-FOO': 'bar'
      },
      // customize post properties
      postTemplate: {
        lat: '@latitude',
        lon: '@longitude',
        foo: 'bar' // you can also add your own properties
      }
    });

    cordova.plugins.BackgroundGeolocation.on('location', function(location) {
      // handle your locations here
      // to perform long running operation on iOS
      // you need to create background task
      cordova.plugins.BackgroundGeolocation.startTask(function(taskKey) {
        // execute long running task
        // eg. ajax post location
        // IMPORTANT: task has to be ended by endTask
        cordova.plugins.BackgroundGeolocation.endTask(taskKey);
      });
    });

    cordova.plugins.BackgroundGeolocation.on('stationary', function(stationaryLocation) {
      // handle stationary locations here
    });

    cordova.plugins.BackgroundGeolocation.on('error', function(error) {
      console.log('[ERROR] cordova.plugins.BackgroundGeolocation error:', error.code, error.message);
    });

    cordova.plugins.BackgroundGeolocation.on('start', function() {
      console.log('[INFO] cordova.plugins.BackgroundGeolocation service has been started');
    });

    cordova.plugins.BackgroundGeolocation.on('stop', function() {
      console.log('[INFO] cordova.plugins.BackgroundGeolocation service has been stopped');
    });

    cordova.plugins.BackgroundGeolocation.on('authorization', function(status) {
      console.log('[INFO] cordova.plugins.BackgroundGeolocation authorization status: ' + status);
      if (status !== cordova.plugins.BackgroundGeolocation.AUTHORIZED) {
        // we need to set delay or otherwise alert may not be shown
        setTimeout(function() {
          var showSettings = confirm('App requires location tracking permission. Would you like to open app settings?');
          if (showSettings) {
            return cordova.plugins.BackgroundGeolocation.showAppSettings();
          }
        }, 1000);
      }
    });

    cordova.plugins.BackgroundGeolocation.on('background', function() {
      console.log('[INFO] App is in background');
      // you can also reconfigure service (changes will be applied immediately)
      cordova.plugins.BackgroundGeolocation.configure({ debug: true });
    });

    cordova.plugins.BackgroundGeolocation.on('foreground', function() {
      console.log('[INFO] App is in foreground');
      cordova.plugins.BackgroundGeolocation.configure({ debug: false });
    });

    cordova.plugins.BackgroundGeolocation.on('abort_requested', function() {
      console.log('[INFO] Server responded with 285 Updates Not Required');
      cordova.plugins.BackgroundGeolocation.stop();
      // Here we can decide whether we want stop the updates or not.
      // If you've configured the server to return 285, then it means the server does not require further update.
      // So the normal thing to do here would be to `cordova.plugins.BackgroundGeolocation.stop()`.
      // But you might be counting on it to receive location updates in the UI, so you could just reconfigure and set `url` to null.
    });

    cordova.plugins.BackgroundGeolocation.on('http_authorization', () => {
      console.log('[INFO] App needs to authorize the http requests');
    });

    cordova.plugins.BackgroundGeolocation.checkStatus(function(status) {
      console.log('[INFO] cordova.plugins.BackgroundGeolocation service is running', status.isRunning);
      console.log('[INFO] cordova.plugins.BackgroundGeolocation services enabled', status.locationServicesEnabled);
      console.log('[INFO] cordova.plugins.BackgroundGeolocation auth status: ' + status.authorization);

      // you don't need to check status before start (this is just the example)
      if (!status.isRunning) {
        cordova.plugins.BackgroundGeolocation.start(); //triggers start on start event
      }
    });

    // you can also just start without checking for status
    // cordova.plugins.BackgroundGeolocation.start();

    // Don't forget to remove listeners at some point!
    // cordova.plugins.BackgroundGeolocation.events.forEach(function(event) {
    //   return cordova.plugins.BackgroundGeolocation.removeAllListeners(event);
    // });
  }

}

Then from app.component:

    import { Component, OnInit } from '@angular/core';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import {
      transition,
      trigger,
      query,
      style,
      animate,
      group,
      animateChild
    } from '@angular/animations';
    import { GeolocationService } from './_services/geolocation.service';

    declare const device;

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      animations: [
        trigger('routeAnimation', [
          transition('* => *', [
            query(
              ':enter',
              [style({ opacity: 0 })],
              { optional: true }
            ),
            query(
              ':leave',
               [style({ opacity: 1 }), animate('0.3s', style({ opacity: 0 }))],
              { optional: true }
            ),
            query(
              ':enter',
              [style({ opacity: 0 }), animate('0.3s', style({ opacity: 1 }))],
              { optional: true }
            )
          ])
        ])
      ]
    })

    export class AppComponent implements OnInit{
      title = 'HLD Phlebotomist App';

  constructor(private geolocationService: GeolocationService) { }

      ngOnInit() {
        document.addEventListener("deviceready", function() {
          this.geolocationService.startBackgroundGeolocation();
          alert(device.platform);
        }, false);
      }
    }

However, when I run this in an android emulator, I get "Uncaught TypeError: Cannot read property 'startBackgroundGeolocation' of undefined".  No idea why.  Can someone help me understand the structure here?  I think my problem is that I don't totally understand how to "call" the Cordova plugin.

Body:
I'm writing this here because I struggled to find these answers in a single place and pieced them together from various blog posts and stackoverflow posts all of which seemed incomplete some how.

(1) Very Important Bootstrapping

A source of continual bugs and head ache turned out to be that in certain conditions Angular and the core App would be bootstrapped before the mobile device (both android and iOS) were ready to provide access to system resources like the camera. This was something that I danced around with until finally adding SSO as a first step in our app made me confront the problem in more than 75% of loading scenarios

The solution here is pretty straight forward in the main.ts of your angular application add a javascript document.addEventListener that waits for cordova to say the device is ready before bootstrapping angular.

document.addEventListener('deviceready', bootstrap, false);

We have actually taken this one step further by adding a conditional block that injects the cordova script tag only when we turn it on in our environment variable. This made it easier to test non cordova features using ng serve in our test environment.

const bootstrap = () => platformBrowserDynamic().bootstrapModule(AppModule).catch(e => console.error(e));
const bootstrapCordova = () => {
  /** Dynamically load cordova JS **/
  console.log('bootstrapped cordova');

  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'cordova.js';

  document.head.appendChild(script);

  if (script['readyState']) {
    // IE 2018 and earlier (?). They're migrating to using Chromium under the hood, so this may change
    script['onreadystatechange'] = () => {
      if (script['readyState'] === "loaded" || script['readyState'] === "complete") {
        document.addEventListener('deviceready', bootstrap, false);

      }
    };
  } else {
    // All other browsers
    document.addEventListener('deviceready', bootstrap, false);
  }
};
environment.cordova ? bootstrapCordova() : bootstrap();

(2) Recognizing typings

Since cordova and its plugins aren't bootstrapped as part of Angular it self we need to add cordova typings to our Angular project. While it is possible to write code without this using "window" functions in a particular way we found that important the typings solved lots of problems. Thankfully someone has contributed typescript typings to almost every single core cordova plugin. We tried just installing these typings in a types file but found that angular would grumble at compile time about having types but no library. For the record we don't feel like the following method should work but time and again they were the only replicable steps that got angular to stop grumbling.

First, we maintain our angular app in a separate filespace from cordova we then write the app to the www folder when ever we run ng build --prod. this means that our cordova app and our angular app each have a unique package.json to manage npm dependencies. in order to get access to cordova typings in angular we need to add cordova and all of the plugins we are using to the package.json of our angular project.

"cordova": "latest",
"cordova-plugin-camera": "latest",
"cordova-plugin-inappbrowser": "latest"

Second - once you have installed these dependencies we need to generate a typings file for our project. its worth noting that the "typings" package is deprecated in npm in favor of "@types" . however we weren't able to figure out how to accomplish the end result we wanted with "@types" so for now we are using "typings"

npm install –g typings
typings search cordova
typings install dt~cordova --global --save

This will generate a typings folder where ever you run the command so we recommend doing that in the root of your angular project. Once this is in place add the types file to your tsconfig.app.json and you are good to start coding.

"types": [
  "./typings/globals/cordova"
]

Third - file level import

in our research we saw lots of ways to implement typings at a code level but only one worked in our project. Logic would dictate that we should be able to do a simple:

import {*} from 'typings/globals/cordova'

and while our ide was fine with this ng build --prod was not. instead we reference the typings file in the following way:

/// <reference path="../../../../typings/globals/cordova/index.d.ts" />

once we had done this we were able to benefit from full intellisense in our IDE.

export class SplashComponent implements AfterViewInit, OnDestroy {
  private browser: InAppBrowser;
  private cordova: Cordova;

  constructor(private route: Router) {
    this.cordova = window['cordova']
this.browser = this.cordova.InAppBrowser;
  }

  ngAfterViewInit(){
      this.currentBrowser = this.browser.open('https://www.google.com', '_blank', 'location=yes');
}

}

(3) Building cordova

If you haven't seen it anywhere else know that the best way to handle any remaining issues you encounter with builds in cordova is to remove you platform and add it again.

cordova platform rm android
cordova platform add android

Using this workflow we were able to eliminate almost 100% of the runtime errors we experienced with our app and performance of our app skyrocketed.

Hopefully if you are having these issues you find this post helpful since its all the things I wish existed.

Notes:
The proper Angular way to handle the "window" elements of this code is to use an injection token. I haven't included it here because this was a long post. I may update it later to include this.


来源: stackexchange

问:
How can i execute one by one statement after delaying some time in iphone?
I have a problem in iPhone programing.

In my app i want to execute one by one statement after delaying some time.

Example:

```<code>Label1.text =@"2";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"3";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"8";
</code>```

Then after delaying some time i want execute:

```<code>Label2.text =@"6";
</code>```

答:
```<code>[self performSelector:@selector(updateText:) withObject:self afterDelay:yourDelay];
</code>```

will help you

ContentLicense: CC BY-SA 3.0

Body:
I have a problem in iPhone programing.

In my app i want to execute one by one statement after delaying some time.

Example:

Label1.text =@"2";

Then after delaying some time i want execute:

Label2.text =@"3";

Then after delaying some time i want execute:

Label2.text =@"8";

Then after delaying some time i want execute:

Label2.text =@"6";

Body:
[self performSelector:@selector(updateText:) withObject:self afterDelay:yourDelay];

will help you


问:
Proper way for json parsing for mutable structure with gson
I'm getting response from server based on such structure:

```<code>{
    "success":true,
    "data":{"can be some kind of data, array or error message"}
}
</code>```

What is the right way to map properly data attribute in such situations?
My attempts was to use Any type and cast after to specified type:

```<code>data class GeneralResponseModel(
    val success: Boolean,
    val data: Any
)
</code>```

Provider

```<code>//
val response = gson.fromJson(it[0].toString(), GeneralResponseModel::class.java)
//
</code>```

ViewModel

```<code>////////
if (res.success) {
    isLoading.postValue(false)
    ///////
} else {
    val result = res.data as ResponseError
    errorMessage.postValue(ErrorWrapper(ErrorType.REQUEST_ERROR,result.detail,result.title))
    isLoading.postValue(false)
}
///////////
</code>```

And I got

io.reactivex.exceptions.OnErrorNotImplementedException:
  com.google.gson.internal.LinkedTreeMap cannot be cast to
  com.myapp.model.response.ResponseError

Another attempt was in using empty interface which was implemented by all possible response types. In this situation I got

java.lang.RuntimeException: Unable to invoke no-args constructor for
  interface com.myapp.model.response.Response.
  Registering an InstanceCreator with Gson for this type may fix this
  problem.

I'm not sure about proper way to handle such trivial case. Any links, code examples or help appreciated. Thanks in advance.

Update

Thanks to Niklas I reconsidered gson into such structure:

```<code> lateinit var gson: Gson
        when (methodName) {
            RequestList.LOGIN.methodName -> {
                gson =
                    GsonBuilder().registerTypeAdapter(
                        GeneralResponseModel::class.java,
                        object : JsonDeserializer<GeneralResponseModel> {
                            override fun deserialize(
                                json: JsonElement?,
                                typeOfT: Type?,
                                context: JsonDeserializationContext?
                            ): GeneralResponseModel {
                                val gsonInner = Gson()
                                val jsonObject: JsonObject = json!!.asJsonObject
                                lateinit var generalResponseModel: GeneralResponseModel
                                generalResponseModel = if (!jsonObject.get("success").asBoolean) {

                                    GeneralResponseModel(
                                        false,
                                        gsonInner.fromJson(jsonObject.get("data"), ResponseError::class.java)
                                    )
                                } else {

                                    GeneralResponseModel(
                                        true,
                                        gsonInner.fromJson(jsonObject.get("data"), DriverData::class.java)
                                    )
                                }
                                return generalResponseModel
                            }

                        }).create()
            }
            RequestList.GET_JOBS.methodName -> {
                gson = GsonBuilder().registerTypeAdapter(
                    GeneralResponseModel::class.java,
                    object : JsonDeserializer<GeneralResponseModel> {
                        override fun deserialize(
                            json: JsonElement?,
                            typeOfT: Type?,
                            context: JsonDeserializationContext?
                        ): GeneralResponseModel {
                            val gsonInner = Gson()
                            val jsonObject: JsonObject = json!!.asJsonObject
                            lateinit var generalResponseModel: GeneralResponseModel
                            generalResponseModel = if (!jsonObject.get("success").asBoolean) {

                                GeneralResponseModel(
                                    false,
                                    gsonInner.fromJson(jsonObject.get("data"), ResponseError::class.java)
                                )
                            } else {

                                GeneralResponseModel(
                                    true,
                                    gsonInner.fromJson(jsonObject.get("data"), Array<JobResponse>::class.java)
                                )
                            }
                            return generalResponseModel
                        }

                    }).create()
            }
            else -> gson = Gson()
        }
</code>```

答:
Since your data is very generic, it can't really be parsed in a type-safe way. Gson can't infer types based on pure text (in your specific case there is nothing telling Gson that your data is a ResponseError).

I would consider a general wrapper class like yours, and then using a GSON TypeAdapter to parse the response to your general wrapper.

You have to instantiate GSON with a Builder to define a custom TypeAdapter.

registerTypeAdapter(Type type, Object typeAdapter)
Configures Gson for custom serialization or deserialization.

Your wrapper:

```<code>public class Response<T> {
    T data;
    String message;

    public Response(T data, String message) {
        this.data = data;
        this.message = message;
    }

    boolean hasData() {
        return data != null;
    }

    T getData() {
        return data;
    }

    String getMessage() {
        return message;
    }

}
</code>```

Initialization:

```<code>GsonBuilder builder = new GsonBuilder();
b.registerTypeAdapter(Response.class, new JsonDeserializer<Response>() {
    @Override
    public Response deserialize(JsonElement arg0, Type arg1,
        JsonDeserializationContext arg2) throws JsonParseException {
    // ... create Response object here
    return response;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting response from server based on such structure:

{
    "success":true,
    "data":{"can be some kind of data, array or error message"}
}

What is the right way to map properly data attribute in such situations?
My attempts was to use Any type and cast after to specified type:

data class GeneralResponseModel(
    val success: Boolean,
    val data: Any
)

Provider

//
val response = gson.fromJson(it[0].toString(), GeneralResponseModel::class.java)
//

ViewModel

////////
if (res.success) {
    isLoading.postValue(false)
    ///////
} else {
    val result = res.data as ResponseError
    errorMessage.postValue(ErrorWrapper(ErrorType.REQUEST_ERROR,result.detail,result.title))
    isLoading.postValue(false)
}
///////////

And I got

io.reactivex.exceptions.OnErrorNotImplementedException:
  com.google.gson.internal.LinkedTreeMap cannot be cast to
  com.myapp.model.response.ResponseError

Another attempt was in using empty interface which was implemented by all possible response types. In this situation I got

java.lang.RuntimeException: Unable to invoke no-args constructor for
  interface com.myapp.model.response.Response.
  Registering an InstanceCreator with Gson for this type may fix this
  problem.

I'm not sure about proper way to handle such trivial case. Any links, code examples or help appreciated. Thanks in advance.

Update

Thanks to Niklas I reconsidered gson into such structure:

 lateinit var gson: Gson
        when (methodName) {
            RequestList.LOGIN.methodName -> {
                gson =
                    GsonBuilder().registerTypeAdapter(
                        GeneralResponseModel::class.java,
                        object : JsonDeserializer<GeneralResponseModel> {
                            override fun deserialize(
                                json: JsonElement?,
                                typeOfT: Type?,
                                context: JsonDeserializationContext?
                            ): GeneralResponseModel {
                                val gsonInner = Gson()
                                val jsonObject: JsonObject = json!!.asJsonObject
                                lateinit var generalResponseModel: GeneralResponseModel
                                generalResponseModel = if (!jsonObject.get("success").asBoolean) {

                                    GeneralResponseModel(
                                        false,
                                        gsonInner.fromJson(jsonObject.get("data"), ResponseError::class.java)
                                    )
                                } else {

                                    GeneralResponseModel(
                                        true,
                                        gsonInner.fromJson(jsonObject.get("data"), DriverData::class.java)
                                    )
                                }
                                return generalResponseModel
                            }

                        }).create()
            }
            RequestList.GET_JOBS.methodName -> {
                gson = GsonBuilder().registerTypeAdapter(
                    GeneralResponseModel::class.java,
                    object : JsonDeserializer<GeneralResponseModel> {
                        override fun deserialize(
                            json: JsonElement?,
                            typeOfT: Type?,
                            context: JsonDeserializationContext?
                        ): GeneralResponseModel {
                            val gsonInner = Gson()
                            val jsonObject: JsonObject = json!!.asJsonObject
                            lateinit var generalResponseModel: GeneralResponseModel
                            generalResponseModel = if (!jsonObject.get("success").asBoolean) {

                                GeneralResponseModel(
                                    false,
                                    gsonInner.fromJson(jsonObject.get("data"), ResponseError::class.java)
                                )
                            } else {

                                GeneralResponseModel(
                                    true,
                                    gsonInner.fromJson(jsonObject.get("data"), Array<JobResponse>::class.java)
                                )
                            }
                            return generalResponseModel
                        }

                    }).create()
            }
            else -> gson = Gson()
        }

Body:
Since your data is very generic, it can't really be parsed in a type-safe way. Gson can't infer types based on pure text (in your specific case there is nothing telling Gson that your data is a ResponseError).

I would consider a general wrapper class like yours, and then using a GSON TypeAdapter to parse the response to your general wrapper.

You have to instantiate GSON with a Builder to define a custom TypeAdapter.

registerTypeAdapter(Type type, Object typeAdapter)
Configures Gson for custom serialization or deserialization.

Your wrapper:

public class Response<T> {
    T data;
    String message;

    public Response(T data, String message) {
        this.data = data;
        this.message = message;
    }

    boolean hasData() {
        return data != null;
    }

    T getData() {
        return data;
    }

    String getMessage() {
        return message;
    }

}

Initialization:

GsonBuilder builder = new GsonBuilder();
b.registerTypeAdapter(Response.class, new JsonDeserializer<Response>() {
    @Override
    public Response deserialize(JsonElement arg0, Type arg1,
        JsonDeserializationContext arg2) throws JsonParseException {
    // ... create Response object here
    return response;
}


问:
Searching XML through Java Codes
I have around 30 xml files with proper formatting  and huge amount of data. I want to search these xml files for specific data retrival. Can you suggest any site or blog which i can use as aguideline to solve my problem.

I need to search inside of each tag for the keyword provided by the user. And also sometime the specific tag name which will return the content inside the tag according to the user request.

example : a.xml, b.xml, c.xml

```<code>inside a.xml

<abc>
some content
</abc>
</code>```

User may search for abc the tag or some keyword inside the content. In both cases it should return the content or if more than one match then it should return the link for both by clicking which the user can see them one by one.

答: You may store your XMLs into an XML database (for example eXist), and then query it using XQuery.</p>

Title: Searching XML through Java Codes

Body:
I have around 30 xml files with proper formatting  and huge amount of data. I want to search these xml files for specific data retrival. Can you suggest any site or blog which i can use as aguideline to solve my problem.

I need to search inside of each tag for the keyword provided by the user. And also sometime the specific tag name which will return the content inside the tag according to the user request.

example : a.xml, b.xml, c.xml

inside a.xml

<abc>
some content
</abc>

User may search for abc the tag or some keyword inside the content. In both cases it should return the content or if more than one match then it should return the link for both by clicking which the user can see them one by one.


问:
Question about functions being called from other files - Javascript
I am looking for some help understanding something on a project I am working on. I have written some code that is functioning, though I am not sure why.

In a Node.js server, in /public/js there are two scripts. One (file1.js) has a function func(). file2.js, in the same directory, calls func() successfully. There is no module.exporting or requireing anywhere, yet the two files work together. They are both referenced in the index.ejs file, however. Is this where they become able to communicate?

```<code>//file1.js
function func() {
    console.log("foo")
}
</code>```

```<code>//file2.js

func()
</code>```

```<code>//index.ejs
...
<script src="public/js/file1.js"></script>
<script src="public/js/file2.js"></script>
...
</code>```

I've spent all day reading and cannot find anything on this topic.

答:
Your question is about how JavaScript works in a browser.

Node.js isn't relevant here. All it is doing is running an HTTP server program that gives static files to the browser.

When you load a script into a browser using a script element (and don't use type="module"), any variable in the outer most scope of the script file (e.g. which isn't let inside a block or var inside a function) becomes a global and is accessible to any other script loaded into the same HTML document that way.

Globals are messy and a good way for different bits of code to accidentally interfere with each other so modern JavaScript generally avoids using them. This style of JavaScript programming wasn't common when JS was first implemented in browsers: Hence the behaviour described above.

This is why people started to use techniques like the revealing module pattern and why AMD and Node modules were designed before standard JavaScript modules were added to the specification.

Body:
I am looking for some help understanding something on a project I am working on. I have written some code that is functioning, though I am not sure why.

In a Node.js server, in /public/js there are two scripts. One (file1.js) has a function func(). file2.js, in the same directory, calls func() successfully. There is no module.exporting or requireing anywhere, yet the two files work together. They are both referenced in the index.ejs file, however. Is this where they become able to communicate?

//file1.js
function func() {
    console.log("foo")
}

//file2.js

func()

//index.ejs
...

...

I've spent all day reading and cannot find anything on this topic.


问:
How to Remove “Powered by ManyChat” footer from a messenger bot

I am developing a chat bot for the messenger platform, but I found myself mesmerized by the fact that “ManyChat” appears on the footer of the users text input field.

I have become an admin of that page and proceed to remove many chat from the list of connected apps for that page, but the footer is still there.

Maybe I have to call the messenger platform API in order to change some property that isn’t available from the Facebook Pages User Interface. But nothing in the documentation mentions anything about a persistent footer on the page.

Does anyone have any clue of how to remove this?

答:
Have you tried to reset the chatbot's persistent menu? This can be done with sending a POST HTTP request to Facebook Messenger API as explained here:

https://developers.facebook.com/docs/messenger-platform/send-messages/persistent-menu


问:
How to reference object in another class
I'm a beginner in java. I have to make shopping cart.
But I'm stuck on reference.

Please help me!

I tried to make private member variable ShoppingCart in Customer class.
But I think it is not right way.

Customer.java

```<code>public class Customer {
    private String id;
    private String firstName;
    private String lastName;
    private ShoppingCart s;

    public Customer(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        s = new ShoppingCart();
    }

    @Override
    public String toString() {
        return ("Customer ID is: " + this.id + "\n" + "Customer's name is: "
                 + this.firstName + " " + this.lastName + "\n\n"
                + s.toString());

    }
}
</code>```

Test.java

```<code>public class Test {
        public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        Customer c1 = new Customer("12345", "David", "Smith");

        //This sentence doesn't work because of s.
        c1.s.addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);

    }

}
</code>```

ShoppingCart.java

```<code>public class ShoppingCart {
    private int itemCount;
    private double totalPrice;
    private static int capacity;
    private Item[] cart;
    public ShoppingCart()
    {
        capacity = 5;
        itemCount = 0;
        totalPrice = 0.0;
        cart = new Item[capacity];
    }

    public void addBooktoCart(String title, String description, double price, int pageCount) {

        if (itemCount < 5) {

        Item item = new Book(title, description, price, pageCount);
        totalPrice += price;
        cart[itemCount] = item;
        itemCount += 1;
        }
        else {
            System.out.println("The maximum number that you can input is 5." +
                     "You cannot add item anymore");
        }

    }

}
</code>```

I want to call addBooktoCart that is in ShoppingCart class in the Test.java.
But it doesn't work. What do I do if I call addBooktoCart? And If there is another problem. Please let me know!

答:
You are absolutely right to private.  Just do not refer to field directly. Instead, please use get/set method.

c1.getS().addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);
```

By the way, please choose your field name carefully. s means nothing.

Body:
I'm a beginner in java. I have to make shopping cart.
But I'm stuck on reference.

Please help me!

I tried to make private member variable ShoppingCart in Customer class.
But I think it is not right way.

Customer.java

public class Customer {
    private String id;
    private String firstName;
    private String lastName;
    private ShoppingCart s;

    public Customer(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        s = new ShoppingCart();
    }

    @Override
    public String toString() {
        return ("Customer ID is: " + this.id + "\n" + "Customer's name is: "
                 + this.firstName + " " + this.lastName + "\n\n"
                + s.toString());

    }
}

Test.java

public class Test {
        public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        Customer c1 = new Customer("12345", "David", "Smith");

        //This sentence doesn't work because of s.
        c1.s.addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);

    }

}

ShoppingCart.java

public class ShoppingCart {
    private int itemCount;
    private double totalPrice;
    private static int capacity;
    private Item[] cart;
    public ShoppingCart()
    {
        capacity = 5;
        itemCount = 0;
        totalPrice = 0.0;
        cart = new Item[capacity];
    }

    public void addBooktoCart(String title, String description, double price, int pageCount) {

        if (itemCount < 5) {

        Item item = new Book(title, description, price, pageCount);
        totalPrice += price;
        cart[itemCount] = item;
        itemCount += 1;
        }
        else {
            System.out.println("The maximum number that you can input is 5." +
                     "You cannot add item anymore");
        }

    }

}

I want to call addBooktoCart that is in ShoppingCart class in the Test.java.
But it doesn't work. What do I do if I call addBooktoCart? And If there is another problem. Please let me know!

Body:
You are absolutely right to private.  Just do not refer to field directly. Instead, please use get/set method.

c1.getS().addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);

By the way, please choose your field name carefully. s means nothing.


问:
Placing image over view in react native
I'm trying to place my image over view that is already on other view but no success...

I had been trying to use position:'absolute' and more other options I had seen but it didn't work for me.

```<code>render() {
    let locationFlag=Platform.OS === 'ios'?true:false
    return (
      <View style={styles.container}>
        <LinearGradient
          colors={[ '#75a4e7','#7d50f6']}
          start={{x: .2, y: 1}}
          end={{x:.8,y:0}}
          locations={locationFlag?[.15,1]:[.18,2.1]}
          style={styles.gradient}>

          <View style={styles.profilePhotoContainer}>
          <TouchableOpacity onPress={this.handleEditProfileImage.bind(this)}>
          <Image
          style={styles.profileImage}
          source={this.state.profilePhoto}
        />
       </TouchableOpacity>

          </View>
        </LinearGradient>

        <View style={
            [styles.profileBox]}
          >
         </View>
        </View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignSelf: 'stretch',
    backgroundColor: Colors.LIGHT_GRAY
  },
gradient: {
    alignSelf: 'stretch',
    alignItems: 'center',
    flexDirection: 'column',
    height: Dimensions.get('window').height * .35,
  },
profilePhotoContainer: {
    zIndex: 50,
    position: 'absolute',
    backgroundColor:'blue',
    top: Dimensions.get('window').height * .12,
    elevation: 4,
  },
  profileImage: {
    zIndex: 5,
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 4,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
  },
 profileBox: {
    zIndex: 1,
    position: 'absolute',
    left: Dimensions.get('window').width * .07,
    top: Dimensions.get('window').height * .18,
    borderRadius: 8,
    shadowRadius: 8,
    elevation: 3,
    shadowOpacity: 0.3,
    backgroundColor: 'yellow',
    width: Dimensions.get('window').width * .86,
    height: Dimensions.get('window').height * .50,
    }

</code>```

In the link you can see what did I do so far and what is the issue:

https://imgur.com/a/kC4ZTUn

I want to achieve this situation:

https://imgur.com/a/KMSRVfZ

Thank you

答:
Get some help from this-</p>

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity
} from 'react-native';

export default class Profile extends Component {

  render() {
    return (
      <View style={styles.container}>
          <View style={styles.header}></View>
          <Image style={styles.avatar} source={{uri: 'https://bootdey.com/img/Content/avatar/avatar6.png'}}/>
          <View style={styles.body}>
            <View style={styles.bodyContent}>
              <Text style={styles.name}>John Doe</Text>
              <Text style={styles.info}>UX Designer / Mobile developer</Text>
              <Text style={styles.description}>Lorem ipsum dolor sit amet, saepe sapientem eu nam. Qui ne assum electram expetendis, omittam deseruisse consequuntur ius an,</Text>

              <TouchableOpacity style={styles.buttonContainer}>
                <Text>Opcion 1</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.buttonContainer}>
                <Text>Opcion 2</Text>
              </TouchableOpacity>
            </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  header:{
    backgroundColor: "#00BFFF",
    height:200,
  },
  avatar: {
    width: 130,
    height: 130,
    borderRadius: 63,
    borderWidth: 4,
    borderColor: "white",
    marginBottom:10,
    alignSelf:'center',
    position: 'absolute',
    marginTop:130
  },
  name:{
    fontSize:22,
    color:"#FFFFFF",
    fontWeight:'600',
  },
  body:{
    marginTop:40,
  },
  bodyContent: {
    flex: 1,
    alignItems: 'center',
    padding:30,
  },
  name:{
    fontSize:28,
    color: "#696969",
    fontWeight: "600"
  },
  info:{
    fontSize:16,
    color: "#00BFFF",
    marginTop:10
  },
  description:{
    fontSize:16,
    color: "#696969",
    marginTop:10,
    textAlign: 'center'
  },
  buttonContainer: {
    marginTop:10,
    height:45,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom:20,
    width:250,
    borderRadius:30,
    backgroundColor: "#00BFFF",
  },
});
</code>```

Title: Placing image over view in react native

Body:
I'm trying to place my image over view that is already on other view but no success...

I had been trying to use position:'absolute' and more other options I had seen but it didn't work for me.

render() {
    let locationFlag=Platform.OS === 'ios'?true:false
    return (
      <View style={styles.container}>
        <LinearGradient
          colors={[ '#75a4e7','#7d50f6']}
          start={{x: .2, y: 1}}
          end={{x:.8,y:0}}
          locations={locationFlag?[.15,1]:[.18,2.1]}
          style={styles.gradient}>

          <View style={styles.profilePhotoContainer}>
          <TouchableOpacity onPress={this.handleEditProfileImage.bind(this)}>
          <Image
          style={styles.profileImage}
          source={this.state.profilePhoto}
        />
       </TouchableOpacity>

          </View>
        </LinearGradient>

        <View style={
            [styles.profileBox]}
          >
         </View>
        </View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignSelf: 'stretch',
    backgroundColor: Colors.LIGHT_GRAY
  },
gradient: {
    alignSelf: 'stretch',
    alignItems: 'center',
    flexDirection: 'column',
    height: Dimensions.get('window').height * .35,
  },
profilePhotoContainer: {
    zIndex: 50,
    position: 'absolute',
    backgroundColor:'blue',
    top: Dimensions.get('window').height * .12,
    elevation: 4,
  },
  profileImage: {
    zIndex: 5,
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 4,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
  },
 profileBox: {
    zIndex: 1,
    position: 'absolute',
    left: Dimensions.get('window').width * .07,
    top: Dimensions.get('window').height * .18,
    borderRadius: 8,
    shadowRadius: 8,
    elevation: 3,
    shadowOpacity: 0.3,
    backgroundColor: 'yellow',
    width: Dimensions.get('window').width * .86,
    height: Dimensions.get('window').height * .50,
    }

In the link you can see what did I do so far and what is the issue:

https://imgur.com/a/kC4ZTUn

I want to achieve this situation:

https://imgur.com/a/KMSRVfZ

Thank you

Body:
Get some help from this-

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity
} from 'react-native';

export default class Profile extends Component {

  render() {
    return (
      <View style={styles.container}>
          <View style={styles.header}></View>
          <Image style={styles.avatar} source={{uri: 'https://bootdey.com/img/Content/avatar/avatar6.png'}}/>
          <View style={styles.body}>
            <View style={styles.bodyContent}>
              <Text style={styles.name}>John Doe</Text>
              <Text style={styles.info}>UX Designer / Mobile developer</Text>
              <Text style={styles.description}>Lorem ipsum dolor sit amet, saepe sapientem eu nam. Qui ne assum electram expetendis, omittam deseruisse consequuntur ius an,</Text>

              <TouchableOpacity style={styles.buttonContainer}>
                <Text>Opcion 1</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.buttonContainer}>
                <Text>Opcion 2</Text>
              </TouchableOpacity>
            </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  header:{
    backgroundColor: "#00BFFF",
    height:200,
  },
  avatar: {
    width: 130,
    height: 130,
    borderRadius: 63,
    borderWidth: 4,
    borderColor: "white",
    marginBottom:10,
    alignSelf:'center',
    position: 'absolute',
    marginTop:130
  },
  name:{
    fontSize:22,
    color:"#FFFFFF",
    fontWeight:'600',
  },
  body:{
    marginTop:40,
  },
  bodyContent: {
    flex: 1,
    alignItems: 'center',
    padding:30,
  },
  name:{
    fontSize:28,
    color: "#696969",
    fontWeight: "600"
  },
  info:{
    fontSize:16,
    color: "#00BFFF",
    marginTop:10
  },
  description:{
    fontSize:16,
    color: "#696969",
    marginTop:10,
    textAlign: 'center'
  },
  buttonContainer: {
    marginTop:10,
    height:45,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom:20,
    width:250,
    borderRadius:30,
    backgroundColor: "#00BFFF",
  },
});


问:
How to fix a for loop that is skipping some values?
I basically have a date entered in cell N3 and a column (column I) that contains date sorted by date. I am trying to write a code that asks the user to input a date at first. Then the program would look for that date in the column I and delete ALL the rows after the row in which the match was found.

My code is somehow working, but here is my problem. Only a part of the rows under the wanted row are being deleted and not all of them. I was thinking that could be an issue with the for-loop or the counter?
Please let me know if you could help :)

```<code>Sub DeleteAllRowsPaymentTooFar()

Worksheets("Master").Activate

Dim date_max As Date
date_max = InputBox("What is the maximum date to filter? ")

Range("N3").Value = date_max
Range("N3").NumberFormat = ("ddddd, mmmmmmmmm d, yyyy")

Dim i As Long
i = Range("A4").End(xlDown).Row
Dim result As Integer
Dim str1 As String, str2 As String
Dim counter As Long

str1 = Cells(3, 14).Text

counter = 4

Do While counter <= i

str2 = Cells(counter, 9).Text

result = StrComp(str1, str2, vbTextCompare)

  If result <> 0 Then
 MsgBox ("The date is not yet reached.")

  Else

        For K = counter To i
        Worksheets("Master").Rows(K).EntireRow.Delete
        Next

    End If

counter = counter + 1
Loop

End Sub
</code>```

I expect to remove all the rows under the row where the match was found.

答:
This may help you:</p>

```<code>For i=LastPoint To FirstPoint Step-1

    Worksheets("Master").Rows(i).EntireRow.Delete

Next i
</code>```

Body:
I basically have a date entered in cell N3 and a column (column I) that contains date sorted by date. I am trying to write a code that asks the user to input a date at first. Then the program would look for that date in the column I and delete ALL the rows after the row in which the match was found.

My code is somehow working, but here is my problem. Only a part of the rows under the wanted row are being deleted and not all of them. I was thinking that could be an issue with the for-loop or the counter?
Please let me know if you could help :)

Sub DeleteAllRowsPaymentTooFar()

Worksheets("Master").Activate

Dim date_max As Date
date_max = InputBox("What is the maximum date to filter? ")

Range("N3").Value = date_max
Range("N3").NumberFormat = ("ddddd, mmmmmmmmm d, yyyy")

Dim i As Long
i = Range("A4").End(xlDown).Row
Dim result As Integer
Dim str1 As String, str2 As String
Dim counter As Long

str1 = Cells(3, 14).Text

counter = 4

Do While counter <= i

str2 = Cells(counter, 9).Text

result = StrComp(str1, str2, vbTextCompare)

  If result <> 0 Then
 MsgBox ("The date is not yet reached.")

  Else

        For K = counter To i
        Worksheets("Master").Rows(K).EntireRow.Delete
        Next

    End If

counter = counter + 1
Loop

End Sub

I expect to remove all the rows under the row where the match was found.

Body:
This may help you:

For i=LastPoint To FirstPoint Step-1

    Worksheets("Master").Rows(i).EntireRow.Delete

Next i


问:
ASP.NET: Implementing Init and Dispose methods
Can an ASP.NET web application have only one Init and one Dispose method or can I implement these per class for those which I want to associate such methods?

More specifically I have Customer component and a CustomerRecord classes and would like to implement Init and Dispose methods in both of them.

What is the proper way to do this?

Requirement:

I want to have independent Init and Dispose methods for each aforementioned class.

答:
For classes that should be disposable, by exposing a public Dispose method, the IDispsable interface must be implemented for 'disposability' to be effective out of the scope of explicit user disposal. This has been covered many times in many places, including here, for example:

```<code>public class Customer : IDisposable
{
    public void Dispose()
    {
        Dispose(true);
        GC.SupressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            //dispose of managed resources
        }
        //dispose of unmanaged resources
    }

    ~Customer()
    {
        Dispose(false);
    }
}
</code>```

Note that the destructor (the method starting with the tilde ~) may not be necessary, but read the details from the answer I linked above for clarity on the situation of what and why - this just answers your question directly.

As for an Init method, are you referring to a constructor?

If so, then look at the destructor in the above example; a constructor (or initialiser) can be defined in the same way minus the tilde and, generally, plus an explicit access modifier (public, private, et cetera), for example:

```<code>public class Customer
{
    public Customer()
    {

    }
}
</code>```

Body:
For classes that should be disposable, by exposing a public Dispose method, the IDispsable interface must be implemented for 'disposability' to be effective out of the scope of explicit user disposal. This has been covered many times in many places, including here, for example:

public class Customer : IDisposable
{
    public void Dispose()
    {
        Dispose(true);
        GC.SupressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            //dispose of managed resources
        }
        //dispose of unmanaged resources
    }

    ~Customer()
    {
        Dispose(false);
    }
}

Note that the destructor (the method starting with the tilde ~) may not be necessary, but read the details from the answer I linked above for clarity on the situation of what and why - this just answers your question directly.

As for an Init method, are you referring to a constructor?

If so, then look at the destructor in the above example; a constructor (or initialiser) can be defined in the same way minus the tilde and, generally, plus an explicit access modifier (public, private, et cetera), for example:

public class Customer
{
    public Customer()
    {

    }
}


问:
Listener keydown : backspace and field length
I'm wondering why my Backspace touch increment my countLetters variable.

I ask him to return the number of characters, without ever manually incrementing the variable. Why does the backspace key increment my variable once, before working properly?

```<code>const $textareas   = document.querySelectorAll('.js-textarea');

$textareas.forEach(function($textarea) {
  $textarea.addEventListener('keydown', function(event) {
    let max = 100;
    let countLetters = $textarea.value.length;

    let $meta = this.nextSibling.nextSibling; // = meta

    $meta.innerHTML = countLetters + ' / ' + max;

    if (countLetters >= max) {
      $textarea.value.toString().substring(0, max);
    }

    if (event.which != 46) {
      return;
    }

    // Disabled <textarea>
    if (countLetters >= max) {
      event.preventDefault();
    }
  });
});
</code>```

Demo is available on Here's Codepen!

Thanks

答:
The value of the text area is changed after your keydown handler runs. You could use the input event instead.

Here is an example:

```<code>const max = 100;
$textarea.addEventListener('input', function() {
    const countLetters = $textarea.value.length;
    const $meta = this.nextSibling.nextSibling;
    $meta.innerHTML = countLetters + ' / ' + max;
});
$textarea.addEventListener('keydown', function(event) {
    if ($textarea.value.length >= max && event.key === 'Backspace') {
      event.preventDefault();
    }
});
</code>```

Body:
I'm wondering why my Backspace touch increment my countLetters variable.

I ask him to return the number of characters, without ever manually incrementing the variable. Why does the backspace key increment my variable once, before working properly?

const $textareas   = document.querySelectorAll('.js-textarea');

$textareas.forEach(function($textarea) {
  $textarea.addEventListener('keydown', function(event) {
    let max = 100;
    let countLetters = $textarea.value.length;

    let $meta = this.nextSibling.nextSibling; // = meta

    $meta.innerHTML = countLetters + ' / ' + max;

    if (countLetters >= max) {
      $textarea.value.toString().substring(0, max);
    }

    if (event.which != 46) {
      return;
    }

    // Disabled <textarea>
    if (countLetters >= max) {
      event.preventDefault();
    }
  });
});

Demo is available on Here's Codepen!

Thanks

Body:
The value of the text area is changed after your keydown handler runs. You could use the input event instead.

Here is an example:

const max = 100;
$textarea.addEventListener('input', function() {
    const countLetters = $textarea.value.length;
    const $meta = this.nextSibling.nextSibling;
    $meta.innerHTML = countLetters + ' / ' + max;
});
$textarea.addEventListener('keydown', function(event) {
    if ($textarea.value.length >= max && event.key === 'Backspace') {
      event.preventDefault();
    }
});


问:
How to set a variable equivalent to single array object while iterating through array?
Noob question. I need to pass 3,000+ URLs from a CSV sheet to Selenium. I need Selenium to navigate to each one of these links, scrape information and then put that information into a CSV.

The issue I am running into is when I push my CSV URLS into an array, I cannot pass one single object (url) into Selenium at a time.

I know I likely need some sort of loop. I have tried setting up loops and selecting from the array using .map, .select. and just a do loop.

```<code>urls.map do |url|
    @driver.navigate.to #{url}
    name = @driver.find_element(:css, '.sites-embed-
footer>a').attribute('href')
    puts name
    kb_link = name
    kb_array.push(kb_link)
    puts 'urls is #{n}'
end
</code>```

In the above example, Selenium returns an "invalid URL" error message. De-bugging with Pry tells me that my 'url' object is not a single url, but rather still the entire array.

How can I set Selenium to visit each URL from the array one by one?

EDIT: ----------------
So, after extensive de-bugging with Pry, I found a couple issues. First being that my CSV was feeding a nested array to my loop which was causing the URL error. I had to flatten my array and un-nest it to get around that issue.

After that, I had to build a rescue into my loop so that my script didn't die when it encountered a page without the CSS element I was looking for.

Here's the finalized loop.

```<code>begin
        @urls1.each do |url|
          @driver.navigate.to(url)
          @driver.manage.timeouts.implicit_wait = 10

          name = @driver.find_element(:css, '.sites-embed-
          footer>a').attribute('href')
          puts name
          kb_link = name
          kb_array.push(kb_link)
          puts 'done'

         rescue Selenium::WebDriver::Error::NoSuchElementError
         puts 'no google doc'
         x = 'no google doc'
         kb_array.push(x)
         next
    end
</code>```

答:
What about using .each?

Example:

```<code>array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }
</code>```

In your code:

```<code>urls.each do |url|
    @driver.navigate.to #{url}
    name = @driver.find_element(:css, '.sites-embed-footer>a').attribute('href')
    puts name
    kb_link = name
    kb_array.push(kb_link)
    puts 'urls is #{n}'
end
</code>```

Body:
Noob question. I need to pass 3,000+ URLs from a CSV sheet to Selenium. I need Selenium to navigate to each one of these links, scrape information and then put that information into a CSV.

The issue I am running into is when I push my CSV URLS into an array, I cannot pass one single object (url) into Selenium at a time.

I know I likely need some sort of loop. I have tried setting up loops and selecting from the array using .map, .select. and just a do loop.

urls.map do |url|
    @driver.navigate.to #{url}
    name = @driver.find_element(:css, '.sites-embed-
footer>a').attribute('href')
    puts name
    kb_link = name
    kb_array.push(kb_link)
    puts 'urls is #{n}'
end

In the above example, Selenium returns an "invalid URL" error message. De-bugging with Pry tells me that my 'url' object is not a single url, but rather still the entire array.

How can I set Selenium to visit each URL from the array one by one?

EDIT: ----------------
So, after extensive de-bugging with Pry, I found a couple issues. First being that my CSV was feeding a nested array to my loop which was causing the URL error. I had to flatten my array and un-nest it to get around that issue.

After that, I had to build a rescue into my loop so that my script didn't die when it encountered a page without the CSS element I was looking for.

Here's the finalized loop.

begin
        @urls1.each do |url|
          @driver.navigate.to(url)
          @driver.manage.timeouts.implicit_wait = 10

          name = @driver.find_element(:css, '.sites-embed-
          footer>a').attribute('href')
          puts name
          kb_link = name
          kb_array.push(kb_link)
          puts 'done'

         rescue Selenium::WebDriver::Error::NoSuchElementError
         puts 'no google doc'
         x = 'no google doc'
         kb_array.push(x)
         next
    end

Body:
What about using .each?

Example:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

In your code:

urls.each do |url|
    @driver.navigate.to #{url}
    name = @driver.find_element(:css, '.sites-embed-footer>a').attribute('href')
    puts name
    kb_link = name
    kb_array.push(kb_link)
    puts 'urls is #{n}'
end


问:
Image in the card appears very poorly because of styles (Bootstrap 4)
If you upload an image which has higher height and less width then it shows very poorly in the card (user cards). Here are the HTML and css parts. We are using Angular with it:

HTML

```<code><div class="container-fluid" >
  <div class="row people-row">
    <div class="col-12 row">
      <div class="m1-* col-md-3 text-center" *ngFor="let user of filteredUsers | filter: searchByKeyword: 'name' | paginate: { itemsPerPage: 12, currentPage: p }">
        <div class="card card-person">
          <a  (click)="ViewUser(user)">
            <img class="card-img-top" src="http://res.cloudinary.com/dfg5p1pww/image/upload/v{{user.picVersion}}/{{user.picId}}"
            alt="Card image" style="width:100%">
            <div class="card-body">
              <h4 class="card-title"> {{user.firstName}} {{user.lastName}}</h4>
              <p class="card-text">{{user.age}}</p>
              <p class="card-text">{{user.country}},{{user.city}}</p>
              <p class="material-icons" *ngIf="CheckIfOnline(user.username)">online</p>
              <a class="btn button-image closeButton btn-message" [routerLink]="['/chat', user.username]">Message</a>
            </div>
          </a>
        </div>
      </div>
    </div>
</code>```

CSS

```<code>.card-img-top {
    position: relative;
    overflow: hidden;
    height: 200px;
    width: auto
}

.card-person {
  margin: 50px auto;
  background-color: #ffffff;
  border-radius: 0;
  border: 0;
  box-shadow: 1em 1em 2em rgba(0,0,0,.2);
}

.card-text {
 margin-bottom:0.2rem
}

.btn-match,
.btn-message {
  color:#ffffff;
  background: #FF512F;  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #FF512F, #DD2476);  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #FF512F, #DD2476); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
transition: all .4s;
margin:5px;
border-radius:40px
}

.button-image:before {
  content: "";
  width: 23px;
  height: 23px;
  display: inline-block;
  background-size: 100%;
  vertical-align: text-top;
  background-color: transparent;
  background-position : center center;
  background-repeat:no-repeat;
}

.btn-match.closeButton:before{
   background-image : url('../../../assets/images/heart-white.png');
}

.btn-message.closeButton:before{
  background-image : url('../../../assets/images/chat-white.png');

}

a.fill {
  width: 100%;
  height: 50px;
  }
</code>```

What can cause such an issue and how can this problem be fixed in Bootstrap 4 so all type of images can be look normal?

答:
if i'm right you are using .card-img-top
    so add the class .card-person.card-img-top

Body:
If you upload an image which has higher height and less width then it shows very poorly in the card (user cards). Here are the HTML and css parts. We are using Angular with it:

HTML

 {{user.firstName}} {{user.lastName}}

{{user.age}}

{{user.country}},{{user.city}}

online

              Message

CSS

.card-img-top {
    position: relative;
    overflow: hidden;
    height: 200px;
    width: auto
}

.card-person {
  margin: 50px auto;
  background-color: #ffffff;
  border-radius: 0;
  border: 0;
  box-shadow: 1em 1em 2em rgba(0,0,0,.2);
}

.card-text {
 margin-bottom:0.2rem
}

.btn-match,
.btn-message {
  color:#ffffff;
  background: #FF512F;  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #FF512F, #DD2476);  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #FF512F, #DD2476); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
transition: all .4s;
margin:5px;
border-radius:40px
}

.button-image:before {
  content: "";
  width: 23px;
  height: 23px;
  display: inline-block;
  background-size: 100%;
  vertical-align: text-top;
  background-color: transparent;
  background-position : center center;
  background-repeat:no-repeat;
}

.btn-match.closeButton:before{
   background-image : url('../../../assets/images/heart-white.png');
}

.btn-message.closeButton:before{
  background-image : url('../../../assets/images/chat-white.png');

}

a.fill {
  width: 100%;
  height: 50px;
  }

What can cause such an issue and how can this problem be fixed in Bootstrap 4 so all type of images can be look normal?


问:
Why I can't disable spring boot auto generated password and user?
I m starting a new spring boot project, desiring to disable the auto configured user in Spring Security, I tried a lot of configuration but none works, I don't know what I m missing ? !!!

First here is my project dependencies

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bridjit.esport</groupId>
    <artifactId>esport_1.0</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>esport 1.0</name>
    <description>hand made spring backend project for esport project</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.9</version>
                <executions>
                    <execution>
                        <id>build-classpath</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>build-classpath</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <outputFile>classpath.txt</outputFile>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

as you see I m using spring boot 2.1.5 with web flux, security, mongo, actuator

to disable  the auto user configuration I tried to implement my own UserDetailService withe security as shown below

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

    private UserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;

    public SecurityConfigurer(EsportUserDetailService userDetailsService, PasswordEncoder passwordEncoder) {
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
        .and()
        .authorizeRequests().anyRequest().authenticated();
    }
}
</code>```

```<code>@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
</code>```

```<code>public class EsportUserDetailService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> userFindByUsername = userRepository.findByUsername(username);
        User user = new User();
        if (userFindByUsername.isPresent()) user = userFindByUsername.get();
        return new EsportPrincipal(user);
    }

}
</code>```

```<code>@Configuration
public class BeansConfig{

    @Bean
    public PasswordEncoder getPasswordEncoding(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public EsportUserDetailService getEsportUsersDetailSericeImplementation(){
        return new EsportUserDetailService();
    }

}
</code>```

when I run using the maven spring-boot plugin my app starts fine it connects to my mongodb docker container, but I m still getting the password and the user autoconfigured, what I m missing in my configuration ?

答:
Since you are using WebFlux rather than Spring MVC , you have to use WebFlux Security .

To disable that default user and password configured by SpringBoot , you have to implement ReactiveUserDetailsService instead.

Body:
I m starting a new spring boot project, desiring to disable the auto configured user in Spring Security, I tried a lot of configuration but none works, I don't know what I m missing ? !!!

First here is my project dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath />
    </parent>
    <groupId>com.bridjit.esport</groupId>
    <artifactId>esport_1.0</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>esport 1.0</name>
    <description>hand made spring backend project for esport project</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>

        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.9</version>
                <executions>
                    <execution>
                        <id>build-classpath</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>build-classpath</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <outputFile>classpath.txt</outputFile>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

as you see I m using spring boot 2.1.5 with web flux, security, mongo, actuator

to disable  the auto user configuration I tried to implement my own UserDetailService withe security as shown below

@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

    private UserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;

    public SecurityConfigurer(EsportUserDetailService userDetailsService, PasswordEncoder passwordEncoder) {
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
        .and()
        .authorizeRequests().anyRequest().authenticated();
    }
}

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

public class EsportUserDetailService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> userFindByUsername = userRepository.findByUsername(username);
        User user = new User();
        if (userFindByUsername.isPresent()) user = userFindByUsername.get();
        return new EsportPrincipal(user);
    }

}

@Configuration
public class BeansConfig{

    @Bean
    public PasswordEncoder getPasswordEncoding(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public EsportUserDetailService getEsportUsersDetailSericeImplementation(){
        return new EsportUserDetailService();
    }

}

when I run using the maven spring-boot plugin my app starts fine it connects to my mongodb docker container, but I m still getting the password and the user autoconfigured, what I m missing in my configuration ?


问:
ORA-00926: missing VALUES keyword while using insert into table as select * from in execute immediate
I have two table emp1 and emp2 i want to create emp3 by using emp1 and emp2 all this i need to do plsql to automate code

I tried coding but getting

ORA-00926: missing VALUES keyword ORA-06512: at line 9

```<code>declare
v1  varchar2(2000);
begin
for i in 1..2
loop
v1:='insert into emp3 as select * from emp'||i||'where 1=1;';
execute immediate v1;
end loop;
end;
</code>```

ORA-00926: missing VALUES keyword
ORA-06512: at line 9.
i have a bigger where condition but i just used 'where 1=1' and bigger tables but i need the logic for this thanks!

答:
First, I don't think there is any as.

Second, if you printed out the sql, the problem would probably be obvious.

You can try this:

```<code>insert into emp3
    select * from emp'||i||' where 1=1;'
</code>```

Body:
I have two table emp1 and emp2 i want to create emp3 by using emp1 and emp2 all this i need to do plsql to automate code

I tried coding but getting

ORA-00926: missing VALUES keyword ORA-06512: at line 9

declare
v1  varchar2(2000);
begin
for i in 1..2
loop
v1:='insert into emp3 as select * from emp'||i||'where 1=1;';
execute immediate v1;
end loop;
end;

ORA-00926: missing VALUES keyword
ORA-06512: at line 9.
i have a bigger where condition but i just used 'where 1=1' and bigger tables but i need the logic for this thanks!

Body:
First, I don't think there is any as.

Second, if you printed out the sql, the problem would probably be obvious.

You can try this:

insert into emp3
    select * from emp'||i||' where 1=1;'


问:
How to duplicate elements in a js array without creating "dependent elements"?
I am trying to modify a single element from an array whose elements were previously duplicated n times. To perform the array duplication I just relied on a custom function duplicateElements(array, times)from this post (see @Bamieh answer). As shown in the exemple below, the problem is I can't modify a single element from the array without modifying other elements:

function duplicateElements(array, times) {
  return array.reduce((res, current) => {
    return res.concat(Array(times).fill(current));
  }, []);
}

var myvar = duplicateElements([{ a: 1 }, { a: 2 }], 2);
myvar[0].a = 3;

console.log(myvar);
// (4) [{…}, {…}, {…}, {…}]
// 0: {a: 3}
// 1: {a: 3}
// 2: {a: 2}
// 3: {a: 2}
// length: 4
```

As you can see myvar[1].a was also modified although this wasn't intended. How can I avoid this issue?

答:
Replace

```<code> Array(times).fill(current)
</code>```

which will add one reference to current multiple times to the array with:

```<code>  Array.from({ length: times }, () => ({...current }))
</code>```

which will shallow clone current. Note that the code will then only work with objects though, not with primitives.

I'd do:

```<code> const duplicateElements = (array, length)  =>
    array.flatMap(current => Array.from({ length }, () => ({ ...current }));
</code>```

Body:
I am trying to modify a single element from an array whose elements were previously duplicated n times. To perform the array duplication I just relied on a custom function duplicateElements(array, times)from this post (see @Bamieh answer). As shown in the exemple below, the problem is I can't modify a single element from the array without modifying other elements:

function duplicateElements(array, times) {
  return array.reduce((res, current) => {
    return res.concat(Array(times).fill(current));
  }, []);
}

var myvar = duplicateElements([{ a: 1 }, { a: 2 }], 2);
myvar[0].a = 3;

console.log(myvar);
// (4) [{…}, {…}, {…}, {…}]
// 0: {a: 3}
// 1: {a: 3}
// 2: {a: 2}
// 3: {a: 2}
// length: 4

As you can see myvar[1].a was also modified although this wasn't intended. How can I avoid this issue?

Body:
Replace

 Array(times).fill(current)

which will add one reference to current multiple times to the array with:

  Array.from({ length: times }, () => ({...current }))

which will shallow clone current. Note that the code will then only work with objects though, not with primitives.

I'd do:

 const duplicateElements = (array, length)  =>
    array.flatMap(current => Array.from({ length }, () => ({ ...current }));


问:
Does Azure Function App restrict outgoing HTTP calls from inside the function to HTTPS only?
I have a NodeJS Azure Function App that is up and running, and recently I have had to change the endpoint of one HTTP call to another URL.

This URL is verified to be working and returning expected responses. However once the previous HTTPS URL on Azure application settings was replaced with the new non-HTTPS URL, everything breaks and the function only shows as "Function started" repeatedly. Changing the environment variable back to the old HTTPS URL fixes it.

So we are suspecting that it is an issue with Azure Function App possibly restricting all outgoing HTTP calls to HTTPS only, but we couldn't find anything in the docs or on the internet.

Thanks!

答: No, Azure Functions do not limit the outbound calls to HTTPS-only. Are you sure your SSL certificate is valid (and signed by a recognized CA)?</p>