问:
How to I detect model changes at a component level?
I need to be able to detect model changes (not only input from the frontend but backend/application changes) at a component level.

I would like to set the focus of a component element when model properties meet certain criteria.

I'm using Angular 7.

I have the following model:

```<code>export class Hello  {
  enabled: boolean;
  name: string;
  focus: boolean;
  selected: boolean;
  text: string;
}
</code>```

And the following component references the model:

```<code>export class HelloComponent  {
  @Input() model: Hello;
}
</code>```

Say now I have a process that updates the model on the backend, for example, the "focus" boolean changes often, I want to be able to detect that change in the component and focus on an element.

答: It's better to use RxJS to that. Just use subscription in component on events from your application service with criteria subject.

Body:
I need to be able to detect model changes (not only input from the frontend but backend/application changes) at a component level.

I would like to set the focus of a component element when model properties meet certain criteria.

I'm using Angular 7.

I have the following model:

export class Hello  {
  enabled: boolean;
  name: string;
  focus: boolean;
  selected: boolean;
  text: string;
}

And the following component references the model:

export class HelloComponent  {
  @Input() model: Hello;
}

Say now I have a process that updates the model on the backend, for example, the "focus" boolean changes often, I want to be able to detect that change in the component and focus on an element.


来源: stackexchange

问:
SE Linux Android 9 AOSP: Adding a permission in platform_app.te file leading to a build failure
I am working on Android9 AOSP, when I add a permission in my platform_app.te (located in /system/sepolicy/public/platform_app.te), my build fails.
system/sepolicy/public/platform_app.te:10:"ERROR 'unknown type xyz_service' at token ';' on line "

The permission that am adding is allow platform_app xyz_service:binder { call transfer };

Background on xyz_service:-
It is a service started by init and its '.te' file is located in /system/sepolicy/vendor/xyz_service.te

One reason I could think of is that the xyz_service.te resides in /system/sepolicy/vendor while the other file is in /system/sepolicy/public. Moving it to /public from /vendor gives more issues. And of-course you cannot have the files in both locations as it results in 'Duplicate declaration of type' error. Can anyone please guide me, thanks!

答: xyz_service type is defined in /system/sepolicy/vendor/xyz_service.te and you are trying to access it from  system/sepolicy/public/platform_app.te where it's not accessible. please check file.te available in system/sepolicy/public and defined xyz_service type in this file.te to get access in system/sepolicy/public/platform_app.te.</p>

ContentLicense: CC BY-SA 4.0


问:
Qt Installer Framework - load binary automatically once installation is finished
I want to load the binary automatically once installation is completed using Qt Installation framework. How this can be achieved?

I am trying to edit this script and added component.addOperation("CreateShortcut", "@TargetDir@/DistributionKit/Abc.sh"); But its not loading the script automatically. What i am missing ?

function Component()
{
    installer.installationFinished.connect(this, Component.prototype.installationFinishedPageIsShown);
    installer.finishButtonClicked.connect(this, Component.prototype.installationFinished);

}

Component.prototype.createOperations = function()
{
    component.createOperations();
}

Component.prototype.installationFinishedPageIsShown = function()
{
    try {
        if (installer.isInstaller() && installer.status == QInstaller.Success) {
            installer.addWizardPageItem( component, "ReadMeCheckBoxForm", QInstaller.InstallationFinished );
        }
    } catch(e) {
        console.log(e);
    }
}

Component.prototype.installationFinished = function()
{
    try {
        if (installer.isInstaller() && installer.status == QInstaller.Success) {
            var isReadMeCheckBoxChecked = component.userInterface( "ReadMeCheckBoxForm" ).readMeCheckBox.checked;
            if (isReadMeCheckBoxChecked) {
                //QDesktopServices.openUrl("file:///" + installer.value("TargetDir") + "/Abc.sh");
  component.addOperation("CreateShortcut", "@TargetDir@/DistributionKit/Abc.sh");
            }
        }
    } catch(e) {
        console.log(e);
    }
}```

答:
Qt installer framework has an executeDetached function in the installer. I believe this is what you need to use to launch your program. In this case, your script would look like (only adding the affected function):

```<code>Component.prototype.installationFinished = function()
{
    try {
        if (installer.isInstaller() && installer.status == QInstaller.Success) {
            var isReadMeCheckBoxChecked = component.userInterface( "ReadMeCheckBoxForm" ).readMeCheckBox.checked;
            if (isReadMeCheckBoxChecked) {
                installer.exectueDetached("bash", installer.value("TargetDir") + "/Abc.sh");
                component.addOperation("CreateShortcut", "@TargetDir@/DistributionKit/Abc.sh");
            }
        }
    } catch(e) {
        console.log(e);
    }
}
</code>```

Note that you actually need to run "bash" as executeDetached and pass your script as an argument to the bash. If you were running an executable you would not have "bash" in the exectueDetached command.

*Note that I did not add "/DistributionKint/" in the exectueDetached. This is because in the commented line in your original question Abc.sh was directly under @TargetDir@. Obviously, you need to pass the installer.executeDetached the right path to your sh script.

Body:
Qt installer framework has an executeDetached function in the installer. I believe this is what you need to use to launch your program. In this case, your script would look like (only adding the affected function):

Component.prototype.installationFinished = function()
{
    try {
        if (installer.isInstaller() && installer.status == QInstaller.Success) {
            var isReadMeCheckBoxChecked = component.userInterface( "ReadMeCheckBoxForm" ).readMeCheckBox.checked;
            if (isReadMeCheckBoxChecked) {
                installer.exectueDetached("bash", installer.value("TargetDir") + "/Abc.sh");
                component.addOperation("CreateShortcut", "@TargetDir@/DistributionKit/Abc.sh");
            }
        }
    } catch(e) {
        console.log(e);
    }
}

Note that you actually need to run "bash" as executeDetached and pass your script as an argument to the bash. If you were running an executable you would not have "bash" in the exectueDetached command.

*Note that I did not add "/DistributionKint/" in the exectueDetached. This is because in the commented line in your original question Abc.sh was directly under @TargetDir@. Obviously, you need to pass the installer.executeDetached the right path to your sh script.


问:
p5.js canvas not visible
Hello to whoever is reading this

I have a problem with the below code, I can't seem to get the browser to display the canvas

JS Code:

sketch.js:

```<code>     var blob;

     function setup() {
        createCanvas(600, 600);
        blob = new Blob();
    }

    function draw() {
        background(0);
        blob.show();
    }
</code>```

blob.js:

```<code>     function Blob() {
        this.pos = createVector(width / 2, height / 2);
        this.r = 64;
    }

    this.show = function() {
        fill(255);
        ellipse(this.pos.x, this.pos.y, this.r * 2, this.r * 2);
    };
