问:
Angular 8, Firebase Push Notification: Not able to get debugger OR custom logic on pushed notification
I have reviewed and implemented some of already asked and answered questions on this platform. I am able to get push default popup on screen but however I am not able to get rid on how I can add those new pushed notification in my custom list and show to end user in UI. I wants to collect new notification and store that in my application variable so I can work around it and display all notifications to user.

Below is my implemented code.

Package.json

```<code>"dependencies": {
"@agm/core": "^1.0.0",
"@angular-devkit/core": "^8.3.16",
"@angular-devkit/schematics": "^8.3.16",
"@angular/animations": "^8.2.12",
"@angular/cdk": "^8.2.3",
"@angular/common": "^8.2.13",
"@angular/compiler": "^8.2.12",
"@angular/core": "^8.2.12",
"@angular/forms": "^8.2.12",
"@angular/platform-browser": "^8.2.12",
"@angular/platform-browser-dynamic": "^8.2.12",
......
"@angular/fire": "^5.2.3",
"@angular/platform-server": "8.0.0",
"@nguniversal/module-map-ngfactory-loader": "8.0.0-rc.1",
"aspnet-prerendering": "^3.0.1",
"firebase": "^7.5.0"
},
</code>```

firebase-messaging-sw.js

```<code>importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in the
firebase.initializeApp({
  apiKey: 'xyz',
  authDomain: 'xyz',
  databaseURL: 'xyz"',
  projectId: 'xyz',
  storageBucket: 'xyz',
  messagingSenderId: '168382776603',
  appId: '1:168382776603:web:65c285a048d740401a3fbe'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
const messaging = firebase.messaging();
</code>```

app.module.ts

```<code>imports: [
    FormsModule,
    BrowserModule,
    AppRoutingModule,
    .....,
    AngularFireModule.initializeApp({
      apiKey: 'xyz',
      authDomain: 'xyz',
      databaseURL: 'xyz"',
      projectId: 'xyz',
      storageBucket: 'xyz',
      messagingSenderId: '168382776603',
      appId: '1:168382776603:web:65c285a048d740401a3fbe'
    }),
    AngularFireMessagingModule,
  ]
</code>```

FirebasePushNotificationService.ts

```<code>    export class FirebasePushNotificationService {

    constructor(private angularFireMessaging: AngularFireMessaging) {
      this.angularFireMessaging.messaging.subscribe(
        (messagingContext: any) => {
          messagingContext.onMessage = messagingContext.onMessage.bind(messagingContext);
          messagingContext.onTokenRefresh = messagingContext.onTokenRefresh.bind(messagingContext);
        });
    }

    currentMessage = new BehaviorSubject(null);

    requestPermission = () => this.angularFireMessaging.requestToken;

    removeToken = (token: string) => this.angularFireMessaging.deleteToken(token);

    receiveMessage = () => this.angularFireMessaging.messages;
  }
</code>```

app.component.ts (onInit): I need debugger in receiveMessage()

```<code>this.firebasePushNotificationService.requestPermission().subscribe(
        token => {
            console.log('Push Token', token);
        },
        error => {
            console.log('Push Error', error);
        }
    );

this.firebasePushNotificationService.receiveMessage().subscribe(message => {
        **// I am not able to get debugger here**
        console.log(message);
    });
</code>```

答:
Finally get rid on the problem. All code is works fine except firebase version, so I have update the version in packag.json as below and it works fine.

```<code>"@angular/fire": "^5.3.0",
"firebase": "7.3.0"
</code>```

and then in firebase-messaging-sw.js

```<code>importScripts('https://www.gstatic.com/firebasejs/7.3.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.3.0/firebase-messaging.js');
</code>```

To get Background Messages add below code in firebase-messaging-sw.js and also click event listener if you wants to navigate on custom url. this "setBackgroundMessageHandler" will execute only in case your push response has data field instead notification example as below

Push response with data field:

```<code>{
    "token" : "epFYFDGqb9ghFezyW5_Wyh:APA91bEDBKPcu7Vq....",
    "data": {
      "title": "FCM Message",
      "body": "This is a message from FCM",
      "click_action": "https://localhost:4200"
    }
}
</code>```

Events for background message

```<code>messaging.setBackgroundMessageHandler(function (payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);

  const notificationTitle = payload.data.title;
  const notificationOptions = {
    body: payload.data.body,
    icon: '/firebase-logo.png',
    data: payload.data
  };

  return self.registration.showNotification(notificationTitle,notificationOptions);
});

self.addEventListener('notificationclick', function (event) {
  event.notification.close();

  let navigateUrl = event.notification.data.click_action;

  event.waitUntil(
    clients.openWindow(navigateUrl)
  );
});
</code>```

Body:
I have reviewed and implemented some of already asked and answered questions on this platform. I am able to get push default popup on screen but however I am not able to get rid on how I can add those new pushed notification in my custom list and show to end user in UI. I wants to collect new notification and store that in my application variable so I can work around it and display all notifications to user.

Below is my implemented code.

Package.json

"dependencies": {
"@agm/core": "^1.0.0",
"@angular-devkit/core": "^8.3.16",
"@angular-devkit/schematics": "^8.3.16",
"@angular/animations": "^8.2.12",
"@angular/cdk": "^8.2.3",
"@angular/common": "^8.2.13",
"@angular/compiler": "^8.2.12",
"@angular/core": "^8.2.12",
"@angular/forms": "^8.2.12",
"@angular/platform-browser": "^8.2.12",
"@angular/platform-browser-dynamic": "^8.2.12",
......
"@angular/fire": "^5.2.3",
"@angular/platform-server": "8.0.0",
"@nguniversal/module-map-ngfactory-loader": "8.0.0-rc.1",
"aspnet-prerendering": "^3.0.1",
"firebase": "^7.5.0"
},

firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in the
firebase.initializeApp({
  apiKey: 'xyz',
  authDomain: 'xyz',
  databaseURL: 'xyz"',
  projectId: 'xyz',
  storageBucket: 'xyz',
  messagingSenderId: '168382776603',
  appId: '1:168382776603:web:65c285a048d740401a3fbe'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
const messaging = firebase.messaging();

app.module.ts

imports: [
    FormsModule,
    BrowserModule,
    AppRoutingModule,
    .....,
    AngularFireModule.initializeApp({
      apiKey: 'xyz',
      authDomain: 'xyz',
      databaseURL: 'xyz"',
      projectId: 'xyz',
      storageBucket: 'xyz',
      messagingSenderId: '168382776603',
      appId: '1:168382776603:web:65c285a048d740401a3fbe'
    }),
    AngularFireMessagingModule,
  ]

FirebasePushNotificationService.ts

    export class FirebasePushNotificationService {

    constructor(private angularFireMessaging: AngularFireMessaging) {
      this.angularFireMessaging.messaging.subscribe(
        (messagingContext: any) => {
          messagingContext.onMessage = messagingContext.onMessage.bind(messagingContext);
          messagingContext.onTokenRefresh = messagingContext.onTokenRefresh.bind(messagingContext);
        });
    }

    currentMessage = new BehaviorSubject(null);

    requestPermission = () => this.angularFireMessaging.requestToken;

    removeToken = (token: string) => this.angularFireMessaging.deleteToken(token);

    receiveMessage = () => this.angularFireMessaging.messages;
  }

app.component.ts (onInit): I need debugger in receiveMessage()

this.firebasePushNotificationService.requestPermission().subscribe(
        token => {
            console.log('Push Token', token);
        },
        error => {
            console.log('Push Error', error);
        }
    );

this.firebasePushNotificationService.receiveMessage().subscribe(message => {
        **// I am not able to get debugger here**
        console.log(message);
    });

Body:
Finally get rid on the problem. All code is works fine except firebase version, so I have update the version in packag.json as below and it works fine.

"@angular/fire": "^5.3.0",
"firebase": "7.3.0"

and then in firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/7.3.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.3.0/firebase-messaging.js');

To get Background Messages add below code in firebase-messaging-sw.js and also click event listener if you wants to navigate on custom url. this "setBackgroundMessageHandler" will execute only in case your push response has data field instead notification example as below

Push response with data field:

{
    "token" : "epFYFDGqb9ghFezyW5_Wyh:APA91bEDBKPcu7Vq....",
    "data": {
      "title": "FCM Message",
      "body": "This is a message from FCM",
      "click_action": "https://localhost:4200"
    }
}

Events for background message

messaging.setBackgroundMessageHandler(function (payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);

  const notificationTitle = payload.data.title;
  const notificationOptions = {
    body: payload.data.body,
    icon: '/firebase-logo.png',
    data: payload.data
  };

  return self.registration.showNotification(notificationTitle,notificationOptions);
});

self.addEventListener('notificationclick', function (event) {
  event.notification.close();

  let navigateUrl = event.notification.data.click_action;

  event.waitUntil(
    clients.openWindow(navigateUrl)
  );
});


来源: stackexchange

问:
64 bit Excel VBA to call a JavaScript function
I need to use a VBA ScriptControl object to call a JavaScript function , but it gave me a "Class Not Registered" error.
I have added Microsoft Script Control 1.0 from Tools->References
I need to call JavaScript to get a JSON object from this Rest API to calculate values in an Excel Macro.

This post told me that ScriptControl is  for use  in 32 bit only. I am using 64 bit Excel.
I also tried using the method mentioned in this link but it didn't work since VBA doesn't recognise the ActiveXObject

My Excel VBA code to call a simple JS function:

```<code>Private Sub CommandButton1_Click()
    Dim jsObj As MSScriptControl.ScriptControl, result As Integer
    Set jsObj = CreateObject("MSScriptControl.ScriptControl")
    jsObj.Language = "JScript"
    With jsObj
        .AddCode ("function prod1(a,b){return a*b;}")
        result = .Run("prod1", 2, 3)
    End With
    MsgBox result
End Sub
</code>```

I am getting a class not registered error for the line Set jsObj = CreateObject("MSScriptControl.ScriptControl")
Is there an alternate way to call a JavaScript function from VBA? Or am I missing something?

答:
There's no need for a ScriptControl object: you can use XMLHTTP and VBA-JSON.

For example:

Public Sub Tester()

    'Import the "JsonConverter.bas" file from
    '     https://github.com/VBA-tools/VBA-JSON
    'and add a reference to the Microsoft Scripting Runtime library
    Dim http As Object, JSON As Object, i As Integer, o As Object, k

    Set http = CreateObject("MSXML2.XMLHTTP")
    http.Open "GET", "https://www.alphavantage.co/query?" & _
          "function=CURRENCY_EXCHANGE_RATE&from_currency=USD" & _
          "&to_currency=JPY&apikey=demo", False

    http.Send

    Debug.Print http.responseText
    Debug.Print "-----------------------------------"

    Set JSON = ParseJson(http.responseText)

    Set o = JSON("Realtime Currency Exchange Rate")
    For Each k In o.keys
        Debug.Print k, o(k)
    Next k

End Sub
```

ContentLicense: CC BY-SA 4.0

Body:
I need to use a VBA ScriptControl object to call a JavaScript function , but it gave me a "Class Not Registered" error.
I have added Microsoft Script Control 1.0 from Tools->References
I need to call JavaScript to get a JSON object from this Rest API to calculate values in an Excel Macro.

This post told me that ScriptControl is  for use  in 32 bit only. I am using 64 bit Excel.
I also tried using the method mentioned in this link but it didn't work since VBA doesn't recognise the ActiveXObject

My Excel VBA code to call a simple JS function:

Private Sub CommandButton1_Click()
    Dim jsObj As MSScriptControl.ScriptControl, result As Integer
    Set jsObj = CreateObject("MSScriptControl.ScriptControl")
    jsObj.Language = "JScript"
    With jsObj
        .AddCode ("function prod1(a,b){return a*b;}")
        result = .Run("prod1", 2, 3)
    End With
    MsgBox result
End Sub

I am getting a class not registered error for the line Set jsObj = CreateObject("MSScriptControl.ScriptControl")
Is there an alternate way to call a JavaScript function from VBA? Or am I missing something?


问:
Split string loaded from SecretsManager
I am trying to create a ListenerRule that would accept only certain IP addresses loaded from Secrets Manager. Here's my original code:

```<code>LoadBalancerRule:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Properties:
        Actions:
            -   TargetGroupArn: !Ref 'TargetGroup'
                Type: 'forward'
        Conditions:
            Fn::If:
                - IsProdEnvironment
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                    -   Field: source-ip
                        SourceIpConfig:
                            Values:
                                - !Split [ ';', !Sub '{{resolve:secretsmanager:/${ProjectName}/${EnvType}/${ServiceName}:SecretString:ALLOWED_IPS}}' ]
</code>```

Resolve above seems to work properly and is resolved to a string like 1.2.3.4/32;2.3.4.5/32;4.5.6.7/29;5.6.7.8/32 (addresses obviously obfuscated but the amount and subnet mask is the same).

However when I try to deploy the template I get an error:

The specified value '1.2.3.4/32;2.3.4.5/32;4.5.6.7/29;5.6.7.8/32' is not a valid CIDR block (Service: AmazonElasticLoadBalancingV2; Status Code: 400; Error Code: ValidationError; Request ID: error-id)

This error by itself suggests that !Split does something because CloudFormation does not report error Value of property Values must be of type List of String. Clearly string was converted to a list containing one element but it was not split by ; character into list of 4 strings.

Also, when I try to run very similar code but with hardcoded value instead of secret it works fine:

```<code>LoadBalancerRule:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Properties:
        Actions:
            -   TargetGroupArn: !Ref 'TargetGroup'
                Type: 'forward'
        Conditions:
            Fn::If:
                - IsProdEnvironment
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                    -   Field: source-ip
                        SourceIpConfig:
                            Values:
                                !Split [';', '1.2.3.4/32;2.3.4.5/32;4.5.6.7/29;5.6.7.8/32' ]
</code>```

I also checked version without !Sub but with hardcoded path to Secret value:

```<code>LoadBalancerRule:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Properties:
        Actions:
            -   TargetGroupArn: !Ref 'TargetGroup'
                Type: 'forward'
        Conditions:
            Fn::If:
                - IsProdEnvironment
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                    -   Field: source-ip
                        SourceIpConfig:
                            Values: !Split [';', '{{resolve:secretsmanager:/dummy-project/dev/foo:SecretString:ALLOWED_IPS}}']
</code>```

As a result I get the same error as in first case: long string is not split into smaller parts.

To make this even weirder... this is a part of quite large template but when I copy this resource to a simple test.yaml that takes a list of Parameters required to generate SecretManager path it seems to be working properly...

What do I do wrong here?

答:
I can't provide full answer as I agree @OleksiiDonoha and I belive that resolve:secretsmanager is resolves last, during change set creation, after all intrinsic functions are executed.

However, I would like to clarify the statement:

This error by itself suggests that !Split does something because CloudFormation does not report error Value of property Values must be of type List of String.

!Split uses only String, not list of strings, unlike Select. Also, if you provide wrong delimiter it will just return the original string.

So what is happening with Split, I think, is the following:

In the expression:

```<code>  Values:
    - !Split [ ';', !Sub '{{resolve:secretsmanager:/${ProjectName}/${EnvType}/${ServiceName}:SecretString:ALLOWED_IPS}}' ]

</code>```

!Sub executes first and you end up with (for example):

```<code>  Values:
    - !Split [ ';', '{{resolve:secretsmanager:/MyProject/TestType/MyService:SecretString:ALLOWED_IPS}}' ]
</code>```

Then !Split executes and attempts to split the string '{{resolve:secretsmanager:/MyProject/TestType/MyService:SecretString:ALLOWED_IPS}}' by ;. It can't, thus you end up with:

```<code>  Values:
    - '{{resolve:secretsmanager:/MyProject/TestType/MyService:SecretString:ALLOWED_IPS}}'
</code>```

And finally now this gets resolved, resulting in:

```<code>  Values:
    - "1.2.3.4/32;2.3.4.5/32;4.5.6.7/29;5.6.7.8/32"
</code>```

This would explain your error.

The only solution I see at present would to use custom resource which would get the secret before the intrinsic functions evaluate or through an inner stack.

Alternatively, you are chaining stacks (one stacks produces outputs which go into parameters of the next stack) you could resolve the secret in the first stack, and just pass the CIDRs string list as a parameter to the second stack.

Hope this helps.

Title: Split string loaded from SecretsManager

Body:
I am trying to create a ListenerRule that would accept only certain IP addresses loaded from Secrets Manager. Here's my original code:

LoadBalancerRule:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Properties:
        Actions:
            -   TargetGroupArn: !Ref 'TargetGroup'
                Type: 'forward'
        Conditions:
            Fn::If:
                - IsProdEnvironment
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                    -   Field: source-ip
                        SourceIpConfig:
                            Values:
                                - !Split [ ';', !Sub '{{resolve:secretsmanager:/${ProjectName}/${EnvType}/${ServiceName}:SecretString:ALLOWED_IPS}}' ]

Resolve above seems to work properly and is resolved to a string like 1.2.3.4/32;2.3.4.5/32;4.5.6.7/29;5.6.7.8/32 (addresses obviously obfuscated but the amount and subnet mask is the same).

However when I try to deploy the template I get an error:

The specified value '1.2.3.4/32;2.3.4.5/32;4.5.6.7/29;5.6.7.8/32' is not a valid CIDR block (Service: AmazonElasticLoadBalancingV2; Status Code: 400; Error Code: ValidationError; Request ID: error-id)

This error by itself suggests that !Split does something because CloudFormation does not report error Value of property Values must be of type List of String. Clearly string was converted to a list containing one element but it was not split by ; character into list of 4 strings.

Also, when I try to run very similar code but with hardcoded value instead of secret it works fine:

LoadBalancerRule:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Properties:
        Actions:
            -   TargetGroupArn: !Ref 'TargetGroup'
                Type: 'forward'
        Conditions:
            Fn::If:
                - IsProdEnvironment
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                    -   Field: source-ip
                        SourceIpConfig:
                            Values:
                                !Split [';', '1.2.3.4/32;2.3.4.5/32;4.5.6.7/29;5.6.7.8/32' ]

I also checked version without !Sub but with hardcoded path to Secret value:

LoadBalancerRule:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Properties:
        Actions:
            -   TargetGroupArn: !Ref 'TargetGroup'
                Type: 'forward'
        Conditions:
            Fn::If:
                - IsProdEnvironment
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                -   -   Field: host-header
                        Values:
                            - !Ref 'BaseUrl'
                    -   Field: source-ip
                        SourceIpConfig:
                            Values: !Split [';', '{{resolve:secretsmanager:/dummy-project/dev/foo:SecretString:ALLOWED_IPS}}']

As a result I get the same error as in first case: long string is not split into smaller parts.

To make this even weirder... this is a part of quite large template but when I copy this resource to a simple test.yaml that takes a list of Parameters required to generate SecretManager path it seems to be working properly...

What do I do wrong here?

Body:
I can't provide full answer as I agree @OleksiiDonoha and I belive that resolve:secretsmanager is resolves last, during change set creation, after all intrinsic functions are executed.

However, I would like to clarify the statement:

This error by itself suggests that !Split does something because CloudFormation does not report error Value of property Values must be of type List of String.

!Split uses only String, not list of strings, unlike Select. Also, if you provide wrong delimiter it will just return the original string.

So what is happening with Split, I think, is the following:

In the expression:

  Values:
    - !Split [ ';', !Sub '{{resolve:secretsmanager:/${ProjectName}/${EnvType}/${ServiceName}:SecretString:ALLOWED_IPS}}' ]

!Sub executes first and you end up with (for example):

  Values:
    - !Split [ ';', '{{resolve:secretsmanager:/MyProject/TestType/MyService:SecretString:ALLOWED_IPS}}' ]

Then !Split executes and attempts to split the string '{{resolve:secretsmanager:/MyProject/TestType/MyService:SecretString:ALLOWED_IPS}}' by ;. It can't, thus you end up with:

  Values:
    - '{{resolve:secretsmanager:/MyProject/TestType/MyService:SecretString:ALLOWED_IPS}}'

And finally now this gets resolved, resulting in:

  Values:
    - "1.2.3.4/32;2.3.4.5/32;4.5.6.7/29;5.6.7.8/32"

This would explain your error.

The only solution I see at present would to use custom resource which would get the secret before the intrinsic functions evaluate or through an inner stack.

Alternatively, you are chaining stacks (one stacks produces outputs which go into parameters of the next stack) you could resolve the secret in the first stack, and just pass the CIDRs string list as a parameter to the second stack.

Hope this helps.


问:
Laravel 7 make relation to found out who invited me
in my web application each can be have unlimited user like with networking system. i can found which user registered with user ref code, but i want to know who is my parent and invited me to register

for example this code can be return how many user registered with my ref code:

```<code>$users = User::whereNull('user_id')->with('child')->get();
</code>```

model:

```<code>public function child()
{
    return $this->hasMany(User::class)->with('child');
}
</code>```

how can i found out who is parent of child? like with from tree branch to root

User migration file:

```<code>Schema::create('users', function (Blueprint $table) {
    $table->id();

    $table->string('name')->nullable();
    $table->string('family')->nullable();
    $table->string('username')->unique();

    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->index()->nullable();

    $table->unsignedBigInteger('user_id')->index()->nullable();
    $table->foreign('user_id')->references('id')->on('users');

    $table->string('password');

    $table->rememberToken();
    $table->softDeletes();
    $table->timestamp('created_at')->useCurrent();
    $table->timestamp('updated_at')->useCurrent();
});
</code>```

User model:

```<code>class User extends Authenticatable
{
    use Notifiable, SoftDeletes;

    protected $guarded = [
        'id',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime'
    ];

    public function users()
    {
        return $this->hasMany(User::class)->with('users');
    }
}
</code>```

答:
this solution work fine:</p>

```<code>public function child()
{
    return $this->hasMany(User::class)->with('child');
}

public function parent()
{
    return $this->belongsTo(User::class, 'user_id');
}
</code>```

Body:
in my web application each can be have unlimited user like with networking system. i can found which user registered with user ref code, but i want to know who is my parent and invited me to register

for example this code can be return how many user registered with my ref code:

$users = User::whereNull('user_id')->with('child')->get();

model:

public function child()
{
    return $this->hasMany(User::class)->with('child');
}

how can i found out who is parent of child? like with from tree branch to root

User migration file:

Schema::create('users', function (Blueprint $table) {
    $table->id();

    $table->string('name')->nullable();
    $table->string('family')->nullable();
    $table->string('username')->unique();

    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->index()->nullable();

    $table->unsignedBigInteger('user_id')->index()->nullable();
    $table->foreign('user_id')->references('id')->on('users');

    $table->string('password');

    $table->rememberToken();
    $table->softDeletes();
    $table->timestamp('created_at')->useCurrent();
    $table->timestamp('updated_at')->useCurrent();
});

User model:

class User extends Authenticatable
{
    use Notifiable, SoftDeletes;

    protected $guarded = [
        'id',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime'
    ];

    public function users()
    {
        return $this->hasMany(User::class)->with('users');
    }
}

Body:
this solution work fine:

public function child()
{
    return $this->hasMany(User::class)->with('child');
}

public function parent()
{
    return $this->belongsTo(User::class, 'user_id');
}


问:
Django - How to get that an object attribute be automatically updated depending on the actual date?
I need that an object attribute be automatically updated past some puntual date and time. I have a class and a method within this class to try to perform this, but the issue here is that I need to call the method (or access a @property) to this be applied.

The code is something like this:

```<code>class Foo(models.Model):
    status =  models.CharField()
    expiring_time = models.DateTimeField()

    def is_active(self):
        date = datetime.datetime.now()
        if date > self.expiring_time:
            self.status = "expired"
        self.save()
</code>```

I found some similar questions but none of them seems to get the point that I'm looking for. I heard about celery to perform scheduled tasks, but as I understood this just be keep calling the method and is not the same that I'm looking for.

I would like to know if is there a way to keep this method "always active", or what could be a way to achieve this?

答:
It does not seem it practical to keep a method "always active". Either some other tool like cronjob or celery needs to keep calling it, or just do not store the value in database. You can use annotate to add status value to an object inside queryset using conditional expression, like this:

```<code>from django.db.models import Case, CharField, Value, When
foo = Foo.objects.annotate(
    is_active = Case(
        When(
            date__lte=datetime.now(), then=Value("expired")
        ),
        default=Value("not expired"),
        output_field=CharField()
    )
)

for val in foo:
   print(val.is_active)
</code>```

Body:
I need that an object attribute be automatically updated past some puntual date and time. I have a class and a method within this class to try to perform this, but the issue here is that I need to call the method (or access a @property) to this be applied.

The code is something like this:

class Foo(models.Model):
    status =  models.CharField()
    expiring_time = models.DateTimeField()

    def is_active(self):
        date = datetime.datetime.now()
        if date > self.expiring_time:
            self.status = "expired"
        self.save()

I found some similar questions but none of them seems to get the point that I'm looking for. I heard about celery to perform scheduled tasks, but as I understood this just be keep calling the method and is not the same that I'm looking for.

I would like to know if is there a way to keep this method "always active", or what could be a way to achieve this?

Body:
It does not seem it practical to keep a method "always active". Either some other tool like cronjob or celery needs to keep calling it, or just do not store the value in database. You can use annotate to add status value to an object inside queryset using conditional expression, like this:

from django.db.models import Case, CharField, Value, When
foo = Foo.objects.annotate(
    is_active = Case(
        When(
            date__lte=datetime.now(), then=Value("expired")
        ),
        default=Value("not expired"),
        output_field=CharField()
    )
)

for val in foo:
   print(val.is_active)


问:
strtod accepts "e" but also "d" -- why?
I find this strange.

While it makes sense that strtod accepts 'e' as one of the characters (exactly one to be precise) in the input string I find that it also accepts 'd'.

Can someone please explain?

```<code>#include < stdio.h >
#include < stdlib.h >
int main ()
{
char *s[] = {"1a1", "1e1", "1d1", "1f1"};
char * pEnd;
double d0, d1, d2, d3;
d0 = strtod (s[0],&pEnd);
d1 = strtod (s[1],NULL);
d2 = strtod (s[2],NULL);
d3 = strtod (s[3],NULL);
printf ("::: [%f] [%f] [%f] [%f] \n", d0, d1, d2, d3);
return 0;
}
</code>```

答:
What Compiler/Libraries are you using to compile this code? Assuming you're on Visual Studio, this behaviour is expected (quoting text from the MSDN):

strtod expects nptr to point to a
  string of the following form:

[whitespace] [sign] [digits] [.digits]
  [ {d | D | e | E}[sign]digits]

You can find the full documentation for strtod here

Other implementations of the library would probably support something similar. However, the man-page for strtod found here, doesn't state that d is recognized as a valid character for the conversion purpose. In such a case, it would cause the parsing of the input string to stop and only characters parsed until that point would be converted (the same happens for the strings containing a and f).

Perhaps you should look at documentation for your library implementation and find out the format that strtod would be able to parse for your specific case.

ContentLicense: CC BY-SA 3.0

Title: strtod accepts "e" but also "d" -- why?

Body:
I find this strange.

While it makes sense that strtod accepts 'e' as one of the characters (exactly one to be precise) in the input string I find that it also accepts 'd'.

Can someone please explain?

#include < stdio.h >
#include < stdlib.h >
int main ()
{
char *s[] = {"1a1", "1e1", "1d1", "1f1"};
char * pEnd;
double d0, d1, d2, d3;
d0 = strtod (s[0],&pEnd);
d1 = strtod (s[1],NULL);
d2 = strtod (s[2],NULL);
d3 = strtod (s[3],NULL);
printf ("::: [%f] [%f] [%f] [%f] \n", d0, d1, d2, d3);
return 0;
}


问:
Unable to change type of a column from uuid to INT in postgresql
I have table in rails calibration_sessions:

```<code>t.uuid "calibration_cycle_id", null: false
t.datetime "created_at", null: false
t.integer "creator_id", null: false
t.datetime "deleted_at"
t.string "name", null: false
t.jsonb "state_transition_progress", default: []
t.string "status", null: false
t.datetime "updated_at", null: false
t.integer "updater_id", null: false
t.uuid "uuid", default: -> { "uuid_generate_v4()" }, null: false
t.index ["calibration_cycle_id", "status", "deleted_at"], name: "index_calibration_sessions_on_cycle_and_status_and_deleted_at", using: :btree
t.index ["creator_id"], name: "index_calibrations_sessions_on_creator_id", using: :btree
</code>```

the above is the schema for the table.

I am trying to change the type of column calibration_cycle_id to type INT.

```<code>TRUNCATE TABLE calibrations_sessions;
ALTER TABLE calibrations_sessions ALTER COLUMN calibration_cycle_id TYPE INT USING calibration_cycle_id::integer;
</code>```

How ever I get the following error:

```<code>ERROR:  cannot cast type uuid to integer
LINE 1: ...ation_cycle_id TYPE INT USING calibration_cycle_id::integer;
</code>```

What am I doing wrong here?

答:
UUID is a 32 digit type that cannot be automatically converted to a int data type which is too small.

You would need to write your own conversion function.
See for example Create big integer from the big end of a uuid in PostgreSQL

Body:
I have table in rails calibration_sessions:

t.uuid "calibration_cycle_id", null: false
t.datetime "created_at", null: false
t.integer "creator_id", null: false
t.datetime "deleted_at"
t.string "name", null: false
t.jsonb "state_transition_progress", default: []
t.string "status", null: false
t.datetime "updated_at", null: false
t.integer "updater_id", null: false
t.uuid "uuid", default: -> { "uuid_generate_v4()" }, null: false
t.index ["calibration_cycle_id", "status", "deleted_at"], name: "index_calibration_sessions_on_cycle_and_status_and_deleted_at", using: :btree
t.index ["creator_id"], name: "index_calibrations_sessions_on_creator_id", using: :btree

the above is the schema for the table.

I am trying to change the type of column calibration_cycle_id to type INT.

TRUNCATE TABLE calibrations_sessions;
ALTER TABLE calibrations_sessions ALTER COLUMN calibration_cycle_id TYPE INT USING calibration_cycle_id::integer;

How ever I get the following error:

ERROR:  cannot cast type uuid to integer
LINE 1: ...ation_cycle_id TYPE INT USING calibration_cycle_id::integer;

What am I doing wrong here?


问:
Cannot access admin URL in Magento 2
My domain is demo_data.local:8085 and my admin is admin_geus3n (got in app/etc/env.php). When I go to demo_data.local:8085/admin_geus3n I received this error:

```<code>This page isn’t working
demo_data.local redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
</code>```

and URL that shown on browser is

```<code>http://demo_data.local:8085/index.php/admin_geus3n/http:/index/demo_data.local:8085/index.php/admin_geus3n/admin/index/index/key/key/8a837d053fd13572cb93a9d361f4efd0382cbe4fd626d08ce3375cb74ab7c91b/
</code>```

How can I do to solve this problem?

答:
Try
http://demo_data.local:8085/index.php/admin_geus3n
or
rename .htaccess in your root folder</p>

Title: Cannot access admin URL in Magento 2

Body:
My domain is demo_data.local:8085 and my admin is admin_geus3n (got in app/etc/env.php). When I go to demo_data.local:8085/admin_geus3n I received this error:

This page isn’t working
demo_data.local redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS

and URL that shown on browser is

http://demo_data.local:8085/index.php/admin_geus3n/http:/index/demo_data.local:8085/index.php/admin_geus3n/admin/index/index/key/key/8a837d053fd13572cb93a9d361f4efd0382cbe4fd626d08ce3375cb74ab7c91b/

How can I do to solve this problem?


问:
Transactional replication errors
I'm trying to set up transactional replication in SQL Server 2012 using AdventureWorks 2012. And right at the end of the publications setup i get the following error:

SQL Server could not start the Snapshot Agent.
  Additional Information:
  An exception occurred while executing a Transact-SQL statement or batch.
  (Microsoft.SqlServer.ConnectionInfo)
  SQL ServerAgent is not currently running so it cannot be modified of this  action.
  Changed database context to 'AdventureWorks2012'.(Microsoft SQL Server,Error 22022)

I'm guessing this error isn't allowing me to execute the following code:

```<code>USE ADRepl;
SELECT * FROM Person.BusinessEntity
</code>```

As every time I do execute this I get the following error:

Msg 208, Level 16, State 1, Line 2
  Invalid object name 'Person.BusinessEntity'.

答:
Set the SQL server agent service Automatically.

Press windows key+R

type services.msc

right Click on sql server agent

properties >> startup >> select automatically.

Title: Transactional replication errors

Body:
I'm trying to set up transactional replication in SQL Server 2012 using AdventureWorks 2012. And right at the end of the publications setup i get the following error:

SQL Server could not start the Snapshot Agent.
  Additional Information:
  An exception occurred while executing a Transact-SQL statement or batch.
  (Microsoft.SqlServer.ConnectionInfo)
  SQL ServerAgent is not currently running so it cannot be modified of this  action.
  Changed database context to 'AdventureWorks2012'.(Microsoft SQL Server,Error 22022)

I'm guessing this error isn't allowing me to execute the following code:

USE ADRepl;
SELECT * FROM Person.BusinessEntity

As every time I do execute this I get the following error:

Msg 208, Level 16, State 1, Line 2
  Invalid object name 'Person.BusinessEntity'.


问:
Pod shows as "Terminating" after node is shutdown
There was a pod named n404-neo4j-core-1 running on k8s-slave2. After k8s-slave2 was turned off, the pod was stuck with the Terminating.

I was expecting the pod to be deleted and a new pod be created on another node.
If this problem is not resolved, the neo4j cluster failed to keep HA.

```<code>kubectl get pods -o wide
    NAME                                     READY   STATUS        RESTARTS   AGE     IP          NODE         NOMINATED NODE   READINESS GATES
    n404-neo4j-core-0                        1/1     Running       0          3d19h   ***   k8s-node1    <none>           <none>
    n404-neo4j-core-1                        1/1     Terminating   0          78m     ***   k8s-slave2   <none>           <none>

    kubectl describe pod n404-neo4j-core-1

Name:                      n404-neo4j-core-1
Namespace:                 default
Priority:                  0
PriorityClassName:         <none>
Node:                      k8s-slave2/10.176.6.67
Start Time:                Mon, 01 Jun 2020 23:53:13 -0700
Labels:                    app.kubernetes.io/component=core
                           app.kubernetes.io/instance=n404
                           app.kubernetes.io/managed-by=Helm
                           app.kubernetes.io/name=neo4j
                           controller-revision-hash=n404-neo4j-core-67484bd88
                           helm.sh/chart=neo4j-4.0.4-1
                           statefulset.kubernetes.io/pod-name=n404-neo4j-core-1
Annotations:               <none>
Status:                    Terminating (lasts 21m)
Termination Grace Period:  30s
IP:                        10.36.0.1
Controlled By:             StatefulSet/n404-neo4j-core
Containers:
  n404-neo4j:
    Container ID:  docker://a045d7747678ca62734800d153d01f634b9972b527289541d357cbc27456bf7b
    Image:         neo4j:4.0.4-enterprise
    Image ID:      docker-pullable://neo4j@sha256:714d83e56a5db61eb44d65c114720f8cb94b06cd044669e16957aac1bd1b5c34
    Ports:         5000/TCP, 7000/TCP, 6000/TCP, 7474/TCP, 7687/TCP, 3637/TCP
    Host Ports:    0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP
    Command:
      /bin/bash
      -c
      export core_idx=$(hostname | sed 's|.*-||')

      # Processes key configuration elements and exports env vars we need.
      . /helm-init/init.sh

      # We advertise the discovery-lb addresses (see discovery-lb.yaml) because
      # it is for internal cluster comms and is limited to private ports.
      export DISCOVERY_HOST="discovery-n404-neo4j-${core_idx}.default.svc.cluster.local"
      export NEO4J_causal__clustering_discovery__advertised__address="$DISCOVERY_HOST:5000"
      export NEO4J_causal__clustering_transaction__advertised__address="$DISCOVERY_HOST:6000"
      export NEO4J_causal__clustering_raft__advertised__address="$DISCOVERY_HOST:7000"

      echo "Starting Neo4j CORE $core_idx on $HOST"
      exec /docker-entrypoint.sh "neo4j"

    State:          Running
      Started:      Mon, 01 Jun 2020 23:53:14 -0700
    Ready:          True
    Restart Count:  0
    Liveness:       tcp-socket :7687 delay=300s timeout=2s period=10s #success=1 #failure=3
    Readiness:      tcp-socket :7687 delay=120s timeout=2s period=10s #success=1 #failure=3
    Environment Variables from:
      n404-neo4j-common-config  ConfigMap  Optional: false
      n404-neo4j-core-config    ConfigMap  Optional: false
    Environment:
      NEO4J_SECRETS_PASSWORD:  <set to the key 'neo4j-password' in secret 'n404-neo4j-secrets'>  Optional: false
    Mounts:
      /data from datadir (rw)
      /helm-init from init-script (rw)
      /plugins from plugins (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from n404-neo4j-sa-token-jp7g9 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   True
  PodScheduled      True
Volumes:
  datadir:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  datadir-n404-neo4j-core-1
    ReadOnly:   false
  init-script:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      n404-init-script
    Optional:  false
  plugins:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  n404-neo4j-sa-token-jp7g9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  n404-neo4j-sa-token-jp7g9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  svc=neo4j
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
</code>```

答:
This is so called 'at-most-one' semantic in K8S, pls check the link:
https://v1-16.docs.kubernetes.io/docs/tasks/run-application/force-delete-stateful-set-pod/

Copied from the link:
StatefulSet ensures that, at any time, there is at most one Pod with a given identity running in a cluster. This is referred to as at most one semantics provided by a StatefulSet.

Body:
There was a pod named n404-neo4j-core-1 running on k8s-slave2. After k8s-slave2 was turned off, the pod was stuck with the Terminating.

I was expecting the pod to be deleted and a new pod be created on another node.
If this problem is not resolved, the neo4j cluster failed to keep HA.

kubectl get pods -o wide
    NAME                                     READY   STATUS        RESTARTS   AGE     IP          NODE         NOMINATED NODE   READINESS GATES
    n404-neo4j-core-0                        1/1     Running       0          3d19h   ***   k8s-node1    <none>           <none>
    n404-neo4j-core-1                        1/1     Terminating   0          78m     ***   k8s-slave2   <none>           <none>

    kubectl describe pod n404-neo4j-core-1

Name:                      n404-neo4j-core-1
Namespace:                 default
Priority:                  0
PriorityClassName:         <none>
Node:                      k8s-slave2/10.176.6.67
Start Time:                Mon, 01 Jun 2020 23:53:13 -0700
Labels:                    app.kubernetes.io/component=core
                           app.kubernetes.io/instance=n404
                           app.kubernetes.io/managed-by=Helm
                           app.kubernetes.io/name=neo4j
                           controller-revision-hash=n404-neo4j-core-67484bd88
                           helm.sh/chart=neo4j-4.0.4-1
                           statefulset.kubernetes.io/pod-name=n404-neo4j-core-1
Annotations:               <none>
Status:                    Terminating (lasts 21m)
Termination Grace Period:  30s
IP:                        10.36.0.1
Controlled By:             StatefulSet/n404-neo4j-core
Containers:
  n404-neo4j:
    Container ID:  docker://a045d7747678ca62734800d153d01f634b9972b527289541d357cbc27456bf7b
    Image:         neo4j:4.0.4-enterprise
    Image ID:      docker-pullable://neo4j@sha256:714d83e56a5db61eb44d65c114720f8cb94b06cd044669e16957aac1bd1b5c34
    Ports:         5000/TCP, 7000/TCP, 6000/TCP, 7474/TCP, 7687/TCP, 3637/TCP
    Host Ports:    0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP
    Command:
      /bin/bash
      -c
      export core_idx=$(hostname | sed 's|.*-||')

      # Processes key configuration elements and exports env vars we need.
      . /helm-init/init.sh

      # We advertise the discovery-lb addresses (see discovery-lb.yaml) because
      # it is for internal cluster comms and is limited to private ports.
      export DISCOVERY_HOST="discovery-n404-neo4j-${core_idx}.default.svc.cluster.local"
      export NEO4J_causal__clustering_discovery__advertised__address="$DISCOVERY_HOST:5000"
      export NEO4J_causal__clustering_transaction__advertised__address="$DISCOVERY_HOST:6000"
      export NEO4J_causal__clustering_raft__advertised__address="$DISCOVERY_HOST:7000"

      echo "Starting Neo4j CORE $core_idx on $HOST"
      exec /docker-entrypoint.sh "neo4j"

    State:          Running
      Started:      Mon, 01 Jun 2020 23:53:14 -0700
    Ready:          True
    Restart Count:  0
    Liveness:       tcp-socket :7687 delay=300s timeout=2s period=10s #success=1 #failure=3
    Readiness:      tcp-socket :7687 delay=120s timeout=2s period=10s #success=1 #failure=3
    Environment Variables from:
      n404-neo4j-common-config  ConfigMap  Optional: false
      n404-neo4j-core-config    ConfigMap  Optional: false
    Environment:
      NEO4J_SECRETS_PASSWORD:  <set to the key 'neo4j-password' in secret 'n404-neo4j-secrets'>  Optional: false
    Mounts:
      /data from datadir (rw)
      /helm-init from init-script (rw)
      /plugins from plugins (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from n404-neo4j-sa-token-jp7g9 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   True
  PodScheduled      True
Volumes:
  datadir:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  datadir-n404-neo4j-core-1
    ReadOnly:   false
  init-script:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      n404-init-script
    Optional:  false
  plugins:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  n404-neo4j-sa-token-jp7g9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  n404-neo4j-sa-token-jp7g9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  svc=neo4j
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s


问:
How to get enum field value by its index in mysql
I have a table with an enum field. I need to calculate average value of this field and show it as one of enum elements.

I'm getting the average like this: SELECT AVG(val) FROM test; It works fine. But then I need to get one of enum values back by this index. To get index I'm using ROUND. But I don't know what to do next.

Is it possible?

Is there some other approach?

Example

Create a table:

```<code>CREATE TABLE test (
    id INT AUTO_INCREMENT PRIMARY KEY,
    val ENUM('bad', 'good', 'perfect')
);
</code>```

Fill the table:

```<code>INSERT INTO test(val) VALUES('bad'), ('bad'), ('good'), ('bad'), ('perfect'), ('perfect'), ('good');
</code>```

Select query to be fixed somehow:

```<code>SELECT AVG(val) average_value_ind, ROUND(AVG(val)) closest_value_ind FROM test;
</code>```

In this example the average value should be good

答:
Thank you all for your answers and comments. You've helped me.

Here what I've managed to do. It works in my case.

```<code>SELECT
    AVG(val) average_value,
    ROUND(AVG(val)) closest_value_id,
    JSON_UNQUOTE(JSON_EXTRACT(val_enum.items, CONCAT("$[", ROUND(AVG(val)) - 1, "]"))) enum_value
FROM test
CROSS JOIN (
    SELECT CAST(CONCAT('[', REPLACE(SUBSTRING(COLUMN_TYPE, 6, LENGTH(COLUMN_TYPE) - 6), "'", '"'), ']') AS JSON) items
    FROM information_schema.COLUMNS
    WHERE TABLE_NAME = 'test' AND COLUMN_NAME = 'val'
) val_enum;
</code>```

Body:
I have a table with an enum field. I need to calculate average value of this field and show it as one of enum elements.

I'm getting the average like this: SELECT AVG(val) FROM test; It works fine. But then I need to get one of enum values back by this index. To get index I'm using ROUND. But I don't know what to do next.

Is it possible?

Is there some other approach?

Example

Create a table:

CREATE TABLE test (
    id INT AUTO_INCREMENT PRIMARY KEY,
    val ENUM('bad', 'good', 'perfect')
);

Fill the table:

INSERT INTO test(val) VALUES('bad'), ('bad'), ('good'), ('bad'), ('perfect'), ('perfect'), ('good');

Select query to be fixed somehow:

SELECT AVG(val) average_value_ind, ROUND(AVG(val)) closest_value_ind FROM test;

In this example the average value should be good

Body:
Thank you all for your answers and comments. You've helped me.

Here what I've managed to do. It works in my case.

SELECT
    AVG(val) average_value,
    ROUND(AVG(val)) closest_value_id,
    JSON_UNQUOTE(JSON_EXTRACT(val_enum.items, CONCAT("$[", ROUND(AVG(val)) - 1, "]"))) enum_value
FROM test
CROSS JOIN (
    SELECT CAST(CONCAT('[', REPLACE(SUBSTRING(COLUMN_TYPE, 6, LENGTH(COLUMN_TYPE) - 6), "'", '"'), ']') AS JSON) items
    FROM information_schema.COLUMNS
    WHERE TABLE_NAME = 'test' AND COLUMN_NAME = 'val'
) val_enum;


问:
Is there a good way to iterate 2 lists with different length continuously?
I have 2 lists.

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c']
```

<p>And I want to print them in this way</p>

```(1, 'a')
(2, 'b')
(3, 'c')
(4, 'a')
(5, 'b')
(1, 'a')
(2, 'b')
# ... and so on ...
```

Is there a clean way to do it?

答:
Wrap both of your lists with itertools.cycle, then pass them to zip to iterate simultaneously and build 2-tuples with one value from each:

```<code>import itertools

for tup in zip(itertools.cycle(a), itertools.cycle(b)):
    print(tup) # or whatever you want to do with the tuples
</code>```

Note, this loop will run forever, so you'll probably want some other code in there to eventually break out of it.

Body:
I have 2 lists.

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c']

And I want to print them in this way

(1, 'a')
(2, 'b')
(3, 'c')
(4, 'a')
(5, 'b')
(1, 'a')
(2, 'b')
# ... and so on ...

Is there a clean way to do it?

Body:
Wrap both of your lists with itertools.cycle, then pass them to zip to iterate simultaneously and build 2-tuples with one value from each:

import itertools

for tup in zip(itertools.cycle(a), itertools.cycle(b)):
    print(tup) # or whatever you want to do with the tuples

Note, this loop will run forever, so you'll probably want some other code in there to eventually break out of it.


问:
Sort operation on Spark Structured Streaming DataFrame
I am trying a very simple sort operation on spark structured streaming dataframe but ending up "Exception in thread "main" org.apache.spark.sql.AnalysisException: Sorting is not supported on streaming DataFrames/Datasets, unless it is on aggregated DataFrame/Dataset in Complete output mode" with below exception. Can you please help me on this.

Code:

```<code>   val df: DataFrame = spark.readStream.format("kafka")
        .option("kafka.bootstrap.servers", kafkaBrokerList)
        .option("kafka.security.protocol", security)
        .option("startingOffsets", "latest")
        .option("subscribe", srcTopic)
        .option("group.id", groupID)
        .option("failOnDataLoss", false)
        .load

      val uDF = df
        .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
        .as[(String, String)]
        .select($"value")
        .select(from_json($"value", uSchema).as("events"))
        .select($"events.*")

     val uDF2 = uDF
        .select($"COL1", $"COL2", $"COL3", $"COL4", $"COL5", $"COL6", $"COL7", $"COL8")
        .sort($"COL5",$"COL3",$"COL8")

    val kDF = uDF2
        .writeStream
        .format("kafka")
        .option("kafka.bootstrap.servers", "localhost:9092")
        .option("kafka.security.protocol", "PLAINTEXT")
        .option("topic", "r_topic")
        .option("checkpointLocation", "/tmp/kafka-sink-checkpoint")
        .start()

    kDF.awaitTermination()
</code>```

Exception:

```<code>Exception in thread "main" org.apache.spark.sql.AnalysisException: Sorting is not supported on streaming DataFrames/Datasets, unless it is on aggregated DataFrame/Dataset in Complete output mode;;
</code>```

DATA:

Want to sort the DF by "COL5","COL3","COL8"

```<code>+------------+--------------------------------------+-------------+-----+-----------+-------------+----------+----------+
|COL1        |COL2                                  |COL3         |COL4 |COL5       |COl6         |COL7      |COl8      |
+------------+--------------------------------------+-------------+-----+-----------+-------------+----------+----------+
|RunKafkaTest|DUMMY VALUE                           |1528326884394|52.0 |Analog     |0            |1528326880|67        |
|RunKafkaTest|DUMMY VALUE                           |1528326884388|53.0 |Analog     |0            |1528326880|68        |
|RunKafkaTest|DUMMY VALUE                           |1528326886400|54.0 |Analog     |0            |1528326880|69        |
|RunKafkaTest|DUMMY VALUE                           |1528326887412|55.0 |Analog     |0            |1528326880|70        |
|RunKafkaTest|DUMMY VALUE                           |1528326887406|56.0 |Analog     |0            |1528326880|71        |
|RunKafkaTest|DUMMY VALUE                           |1528326889418|57.0 |Analog     |0            |1528326880|72        |
|RunKafkaTest|DUMMY VALUE                           |1528326890423|58.0 |Analog     |0            |1528326880|73        |
|RunKafkaTest|DUMMY VALUE                           |1528326891429|59.0 |Analog     |0            |1528326880|74        |
|RunKafkaTest|DUMMY VALUE                           |1528326892435|1.0  |Analog     |0            |1528326880|76        |
|RunKafkaTest|DUMMY VALUE                           |1528326893449|2.0  |Analog     |0            |1528326880|77        |
|RunKafkaTest|DUMMY VALUE                           |1528326894447|3.0  |Analog     |0            |1528326880|78        |
|RunKafkaTest|DUMMY VALUE                           |1528326895459|4.0  |Analog     |0            |1528326880|79        |
|RunKafkaTest|DUMMY VALUE                           |1528326896458|5.0  |Analog     |0            |1528326880|80        |
|RunKafkaTest|DUMMY VALUE                           |1528326897464|6.0  |Analog     |0            |1528326880|81        |
|RunKafkaTest|DUMMY VALUE                           |1528326898370|7.0  |Analog     |0            |1528326880|82        |
|RunKafkaTest|DUMMY VALUE                           |1528326899476|8.0  |Analog     |0            |1528326880|83        |
|RunKafkaTest|DUMMY VALUE                           |1528326900482|9.0  |Analog     |0            |1528326880|84        |
|RunKafkaTest|DUMMY VALUE                           |1528326901488|10.0 |Analog     |0            |1528326880|85        |
|RunKafkaTest|DUMMY VALUE                           |1528326902493|11.0 |Analog     |0            |1528326880|86        |
+------------+--------------------------------------+-------------+-----+-----------+-------------+----------+----------+
</code>```

答:
you need to group by action before sort(order by) like:</p>

```<code>uDF.select($"COL1", $"COL2", $"COL3", $"COL4", $"COL5", $"COL6", $"COL7", $"COL8")
   .groupBy("COL1")
   .agg(max("COL2").as("COL2")......).sort("........")
</code>```

Body:
I am trying a very simple sort operation on spark structured streaming dataframe but ending up "Exception in thread "main" org.apache.spark.sql.AnalysisException: Sorting is not supported on streaming DataFrames/Datasets, unless it is on aggregated DataFrame/Dataset in Complete output mode" with below exception. Can you please help me on this.

Code:

   val df: DataFrame = spark.readStream.format("kafka")
        .option("kafka.bootstrap.servers", kafkaBrokerList)
        .option("kafka.security.protocol", security)
        .option("startingOffsets", "latest")
        .option("subscribe", srcTopic)
        .option("group.id", groupID)
        .option("failOnDataLoss", false)
        .load

      val uDF = df
        .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
        .as[(String, String)]
        .select($"value")
        .select(from_json($"value", uSchema).as("events"))
        .select($"events.*")

     val uDF2 = uDF
        .select($"COL1", $"COL2", $"COL3", $"COL4", $"COL5", $"COL6", $"COL7", $"COL8")
        .sort($"COL5",$"COL3",$"COL8")

    val kDF = uDF2
        .writeStream
        .format("kafka")
        .option("kafka.bootstrap.servers", "localhost:9092")
        .option("kafka.security.protocol", "PLAINTEXT")
        .option("topic", "r_topic")
        .option("checkpointLocation", "/tmp/kafka-sink-checkpoint")
        .start()

    kDF.awaitTermination()

Exception:

Exception in thread "main" org.apache.spark.sql.AnalysisException: Sorting is not supported on streaming DataFrames/Datasets, unless it is on aggregated DataFrame/Dataset in Complete output mode;;

DATA:

Want to sort the DF by "COL5","COL3","COL8"

+------------+--------------------------------------+-------------+-----+-----------+-------------+----------+----------+
|COL1        |COL2                                  |COL3         |COL4 |COL5       |COl6         |COL7      |COl8      |
+------------+--------------------------------------+-------------+-----+-----------+-------------+----------+----------+
|RunKafkaTest|DUMMY VALUE                           |1528326884394|52.0 |Analog     |0            |1528326880|67        |
|RunKafkaTest|DUMMY VALUE                           |1528326884388|53.0 |Analog     |0            |1528326880|68        |
|RunKafkaTest|DUMMY VALUE                           |1528326886400|54.0 |Analog     |0            |1528326880|69        |
|RunKafkaTest|DUMMY VALUE                           |1528326887412|55.0 |Analog     |0            |1528326880|70        |
|RunKafkaTest|DUMMY VALUE                           |1528326887406|56.0 |Analog     |0            |1528326880|71        |
|RunKafkaTest|DUMMY VALUE                           |1528326889418|57.0 |Analog     |0            |1528326880|72        |
|RunKafkaTest|DUMMY VALUE                           |1528326890423|58.0 |Analog     |0            |1528326880|73        |
|RunKafkaTest|DUMMY VALUE                           |1528326891429|59.0 |Analog     |0            |1528326880|74        |
|RunKafkaTest|DUMMY VALUE                           |1528326892435|1.0  |Analog     |0            |1528326880|76        |
|RunKafkaTest|DUMMY VALUE                           |1528326893449|2.0  |Analog     |0            |1528326880|77        |
|RunKafkaTest|DUMMY VALUE                           |1528326894447|3.0  |Analog     |0            |1528326880|78        |
|RunKafkaTest|DUMMY VALUE                           |1528326895459|4.0  |Analog     |0            |1528326880|79        |
|RunKafkaTest|DUMMY VALUE                           |1528326896458|5.0  |Analog     |0            |1528326880|80        |
|RunKafkaTest|DUMMY VALUE                           |1528326897464|6.0  |Analog     |0            |1528326880|81        |
|RunKafkaTest|DUMMY VALUE                           |1528326898370|7.0  |Analog     |0            |1528326880|82        |
|RunKafkaTest|DUMMY VALUE                           |1528326899476|8.0  |Analog     |0            |1528326880|83        |
|RunKafkaTest|DUMMY VALUE                           |1528326900482|9.0  |Analog     |0            |1528326880|84        |
|RunKafkaTest|DUMMY VALUE                           |1528326901488|10.0 |Analog     |0            |1528326880|85        |
|RunKafkaTest|DUMMY VALUE                           |1528326902493|11.0 |Analog     |0            |1528326880|86        |
+------------+--------------------------------------+-------------+-----+-----------+-------------+----------+----------+

Body:
you need to group by action before sort(order by) like:

uDF.select($"COL1", $"COL2", $"COL3", $"COL4", $"COL5", $"COL6", $"COL7", $"COL8")
   .groupBy("COL1")
   .agg(max("COL2").as("COL2")......).sort("........")


问:
Twitter streaming API : does the bandwidth is limited?
I would like to stream all the twitter tweets (Yes, I am crazy), in order to make some stats.
I have no special permission, I am just a simple twitter user.
To begin, I am just testing whether it is possible : I go on my server, it has a 100 Mbs bandwidth (I checked it is true),
and I run this command :

```<code>curl -d 'track=http' http://stream.twitter.com/1/statuses/filter.json -umyuser:mypasswd | grep 'xxxxxx'
</code>```

I put the 'grep' just to not have the tweets displayed and not have limitations due to displaying text on screen.
Then I used 'dstat' to check the bandwidth used : it is all the time limited to 128KB/s (that is only 1Mbs). As a tweet weight is about 2K, it seems I can stream only about 64 tweets per seconds... much less than the reality (more than 1000 tweets/s I believe...).
Event if I add some frequent term into the track list, The bandwidth is stuck to 128KB/s.

Do you have any idea to get the full streaming ?

答:
Unless you have been granted the privilege, you can't access the fully unmetered firehose stream.  With just basic privileges, you will be relegated to what you are doing now, using filter, or using sample (which will deliver approximately 1% of Twitter's tweet volume.)

You can try to gain elevated access by asking Twitter, however they don't seem to be handing elevated privileges out unless you can justify your use case pretty well.

Body:
I would like to stream all the twitter tweets (Yes, I am crazy), in order to make some stats.
I have no special permission, I am just a simple twitter user.
To begin, I am just testing whether it is possible : I go on my server, it has a 100 Mbs bandwidth (I checked it is true),
and I run this command :

curl -d 'track=http' http://stream.twitter.com/1/statuses/filter.json -umyuser:mypasswd | grep 'xxxxxx'

I put the 'grep' just to not have the tweets displayed and not have limitations due to displaying text on screen.
Then I used 'dstat' to check the bandwidth used : it is all the time limited to 128KB/s (that is only 1Mbs). As a tweet weight is about 2K, it seems I can stream only about 64 tweets per seconds... much less than the reality (more than 1000 tweets/s I believe...).
Event if I add some frequent term into the track list, The bandwidth is stuck to 128KB/s.

Do you have any idea to get the full streaming ?


问:
Match first row of first column if matched then send its corresponding row of second column into Word document
I am having an excel with two columns Requirement and Source. I have another Word document with Requirement which are there in excel. I want it to be matched. If it is matched then its corresponding source need to be sent to Requirement in word document.
The excel file data:

In the word document the data should be displayed like this:
enter image description here

I tried in this way:

```<code>Sub SearchItem()
  Dim shtSearchItem As Worksheet
  Dim shtExtract As Worksheet
  Dim oWord As Word.Application
  Dim WordNotOpen As Boolean
  Dim oDoc As Word.Document
  Dim oRange As Word.Range
  Dim LastRow As Long
  Dim CurrRowShtSearchItem As Long
  Dim CurrRowShtExtract As Long
  Dim myPara As Long

  On Error Resume Next

  Set oWord = GetObject(, "Word.Application")

  If Err Then
    Set oWord = New Word.Application
    WordNotOpen = True
  End If

  On Error GoTo Err_Handler

  oWord.Visible = True
  oWord.Activate
  Set oDoc = oWord.Documents.Open("File Location")

  Set shtSearchItem = ThisWorkbook.Worksheets(1)
  If ThisWorkbook.Worksheets.Count < 2 Then
      ThisWorkbook.Worksheets.Add After:=shtSearchItem
  End If
  Set shtExtract = ThisWorkbook.Worksheets(2)

  LastRow = shtSearchItem.UsedRange.Rows(shtSearchItem.UsedRange.Rows.Count).Row

  For CurrRowShtSearchItem = 2 To LastRow
    Set oRange = oDoc.Range
      With oRange.Find
        .Text = shtSearchItem.Cells(CurrRowShtSearchItem, 1).Text
        .MatchCase = False
        .MatchWholeWord = True
        While oRange.Find.Execute = True
            oRange.Select
            If .Found Then
                oRange.InsertAfter ("Reference" & ":")   ' <= what need to be done?

            End If
            oRange.Start = oRange.End
            oRange.End = ActiveDocument.Range.End
            oRange.Collapse wdCollapseEnd
       Wend
     End With
  Next CurrRowShtSearchItem

  If WordNotOpen Then
    oWord.Quit
  End If

  'Release object references

  Set oWord = Nothing
  Set oDoc = Nothing

  Exit Sub
  Err_Handler:
  MsgBox "Word caused a problem. " & Err.Description, vbCritical, "Error: " & Err.Number
  If WordNotOpen Then
    oWord.Quit

  End If

End Sub
</code>```

Please Help. Thank You

答:
Try something based on:</p>

```<code>Sub SendRefsToDoc()
'Note: A reference to the Word library must be set, via Tools|References
Dim wdApp As New Word.Application, wdDoc As Word.Document, StrNm As String
Dim r As Long, xlFList As String, xlRList As String
StrNm = "C:\Users\" & Environ("UserName") & "\Documents\MyDocument.docx"
If Dir(StrNm) <> "" Then
  With Worksheets("Sheet1")
    For r = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
      If .Range("A" & r).Text = "" Then
      xlRList = xlRList & ", " & Trim(.Range("B" & r))
      Else
        xlFList = xlFList & "|" & Trim(.Range("A" & r))
        xlRList = xlRList & "|" & Trim(.Range("B" & r))
      End If
    Next
  End With
  With wdApp
    .Visible = False
    Set wdDoc = Documents.Open(Filename:=StrNm, AddToRecentFiles:=False, Visible:=False)
    With wdDoc
      For r = 1 To UBound(Split(xlFList, "|"))
        With .Range
          With .Find
            .Replacement.ClearFormatting
            .Text = Split(xlFList, "|")(r)
            .Replacement.Text = ""
            .Forward = True
            .Format = False
            .Wrap = wdFindStop
          End With
          Do While .Find.Execute
            .Paragraphs.First.Range.Characters.Last.InsertBefore vbCr _
              & "Reference: " & Split(xlRList, "|")(r)
            With .Paragraphs.First.Range.Font
              .Bold = True
              .Italic = True
            End With
            With .Paragraphs.Last.Range.Font
              .Bold = False
              .Italic = False
            End With
            .Collapse wdCollapseEnd
          Loop
        End With
      Next
      .Close True
    End With
    .Quit
  End With
Else
  MsgBox "File not found: " & vbCr & StrNm, vbExclamation
End If
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub
</code>```

Body:
I am having an excel with two columns Requirement and Source. I have another Word document with Requirement which are there in excel. I want it to be matched. If it is matched then its corresponding source need to be sent to Requirement in word document.
The excel file data:

In the word document the data should be displayed like this:
enter image description here

I tried in this way:

Sub SearchItem()
  Dim shtSearchItem As Worksheet
  Dim shtExtract As Worksheet
  Dim oWord As Word.Application
  Dim WordNotOpen As Boolean
  Dim oDoc As Word.Document
  Dim oRange As Word.Range
  Dim LastRow As Long
  Dim CurrRowShtSearchItem As Long
  Dim CurrRowShtExtract As Long
  Dim myPara As Long

  On Error Resume Next

  Set oWord = GetObject(, "Word.Application")

  If Err Then
    Set oWord = New Word.Application
    WordNotOpen = True
  End If

  On Error GoTo Err_Handler

  oWord.Visible = True
  oWord.Activate
  Set oDoc = oWord.Documents.Open("File Location")

  Set shtSearchItem = ThisWorkbook.Worksheets(1)
  If ThisWorkbook.Worksheets.Count < 2 Then
      ThisWorkbook.Worksheets.Add After:=shtSearchItem
  End If
  Set shtExtract = ThisWorkbook.Worksheets(2)

  LastRow = shtSearchItem.UsedRange.Rows(shtSearchItem.UsedRange.Rows.Count).Row

  For CurrRowShtSearchItem = 2 To LastRow
    Set oRange = oDoc.Range
      With oRange.Find
        .Text = shtSearchItem.Cells(CurrRowShtSearchItem, 1).Text
        .MatchCase = False
        .MatchWholeWord = True
        While oRange.Find.Execute = True
            oRange.Select
            If .Found Then
                oRange.InsertAfter ("Reference" & ":")   ' <= what need to be done?

            End If
            oRange.Start = oRange.End
            oRange.End = ActiveDocument.Range.End
            oRange.Collapse wdCollapseEnd
       Wend
     End With
  Next CurrRowShtSearchItem

  If WordNotOpen Then
    oWord.Quit
  End If

  'Release object references

  Set oWord = Nothing
  Set oDoc = Nothing

  Exit Sub
  Err_Handler:
  MsgBox "Word caused a problem. " & Err.Description, vbCritical, "Error: " & Err.Number
  If WordNotOpen Then
    oWord.Quit

  End If

End Sub

Please Help. Thank You

Body:
Try something based on:

Sub SendRefsToDoc()
'Note: A reference to the Word library must be set, via Tools|References
Dim wdApp As New Word.Application, wdDoc As Word.Document, StrNm As String
Dim r As Long, xlFList As String, xlRList As String
StrNm = "C:\Users\" & Environ("UserName") & "\Documents\MyDocument.docx"
If Dir(StrNm) <> "" Then
  With Worksheets("Sheet1")
    For r = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
      If .Range("A" & r).Text = "" Then
      xlRList = xlRList & ", " & Trim(.Range("B" & r))
      Else
        xlFList = xlFList & "|" & Trim(.Range("A" & r))
        xlRList = xlRList & "|" & Trim(.Range("B" & r))
      End If
    Next
  End With
  With wdApp
    .Visible = False
    Set wdDoc = Documents.Open(Filename:=StrNm, AddToRecentFiles:=False, Visible:=False)
    With wdDoc
      For r = 1 To UBound(Split(xlFList, "|"))
        With .Range
          With .Find
            .Replacement.ClearFormatting
            .Text = Split(xlFList, "|")(r)
            .Replacement.Text = ""
            .Forward = True
            .Format = False
            .Wrap = wdFindStop
          End With
          Do While .Find.Execute
            .Paragraphs.First.Range.Characters.Last.InsertBefore vbCr _
              & "Reference: " & Split(xlRList, "|")(r)
            With .Paragraphs.First.Range.Font
              .Bold = True
              .Italic = True
            End With
            With .Paragraphs.Last.Range.Font
              .Bold = False
              .Italic = False
            End With
            .Collapse wdCollapseEnd
          Loop
        End With
      Next
      .Close True
    End With
    .Quit
  End With
Else
  MsgBox "File not found: " & vbCr & StrNm, vbExclamation
End If
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub


问:
TypeScript: Create class properties with single point of control
So I want to have as much single point of control in my typescript classes, as well as intellisense (using vscode). I havent found a good way to do this, however.

What I want to do is make a class that
1. Has properties
2. Takes in properties via a constructor
3. Assigns the constructor values to the class properties

Sounds really easy. However, the solution has to be able to add new properties, or remove properties, by only changing a single line of code, and still have intellisense know what properties are in my class. Additionally, I don't want my object to merely hold another object with all my desired properties.

Examples. (warning, 4 space tab width and no semicolons)

```<code>class Entity {
    name: string
    val: number

    constructor(name: string, val: number) {
        this.name = name
        this.val = val
    }
}
</code>```

In this example, if I want to add a new property, I'd have to add it in three new places.
1. The properties list
2. The constructor signature
3. Assigning inside the constructor
So I don't have single point of control, moreso triple point of control

The benefits of this, however, is that theres full intellisense support, and all the properties are part of the class itself, not an object inside my class

Another example

```<code>interface IEntity {
    name: string
    val: number
}

class Entity {
    data: IEntity

    constructor(data: IEntity) {
        this.data = data
    }
}

</code>```

Here, if I want to add or remove a property, I only have to do so in one place, in the interface. Awesome! Additionally, I get full intellisense support. However, if i wanna access any of my properties, I'd have to do class.data. , rather than class., which is an unnecessary abstraction. I could add getters and setters, but that would ruin the point of single point of control.

Last example

```<code>class Entity {
    name: string
    val: number

    constructor(data: Entity) {
        ;(<any>Object).assign(this, data)
    }
}

</code>```

This, IMO, is the best example I can think of.
1. Single point of change (only have to change what my class properties are)
2. I don't have to access by using class.data., i can do class. (however, i do have to pass an object into the constructor, which some may argue is instrinsically better)
3. Full intellisense support

Anybody have better ideas, or a method similar to the third example that doesnt force me to pass in an object to the constructor?

Thanks!

答:
There is a shortcut in TypeScript for class property assignment. You just need to put the access type keyword in parameter declaration in the constructor. For example, if you want your name and val to be public (which is the default), you simply have to do:

class Entity {
    constructor(public name: string, public val: number) { }
}
```

And that's it! It will replace properties declaration, parameters, and assignments.

Body:
So I want to have as much single point of control in my typescript classes, as well as intellisense (using vscode). I havent found a good way to do this, however.

What I want to do is make a class that
1. Has properties
2. Takes in properties via a constructor
3. Assigns the constructor values to the class properties

Sounds really easy. However, the solution has to be able to add new properties, or remove properties, by only changing a single line of code, and still have intellisense know what properties are in my class. Additionally, I don't want my object to merely hold another object with all my desired properties.

Examples. (warning, 4 space tab width and no semicolons)

class Entity {
    name: string
    val: number

    constructor(name: string, val: number) {
        this.name = name
        this.val = val
    }
}

In this example, if I want to add a new property, I'd have to add it in three new places.
1. The properties list
2. The constructor signature
3. Assigning inside the constructor
So I don't have single point of control, moreso triple point of control

The benefits of this, however, is that theres full intellisense support, and all the properties are part of the class itself, not an object inside my class

Another example

interface IEntity {
    name: string
    val: number
}

class Entity {
    data: IEntity

    constructor(data: IEntity) {
        this.data = data
    }
}

Here, if I want to add or remove a property, I only have to do so in one place, in the interface. Awesome! Additionally, I get full intellisense support. However, if i wanna access any of my properties, I'd have to do class.data. , rather than class., which is an unnecessary abstraction. I could add getters and setters, but that would ruin the point of single point of control.

Last example

class Entity {
    name: string
    val: number

    constructor(data: Entity) {
        ;(<any>Object).assign(this, data)
    }
}

This, IMO, is the best example I can think of.
1. Single point of change (only have to change what my class properties are)
2. I don't have to access by using class.data., i can do class. (however, i do have to pass an object into the constructor, which some may argue is instrinsically better)
3. Full intellisense support

Anybody have better ideas, or a method similar to the third example that doesnt force me to pass in an object to the constructor?

Thanks!

Body:
There is a shortcut in TypeScript for class property assignment. You just need to put the access type keyword in parameter declaration in the constructor. For example, if you want your name and val to be public (which is the default), you simply have to do:

class Entity {
    constructor(public name: string, public val: number) { }
}

And that's it! It will replace properties declaration, parameters, and assignments.


问:
Java Selenium - Web element does not show up every time, but it shows up on some condition. How doI handle this?
public class LoginPage extends BasePage {

```<code>public LoginPage(WebDriver driver) {
    super(driver);
    // TODO Auto-generated constructor stub
}

private By username = By.id("userid");

private By password = By.id("Bharosa_Password_PadDataField");

private By continueButton = By.xpath("//input[@type ='submit']");

private By enterButton = By.xpath("/html/body/div[1]/div[2]/form/div/table/tbody/tr/td/map/area[5]");

private By continueButtonNxt = By.cssSelector("input[value=Continue][type=submit]");

private By verificationCodeField = By.id("Bharosa_Challenge_PadDataField");

private By enterButtonVerficationCode = By.xpath("/html/body/div[1]/div[2]/form/div/table/tbody/tr/td/map/area[5]");

private By landingPageTitle = By.xpath("//a/img[@class='logo-info']");

public WebElement getUsername() {
    return getWebElement(username);
}

public WebElement getPassword() {
    return  getWebElement(password);
}

public WebElement getContinueButtonNxt() {
    return getWebElement(continueButtonNxt);
}

public WebElement getContinuebutton() {
    return getWebElement(continueButton);
}

public WebElement getenterButtonVerficationCode() {
    return getWebElement(enterButtonVerficationCode);
}

public WebElement getVerificationCodeField() {
    return getWebElement(verificationCodeField);
}

public WebElement getEnterbutton() {
    return getWebElement(enterButton);
}

public LandingPage login(String user, String pass)
{

    getUsername().sendKeys(user);
    if(isElementPresent(continueButton).isDisplayed())
    {
    getContinuebutton().click();
    }
    getPassword().sendKeys(pass);
     getEnterbutton().submit();

     if(getContinueButtonNxt().isEnabled())
     {
     getContinueButtonNxt().click();
    getVerificationCodeField().sendKeys("888888");
     getenterButtonVerficationCode().submit();
     }
     else
     isElementPresentFluentWait(landingPageTitle);
     return new LandingPage(driver);
}
</code>```

}

Error
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"input[value=Continue][type=submit]"}
  (Session info: chrome=83.0.4103.61)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'EHL5CG009176X', ip: '10.0.0.17', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_251'
Driver info: org.openqa.selenium.chrome.ChromeDriver

答:
I think first you have to create one method/function which return you element if it is there on page else it will return null value.then following code may be help you .</p>

```<code>    //method which return element or null
   // return element in this is 'xyzelement'
    if(xyzelement!=null)
    {
    if(xyzelement.isDisplayed() && xyzelement.isEnabled())
    {
    //Action
    }
    }
</code>```

Body:
public class LoginPage extends BasePage {

public LoginPage(WebDriver driver) {
    super(driver);
    // TODO Auto-generated constructor stub
}

private By username = By.id("userid");

private By password = By.id("Bharosa_Password_PadDataField");

private By continueButton = By.xpath("//input[@type ='submit']");

private By enterButton = By.xpath("/html/body/div[1]/div[2]/form/div/table/tbody/tr/td/map/area[5]");

private By continueButtonNxt = By.cssSelector("input[value=Continue][type=submit]");

private By verificationCodeField = By.id("Bharosa_Challenge_PadDataField");

private By enterButtonVerficationCode = By.xpath("/html/body/div[1]/div[2]/form/div/table/tbody/tr/td/map/area[5]");

private By landingPageTitle = By.xpath("//a/img[@class='logo-info']");

public WebElement getUsername() {
    return getWebElement(username);
}

public WebElement getPassword() {
    return  getWebElement(password);
}

public WebElement getContinueButtonNxt() {
    return getWebElement(continueButtonNxt);
}

public WebElement getContinuebutton() {
    return getWebElement(continueButton);
}

public WebElement getenterButtonVerficationCode() {
    return getWebElement(enterButtonVerficationCode);
}

public WebElement getVerificationCodeField() {
    return getWebElement(verificationCodeField);
}

public WebElement getEnterbutton() {
    return getWebElement(enterButton);
}

public LandingPage login(String user, String pass)
{

    getUsername().sendKeys(user);
    if(isElementPresent(continueButton).isDisplayed())
    {
    getContinuebutton().click();
    }
    getPassword().sendKeys(pass);
     getEnterbutton().submit();

     if(getContinueButtonNxt().isEnabled())
     {
     getContinueButtonNxt().click();
    getVerificationCodeField().sendKeys("888888");
     getenterButtonVerficationCode().submit();
     }
     else
     isElementPresentFluentWait(landingPageTitle);
     return new LandingPage(driver);
}

}

Error
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"input[value=Continue][type=submit]"}
  (Session info: chrome=83.0.4103.61)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'EHL5CG009176X', ip: '10.0.0.17', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_251'
Driver info: org.openqa.selenium.chrome.ChromeDriver

Body:
I think first you have to create one method/function which return you element if it is there on page else it will return null value.then following code may be help you .

    //method which return element or null
   // return element in this is 'xyzelement'
    if(xyzelement!=null)
    {
    if(xyzelement.isDisplayed() && xyzelement.isEnabled())
    {
    //Action
    }
    }


问:
Risks involved with publicly accessible AWS RDS databases
I've come across multiple guidelines stating that AWS RDS instances should not be configured to be publicly accessible, because it is a major security risk. Example:RDS Publicly Accessible - RDS best practice

If the RDS instance is configured with a sufficiently strong and unique password which is practically impossible to brute-force, is it still a security risk? Wouldn't a strong and unique password make the instance reasonably safe, even if it is publicly accessible?

答:
Remember that by having your Database publicly accessible you are effectively removing that top layer of security you have.

Despite you having a strong password, attackers could be developing several ways of getting in (not just brute force of a password).

Even if they don't get in they could potentially stop you being able to access it through a series of attacks, whether they overwhelm the resources (CPU, Memory, Disk) or maximise total available connections or ports.

I would go as far as saying that your DB should never need directly public access, at very minimum look at using some kind of bastion host, or look at using either a Client VPN (AWS managed or OpenVPN) if you're on a tight budget (you can always turn them off when not using).

If time permits take a look at the security pillar of the Well-Architected Framework.


问:
from C++ to C#
What are good c++ to C# articles/tutorial or books?
I am reading http://msdn.microsoft.com/en-us/magazine/cc301520.aspx and will read http://andymcm.com/csharpfaq.htm and http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html afterwards. Have any of you read any good books for ppl who have a strong understanding of programming && || C++ on the C# language (and libraries)?</p>

答: I recommend Accelerated C# book for programmers who's came from C++ and Java Languages.

ContentLicense: CC BY-SA 2.5

Title: from C++ to C#

OwnerDisplayName: ecleel


问:
How to insert a titles row into a csv file
I have a .csv file which has data but not the column headers. I can able to create new .csv file with oldcsv file's content. But I need to add column headers in first row and from second row the existing data should appear.

Here is the code I have written:

```<code> Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String      Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()
</code>```

Now i need to add column headers in new.csv as "ID","Name","Number","Amount"

答:
You can set up the Reader and Writer to read and write within the loop and avoid creating a oiLines construct.

```<code>Dim reader as New StreamReader(inputFileName)
Dim writer as New StreamWriter(outputFileName)
Dim line as String

'Do you have a definition of what has to be added here?
writer.WriteLine(headerLine)

While (Nothing <> (line = reader.ReadLine()))
  writer.WriteLine(line)
End While

reader.Dispose()
writer.Dispose()
</code>```

Check the code, as I wrote it blind. I am more C#, but the idea is sound. You just need to supply the inputFileName, outputFileName and headerLine. This also allows putting this in a method, where it is reuseable. :-)

Body:
I have a .csv file which has data but not the column headers. I can able to create new .csv file with oldcsv file's content. But I need to add column headers in first row and from second row the existing data should appear.

Here is the code I have written:

 Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String      Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()

Now i need to add column headers in new.csv as "ID","Name","Number","Amount"

Body:
You can set up the Reader and Writer to read and write within the loop and avoid creating a oiLines construct.

Dim reader as New StreamReader(inputFileName)
Dim writer as New StreamWriter(outputFileName)
Dim line as String

'Do you have a definition of what has to be added here?
writer.WriteLine(headerLine)

While (Nothing <> (line = reader.ReadLine()))
  writer.WriteLine(line)
End While

reader.Dispose()
writer.Dispose()

Check the code, as I wrote it blind. I am more C#, but the idea is sound. You just need to supply the inputFileName, outputFileName and headerLine. This also allows putting this in a method, where it is reuseable. :-)