</code>```

I first used a script-src attribute to link it as an external javascript file, which didn't work, then I tried to embed it inside an HTML document, but that didn't work either.

I also tried to change the browser, which failed to change the look of the webpage, which is still blank.

Then I tried to use the  element to display the canvas, which didn't work as well.

please help, I'm new to using the p5.js canvas

答:
The this.show() method should be part of your Blob() object like this

```<code>function Blob() {
  this.pos = createVector(width / 2, height / 2);
  this.r = 64;
  this.show = function() {
    fill(255);
    ellipse(this.pos.x, this.pos.y, this.r * 2, this.r * 2);
  }
};
</code>```

Here's a working example.

Title: p5.js canvas not visible

Body:
Hello to whoever is reading this

I have a problem with the below code, I can't seem to get the browser to display the canvas

JS Code:

sketch.js:

     var blob;

     function setup() {
        createCanvas(600, 600);
        blob = new Blob();
    }

    function draw() {
        background(0);
        blob.show();
    }

blob.js:

     function Blob() {
        this.pos = createVector(width / 2, height / 2);
        this.r = 64;
    }

    this.show = function() {
        fill(255);
        ellipse(this.pos.x, this.pos.y, this.r * 2, this.r * 2);
    };

I first used a script-src attribute to link it as an external javascript file, which didn't work, then I tried to embed it inside an HTML document, but that didn't work either.

I also tried to change the browser, which failed to change the look of the webpage, which is still blank.

Then I tried to use the  element to display the canvas, which didn't work as well.

please help, I'm new to using the p5.js canvas

Body:
The this.show() method should be part of your Blob() object like this

function Blob() {
  this.pos = createVector(width / 2, height / 2);
  this.r = 64;
  this.show = function() {
    fill(255);
    ellipse(this.pos.x, this.pos.y, this.r * 2, this.r * 2);
  }
};

Here's a working example.


问:
flutter: on background message handler is not being called
I have implemented firebase cloud messaging and firebase functions to my app and used flutter local notifications and added a showNotifications function to make a channel ID and change its importance and priority so i get notifications as heads up (banner), but for some reason the onbackgroundmessagehandler callback is not being called when i send a message from firestore,

here's my code:

```<code>  Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
      print('background message handler');
      return await _TabsScreenState()._showNotification(message);
    }

    class TabsScreen extends StatefulWidget {
      static const String id = '/tabs screen';

      @override
      _TabsScreenState createState() => _TabsScreenState();
    }

    class _TabsScreenState extends State<TabsScreen> {
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          FlutterLocalNotificationsPlugin();
      FirebaseMessaging _fcm = FirebaseMessaging();
      Firestore _fireStore = Firestore.instance;

      void _onSaved() async {
        String myToken = await _fcm.getToken();

        if (myToken != null) {
          var tokenRef = _fireStore.collection('tokens').document(myToken);
          print(myToken);

          await tokenRef.setData({
            'token': myToken,
            'createdAt': DateTime.now(),
            'platform': Platform.operatingSystem,
          });
        }
      }

      Future _showNotification(Map<String, dynamic> message) async {
        print('show notifications');
        var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
          'channel id',
          'channel name',
          'channel desc',
          importance: Importance.Max,
          priority: Priority.High,
        );

        var platformChannelSpecifics =
            new NotificationDetails(androidPlatformChannelSpecifics, null);
        await flutterLocalNotificationsPlugin.show(
          0,
          message['notifications']['title'],
          'hi',
          platformChannelSpecifics,
          payload: 'default sound',
        );
      }

      Future selectNotification(String payload) async {
        await flutterLocalNotificationsPlugin.cancelAll();
      }

      void initState() {
        var initializationSettingsAndroid =
            AndroidInitializationSettings('@mipmap/ic_launcher');
        var initializationSettings =
            InitializationSettings(initializationSettingsAndroid, null);
        flutterLocalNotificationsPlugin.initialize(initializationSettings,
            onSelectNotification: selectNotification);
        _onSaved();
        _fcm.configure(
            onBackgroundMessage: myBackgroundMessageHandler,
            onMessage: (Map<String, dynamic> message) async {
              print("On Message: $message");
              print(message['data']['message']);
              showDialog(
                context: context,
                builder: (ctx) {
                  return AlertDialog(
                    content: ListTile(
                      title: Text(message['data']['message']),
                    ),
                    actions: <Widget>[
                      FlatButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text('Ok'),
                      )
                    ],
                  );
                },
              );
            },
            onResume: (Map<String, dynamic> resume) async {
              print("on resume: $resume");
            },
            onLaunch: (Map<String, dynamic> launch) async {
              print("on launch: $launch");
            });

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
          title: Text("My App"),
        );
      }
    }
</code>```

here is my andoird manifest:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tamataapp">
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. "io.flutter.app.FlutterApplication" -->
    <application
        android:name=".Application"
        android:label="tamataapp"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value="default_notification_channel_id”>Channel ID"/>
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme"
                />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
                android:name="io.flutter.embedding.android.SplashScreenDrawable"
                android:resource="@drawable/launch_background"
                />
            <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="FLUTTER_NOTIFICATION_CLICK" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <service
            android:name=".java.MyFirebaseMessagingService"
            android:exported="false">
        </service>
    </application>
</manifest>
</code>```

and heres my index.js code:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

var newData;

exports.messageTrigger = functions.firestore.document('messages/{messagesId}').onCreate(async (snapshot, context) => {

    if (snapshot.empty) {
        console.log('No Devices');
        return;
    }

    newData = snapshot.data();

    const deviceIdTokens = await admin
        .firestore()
        .collection('tokens')
        .get();

    var tokenm = [];

    for (var one of deviceIdTokens.docs) {
        tokenm.push(one.data().token);
    }
    const payload = {
        data: {
          click_action: 'FLUTTER_NOTIFICATION_CLICK',
          message: newData.message,

        }
      };

    try {
        const response = await admin.messaging().sendToDevice(tokenm, payload);
        console.log('Notification sent successfully');
    } catch (err) {
        console.log(err);
    }
});
</code>```

答:
What version of firebase_messaging are you using ?

From pub page https://pub.dev/packages/flutter_local_notifications:

Compatibility with firebase_messaging

Previously, there were issues that prevented this plugin working
  properly with the firebase_messaging plugin. This meant that callbacks
  from each plugin might not be invoked. Version 6.0.13 of
  firebase_messaging should resolve this issue so please bump your
  firebase_messaging dependency and follow the steps covered in
  firebase_messaging's readme file.

Body:
I have implemented firebase cloud messaging and firebase functions to my app and used flutter local notifications and added a showNotifications function to make a channel ID and change its importance and priority so i get notifications as heads up (banner), but for some reason the onbackgroundmessagehandler callback is not being called when i send a message from firestore,

here's my code:

  Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
      print('background message handler');
      return await _TabsScreenState()._showNotification(message);
    }

    class TabsScreen extends StatefulWidget {
      static const String id = '/tabs screen';

      @override
      _TabsScreenState createState() => _TabsScreenState();
    }

    class _TabsScreenState extends State<TabsScreen> {
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          FlutterLocalNotificationsPlugin();
      FirebaseMessaging _fcm = FirebaseMessaging();
      Firestore _fireStore = Firestore.instance;

      void _onSaved() async {
        String myToken = await _fcm.getToken();

        if (myToken != null) {
          var tokenRef = _fireStore.collection('tokens').document(myToken);
          print(myToken);

          await tokenRef.setData({
            'token': myToken,
            'createdAt': DateTime.now(),
            'platform': Platform.operatingSystem,
          });
        }
      }

      Future _showNotification(Map<String, dynamic> message) async {
        print('show notifications');
        var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
          'channel id',
          'channel name',
          'channel desc',
          importance: Importance.Max,
          priority: Priority.High,
        );

        var platformChannelSpecifics =
            new NotificationDetails(androidPlatformChannelSpecifics, null);
        await flutterLocalNotificationsPlugin.show(
          0,
          message['notifications']['title'],
          'hi',
          platformChannelSpecifics,
          payload: 'default sound',
        );
      }

      Future selectNotification(String payload) async {
        await flutterLocalNotificationsPlugin.cancelAll();
      }

      void initState() {
        var initializationSettingsAndroid =
            AndroidInitializationSettings('@mipmap/ic_launcher');
        var initializationSettings =
            InitializationSettings(initializationSettingsAndroid, null);
        flutterLocalNotificationsPlugin.initialize(initializationSettings,
            onSelectNotification: selectNotification);
        _onSaved();
        _fcm.configure(
            onBackgroundMessage: myBackgroundMessageHandler,
            onMessage: (Map<String, dynamic> message) async {
              print("On Message: $message");
              print(message['data']['message']);
              showDialog(
                context: context,
                builder: (ctx) {
                  return AlertDialog(
                    content: ListTile(
                      title: Text(message['data']['message']),
                    ),
                    actions: <Widget>[
                      FlatButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text('Ok'),
                      )
                    ],
                  );
                },
              );
            },
            onResume: (Map<String, dynamic> resume) async {
              print("on resume: $resume");
            },
            onLaunch: (Map<String, dynamic> launch) async {
              print("on launch: $launch");
            });

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
          title: Text("My App"),
        );
      }
    }

here is my andoird manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tamataapp">

    <application
        android:name=".Application"
        android:label="tamataapp"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value="default_notification_channel_id”>Channel ID"/>

            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme"
                />

            <meta-data
                android:name="io.flutter.embedding.android.SplashScreenDrawable"
                android:resource="@drawable/launch_background"
                />
            <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="FLUTTER_NOTIFICATION_CLICK" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        </activity>

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <service
            android:name=".java.MyFirebaseMessagingService"
            android:exported="false">
        </service>
    </application>
</manifest>

and heres my index.js code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

var newData;

exports.messageTrigger = functions.firestore.document('messages/{messagesId}').onCreate(async (snapshot, context) => {

    if (snapshot.empty) {
        console.log('No Devices');
        return;
    }

    newData = snapshot.data();

    const deviceIdTokens = await admin
        .firestore()
        .collection('tokens')
        .get();

    var tokenm = [];

    for (var one of deviceIdTokens.docs) {
        tokenm.push(one.data().token);
    }
    const payload = {
        data: {
          click_action: 'FLUTTER_NOTIFICATION_CLICK',
          message: newData.message,

        }
      };

    try {
        const response = await admin.messaging().sendToDevice(tokenm, payload);
        console.log('Notification sent successfully');
    } catch (err) {
        console.log(err);
    }
});


问:
Add controller to Prestashop module
I am using the payment module that puts prestashop in GitHub as an example, but when adding a new controller I get the following error:

```<code>Uncaught Error: Class 'paymentexampleMyControllerModuleFrontController' not found in /opt/bitnami/apps/prestashop/htdocs/classes/controller/Controller.php:208
</code>```

Check the builder which is shown as follows:

```<code>    $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
    $this->author = 'PrestaShop';
    $this->controllers = array('validation', 'MyController');
</code>```

I already cleared cache and gave reset to the module but I keep getting the same error, I use prestashop 1.7

答:
How do you declare it?

It should be:

```<code>class PaymentExampleMyControllerModuleFrontController extends ModuleFrontController
</code>```

and the location should be:

If a legacy controller controllers/front.

If a Symfony controller src/controller/front

Title: Add controller to Prestashop module

Body:
I am using the payment module that puts prestashop in GitHub as an example, but when adding a new controller I get the following error:

Uncaught Error: Class 'paymentexampleMyControllerModuleFrontController' not found in /opt/bitnami/apps/prestashop/htdocs/classes/controller/Controller.php:208

Check the builder which is shown as follows:

    $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
    $this->author = 'PrestaShop';
    $this->controllers = array('validation', 'MyController');

I already cleared cache and gave reset to the module but I keep getting the same error, I use prestashop 1.7

Body:
How do you declare it?

It should be:

class PaymentExampleMyControllerModuleFrontController extends ModuleFrontController

and the location should be:

If a legacy controller controllers/front.

If a Symfony controller src/controller/front


问:
How to insert NULL into Django's DateField?
I have an optional datefield in my django model:

```<code>award_grant_date = models.DateField(null=True, blank=True)
</code>```

When the user leaves the date field blank, NULL is inserted into the DateField, otherwise the date is inserted.

However, if the user does enter a date into the DateField, and the user has selected some other specific data in the form, then I want to insert NULL into the DateField.

So, in my form I have the following code:

```<code>    class AwardGrantDetailsForm(forms.Form):
    ...
    award_grant_date = forms.DateField(
    widget=forms.DateInput(attrs={'id':'id_award_grant_date'}),
    input_formats=settings.DATE_INPUT_FORMATS,
    label=_('Date'),
    required=False)
    ...
    elif cd_agdf['award_grant_type'] == 8888 or cd_agdf['award_grant_type'] == 9999:

        self.cleaned_data['award_grant_type_description'] = ''
        self.cleaned_data['award_grant_date'] = 'NULL' //this is the issue here!
</code>```

The error I am getting is:

```<code>[u"'NULL' value has an invalid date format. It must be in YYYY-MM-DD format."]
</code>```

I cannot  seem to get the syntax correct to enter the NULL in to the award_grant_date date field.

I am using bootstrap datepicker and django 1.4.

How do I write the code self.cleaned_data['award_grant_date'] = '' to insert the required NULL? I have set the models field to null=True, blank=True!

答:
NULL value has an invalid date format. It must be in YYYY-MM-DD format

If you want to store Null value into model use model_field = None

Solution:

```<code>registration_date = request.POST.get('registration_date')

if not registration_date:
    registration_date = None

#StudentInfo is my model
student = StudentInfo(name=request.POST.get('name'), std=request.POST.get('std'), registration_date=registration_date)

#Now you can save your model data
student.save()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an optional datefield in my django model:

award_grant_date = models.DateField(null=True, blank=True)

When the user leaves the date field blank, NULL is inserted into the DateField, otherwise the date is inserted.

However, if the user does enter a date into the DateField, and the user has selected some other specific data in the form, then I want to insert NULL into the DateField.

So, in my form I have the following code:

    class AwardGrantDetailsForm(forms.Form):
    ...
    award_grant_date = forms.DateField(
    widget=forms.DateInput(attrs={'id':'id_award_grant_date'}),
    input_formats=settings.DATE_INPUT_FORMATS,
    label=_('Date'),
    required=False)
    ...
    elif cd_agdf['award_grant_type'] == 8888 or cd_agdf['award_grant_type'] == 9999:

        self.cleaned_data['award_grant_type_description'] = ''
        self.cleaned_data['award_grant_date'] = 'NULL' //this is the issue here!

The error I am getting is:

[u"'NULL' value has an invalid date format. It must be in YYYY-MM-DD format."]

I cannot  seem to get the syntax correct to enter the NULL in to the award_grant_date date field.

I am using bootstrap datepicker and django 1.4.

How do I write the code self.cleaned_data['award_grant_date'] = '' to insert the required NULL? I have set the models field to null=True, blank=True!

Body:
NULL value has an invalid date format. It must be in YYYY-MM-DD format

If you want to store Null value into model use model_field = None

Solution:

registration_date = request.POST.get('registration_date')

if not registration_date:
    registration_date = None

#StudentInfo is my model
student = StudentInfo(name=request.POST.get('name'), std=request.POST.get('std'), registration_date=registration_date)

#Now you can save your model data
student.save()


问:
How to get the current logged in user ID in ASP.NET Core?
I've done this before with MVC5 using User.Identity.GetUserId() but that doesn't seem to work here.
The User.Identity doesn't have the GetUserId() method.

I am using Microsoft.AspNet.Identity.

答:
For getting current user id in razor views, we can inject UserManager in the view like this:

```<code>@inject Microsoft.AspNetCore.Identity.UserManager<ApplicationUser> _userManager
@{ string userId = _userManager.GetUserId(User); }
</code>```

I hope you find it useful.

Body:
For getting current user id in razor views, we can inject UserManager in the view like this:

@inject Microsoft.AspNetCore.Identity.UserManager<ApplicationUser> _userManager
@{ string userId = _userManager.GetUserId(User); }

I hope you find it useful.


答:
if I get you right

detect model changes (not only input from the frontend but backend/application changes)

you want to be informed in your component, when your model changes.

I would suggest using Observables. You can subscribe to the Observable (e.g. login state).

You do not have to look for changes, but would be informed about changes. In connection with your UI, the changes can be bound, that the UI updates automatically.

Could be sth. like:

```<code>loggedIn$: Observable<Boolean>;

public ngOnInit() {
    this.loggedIn$ = this.loginService.getLoginState()
}
</code>```

When it comes to Observables "State Management" is really interesting - e.g. RXJS or NGXS when it comes to Angular.
Have a look, at some articles.

Title: How to I detect model changes at a component level?

Body:
if I get you right

detect model changes (not only input from the frontend but backend/application changes)

you want to be informed in your component, when your model changes.

I would suggest using Observables. You can subscribe to the Observable (e.g. login state).

You do not have to look for changes, but would be informed about changes. In connection with your UI, the changes can be bound, that the UI updates automatically.

Could be sth. like:

loggedIn$: Observable<Boolean>;

public ngOnInit() {
    this.loggedIn$ = this.loginService.getLoginState()
}

When it comes to Observables "State Management" is really interesting - e.g. RXJS or NGXS when it comes to Angular.
Have a look, at some articles.


问:
How can I create a Class file and JAR file without main function?
How can I create the class file and jar file for this coding, when I compile this program its not working because there is no main function in the program. And also I am trying in command prompt but I don't know how to set the classpath? please help me
My Coding is here</p>

```<code>public class NewLogFields implements ILogNotify
{
    public void onLog(Level level, String comment, IMediaStream stream, String category,String event, int status, String context) {
        if (category.equals(WMSLoggerIDs.CAT_session) && event.equals(WMSLoggerIDs.EVT_destroy))
        {
            Long csBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_cs_bytes);
            Long scBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_sc_bytes);
            System.out.println("disconnect: csBytes:"+csBytes+" scBytes:"+scBytes);
        }
    }
}
</code>```

答:
You can set use switch -cp or -classpath with javac command.

for example javac -cp path and name of jat file or class file yourjavafile.java

Body:
How can I create the class file and jar file for this coding, when I compile this program its not working because there is no main function in the program. And also I am trying in command prompt but I don't know how to set the classpath? please help me
My Coding is here

public class NewLogFields implements ILogNotify
{
    public void onLog(Level level, String comment, IMediaStream stream, String category,String event, int status, String context) {
        if (category.equals(WMSLoggerIDs.CAT_session) && event.equals(WMSLoggerIDs.EVT_destroy))
        {
            Long csBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_cs_bytes);
            Long scBytes = (Long)WMSLoggerFactory.getGlobalLogValue(WMSLogger IDs.FD_sc_bytes);
            System.out.println("disconnect: csBytes:"+csBytes+" scBytes:"+scBytes);
        }
    }
}


问:
Resources ids not updating in Android Studio 3.0
I recently updated to Android Studio 3.0 and noticed that when I for example add any android:id, or create new drawable, or basically any resource, Android Studio does not update it in project until I build application. Every resource I create in xml, in class is marked as red and standard "Cannot resolve symbol ..." is shown. But surprisingly if you try to go to declaration, it correctly goes to the resource. Is there any option for this not to happen?
It's very irritating.

Edit:

It's still occuring sometimes, but I just got used to it. If someone fixed it I will be thankful for your answer.

答:
A workaround:

File > Invalidate Caches / Restart > Invalidate and Restart


问:
Git push error pre-receive hook declined
I have run gitlabhq rails server on virtual machine, following 1-6 steps from this tutorial https://github.com/gitlabhq/gitlab-recipes/blob/master/install/centos/README.md and starts rails server executing command sudo -u git -H bundle exec rails s -e production. After that I created user, using admin tools and created new project under this user. Then I'm trying to push the existing project to this repo as always. But in the last step, git push origin master fails with the error

[remote rejected] master -> master (pre-receive hook declined)

Additional info:

1) I haven't activated user (project owner) via email activation link, because I haven't configured post service on server-side and I didn't find instructions how to do that in this manual.

2) Gitlab server generates tips how to push project to repo and there is not repositories/ in path. I mean it generates git@mygitlabhost:user/repo.git instead of git@mygitlabhost:repositories/user/repo.git which is correct.

3) When i tried to debug it, I opened pre-receive script inside repo on server and tried to output variables (there is 3 of them): refs = ARGF.read, key_id  = ENV['GL_ID'] and repo_path = Dir.pwd and found, that key_id is always empty. Maybe the problem is here... If so, please give me suggestions on how to fix that. Thanks

答: I've faced the same issue, this is because I am pushing my code directly in the master branch, and I don't have rights for this. So I push my code in a new branch and after that, I created a pull request to merge with master.</p>


问:
NameError: name 'dbutils' is not defined in pyspark
I am running a pyspark job in databricks cloud. I need to write some of the csv files to databricks filesystem (dbfs) as part of this job and also i need to use some of the dbutils native commands like,

```<code>#mount azure blob to dbfs location
dbutils.fs.mount (source="...",mount_point="/mnt/...",extra_configs="{key:value}")
</code>```

I am also trying to unmount once the files has been written to the mount directory. But, when i am using dbutils directly in the pyspark job it is failing with

```<code>NameError: name 'dbutils' is not defined
</code>```

Should i import any of the package to use dbutils in pyspark code ? Thanks in advance.

答:
To access the DBUtils module in a way that works both locally and in Azure Databricks clusters, on Python, use the following get_dbutils():

```<code>def get_dbutils(spark):
  try:
    from pyspark.dbutils import DBUtils
    dbutils = DBUtils(spark)
  except ImportError:
    import IPython
    dbutils = IPython.get_ipython().user_ns["dbutils"]
  return dbutils
</code>```

See: https://learn.microsoft.com/en-us/azure/databricks/dev-tools/databricks-connect

Body:
I am running a pyspark job in databricks cloud. I need to write some of the csv files to databricks filesystem (dbfs) as part of this job and also i need to use some of the dbutils native commands like,

#mount azure blob to dbfs location
dbutils.fs.mount (source="...",mount_point="/mnt/...",extra_configs="{key:value}")

I am also trying to unmount once the files has been written to the mount directory. But, when i am using dbutils directly in the pyspark job it is failing with

NameError: name 'dbutils' is not defined

Should i import any of the package to use dbutils in pyspark code ? Thanks in advance.

Body:
To access the DBUtils module in a way that works both locally and in Azure Databricks clusters, on Python, use the following get_dbutils():

def get_dbutils(spark):
  try:
    from pyspark.dbutils import DBUtils
    dbutils = DBUtils(spark)
  except ImportError:
    import IPython
    dbutils = IPython.get_ipython().user_ns["dbutils"]
  return dbutils

See: https://learn.microsoft.com/en-us/azure/databricks/dev-tools/databricks-connect


问:
Get Service Information without WMI
presently I am writing a small piece of code to get the list of web services hosted on IIS in a remote system,

the working code right now is :

```<code>       string q2 = "select * from Win32_PerfFormattedData_W3SVC_WebService";
        ManagementScope scope2 = new ManagementScope(string.Format(@"\\dtp-robaro2\{1}", host, ns), options);

        // ns here is string ns = @"root\cimv2";

        scope2.Connect();

        ManagementObjectSearcher search2 = new ManagementObjectSearcher(scope, new ObjectQuery(q2));
        foreach (ManagementObject mo in search2.Get())
        {
            Console.WriteLine(mo.ClassPath);
            Console.WriteLine(mo.GetText(TextFormat.Mof));
        }
</code>```

now I was wondering if WMI is turned off on the remote system that i am querying then is there any alternative way to access the information i get with the above code?

答:
I have converted this from VB.Net to C# so it may not be exactly correct, but this will do what you need:</p>

```<code>public List<string> GetSites(string MachineName)
{

    List<string> siteList = new List<string>();

    DirectoryEntry iis = new DirectoryEntry(string.Format("IIS://{0}/w3svc/1/root", MachineName));

    foreach (DirectoryEntry site in iis.Children) {

        if (site.SchemaClassName == "IIsWebServer") {
            siteList.Add(site.Properties("ServerComment").Value.ToString());

        }
    }

    return siteList;

}
</code>```

Title: Get Service Information without WMI

Body:
presently I am writing a small piece of code to get the list of web services hosted on IIS in a remote system,

the working code right now is :

       string q2 = "select * from Win32_PerfFormattedData_W3SVC_WebService";
        ManagementScope scope2 = new ManagementScope(string.Format(@"\\dtp-robaro2\{1}", host, ns), options);

        // ns here is string ns = @"root\cimv2";

        scope2.Connect();

        ManagementObjectSearcher search2 = new ManagementObjectSearcher(scope, new ObjectQuery(q2));
        foreach (ManagementObject mo in search2.Get())
        {
            Console.WriteLine(mo.ClassPath);
            Console.WriteLine(mo.GetText(TextFormat.Mof));
        }

now I was wondering if WMI is turned off on the remote system that i am querying then is there any alternative way to access the information i get with the above code?

Body:
I have converted this from VB.Net to C# so it may not be exactly correct, but this will do what you need:

public List<string> GetSites(string MachineName)
{

    List<string> siteList = new List<string>();

    DirectoryEntry iis = new DirectoryEntry(string.Format("IIS://{0}/w3svc/1/root", MachineName));

    foreach (DirectoryEntry site in iis.Children) {

        if (site.SchemaClassName == "IIsWebServer") {
            siteList.Add(site.Properties("ServerComment").Value.ToString());

        }
    }

    return siteList;

}


问:
Is there a way of getting outerHTML of outerHTML of a web element using Selenium in Python?
I am using this for get a row in a table:

```<code>element = browser.find_element_by_xpath("//*[contains(text(),'Sample Text')]")
html_text = element.get_attribute('outerHTML')
</code>```

this gives me ...	 but I want
...	...

How do I do this?

答:
```<code>    String `val=driver.findElement(By.xpath("//input[@id='fileToUpload']")).getAttribute("outerHTML");`
</code>```

For Java,Tested in 2020 with chrome 83 which gives
Outter html value is

Body:
I am using this for get a row in a table:

element = browser.find_element_by_xpath("//*[contains(text(),'Sample Text')]")
html_text = element.get_attribute('outerHTML')

this gives me ...	 but I want
...	...

How do I do this?

Body:
    String `val=driver.findElement(By.xpath("//input[@id='fileToUpload']")).getAttribute("outerHTML");`

For Java,Tested in 2020 with chrome 83 which gives
Outter html value is


问:
Keycloak getAccessToken works in Java Eclipse/Maven project but throws ProcessingException running via commandline
My Maven project in Eclipse retrieves an access token from our keycloak server when run in the Eclipse environment. When I compile a fat jar, which includes all the dependencies, the same code, running on the same JDK/JRE(1.8) throws a ProcessingException. What is throwing me for a loop is the fact that it works on the same computer via Eclipse (thin JAR) but not via the command line (fat JAR). Both environments use the same Java installation as well as the same libraries.

```<code>javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:325)
</code>```

I have read through similar issues on stackoverflow and searched on the web for the exception as well as the RESTEASY codes. I have tried the following changes with no change in behavior...

Using jboss ApacheHttpClient4Engine vs. ResteasyClientBuilder

keycloak versions: 6.0.1, 7.0.1, 8.0.1

Code environment:

OS: Windows 10

Eclipse RCP release 2019-12

Windows 10 commandline

JDK 1.8.0_231 (the same installation of binaries and libraries for both commandline and eclipse)

The relevant section of the code, pom.xml, and the complete stack trace are below. Please let me know if more details will help. Thanks!

```<code>          if (!requireValidToken) return;

            keycloak = KeycloakBuilder.builder()
                    .serverUrl(deployment.getAuthServerBaseUrl())
                    .realm(deployment.getRealm())
                    .username(username).password(passwd)
                    .clientId(deployment.getResourceName())
                    .resteasyClient(new ResteasyClientBuilder().build()).build();

            System.out.println("CODE ALWAYS THROWS AN EXCEPTION AT THE NEXT LINE");
            AccessTokenResponse tokenResponse = keycloak.tokenManager().getAccessToken();
            System.out.println("CODE ALWAYS THROWS AN EXCEPTION BEFORE THIS LINE");
            setAccessToken(tokenResponse.getToken());
            verifyToken(tokenResponse.getToken(), null, null, null);

        } catch (Exception e) {
        e.printStackTrace();
</code>```

```<code>    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <keycloak.version>7.0.1</keycloak.version>
        <resteasy.version>3.7.0.Final</resteasy.version>
        <jackson.version>2.9.9</jackson.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson2-provider</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-admin-client</artifactId>
            <version>${keycloak.version}</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-adapter-core</artifactId>
            <version>${keycloak.version}</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-installed-adapter</artifactId>
            <version>${keycloak.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.keycloak/keycloak-core -->
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-core</artifactId>
            <version>${keycloak.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.11</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jdom/jdom -->
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>1.1.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.imagej/ij -->
        <dependency>
            <groupId>net.imagej</groupId>
            <artifactId>ij</artifactId>
            <version>1.49c</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.openrdf/rio -->
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-api</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-rdfxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-turtle</artifactId>
            <version>4.1.2</version>
        </dependency>
    </dependencies>

</code>```

The exception trace:

```<code>javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:325)
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:443)
        at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:149)
        at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
        at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
        at com.sun.proxy.$Proxy16.grantToken(Unknown Source)
        at org.keycloak.admin.client.token.TokenManager.grantToken(TokenManager.java:89)
        at org.keycloak.admin.client.token.TokenManager.getAccessToken(TokenManager.java:69)
        at org.emile.cirilo.business.KeycloakProxy.<init>(KeycloakProxy.java:109)
        at org.emile.cirilo.fedora.FedoraConnector.stubOpenConnection(FedoraConnector.java:133)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.lang.Thread.run(Thread.java:748)
Caused by: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
        at org.jboss.resteasy.core.interception.ClientWriterInterceptorContext.throwWriterNotFoundException(ClientWriterInterceptorContext.java:38)
        at org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.getWriter(AbstractWriterInterceptorContext.java:146)
        at org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:121)
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.writeRequestBody(ClientInvocation.java:398)
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.writeRequestBodyToOutputStream(ApacheHttpClient4Engine.java:671)
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.buildEntity(ApacheHttpClient4Engine.java:636)
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.loadHttpMethod(ApacheHttpClient4Engine.java:514)
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:313)
        ... 20 more
</code>```

答:
Kinda late, but for a Maven project, look here:
resteasy providers missing after mvn package

As for Gradle project, the usage of Gradle Shadow Plugin is needed.

```<code>shadowJar {
    mergeServiceFiles()

    append 'META-INF/services/javax.ws.rs.ext.Providers'
}
</code>```

Body:
My Maven project in Eclipse retrieves an access token from our keycloak server when run in the Eclipse environment. When I compile a fat jar, which includes all the dependencies, the same code, running on the same JDK/JRE(1.8) throws a ProcessingException. What is throwing me for a loop is the fact that it works on the same computer via Eclipse (thin JAR) but not via the command line (fat JAR). Both environments use the same Java installation as well as the same libraries.

javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:325)

I have read through similar issues on stackoverflow and searched on the web for the exception as well as the RESTEASY codes. I have tried the following changes with no change in behavior...

Using jboss ApacheHttpClient4Engine vs. ResteasyClientBuilder

keycloak versions: 6.0.1, 7.0.1, 8.0.1

Code environment:

OS: Windows 10

Eclipse RCP release 2019-12

Windows 10 commandline

JDK 1.8.0_231 (the same installation of binaries and libraries for both commandline and eclipse)

The relevant section of the code, pom.xml, and the complete stack trace are below. Please let me know if more details will help. Thanks!

          if (!requireValidToken) return;

            keycloak = KeycloakBuilder.builder()
                    .serverUrl(deployment.getAuthServerBaseUrl())
                    .realm(deployment.getRealm())
                    .username(username).password(passwd)
                    .clientId(deployment.getResourceName())
                    .resteasyClient(new ResteasyClientBuilder().build()).build();

            System.out.println("CODE ALWAYS THROWS AN EXCEPTION AT THE NEXT LINE");
            AccessTokenResponse tokenResponse = keycloak.tokenManager().getAccessToken();
            System.out.println("CODE ALWAYS THROWS AN EXCEPTION BEFORE THIS LINE");
            setAccessToken(tokenResponse.getToken());
            verifyToken(tokenResponse.getToken(), null, null, null);

        } catch (Exception e) {
        e.printStackTrace();

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <keycloak.version>7.0.1</keycloak.version>
        <resteasy.version>3.7.0.Final</resteasy.version>
        <jackson.version>2.9.9</jackson.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson2-provider</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-admin-client</artifactId>
            <version>${keycloak.version}</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-adapter-core</artifactId>
            <version>${keycloak.version}</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-installed-adapter</artifactId>
            <version>${keycloak.version}</version>
        </dependency>

        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-core</artifactId>
            <version>${keycloak.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-base</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.11</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>1.1.3</version>
        </dependency>

        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.2.0</version>
        </dependency>

        <dependency>
            <groupId>net.imagej</groupId>
            <artifactId>ij</artifactId>
            <version>1.49c</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
        </dependency>

        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-api</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-rdfxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openrdf.sesame</groupId>
            <artifactId>sesame-rio-turtle</artifactId>
            <version>4.1.2</version>
        </dependency>
    </dependencies>

The exception trace:

javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:325)
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:443)
        at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:149)
        at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
        at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
        at com.sun.proxy.$Proxy16.grantToken(Unknown Source)
        at org.keycloak.admin.client.token.TokenManager.grantToken(TokenManager.java:89)
        at org.keycloak.admin.client.token.TokenManager.getAccessToken(TokenManager.java:69)
        at org.emile.cirilo.business.KeycloakProxy.<init>(KeycloakProxy.java:109)
        at org.emile.cirilo.fedora.FedoraConnector.stubOpenConnection(FedoraConnector.java:133)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.lang.Thread.run(Thread.java:748)
Caused by: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form$1
        at org.jboss.resteasy.core.interception.ClientWriterInterceptorContext.throwWriterNotFoundException(ClientWriterInterceptorContext.java:38)
        at org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.getWriter(AbstractWriterInterceptorContext.java:146)
        at org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:121)
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.writeRequestBody(ClientInvocation.java:398)
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.writeRequestBodyToOutputStream(ApacheHttpClient4Engine.java:671)
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.buildEntity(ApacheHttpClient4Engine.java:636)
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.loadHttpMethod(ApacheHttpClient4Engine.java:514)
        at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:313)
        ... 20 more

Body:
Kinda late, but for a Maven project, look here:
resteasy providers missing after mvn package

As for Gradle project, the usage of Gradle Shadow Plugin is needed.

shadowJar {
    mergeServiceFiles()

    append 'META-INF/services/javax.ws.rs.ext.Providers'
}


问:
Allow Azure Web App to Access Database on the VM Without Exposing that VM to the World
We have Web Apps that need to access database hosted on VM. What options exist that will allow Web Apps to access the databases without opening the database VM port to the internet? </p>

答:
For this requirement, you can integrate with the VNet for the Web App, it can make your Web App access the resources in the VNet. The VM that hosts the database can be created in the VNet without public IP address so that the VM can only be accessible in the VNet. Here is the description that can help understand it:

VNet Integration gives your app access to resources in your VNet, but
  it doesn't grant inbound private access to your app from the VNet.


问:
How is pointer to member function implemented in C++?
The pointer to member function in c++ is in three parts:

```<code>Offset
Address/index
virtual?
</code>```

Offset is used for Pointer adjustment when derived object is called using base pointer.

How is this offset implemented? Is it pointer to some table, one table for each derived class and the table contains entries of the form (base X, offset)?

Also, where can I get more info about this?

答:
This is a comment regarding 6502's answer, but I lack reputation.

a method pointer for a simple class that has no virtual methods can be implemented as a regular pointer to the method

I believe this statement is incorrect because multiple inheritance complicates things.  Consider this code:

```<code>struct A {
    int a;
    void f() {
        // use a
    }
};

struct B {
    int b;
    void g() {
        // use b
    }
};

// C objects may look like this in memory:
//
//     |-----|
//     |  A  |
//     |-----|
//     |  B  |
//     |-----|
//
// Since only one of A and B can be at the start of C in terms of memory
// layout, at least one of the following can't work:
//
// * naively interpreting a pointer to C as a pointer to A
// * naively interpreting a pointer to C as a pointer to B
struct C : A, B {};

void call_ptm(void (C::*ptm)()) {
    C c;
    // `ptm` could be `A::f` or `B::g`.  We don't know.  At what offset
    // relative to `this` do we expect to find data members then?  It depends
    // on whether `ptm` points to `A::f` or `B::g`, which isn't known at
    // compile time.
    (c.*ptm)();
}
</code>```

One way or another, a pointer to a member function needs to store an offset that can be applied to this upon invocation.

Body:
The pointer to member function in c++ is in three parts:

Offset
Address/index
virtual?

Offset is used for Pointer adjustment when derived object is called using base pointer.

How is this offset implemented? Is it pointer to some table, one table for each derived class and the table contains entries of the form (base X, offset)?

Also, where can I get more info about this?

Body:
This is a comment regarding 6502's answer, but I lack reputation.

a method pointer for a simple class that has no virtual methods can be implemented as a regular pointer to the method

I believe this statement is incorrect because multiple inheritance complicates things.  Consider this code:

struct A {
    int a;
    void f() {
        // use a
    }
};

struct B {
    int b;
    void g() {
        // use b
    }
};

// C objects may look like this in memory:
//
//     |-----|
//     |  A  |
//     |-----|
//     |  B  |
//     |-----|
//
// Since only one of A and B can be at the start of C in terms of memory
// layout, at least one of the following can't work:
//
// * naively interpreting a pointer to C as a pointer to A
// * naively interpreting a pointer to C as a pointer to B
struct C : A, B {};

void call_ptm(void (C::*ptm)()) {
    C c;
    // `ptm` could be `A::f` or `B::g`.  We don't know.  At what offset
    // relative to `this` do we expect to find data members then?  It depends
    // on whether `ptm` points to `A::f` or `B::g`, which isn't known at
    // compile time.
    (c.*ptm)();
}

One way or another, a pointer to a member function needs to store an offset that can be applied to this upon invocation.


问:
How to assign array value into variable inside foreach loop in codeigniter
I have an array of users with different userIds and I am trying to loop these array using a foreach loop. Inside that loop I am calling a function to get values of each users by passing their userid into a function. But its only passing one index of array.

My code

```<code>public function getDailyReportTest($orgId, $date)
{
    $query = $this->db->query("SELECT *  FROM `organization_users` WHERE orgId='7'");

       $timestamp = strtotime($date);
       $day = date('l', $timestamp);

   $data = array();
$i = 0;
foreach ($query->result_array() as $row) {

  $data[$i]['date']    = $date;
  $data[$i]['day']     = $day;
  $data[$i]['user_id'] = $row['orgUserId'];
  $data[$i]['user_name'] = $row['orgUserName'];

  $data[$i]['workingHours'] = self::getUserWorkingHours($data[$i]['user_id'],$date);

  $delayTime=self::getUserDelayTime($row['orgUserId'],$date);
  $shortTime=self::getUserShortTime($row['orgUserId'],$date);
  $overTime=self::getUserOverTime($row['orgUserId'],$date);

     $data[$i]['delayTime']   =$delayTime;
     $data[$i]['shortTime']   =$shortTime;
     $data[$i]['overTime']    =$overTime;

   $data[$i]['shift1_start'] = self::getUserShiftStartTime($row['orgUserId'], $date);

  $i=$i+1;
}
//return $data;
print_r($data);
die();

}

public function getUserShiftStartTime($userId, $date)
{
    $query = $this->db->query("SELECT * FROM `office_employee_assigned_shifts` WHERE employeeId='$userId' &&shiftdate='$date'");
    $entry = $query->num_rows();

    $data = $query->result_array();

    if($entry==0)
    {
        return NULL;
    }
    else
    {
        $shiftId = $data[0]['shiftId'];
        $shiftquery = $this->db->query("SELECT startTimeSpan, endTimeSpan FROM `office_shift_time` WHERE officeShiftId='$shiftId'");
        $dataShift = $shiftquery->result_array();
        $startSpan = $dataShift[0]['startTimeSpan'];
        $endSpan = $dataShift[0]['endTimeSpan'];

        $firstPunchQuery = $this->db->query("SELECT punchTime AS firstPunch FROM `employee_punch_log` WHERE punchDate='$date' && employeeId='140' && punchTime BETWEEN '$startSpan' AND '$endSpan' AND punchType='1' LIMIT 1");
        $punchEntryCount  = $firstPunchQuery->num_rows();
         if($punchEntryCount>0)
         {
        $dataFirstPunch = $firstPunchQuery->result_array();
        $firstPunchStartTime = $dataFirstPunch[0]['firstPunch'];
        return $firstPunchStartTime;
         }
         else
         {
             return "AB";
         }

    }
   // return $entry;
}
</code>```

It only passes the $data[1]['user_id'].

I want to pass $data[0]['user_id'], $data[1]['user_id'], $data[2]['user_id'] to the function
named getUserShiftStartTime($userId, $date)

Any Help?
Thanks for the help in advance

答:
Then pass the current variable to your method:</p>

```<code>self::getUserShiftStartTime($data[$i]['user_id'], $date);
</code>```

Body:
I have an array of users with different userIds and I am trying to loop these array using a foreach loop. Inside that loop I am calling a function to get values of each users by passing their userid into a function. But its only passing one index of array.

My code

public function getDailyReportTest($orgId, $date)
{
    $query = $this->db->query("SELECT *  FROM `organization_users` WHERE orgId='7'");

       $timestamp = strtotime($date);
       $day = date('l', $timestamp);

   $data = array();
$i = 0;
foreach ($query->result_array() as $row) {

  $data[$i]['date']    = $date;
  $data[$i]['day']     = $day;
  $data[$i]['user_id'] = $row['orgUserId'];
  $data[$i]['user_name'] = $row['orgUserName'];

  $data[$i]['workingHours'] = self::getUserWorkingHours($data[$i]['user_id'],$date);

  $delayTime=self::getUserDelayTime($row['orgUserId'],$date);
  $shortTime=self::getUserShortTime($row['orgUserId'],$date);
  $overTime=self::getUserOverTime($row['orgUserId'],$date);

     $data[$i]['delayTime']   =$delayTime;
     $data[$i]['shortTime']   =$shortTime;
     $data[$i]['overTime']    =$overTime;

   $data[$i]['shift1_start'] = self::getUserShiftStartTime($row['orgUserId'], $date);

  $i=$i+1;
}
//return $data;
print_r($data);
die();

}

public function getUserShiftStartTime($userId, $date)
{
    $query = $this->db->query("SELECT * FROM `office_employee_assigned_shifts` WHERE employeeId='$userId' &&shiftdate='$date'");
    $entry = $query->num_rows();

    $data = $query->result_array();

    if($entry==0)
    {
        return NULL;
    }
    else
    {
        $shiftId = $data[0]['shiftId'];
        $shiftquery = $this->db->query("SELECT startTimeSpan, endTimeSpan FROM `office_shift_time` WHERE officeShiftId='$shiftId'");
        $dataShift = $shiftquery->result_array();
        $startSpan = $dataShift[0]['startTimeSpan'];
        $endSpan = $dataShift[0]['endTimeSpan'];

        $firstPunchQuery = $this->db->query("SELECT punchTime AS firstPunch FROM `employee_punch_log` WHERE punchDate='$date' && employeeId='140' && punchTime BETWEEN '$startSpan' AND '$endSpan' AND punchType='1' LIMIT 1");
        $punchEntryCount  = $firstPunchQuery->num_rows();
         if($punchEntryCount>0)
         {
        $dataFirstPunch = $firstPunchQuery->result_array();
        $firstPunchStartTime = $dataFirstPunch[0]['firstPunch'];
        return $firstPunchStartTime;
         }
         else
         {
             return "AB";
         }

    }
   // return $entry;
}

It only passes the $data[1]['user_id'].

I want to pass $data[0]['user_id'], $data[1]['user_id'], $data[2]['user_id'] to the function
named getUserShiftStartTime($userId, $date)

Any Help?
Thanks for the help in advance

Body:
Then pass the current variable to your method:

self::getUserShiftStartTime($data[$i]['user_id'], $date);


问:
How to find the minimal element of each column in a two-dimensional array in Python
```<code>import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')
</code>```

I need to find minimal element of each column in a  two-dimensional array and add them in a new array(one-dimensional array)

答: Use np.min(arr_name, axis=1).

Body:
import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')

I need to find minimal element of each column in a  two-dimensional array and add them in a new array(one-dimensional array)

Body: Use np.min(arr_name, axis=1).


问:
fetch multiple image source before render react native
I would like show image on my markers, but it works only when I use the icon attribute of the marker. I need to use the subview to manage the style. When I use the ICON attribute, the view image appear (so I have two image on the map) but not showing when it's in comment.

This how I fetch the data and update the state.

```<code>componentDidMount(){
  getmarkers().then(data => {
    let test = []
    data.forEach(element => {
      test.push(
        {
          latlng:
          {
            latitude: JSON.parse(element.latitude),
            longitude: JSON.parse(element.longitude)
          },
          name: JSON.parse(element.images)[0],
          id: element.id,
          image: JSON.parse(element.images)[0]
        }
      )
    });

    this.setState({ markers: test, loaded: true })

  })
}
</code>```

}

This is my view

```<code>            {this.state.markers.map((marker, i) => (
          <Marker
            key={i}
            coordinate={marker.latlng}
            title={marker.name}
            description={marker.name}
            tracksViewChanges={false}
          // icon={{ uri: 'https://www.testeed.com/uploads/minifiedplaces/' + marker.image}}
          >

            <View>
              <Image source={{ uri: 'https://www.testeed.com/uploads/minifiedplaces/' + marker.image }} style={{ width: 40, height: 40, borderRadius: 6 }} />
            </View>

          </Marker>
        ))}
</code>```

答:
The issue come from Trackviewchange. If you put this value to false. the application is lagging. then if you put the value to false, the application do not load the image at first loading.

So you have to init Trackviewchange to True and create promise after the execution of your fetch/foreach, if it doesn't work, you can do a a setimeout or setinterval to change the value of trackviewchange to false to show images changes and get a better smooth user experience.

Body:
I would like show image on my markers, but it works only when I use the icon attribute of the marker. I need to use the subview to manage the style. When I use the ICON attribute, the view image appear (so I have two image on the map) but not showing when it's in comment.

This how I fetch the data and update the state.

componentDidMount(){
  getmarkers().then(data => {
    let test = []
    data.forEach(element => {
      test.push(
        {
          latlng:
          {
            latitude: JSON.parse(element.latitude),
            longitude: JSON.parse(element.longitude)
          },
          name: JSON.parse(element.images)[0],
          id: element.id,
          image: JSON.parse(element.images)[0]
        }
      )
    });

    this.setState({ markers: test, loaded: true })

  })
}

}

This is my view

            {this.state.markers.map((marker, i) => (
          <Marker
            key={i}
            coordinate={marker.latlng}
            title={marker.name}
            description={marker.name}
            tracksViewChanges={false}
          // icon={{ uri: 'https://www.testeed.com/uploads/minifiedplaces/' + marker.image}}
          >

            <View>
              <Image source={{ uri: 'https://www.testeed.com/uploads/minifiedplaces/' + marker.image }} style={{ width: 40, height: 40, borderRadius: 6 }} />
            </View>

          </Marker>
        ))}


问:
Difference between "" and String.Empty()

Possible Duplicate:

  What is the difference between String.Empty and “”

What is the difference between code and where it is applicable??

```<code>string mystr = "";

string mystr1 = String.Empty();
</code>```

答:
The answer appears to be 'nothing'.

However, good programming practice says that you should preferably use string.Empty, as if in the future an empty string were to be represented by something other than "", your code otherwise might break. (I can't see tha change happening, but in principle it might).

Body:
Possible Duplicate:

  What is the difference between String.Empty and “”

What is the difference between code and where it is applicable??

string mystr = "";

string mystr1 = String.Empty();


问:
error with user for pip install with custom index-url
I have an internal nexus server where I store my python packages.

When I try to run

pip install --index-url=https://my_pip_user:my_pip_pass@my_pip_url ...

while building docker image I'm getting

my_pip_user is not a valid value for user option, please specify a boolean value like yes/no, true/false or 1/0 instead.

The error is not thrown if cmd is run just in bash.

I've tried to put index-url into ~/.pip/pip.conf but it doesn't change anything.

答:
I had the similar problem before, just check your environment variables, make sure you do not have any env vars which start with "PIP_", e.g. "PIP_USER", otherwise it will consider this is a pip command option and will be passed to pip command.

Reference: https://pip.pypa.io/en/stable/user_guide/#environment-variables


问:
Jenkins CI / CD on an Open Source Github project with confidential properties files
I'm struggling on doing Jenkins CI/CD pipelines for an Open Source project which has a set of confidential .properties files.

The .properties files are necessary for maintainability in a Spring boot project, and some of the .properties files are confidential, and so must not be disclosed in the open sourced code-base.

For each confidential .properties we provide an example .properties in the open source.

The question is, how do you smoothly (i.e. automize) incorporate the confidential .properties or files in the Jenkins CI/CD pipelines, and have a great version controllability using git over those files? So that those confidential .properties can effect durring every CI/CD phase and so in the production.

This seems to be a hard-to-automize challenge, any comments, suggestions or experiences are appreciated!

What I've tried

Git secret

This is a great solution but it doesn't support Windows, so I can't go with it. (Every alternative to git-secret I've found also doesn't support cross-platform.

答:
There is a plugin called Config File Provider Plugin that was a life saver for me.
It is able to replace entire config files with the ones stored in JK or just tokens in XML , Json etc.

In pipeline, when you want to replace the whole file, it looks something like this:

```<code> stage('Add Config files') {
        steps {
            configFileProvider([configFile(fileId: 'IDOfTheFileStoredInJenkins', targetLocation: pathToMyFileRelativeToWorkspace/myPropertiesFile')]) {
            // some block, maybe a nice log message
            }
}
}
</code>```

similar  thread:

Body:
There is a plugin called Config File Provider Plugin that was a life saver for me.
It is able to replace entire config files with the ones stored in JK or just tokens in XML , Json etc.

In pipeline, when you want to replace the whole file, it looks something like this:

 stage('Add Config files') {
        steps {
            configFileProvider([configFile(fileId: 'IDOfTheFileStoredInJenkins', targetLocation: pathToMyFileRelativeToWorkspace/myPropertiesFile')]) {
            // some block, maybe a nice log message
            }
}
}

similar  thread:


问:
Inaccuracies in retrieval of road functional class in proximity of a point
As a way to meke it more interactive, I will use the demo from this page: https://developer.here.com/documentation/examples/rest/traffic/traffic-flow-proximity-shape-fc

Here is an example of an API call:

https://traffic.api.here.com/traffic/6.1/flow.json?prox=51.2141%2C4.4551%2C10&locationreferences=shp&responseattributes=fc&app_id=devportal-demo-20180625&app_code=9v2BkviRwi9Ot26kp2IysQ

Response:

```<code>{
  "RWS": [],
  "MAP_VERSION": "",
  "CREATED_TIMESTAMP": "2020-05-28T12:05:18.000+0000",
  "VERSION": "3.1",
  "UNITS": "metric"
}
</code>```

The result is empty, but clearly, S County Road 250 W is within the circle and I would expect that the request would return the functional class of this road.

Note that if I use TMC, then I will get a ton of information about roads/locations that are not in the circle.

Am I doing something wrong? All I need are roads within the circle, and their functional class (ideally supplied with traffic information). Is that possible?

答:
API is giving correct response however the problem is, that even if you can specify 1 or 100 meters as radius the service really support only the smallest resolution of 1 km. This is due to how the data is stored in the service, which is tile based.

and each such a request is then converted to tiles - which have a predefined size. So a 100 meters request can end up in a tile of size 1x1 km easily. That is why you get traffic outside of a smaller proximity.

You can refer to Here Traffic API Documentation to get the response elements and meanings documentation.developer.here.com/pdf/traffic_hlp/6.0.85.0/Traffic%20API%20v6.0.85.0%20Developer's%20Guide.pdf. You can also go to `

developer.here.com/documentation/versions

and download this file.

Body:
As a way to meke it more interactive, I will use the demo from this page: https://developer.here.com/documentation/examples/rest/traffic/traffic-flow-proximity-shape-fc

Here is an example of an API call:

https://traffic.api.here.com/traffic/6.1/flow.json?prox=51.2141%2C4.4551%2C10&locationreferences=shp&responseattributes=fc&app_id=devportal-demo-20180625&app_code=9v2BkviRwi9Ot26kp2IysQ

Response:

{
  "RWS": [],
  "MAP_VERSION": "",
  "CREATED_TIMESTAMP": "2020-05-28T12:05:18.000+0000",
  "VERSION": "3.1",
  "UNITS": "metric"
}

The result is empty, but clearly, S County Road 250 W is within the circle and I would expect that the request would return the functional class of this road.

Note that if I use TMC, then I will get a ton of information about roads/locations that are not in the circle.

Am I doing something wrong? All I need are roads within the circle, and their functional class (ideally supplied with traffic information). Is that possible?


问:
Why can't i get the content of an html table ?
I have this code that somehow scrapes a certain site. The problem is I can't proceed because I can't view the content of a table especially its . You can see when you print(table), it only shows the opening and closing tags if
 and doesn't include its content.

```<code>import requests
from bs4 import BeautifulSoup

url = 'http://www.scstac.org/pc.jsp'
page = requests.get(url)

soup = BeautifulSoup(page.text,'lxml')
table = soup.find('table', class_='table02')
print(table)
</code>```

答:
The website you are scraping is a dynamic website. The url you provide only has the skeleton of the table in the html. Later with JQuery scripts the table rows and cells are populated.

I suggest you research scraping dynamic websites. Se this site, does calls with a session cookie to get the data. I think the easiest way is a scraping browser setup to retrieve the data.

Title: Why can't i get the content of an html table <td>?

Body:
I have this code that somehow scrapes a certain site. The problem is I can't proceed because I can't view the content of a table especially its . You can see when you print(table), it only shows the opening and closing tags if
 and doesn't include its content.

import requests
from bs4 import BeautifulSoup

url = 'http://www.scstac.org/pc.jsp'
page = requests.get(url)

soup = BeautifulSoup(page.text,'lxml')
table = soup.find('table', class_='table02')
print(table)


问:
R: plotting - visualizing the common time period of events in a 24 hours timeframe from multiple dataframes
I have dataframes of events captured and i am finding a way to visualize which time period (1hr window) does these events usually occur in a 24 hours timeframe.

I'm only interested in the event starttime.
So x-axis of the plot should be a 24 hours series, breaks at 1hour.
and y-axis would be the different dataframes represented by a geom_point or something
And I like to seek advice how can I do this from multiple dataframes.

df1

```<code>        TimeStamp_start         TimeStamp_end  Fab23.A_start   Fab23.A_end
1   2020-03-01 21:56:00   2020-03-01 21:58:00       38.67555      184.4875
2   2020-03-02 20:48:00   2020-03-02 20:50:00       31.98126      186.0867
3   2020-03-03 18:14:00   2020-03-03 18:16:00       41.42305      189.7806
4   2020-03-04 17:50:00   2020-03-04 17:52:00       36.79726      190.0810
5   2020-03-05 16:58:00   2020-03-05 17:00:00       39.70075      189.8803
.
.
.

</code>```

df2

```<code>        TimeStamp_start         TimeStamp_end    Fab7.A_start    Fab7.A_end
1   2020-03-03 05:20:00   2020-03-03 05:22:00        39.98769      141.9722
2   2020-03-06 02:04:00   2020-03-06 02:06:00        40.59314      189.5027
3   2020-03-08 17:18:00   2020-03-08 17:20:00        47.79272      191.8802
4   2020-03-10 16:00:00   2020-03-10 16:02:00        42.69026      190.4804
.
.
</code>```

I'm wondering if it's possible to look like a dumbbell chart, but instead of the dumbbell it's presented by geom_point in density.

答:
You could make a dummy varialbe indicating the df and then bind the dfs together and then plot them:

```<code>df1 <- tibble::tribble(
              ~TimeStamp_start,        ~TimeStamp_end, ~Fab23.A_start, ~Fab23.A_end,
         "2020-03-01 21:56:00", "2020-03-01 21:58:00",       38.67555,     184.4875,
         "2020-03-02 20:48:00", "2020-03-02 20:50:00",       31.98126,     186.0867,
         "2020-03-03 18:14:00", "2020-03-03 18:16:00",       41.42305,     189.7806,
         "2020-03-04 17:50:00", "2020-03-04 17:52:00",       36.79726,      190.081,
         "2020-03-05 16:58:00", "2020-03-05 17:00:00",       39.70075,     189.8803
         )

df2 <- tibble::tribble(
              ~TimeStamp_start,        ~TimeStamp_end, ~Fab7.A_start, ~Fab7.A_end,
         "2020-03-03 05:20:00", "2020-03-03 05:22:00",      39.98769,    141.9722,
         "2020-03-06 02:04:00", "2020-03-06 02:06:00",      40.59314,    189.5027,
         "2020-03-08 17:18:00", "2020-03-08 17:20:00",      47.79272,    191.8802,
         "2020-03-10 16:00:00", "2020-03-10 16:02:00",      42.69026,    190.4804
         )

library(tidyverse)
library(lubridate)
library(ggridges)
df1 <- df1 %>%
  mutate(TimeStamp_start = ymd_hms(TimeStamp_start),
         df_dummy = "df1")

df2 <- df2 %>%
  mutate(TimeStamp_start = ymd_hms(TimeStamp_start),
         df_dummy = "df2")

dfs <- bind_rows(df1,df2)

dfs %>%
  mutate(by_hour = hour(TimeStamp_start)) %>%
  ggplot(aes(x = by_hour, y = df_dummy)) +
  geom_density_ridges()
</code>```

The problem with this plot is that the density expands past 0 and 24. We could cut the density or indicate that the data does not expand past 0 and 24 with a graph like this (customized x axis tick marks and show where actual data is):

```<code>dfs %>%
  mutate(by_hour = hour(TimeStamp_start)) %>%
  ggplot(aes(x = by_hour, y = df_dummy)) +
  geom_density_ridges(rel_min_height = 0.01, jittered_points = TRUE,
                      position = position_points_jitter(width = 0.1, height = 0),
                      point_shape = "|", point_size = 4,
                      alpha = 0.7) +
  scale_x_continuous(breaks = 0:24)
</code>```

Body:
I have dataframes of events captured and i am finding a way to visualize which time period (1hr window) does these events usually occur in a 24 hours timeframe.

I'm only interested in the event starttime.
So x-axis of the plot should be a 24 hours series, breaks at 1hour.
and y-axis would be the different dataframes represented by a geom_point or something
And I like to seek advice how can I do this from multiple dataframes.

df1

        TimeStamp_start         TimeStamp_end  Fab23.A_start   Fab23.A_end
1   2020-03-01 21:56:00   2020-03-01 21:58:00       38.67555      184.4875
2   2020-03-02 20:48:00   2020-03-02 20:50:00       31.98126      186.0867
3   2020-03-03 18:14:00   2020-03-03 18:16:00       41.42305      189.7806
4   2020-03-04 17:50:00   2020-03-04 17:52:00       36.79726      190.0810
5   2020-03-05 16:58:00   2020-03-05 17:00:00       39.70075      189.8803
.
.
.

df2

        TimeStamp_start         TimeStamp_end    Fab7.A_start    Fab7.A_end
1   2020-03-03 05:20:00   2020-03-03 05:22:00        39.98769      141.9722
2   2020-03-06 02:04:00   2020-03-06 02:06:00        40.59314      189.5027
3   2020-03-08 17:18:00   2020-03-08 17:20:00        47.79272      191.8802
4   2020-03-10 16:00:00   2020-03-10 16:02:00        42.69026      190.4804
.
.

I'm wondering if it's possible to look like a dumbbell chart, but instead of the dumbbell it's presented by geom_point in density.

Body:
You could make a dummy varialbe indicating the df and then bind the dfs together and then plot them:

df1 <- tibble::tribble(
              ~TimeStamp_start,        ~TimeStamp_end, ~Fab23.A_start, ~Fab23.A_end,
         "2020-03-01 21:56:00", "2020-03-01 21:58:00",       38.67555,     184.4875,
         "2020-03-02 20:48:00", "2020-03-02 20:50:00",       31.98126,     186.0867,
         "2020-03-03 18:14:00", "2020-03-03 18:16:00",       41.42305,     189.7806,
         "2020-03-04 17:50:00", "2020-03-04 17:52:00",       36.79726,      190.081,
         "2020-03-05 16:58:00", "2020-03-05 17:00:00",       39.70075,     189.8803
         )

df2 <- tibble::tribble(
              ~TimeStamp_start,        ~TimeStamp_end, ~Fab7.A_start, ~Fab7.A_end,
         "2020-03-03 05:20:00", "2020-03-03 05:22:00",      39.98769,    141.9722,
         "2020-03-06 02:04:00", "2020-03-06 02:06:00",      40.59314,    189.5027,
         "2020-03-08 17:18:00", "2020-03-08 17:20:00",      47.79272,    191.8802,
         "2020-03-10 16:00:00", "2020-03-10 16:02:00",      42.69026,    190.4804
         )

library(tidyverse)
library(lubridate)
library(ggridges)
df1 <- df1 %>%
  mutate(TimeStamp_start = ymd_hms(TimeStamp_start),
         df_dummy = "df1")

df2 <- df2 %>%
  mutate(TimeStamp_start = ymd_hms(TimeStamp_start),
         df_dummy = "df2")

dfs <- bind_rows(df1,df2)

dfs %>%
  mutate(by_hour = hour(TimeStamp_start)) %>%
  ggplot(aes(x = by_hour, y = df_dummy)) +
  geom_density_ridges()

The problem with this plot is that the density expands past 0 and 24. We could cut the density or indicate that the data does not expand past 0 and 24 with a graph like this (customized x axis tick marks and show where actual data is):

dfs %>%
  mutate(by_hour = hour(TimeStamp_start)) %>%
  ggplot(aes(x = by_hour, y = df_dummy)) +
  geom_density_ridges(rel_min_height = 0.01, jittered_points = TRUE,
                      position = position_points_jitter(width = 0.1, height = 0),
                      point_shape = "|", point_size = 4,
                      alpha = 0.7) +
  scale_x_continuous(breaks = 0:24)