问:
How do I iterate through array in Kusto?
I need to iterate through managed data disks in Azure Resource Graph Explorer (https://preview.portal.azure.com/). My query is below but it returns JSON array, I need to extract name of disk and type of storage account which is being used (sample JSON return is below). So I'd like to see on screen grouping by machine name, disk name and then storage account type. My current query is below but obviously it does not work due to return of JSON

```<code>where type =~ 'Microsoft.Compute/virtualmachines' |
extend disks = properties.storageProfile.dataDisks |
project name, disks
</code>```

Same JSON output

```<code>[
    {
        "name": "COMP02_DDisk1",
        "createOption": "Attach",
        "diskSizeGB": 400,
        "managedDisk": {
            "id": "/subscriptions/5f5c5be9-77d4db790171/resourceGroups/BRAZILSOUTHDB/providers/Microsoft.Compute/disks/COMP02_DDisk1",
            "storageAccountType": "Premium_LRS"
        },
        "caching": "None",
        "toBeDetached": false,
        "lun": 0,
        "writeAcceleratorEnabled": false
    },
    {
        "name": "COMP02_DDisk2",
        "createOption": "Attach",
        "diskSizeGB": 400,
        "managedDisk": {
            "id": "/subscriptions/5f5c5be9-77d4db790171/resourceGroups/BRAZILSOUTHDB/providers/Microsoft.Compute/disks/COMP02_DDisk2",
            "storageAccountType": "Premium_LRS"
        },
        "caching": "None",
        "toBeDetached": false,
        "lun": 1,
        "writeAcceleratorEnabled": false
    }
]
</code>```

答:
Hope you are doing good .

You can try this way also, First i found networksecuritygroups from entire collection and later filtered defaultSecurityRules which is again an array.
After collecting it using mvexpand in local variable rules you should be able to fetch the desired after applying.

```<code> where type =~ "microsoft.network/networksecuritygroups"
| mvexpand rules = properties.defaultSecurityRules
| where rules.properties.destinationAddressPrefix =~ "*"
</code>```

You can also refer given below link and wish it will help you also.

Body:
I need to iterate through managed data disks in Azure Resource Graph Explorer (https://preview.portal.azure.com/). My query is below but it returns JSON array, I need to extract name of disk and type of storage account which is being used (sample JSON return is below). So I'd like to see on screen grouping by machine name, disk name and then storage account type. My current query is below but obviously it does not work due to return of JSON

where type =~ 'Microsoft.Compute/virtualmachines' |
extend disks = properties.storageProfile.dataDisks |
project name, disks

Same JSON output

[
    {
        "name": "COMP02_DDisk1",
        "createOption": "Attach",
        "diskSizeGB": 400,
        "managedDisk": {
            "id": "/subscriptions/5f5c5be9-77d4db790171/resourceGroups/BRAZILSOUTHDB/providers/Microsoft.Compute/disks/COMP02_DDisk1",
            "storageAccountType": "Premium_LRS"
        },
        "caching": "None",
        "toBeDetached": false,
        "lun": 0,
        "writeAcceleratorEnabled": false
    },
    {
        "name": "COMP02_DDisk2",
        "createOption": "Attach",
        "diskSizeGB": 400,
        "managedDisk": {
            "id": "/subscriptions/5f5c5be9-77d4db790171/resourceGroups/BRAZILSOUTHDB/providers/Microsoft.Compute/disks/COMP02_DDisk2",
            "storageAccountType": "Premium_LRS"
        },
        "caching": "None",
        "toBeDetached": false,
        "lun": 1,
        "writeAcceleratorEnabled": false
    }
]

Body:
Hope you are doing good .

You can try this way also, First i found networksecuritygroups from entire collection and later filtered defaultSecurityRules which is again an array.
After collecting it using mvexpand in local variable rules you should be able to fetch the desired after applying.

 where type =~ "microsoft.network/networksecuritygroups"
| mvexpand rules = properties.defaultSecurityRules
| where rules.properties.destinationAddressPrefix =~ "*"

You can also refer given below link and wish it will help you also.


来源: stackexchange

问:
What is the difference between a Functor and the Command pattern?
I am very familiar with the Command pattern, but I don't yet understand the difference in theory between a Functor and a command. In particular, I am thinking of Java implementations. Both are basically programming "verbs" represented as objects. However, in the case of functors, as I have seen from some examples anonymous inner class implementations seem common. Can anyone out there clear this up for me nicely?</p>

答:
According to GOF (Gang of Four) cited definition (by Comptrol), Functor and Command are two different Patterns.

As already stated, Functor represents a Class containing a service method, in other terms: the main responsibility for the functor class is to store the specific logic implemented in its own method. Hence, we can think at the functor how a container for its own method's inner logic. Historically, Functor borns because in the Java specification is not present the implementation and/or concept of 'function pointer', which is very useful in the context of registered callbacks (specific implementation for the observer pattern).

The Command Pattern represents a Design pattern aimed to decouple an Invoker entity from a Receiver one. It is mainly used when it is needed to decuple the actions (generating the events) from the action listeners (think to GUIs). It has a method responsible for the excecution of a specific operation (depending on the particular command implementation from its own superclass) referring to a specific Object Receiver; in the stated definition, the execution method can be defined as "not smart", in fact with a smart implementation could be itself to implement operative logic instead of delegating it to a third object.
When we have a smart execution method, we are implementing a functor, and we are putting the functor (specific command subpart implementation) in the context of command pattern.

I hope this will be helpful for you.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Totophil

ContentLicense: CC BY-SA 3.0


问:
how to check if today is between two dates in Twig?
I'd like to check if today's date is between two dates from the database. Here's my code.

```<code>{% if today < room.price_start_date and today > room.price_end_date %}
<a href="{{'/'|app}}/book/{{room.id}}"><button type="button" class="btn btn-default btn-xs">Book this room</button></a>
{% else %}
<a href="{{'/'|app}}/contact"><button type="button" class="btn btn-default btn-xs">Book this room</button></a>
{% endif %}
</code>```

The today variable gets its value from this code:

```<code>$todayDate = date('Y-m-d');
$this['today'] = date('Y-m-d', strtotime($todayDate));
</code>```

The price_start_date and price_end_date I get them from database and their columns' type is Date

Any idea how to check if today is between room.price_start_date and room.price_end_date in Twig?

答:
For open dates solution consider extending @Farside solution a bit as follows:

```<code>    {% if ( date(room.price_start_date) is null or date(room.price_start_date) < date())  and
          ( date(room.price_end_date)   is null or date(room.price_end_date)   > date()) %}

      {# condition met #}

    {% endif %}
</code>```

Also take into account that if neither start or end is set it will consider everything inside the range.

Body:
I'd like to check if today's date is between two dates from the database. Here's my code.

{% if today < room.price_start_date and today > room.price_end_date %}
<button type="button" class="btn btn-default btn-xs">Book this room</button>
{% else %}
<button type="button" class="btn btn-default btn-xs">Book this room</button>
{% endif %}

The today variable gets its value from this code:

$todayDate = date('Y-m-d');
$this['today'] = date('Y-m-d', strtotime($todayDate));

The price_start_date and price_end_date I get them from database and their columns' type is Date

Any idea how to check if today is between room.price_start_date and room.price_end_date in Twig?

Body:
For open dates solution consider extending @Farside solution a bit as follows:

    {% if ( date(room.price_start_date) is null or date(room.price_start_date) < date())  and
          ( date(room.price_end_date)   is null or date(room.price_end_date)   > date()) %}

      {# condition met #}

    {% endif %}

Also take into account that if neither start or end is set it will consider everything inside the range.

ContentLicense: CC BY-SA 4.0


问:
Cannot fide modules gulp
How can i fix this problem? Im usin VSCode  and trying to install gulp in my project. What`s the problem ot this?

```<code>
SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
</code>```

gulpfile.js

```<code>import { src, dest } from 'gulp';
import sass from 'gulp-sass';
import minifyCSS from 'gulp-csso';

function style() {
    return src('./scss/**/*.scss')
        .pipe(sass())
        .pipe(minifyCSS())
        .pipe(dest('./css'))
}

const _style = style;
export { _style as style };
</code>```

terminal code: gulp _style

答:
node --experimental-modules gulpfile.js and after it works
and change gulpfile.js to this type</p>

```<code>const gulp = require('gulp');
const sass = require('gulp-sass');
const minifyCSS = require('gulp-csso');

function style() {
    return gulp.src('./scss/**/*.scss')
        .pipe(sass())
        .pipe(minifyCSS())
        .pipe(gulp.dest('./css'))
}

exports.style = style;
</code>```

Title: Cannot fide modules gulp

Body:
How can i fix this problem? Im usin VSCode  and trying to install gulp in my project. What`s the problem ot this?

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)

gulpfile.js

import { src, dest } from 'gulp';
import sass from 'gulp-sass';
import minifyCSS from 'gulp-csso';

function style() {
    return src('./scss/**/*.scss')
        .pipe(sass())
        .pipe(minifyCSS())
        .pipe(dest('./css'))
}

const _style = style;
export { _style as style };

terminal code: gulp _style

Body:
node --experimental-modules gulpfile.js and after it works
and change gulpfile.js to this type

const gulp = require('gulp');
const sass = require('gulp-sass');
const minifyCSS = require('gulp-csso');

function style() {
    return gulp.src('./scss/**/*.scss')
        .pipe(sass())
        .pipe(minifyCSS())
        .pipe(gulp.dest('./css'))
}

exports.style = style;


问:
Optimized Paging and Sorting based on DateTime column having varchar type
I want optimized paging in sorting solution on my web application. For which I am using a stored procedure in SQL Server 2012.

I have used the following SQL statements in order to sort my column CreatedTime where I have saved date and time of orders.

However, that column's datatype is VARCHAR in the database.

I want to convert that column to datetime first and then sort based on that column. Apart from this I also want to sort based on Profit column and that column is also saved as VARCHAR.

Here is what I have done so far:

```<code>DECLARE @SortColumn VARCHAR(20),
        @SortDirection VARCHAR(20)

SET @SortColumn = 'CreatedTime'
SET @SortDirection = ' DESC'

SELECT ROW_NUMBER() OVER
      (
            ORDER BY
            concat (CONVERT(DateTime, CreatedTime,101), ' ' , @SortDirection)

             CASE
                WHEN @SortColumn ='CreatedTime' THEN concat (CONVERT(DateTime, CreatedTime,101), ' ' , @SortDirection)

                WHEN @SortColumn = 'Profit' THEN concat (CONVERT(DECIMAL(16,2), Profit), ' ' , @SortDirection)
            END

     ) AS RowNumber
      ,OrderID
,CreatedTime
,Profit
From Orders
</code>```

The result of the above statement is not sorted based on the CreatedTime column.

答:
I think the problem is concatenating the CreatedTime column and @SortDirection variable so the following will be helpful to resolve your issue.

The following query is used as a sample table and data;

```<code>CREATE TABLE Orders (OrderID INT IDENTITY(1,1) ,CreatedTime VARCHAR(100),Profit VARCHAR(100) )
GO
INSERT INTO Orders VALUES('2020-02-19 12:10:57.083', '100.234')
INSERT INTO Orders VALUES('2020-02-17 12:11:17.973', '999.234')
INSERT INTO Orders VALUES('2020-02-25 12:11:48.277', '8892.234')
</code>```

The following query will sort the column values according to the variable.

```<code>DECLARE @SortColumn VARCHAR(20),
        @SortDirection VARCHAR(20)

SET @SortColumn = 'CreatedTime'
SET @SortDirection = 'ASC'
IF @SortDirection= 'DESC'
BEGIN
SELECT ROW_NUMBER() OVER
      (
            ORDER BY
          --  concat (CONVERT(DateTime, CreatedTime,101), ' ' , @SortDirection)

             CASE
                WHEN @SortColumn ='CreatedTime' THEN CONVERT(DateTime, CreatedTime,101)

            END
            DESC
            ,
              CASE  WHEN @SortColumn = 'Profit' THEN CONVERT(DECIMAL(16,2), Profit)
            END  DESC

     ) AS RowNumber
      ,OrderID
,CreatedTime
,Profit
From Orders
END

IF @SortDirection= 'ASC'
BEGIN
SELECT ROW_NUMBER() OVER
      (
            ORDER BY
          --  concat (CONVERT(DateTime, CreatedTime,101), ' ' , @SortDirection)

             CASE
                WHEN @SortColumn ='CreatedTime' THEN CONVERT(DateTime, CreatedTime,101)

            END
            ASC
            ,
              CASE  WHEN @SortColumn = 'Profit' THEN CONVERT(DECIMAL(16,2), Profit)
            END  ASC

     ) AS RowNumber
      ,OrderID
,CreatedTime
,Profit
From Orders
END
</code>```

Body:
I want optimized paging in sorting solution on my web application. For which I am using a stored procedure in SQL Server 2012.

I have used the following SQL statements in order to sort my column CreatedTime where I have saved date and time of orders.

However, that column's datatype is VARCHAR in the database.

I want to convert that column to datetime first and then sort based on that column. Apart from this I also want to sort based on Profit column and that column is also saved as VARCHAR.

Here is what I have done so far:

DECLARE @SortColumn VARCHAR(20),
        @SortDirection VARCHAR(20)

SET @SortColumn = 'CreatedTime'
SET @SortDirection = ' DESC'

SELECT ROW_NUMBER() OVER
      (
            ORDER BY
            concat (CONVERT(DateTime, CreatedTime,101), ' ' , @SortDirection)

             CASE
                WHEN @SortColumn ='CreatedTime' THEN concat (CONVERT(DateTime, CreatedTime,101), ' ' , @SortDirection)

                WHEN @SortColumn = 'Profit' THEN concat (CONVERT(DECIMAL(16,2), Profit), ' ' , @SortDirection)
            END

     ) AS RowNumber
      ,OrderID
,CreatedTime
,Profit
From Orders

The result of the above statement is not sorted based on the CreatedTime column.

Body:
I think the problem is concatenating the CreatedTime column and @SortDirection variable so the following will be helpful to resolve your issue.

The following query is used as a sample table and data;

CREATE TABLE Orders (OrderID INT IDENTITY(1,1) ,CreatedTime VARCHAR(100),Profit VARCHAR(100) )
GO
INSERT INTO Orders VALUES('2020-02-19 12:10:57.083', '100.234')
INSERT INTO Orders VALUES('2020-02-17 12:11:17.973', '999.234')
INSERT INTO Orders VALUES('2020-02-25 12:11:48.277', '8892.234')

The following query will sort the column values according to the variable.

DECLARE @SortColumn VARCHAR(20),
        @SortDirection VARCHAR(20)

SET @SortColumn = 'CreatedTime'
SET @SortDirection = 'ASC'
IF @SortDirection= 'DESC'
BEGIN
SELECT ROW_NUMBER() OVER
      (
            ORDER BY
          --  concat (CONVERT(DateTime, CreatedTime,101), ' ' , @SortDirection)

             CASE
                WHEN @SortColumn ='CreatedTime' THEN CONVERT(DateTime, CreatedTime,101)

            END
            DESC
            ,
              CASE  WHEN @SortColumn = 'Profit' THEN CONVERT(DECIMAL(16,2), Profit)
            END  DESC

     ) AS RowNumber
      ,OrderID
,CreatedTime
,Profit
From Orders
END

IF @SortDirection= 'ASC'
BEGIN
SELECT ROW_NUMBER() OVER
      (
            ORDER BY
          --  concat (CONVERT(DateTime, CreatedTime,101), ' ' , @SortDirection)

             CASE
                WHEN @SortColumn ='CreatedTime' THEN CONVERT(DateTime, CreatedTime,101)

            END
            ASC
            ,
              CASE  WHEN @SortColumn = 'Profit' THEN CONVERT(DECIMAL(16,2), Profit)
            END  ASC

     ) AS RowNumber
      ,OrderID
,CreatedTime
,Profit
From Orders
END


问:
Angular Renderer2 remove listener
Is it possible to remove listeners with the new angular 4 renderer?

here is the interface:

```<code>abstract listen(target: 'window' | 'document' | 'body' | any, eventName: string, callback: (event: any) => boolean | void): () => void;
</code>```

In the renderer v1 listen and listenGlobal returns a Function, but this one returns void.

Is it an issue? If not, how can I remove a listener?

答:
You could also use the fromEventPattern function from rxjs.

  private createOnClickObservable(renderer: Renderer2) {
    let removeClickEventListener: () => void;
    const createClickEventListener = (
      handler: (e: Event) => boolean | void
    ) => {
      removeClickEventListener = renderer.listen("document", "click", handler);
    };

    this.onClick$ = fromEventPattern<Event>(createClickEventListener, () =>
      removeClickEventListener()
    ).pipe(takeUntil(this._destroy$));
  }
```

<p>just use/subscribe to it as expected</p>

<pre class="lang-js prettyprint-override"><code>   myMouseService.onClick$.subscribe((e: Event) => {
      console.log("CLICK", e);
    });
</code>```

and dont worry about destroying, it will be handled by rxjs during closing the observable!

live-demo: https://stackblitz.com/edit/angular-so4?file=src%2Fapp%2Fmy-mouse.service.ts

see another answer, to explore more details: Is it possible to use HostListener in a Service? Or how to use DOM events in an Angular service?

Title: Angular Renderer2 remove listener

Body:
Is it possible to remove listeners with the new angular 4 renderer?

here is the interface:

abstract listen(target: 'window' | 'document' | 'body' | any, eventName: string, callback: (event: any) => boolean | void): () => void;

In the renderer v1 listen and listenGlobal returns a Function, but this one returns void.

Is it an issue? If not, how can I remove a listener?

Body:
You could also use the fromEventPattern function from rxjs.

  private createOnClickObservable(renderer: Renderer2) {
    let removeClickEventListener: () => void;
    const createClickEventListener = (
      handler: (e: Event) => boolean | void
    ) => {
      removeClickEventListener = renderer.listen("document", "click", handler);
    };

    this.onClick$ = fromEventPattern<Event>(createClickEventListener, () =>
      removeClickEventListener()
    ).pipe(takeUntil(this._destroy$));
  }

just use/subscribe to it as expected

   myMouseService.onClick$.subscribe((e: Event) => {
      console.log("CLICK", e);
    });

and dont worry about destroying, it will be handled by rxjs during closing the observable!

live-demo: https://stackblitz.com/edit/angular-so4?file=src%2Fapp%2Fmy-mouse.service.ts

see another answer, to explore more details: Is it possible to use HostListener in a Service? Or how to use DOM events in an Angular service?


问:
Detect which field != null in POJO class?
Here I am trying to get values from Firebase database.

```<code>public class User {

    String id = null;
    String name = null;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}
</code>```

Some of those getter fields are null, and checking one by one is lengthy coding.

```<code>activityRef.child(uid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot)
    {
        User usr =dataSnapshot.getValue(User.class);
        //here i want to check which value!=null
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

答:
I think this will help you to find solution.</p>

```<code>activityRef.child(uid).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                User usr =dataSnapshot.getValue(User.class);
                for (Field f : User.class.getDeclaredFields()){
                   if(f.get(usr) != null){

                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
</code>```

Body:
Here I am trying to get values from Firebase database.

public class User {

    String id = null;
    String name = null;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

Some of those getter fields are null, and checking one by one is lengthy coding.

activityRef.child(uid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot)
    {
        User usr =dataSnapshot.getValue(User.class);
        //here i want to check which value!=null
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Body:
I think this will help you to find solution.

activityRef.child(uid).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                User usr =dataSnapshot.getValue(User.class);
                for (Field f : User.class.getDeclaredFields()){
                   if(f.get(usr) != null){

                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


问:
google cloud storage: access cloud storage and provide download link for users
In my developent server, i am able to use the blobkey to download a csv object.  The problem is that in production, the blobkey does not download anything (it returns a 404); presumably because the blobkey is inaccurate.  I think this is because googles deprecation of the blobstore and is no longer using blobkeys. This means i need to try and download from google storage bucket.  I am not sure how to do this; In development server, i would go to this endpoint to download /data?key=<blob_key> to download the blob object.

I can also download the csv object if i navigate to the bucket and ot the item and then click download.  Is there some minor adjustments i can make to get the download to occur? BI would appreciate if someone could point me to a particular direction.

答:
To download objects from your buckets in Cloud Storage depending on your preferences you can check the following code sample (Python):

```<code>from google.cloud import storage

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )
</code>```

Be sure that you are not using Python 2.7 anymore since it became deprecated and it is not supported anymore. If you have Python 2.7 please upgrade to Python 3.7.

Body:
To download objects from your buckets in Cloud Storage depending on your preferences you can check the following code sample (Python):

from google.cloud import storage

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )

Be sure that you are not using Python 2.7 anymore since it became deprecated and it is not supported anymore. If you have Python 2.7 please upgrade to Python 3.7.


问:
Basic dialect, what language is this?
I'm using Concerto post processing app from AVL and I'm having hard time with scripting language we use here. It looks like MS visual basic but not that much and I want to know more about what version of Basic is this, so that I can find more documentation on the web.

When I try code from MS Visual Basic documentation site, like generating int array and puting some elements to initialize it (as you can see below), I got syntax error on Concerto Scripting editor

```<code>' Declare a single-dimension array and set its 4 values.
Dim numbers = New Integer() {1, 2, 4, 8}
</code>```

This is from Concerto's own documentation and I cannot find how to create a simple array but Dataset istead, which is something similar I beleive

NewDSArray

This function generates a new array.

Syntax:

A = NewDSArray([Rows], [Columns])

Parameters:

Rows (optional, 1 = default): Numeric initial number of lines

Columns (optional, 0 = default): Numeric initial number of columns

Function:

A is now a new array with which the Dataset Array class commands can be used.

```<code>thisDSMatrix=newdsarray(1,2)
FirstCol={1,2,3}
FirstCol.name="FirstCol" //.name will pass the name into the matrix
thisDSMatrix.PutCell(FirstCol,1,1)
SecondCol={4,5,6}
SecondCol.name="SecondCol"
thisDSMatrix.PutCell(SecondCol,1,2)
Mcols=thisDSMatrix.ColCount //returns 2
Mrows=thisDSMatrix.RowCount //returns 1
thisDSMatrix.AddColumn("MyNewCol") //a column is added and thisDSMatrix.ColCount will now show 3
thisDSMatrix.PutCell({7,8,9},1,thisDSMatrix.ColCount)
return thisDSMatrix
</code>```

I appreciate if you can help me to spot exact version of Basic Concerto uses. Thank you.

答: We had basically the same issue and because I didn't want to learn a proprietary language I dicided to go with Python. AVL Concerto provides from version V5.x onwards a Python-API. Despite that the API is not perfect from my point of view, this might be an alternative to the Concerto scripting language. And learning Python will thertenly the better solution.</p>

Title: Basic dialect, what language is this?

Body:
I'm using Concerto post processing app from AVL and I'm having hard time with scripting language we use here. It looks like MS visual basic but not that much and I want to know more about what version of Basic is this, so that I can find more documentation on the web.

When I try code from MS Visual Basic documentation site, like generating int array and puting some elements to initialize it (as you can see below), I got syntax error on Concerto Scripting editor

' Declare a single-dimension array and set its 4 values.
Dim numbers = New Integer() {1, 2, 4, 8}

This is from Concerto's own documentation and I cannot find how to create a simple array but Dataset istead, which is something similar I beleive

NewDSArray

This function generates a new array.

Syntax:

A = NewDSArray([Rows], [Columns])

Parameters:

Rows (optional, 1 = default): Numeric initial number of lines

Columns (optional, 0 = default): Numeric initial number of columns

Function:

A is now a new array with which the Dataset Array class commands can be used.

thisDSMatrix=newdsarray(1,2)
FirstCol={1,2,3}
FirstCol.name="FirstCol" //.name will pass the name into the matrix
thisDSMatrix.PutCell(FirstCol,1,1)
SecondCol={4,5,6}
SecondCol.name="SecondCol"
thisDSMatrix.PutCell(SecondCol,1,2)
Mcols=thisDSMatrix.ColCount //returns 2
Mrows=thisDSMatrix.RowCount //returns 1
thisDSMatrix.AddColumn("MyNewCol") //a column is added and thisDSMatrix.ColCount will now show 3
thisDSMatrix.PutCell({7,8,9},1,thisDSMatrix.ColCount)
return thisDSMatrix

I appreciate if you can help me to spot exact version of Basic Concerto uses. Thank you.


问:
Teradata SQL returning previous two months, based on CURRENT_DATE
TLDR:
I want to get a table with the previous two months in Teradata, based on CURRENT_DATE. Currently I can only get the previous month:

```<code>SELECT
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM') MM;
</code>```

Expected output is:

```<code>+--------+
|   MM   |
+--------+
| 2020-01|
| 2019-12|
+--------+
</code>```

Long version:
I want something, that could be used in a bigger query like this, valid for every day of the year, without hardcoding the dates. The bigger query with the hardcoded dates looks like this:

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN ('2020-01', '2019-12')
</code>```

and it works perfectly. The below one returns results ok, but only for 1 month.

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM')
)
</code>```

Tried to add a comma and add the same line with -2, did not work:

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM'),
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -2), 'YYYY-MM')
)
</code>```

the error is:

SELECT Failed 3706: Syntax error: expected something between ')' and '.'.

答:
Try something with sub query:</p>

```<code>select * from table where date in
(SELECT To_char(ADD_MONTHS(CURRENT_DATE , -2),'YYYY-MM') MM
union
SELECT To_char(ADD_MONTHS(CURRENT_DATE , -1),'YYYY-MM') MM
);
</code>```

Body:
TLDR:
I want to get a table with the previous two months in Teradata, based on CURRENT_DATE. Currently I can only get the previous month:

SELECT
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM') MM;

Expected output is:

+--------+
|   MM   |
+--------+
| 2020-01|
| 2019-12|
+--------+

Long version:
I want something, that could be used in a bigger query like this, valid for every day of the year, without hardcoding the dates. The bigger query with the hardcoded dates looks like this:

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN ('2020-01', '2019-12')

and it works perfectly. The below one returns results ok, but only for 1 month.

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM')
)

Tried to add a comma and add the same line with -2, did not work:

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM'),
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -2), 'YYYY-MM')
)

the error is:

SELECT Failed 3706: Syntax error: expected something between ')' and '.'.

Body:
Try something with sub query:

select * from table where date in
(SELECT To_char(ADD_MONTHS(CURRENT_DATE , -2),'YYYY-MM') MM
union
SELECT To_char(ADD_MONTHS(CURRENT_DATE , -1),'YYYY-MM') MM
);


问:
Override props with styled-components and typescript
I'm using a component that has a property that is required.
I want to style that component with said property set and not being required to set it again when rendering. If I don't set it again Typescript complains.

The jist of what I want to do:

```<code>const Arrow = styled(<Icon icon={"ArrowRight"}/>)`
    ...
`;
</code>```

And not being required to set icon when rendering.

If I do this

```<code>const Arrow = styled(Icon)`
    ...
`;

Arrow.defaultProps = {
    icon: "ArrowRight",
};
</code>```

I still have to set icon when rendering.

Is there some way I can achieve this or is my only way out to modify props of Arrow with typescript-magic?

Using

typescript 3.7.5

react 16.12.0

styled-components 5.0.1

答:
styled-components has an API named attrs so you can attach properties to DOM elements or components.

```<code>const Arrow = styled(Icon).attrs(props => ({
  icon: props.icon // or whatever you want here
}))`

`;
</code>```

Docs

Body:
I'm using a component that has a property that is required.
I want to style that component with said property set and not being required to set it again when rendering. If I don't set it again Typescript complains.

The jist of what I want to do:

const Arrow = styled(<Icon icon={"ArrowRight"}/>)`
    ...
`;

And not being required to set icon when rendering.

If I do this

const Arrow = styled(Icon)`
    ...
`;

Arrow.defaultProps = {
    icon: "ArrowRight",
};

I still have to set icon when rendering.

Is there some way I can achieve this or is my only way out to modify props of Arrow with typescript-magic?

Using

typescript 3.7.5

react 16.12.0

styled-components 5.0.1

Body:
styled-components has an API named attrs so you can attach properties to DOM elements or components.

const Arrow = styled(Icon).attrs(props => ({
  icon: props.icon // or whatever you want here
}))`

`;

Docs


问:
Calculate if two lines are symmetrical
I'm developing an app to check if a draw is symmetric or not. All the users line are stored into an ArrayList composed by a list of points, structured as well:

```<code>private ArrayList<ArrayList<Pair<Float,Float>>> segments = new ArrayList<>();
</code>```

This is how I build the drawing area:

The black shape is part of the background and I don't need to consider it when I have to check the symmetry. I only need its center (which I store as a single coordinate) since I need to consider checking the symmetry by it. Since the draws are made by children, I also need to consider a bit of flexibility since the lines will never be exactly symmetric. I implemented a method which divides each segments in 10 parts and then check if the coordinates of each part have a similare increase/decrease:

```<code>private boolean checkShape (int z, ArrayList<Pair<Float,Float>> points) {
    ArrayList<Pair<Float,Float>> copia = segments.get(z);
    int nGroupsFirstShape = (segments.get(z).size()*10)/100;
    int nValuesFirstShape[] = new int[10];
    for (int j=0, j2=0; j<10; j++, j2+=nGroupsFirstShape) {
        int sumValues=0;
        sumValues+=copia.get(j2).first-copia.get(j2+nGroupsFirstShape-1).first;
        sumValues+=copia.get(j2).second-copia.get(j2+nGroupsFirstShape-1).second;
        nValuesFirstShape[j] = sumValues;
    }
    ArrayList<Pair<Float,Float>> copia2 = points;
    int nGroupSecondShape = (copia2.size()*10)/100;
    int nValuesSecondShape[] = new int[10];
    for (int j=0, j2=0; j<10; j++, j2+=nGroupSecondShape) {
        int sumValues=0;
        sumValues+=copia2.get(j2).first-copia2.get(j2+nGroupSecondShape-1).first;
        sumValues+=copia2.get(j2).second-copia2.get(j2+nGroupSecondShape-1).second;
        nValuesSecondShape[j] = sumValues;
    }
    int differences[] = new int[10];
    int numberOf = 0;
    for (int index=0; index<10; index++) {
        differences[index] = nValuesFirstShape[index] - nValuesSecondShape[index];
        if (differences[index]<0) differences[index] = -differences[index];
        if (differences[index]<nGroupsFirstShape*2.5) numberOf++;
    }
    if (numberOf>=6) return true; else return false;
}
</code>```

If this is verified for at least 6 parts, then I can considerer the segments symmetric. The huge problem of this method is that the lines can have different sizes. Do you know any methods to calculate the symmetry of a drawing area? Since I save the image as a bitmap, I also tried to find a method to calculate it directly on the image file, but I didn't find anything

答:
I think this is good mathematical algorithm:

step 1:
divide each line into N parts. (squares in the diagram)
the number of points on the lines may vary, but the number of parts will now be the same.

for example, 1 line was 100 points, divide it into 10 parts, 10 points will fall into each.
the second of 90 points, it will get 10 parts of 9 points.

Calculate the midpoint of each part.
fig1

step 2:
between each midpoint of both lines we find the middle. (black dots in the diagram)
fig2

step 3:
we build a line with a minimum deviation from these points. (red line in the diagram)
fig3

step 4:
estimation of deviation of midpoints from the line. by the average and maximum deviation it will be possible to measure how similar the lines are.

good luck

Title: Calculate if two lines are symmetrical

Body:
I'm developing an app to check if a draw is symmetric or not. All the users line are stored into an ArrayList composed by a list of points, structured as well:

private ArrayList<ArrayList<Pair<Float,Float>>> segments = new ArrayList<>();

This is how I build the drawing area:

The black shape is part of the background and I don't need to consider it when I have to check the symmetry. I only need its center (which I store as a single coordinate) since I need to consider checking the symmetry by it. Since the draws are made by children, I also need to consider a bit of flexibility since the lines will never be exactly symmetric. I implemented a method which divides each segments in 10 parts and then check if the coordinates of each part have a similare increase/decrease:

private boolean checkShape (int z, ArrayList<Pair<Float,Float>> points) {
    ArrayList<Pair<Float,Float>> copia = segments.get(z);
    int nGroupsFirstShape = (segments.get(z).size()*10)/100;
    int nValuesFirstShape[] = new int[10];
    for (int j=0, j2=0; j<10; j++, j2+=nGroupsFirstShape) {
        int sumValues=0;
        sumValues+=copia.get(j2).first-copia.get(j2+nGroupsFirstShape-1).first;
        sumValues+=copia.get(j2).second-copia.get(j2+nGroupsFirstShape-1).second;
        nValuesFirstShape[j] = sumValues;
    }
    ArrayList<Pair<Float,Float>> copia2 = points;
    int nGroupSecondShape = (copia2.size()*10)/100;
    int nValuesSecondShape[] = new int[10];
    for (int j=0, j2=0; j<10; j++, j2+=nGroupSecondShape) {
        int sumValues=0;
        sumValues+=copia2.get(j2).first-copia2.get(j2+nGroupSecondShape-1).first;
        sumValues+=copia2.get(j2).second-copia2.get(j2+nGroupSecondShape-1).second;
        nValuesSecondShape[j] = sumValues;
    }
    int differences[] = new int[10];
    int numberOf = 0;
    for (int index=0; index<10; index++) {
        differences[index] = nValuesFirstShape[index] - nValuesSecondShape[index];
        if (differences[index]<0) differences[index] = -differences[index];
        if (differences[index]<nGroupsFirstShape*2.5) numberOf++;
    }
    if (numberOf>=6) return true; else return false;
}

If this is verified for at least 6 parts, then I can considerer the segments symmetric. The huge problem of this method is that the lines can have different sizes. Do you know any methods to calculate the symmetry of a drawing area? Since I save the image as a bitmap, I also tried to find a method to calculate it directly on the image file, but I didn't find anything


问:
Calling Typescript function from Highcharts load event
I am trying to call typescript function openDialog() from the events.load of highcharts but I am not able to call it. Even though I am using arrow function I am not able to get it. Here is my code :

```<code>events: {
    load: () => {
       var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>this.openDialog(point.options,'all')
            );
            }
          })(i)
        }
      }
    }
  },

  public openDialog(option,type){
       //Do Something
  }
</code>```

EDIT

I have got one link where there are binding this with function.

Is there anything that I am missing ?

答:
Check the update code replacing arrow function,

Here assigning chart options has moved to a function, init(){} and declared var that = this; inside it, also replaced the ()=>{} with function().

You can check the stackblitz update Here

```<code>import {  Component, OnInit, ElementRef, ViewChild} from '@angular/core';
import { Chart } from 'angular-highcharts';
import { HighchartsService } from './highcharts.service.ts'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('charts') public chartEl: ElementRef;
  myOptions={};
  constructor(private highcharts: HighchartsService) { }
  ngOnInit(){
    this.init();
    this.highcharts.createChart(this.chartEl.nativeElement, this.myOptions);
  }
  init(){
   var that = this;
   this.myOptions = {
    chart: {
      type: 'bar',
      events: {
      load: function(){
      var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>that.openDialog()
            );
            }
          })(i)
        }
      }
      }
    },
    },
    title: {
      text: 'Stacked bar chart'
    },
    xAxis: {
      categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
      min: 0,
      title: {
        text: 'Total fruit consumption'
      }
    },
    legend: {
      reversed: true
    },
    plotOptions: {
      series: {
        stacking: 'normal'
      }
    },
    series: [{
      name: 'John',
      data: [5, 3, 4, 7, 2]
    }, {
      name: 'Jane',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Joe',
      data: [3, 4, 4, 2, 5]
    }]
  };
      }

  public openDialog(){
       console.log('open dialog, hey this works here')
  }
}
</code>```

Body:
I am trying to call typescript function openDialog() from the events.load of highcharts but I am not able to call it. Even though I am using arrow function I am not able to get it. Here is my code :

events: {
    load: () => {
       var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>this.openDialog(point.options,'all')
            );
            }
          })(i)
        }
      }
    }
  },

  public openDialog(option,type){
       //Do Something
  }

EDIT

I have got one link where there are binding this with function.

Is there anything that I am missing ?

Body:
Check the update code replacing arrow function,

Here assigning chart options has moved to a function, init(){} and declared var that = this; inside it, also replaced the ()=>{} with function().

You can check the stackblitz update Here

import {  Component, OnInit, ElementRef, ViewChild} from '@angular/core';
import { Chart } from 'angular-highcharts';
import { HighchartsService } from './highcharts.service.ts'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('charts') public chartEl: ElementRef;
  myOptions={};
  constructor(private highcharts: HighchartsService) { }
  ngOnInit(){
    this.init();
    this.highcharts.createChart(this.chartEl.nativeElement, this.myOptions);
  }
  init(){
   var that = this;
   this.myOptions = {
    chart: {
      type: 'bar',
      events: {
      load: function(){
      var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>that.openDialog()
            );
            }
          })(i)
        }
      }
      }
    },
    },
    title: {
      text: 'Stacked bar chart'
    },
    xAxis: {
      categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
      min: 0,
      title: {
        text: 'Total fruit consumption'
      }
    },
    legend: {
      reversed: true
    },
    plotOptions: {
      series: {
        stacking: 'normal'
      }
    },
    series: [{
      name: 'John',
      data: [5, 3, 4, 7, 2]
    }, {
      name: 'Jane',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Joe',
      data: [3, 4, 4, 2, 5]
    }]
  };
      }

  public openDialog(){
       console.log('open dialog, hey this works here')
  }
}


问:
Azure IoT Devices Receiving Twin Update Notifications
I tried to receive desired properties update notifications by subscribing topic "$iothub/twin/PATCH/properties/#"  (reference) and also by sdk (refernece). Both went okay and I did get notifications when I changed the desired properties by back-end services, but with all the desired properties in response. Is there a topic or a function in sdk to just get the properties that where changed? Or to know witch properties were changed without looking through all the desired properties?

Appreciate your help!

答:
You should use a PATCH request to update a desired property in your back-end service. The following screen snippets show an example of the updating only one desired property such as color. For quick demonstration purpose, the Azure IoT Hub Tester is used:

Creating two desired properties (color, abc):

device8 received a changes notification (version=2):

In this step, we need to update only one desired property (color):

device8 received a changes notification (version=3) such as the preperty color:

As you can see in the above pictures, the device8 subscribed on the topic like you mentioned it. You didn't describe how your backend service updating your desired properties.

Note, that the above example using the REST PATCH call for updating a desired properties.


问:
Angular 6 injecting service into class without using the constructor
Using Angular 6 and Typescript 2.7. I have a class with a constructor that I pass arguments to when I create an instance from a controller. This class also has a service that needs to be injected.   But then the controller that creates the instance needs to provide the service as a parameter. Is this common or is there a way to just inject the service in the class and not the constructor. I have read in other posts that the constructor should only be used to inject dependencies.

So I have the configuration class that takes simple string parameters.

```<code>export class Configuration{
    //public uiService: UiService;
    public configName:string;
    public configType: ConfigType;
    public shape:any;

    constructor(_configName: string, _configType: ConfigType){
        this.configName = _configName;
        this.configType = _configType;
....
</code>```

I create a new instance of this class from my controller like this:

```<code>let config = new Configuration("NEWconfiguration", configType);
</code>```

I have a common service with utility functions that I need to use in the Configuration class. Reading here and other sites I see that this should be injected through the constructor. So then my configuration constructor would include a new parameter for the service and then the controller would inject it. But the service is not used in the controller so I don't want to have to include it there.

Is there a way in the Configuration class to access the service without using the constructor? Or is this bad practice. I think I could create an instance of the service within the Configuration class or make the functions in the service static but then I am not using dependency injection. Does that matter?

答:
I faced a similar issue recently, where I had to create multiple instances of the same class, which isn't possible with Angular DI, which creates singletons by default. The class instances did however have dependencies on other services in my application.

The way I solved it was to inject the dependencies into my controller, and instantiate the classes using their constructors without DI.

Let me know if the above is sufficient, if not I can add example code to improve clarity.

Body:
Using Angular 6 and Typescript 2.7. I have a class with a constructor that I pass arguments to when I create an instance from a controller. This class also has a service that needs to be injected.   But then the controller that creates the instance needs to provide the service as a parameter. Is this common or is there a way to just inject the service in the class and not the constructor. I have read in other posts that the constructor should only be used to inject dependencies.

So I have the configuration class that takes simple string parameters.

export class Configuration{
    //public uiService: UiService;
    public configName:string;
    public configType: ConfigType;
    public shape:any;

    constructor(_configName: string, _configType: ConfigType){
        this.configName = _configName;
        this.configType = _configType;
....

I create a new instance of this class from my controller like this:

let config = new Configuration("NEWconfiguration", configType);

I have a common service with utility functions that I need to use in the Configuration class. Reading here and other sites I see that this should be injected through the constructor. So then my configuration constructor would include a new parameter for the service and then the controller would inject it. But the service is not used in the controller so I don't want to have to include it there.

Is there a way in the Configuration class to access the service without using the constructor? Or is this bad practice. I think I could create an instance of the service within the Configuration class or make the functions in the service static but then I am not using dependency injection. Does that matter?


问:
Error 1004 Looping through range to get max date
I am currently learning VBA and cant figure this one out. I'm trying to look at the max date in a range (W:AC) of each row and place the result in cell "BU" of the same row. I'm getting a 1004 error on the line defining which cell to place the result. Am I getting the error because I have defined the range as W:AC?</p>

```<code>
Sub Max_Date()
Dim MaxDate As Date
Dim CellRange As Range
Dim Source As Worksheet: Set Source = ActiveWorkbook.Sheets("Sheet1")
Dim row As Variant
row = Source.Rows.Count

Set CellRange = Source.Range("W:AC")

For Each row In CellRange

 MaxDate = Application.WorksheetFunction.Max(CellRange)
 Range("BU").Value = MaxDate

Next row

End Sub

</code>```

答:
As SJR mentioned you cannot paste a value in a row.
But also, you are looking at a max in the entire range, not only the row.
Use an integer (here i) to go through each row.

This should to the trick

```<code>Sub Max_Date()
Dim MaxDate As Date
Dim i As Double
Dim Source As Worksheet: Set Source = ActiveWorkbook.Sheets("Sheet1")
Dim row As Variant
row = Source.Rows.Count

For i = 1 To row

 MaxDate = Application.WorksheetFunction.Max(Source.Range("W" & i & ":AC" & i))
 Range("BU" & i).Value = MaxDate

Next

End Sub
</code>```

Body:
I am currently learning VBA and cant figure this one out. I'm trying to look at the max date in a range (W:AC) of each row and place the result in cell "BU" of the same row. I'm getting a 1004 error on the line defining which cell to place the result. Am I getting the error because I have defined the range as W:AC?

Sub Max_Date()
Dim MaxDate As Date
Dim CellRange As Range
Dim Source As Worksheet: Set Source = ActiveWorkbook.Sheets("Sheet1")
Dim row As Variant
row = Source.Rows.Count

Set CellRange = Source.Range("W:AC")

For Each row In CellRange

 MaxDate = Application.WorksheetFunction.Max(CellRange)
 Range("BU").Value = MaxDate

Next row

End Sub

Body:
As SJR mentioned you cannot paste a value in a row.
But also, you are looking at a max in the entire range, not only the row.
Use an integer (here i) to go through each row.

This should to the trick

Sub Max_Date()
Dim MaxDate As Date
Dim i As Double
Dim Source As Worksheet: Set Source = ActiveWorkbook.Sheets("Sheet1")
Dim row As Variant
row = Source.Rows.Count

For i = 1 To row

 MaxDate = Application.WorksheetFunction.Max(Source.Range("W" & i & ":AC" & i))
 Range("BU" & i).Value = MaxDate

Next

End Sub


问:
ERR_CONNECTION_REFUSED in POST data to Mysql using NodeJs and ReactJs
I am working on ReactJs and NodeJS in sending data to MySql, in my frontPage.js The problem is I already tested the API to post data using Postman and no error appears. And the problem comes when I tried in ReactJs, I coded this :

```<code>class InputEndUser extends Component {
    constructor(props){
        super(props);

        this.state = {
            project_type: '',
            status : '',
            subject : '',
            enduser_name : '',
            location : '',
            cp_1 : '',
            cp1_hp : '',
            cp1_jpos: '',
            cp_2 : '',
            cp2_hp : '',
            cp2_jpos : '',
            quot_num : '',
            quot_date : '',
            note : ''

        }
        this.handleProject_type = this.handleProject_type.bind(this);
        this.handleStatus = this.handleStatus.bind(this);
        this.handleSubject = this.handleSubject.bind(this);
        this.handleEnduser_name = this.handleEnduser_name.bind(this);
        this.handleLocation = this.handleLocation.bind(this);
        this.handleCP1 = this.handleCP1.bind(this);
        this.handleCP1_hp = this.handleCP1_hp.bind(this);
        this.handleCP1_jpos = this.handleCP1_jpos.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2_hp = this.handleCP2_hp.bind(this);
        this.handleCP2_jpos = this.handleCP2_jpos.bind(this);
        this.handleQuot_num = this.handleQuot_num.bind(this);
        this.handleQuot_date = this.handleQuot_date.bind (this);
        this.handleNotes = this.handleNotes.bind(this);
    }

    handleProject_type(event){
        this.setState ({
            project_type : event.target.value
        })
    }

    handleStatus(event){
        this.setState({
            status: event.target.value
        })
    }

    handleSubject(event){
        this.setState({
            subject: event.target.value
        })
    }

    handleEnduser_name (event) {
        this.setState({
            enduser_name: event.target.value
        })
    }

    handleLocation(event){
        this.setState({
            location: event.target.value
        })
    }

    handleCP1(event){
        this.setState({
            cp_1: event.target.value
        })
    }

    handleCP1_hp(event){
        this.setState ({
            cp1_hp : event.target.value
        })
    }

    handleCP1_jpos(event){
        this.setState ({
            cp1_jpos : event.target.value
        })
    }

    handleCP2(event){
        this.setState({
            cp_2: event.target.value
        })
    }

    handleCP2_hp(event){
        this.setState ({
            cp2_hp : event.target.value
        })
    }

    handleCP2_jpos(event){
        this.setState ({
            cp2_jpos : event.target.value
        })
    }

    handleQuot_num(event) {
        this.setState ({
            quot_num : event.target.value
        })
    }

    handleQuot_date (event) {
        this.setState({
            quot_date : event.target.value
        })
    }

    handleNotes(event) {
        this.setState({
            note : event.target.value
        })
    }

    submitEndUser(event){
        event.preventDefault();
        fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then ((response) => {
            return response.json;
        })
        .then ((body) => {
            console.log(body);
        })
        .catch((error) => {
            console.log(error)
        })
    }
</code>```

and My API in server.js :

```<code>app.post('/enduser', (req, res) => {
  let POST_ENDUSER_QUERY =  {
    project_id: req.body.project_id,
    project_type: req.body.project_type,
    status: req.body.status,
    subject: req.body.subject,
    endUser_name: req.body.endUser_name,
    location: req.body.location,
    cp_1: req.body.cp_1,
    cp1_hp: req.body.cp1_hp,
    cp1_jpos: req.body.cp1_jpos,
    cp_2: req.body.cp_1,
    cp2_hp: req.body.cp1_hp,
    cp2_jpos: req.body.cp1_jpos,
    quot_num: req.body.quot_num,
    quot_date: req.body.quot_date,
    note: req.body.note,
    image: req.body.image,
    estimated_value: req.body.estimated_value
  };
  if (!POST_ENDUSER_QUERY) {
    return res.status(400).send({ err: true, message: 'Please project name' });
  }

  let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
    '${POST_ENDUSER_QUERY.project_id}',
    '${POST_ENDUSER_QUERY.project_type}',
    '${POST_ENDUSER_QUERY.status}',
    '${POST_ENDUSER_QUERY.subject}',
    '${POST_ENDUSER_QUERY.endUser_name}',
    '${POST_ENDUSER_QUERY.location}',
    '${POST_ENDUSER_QUERY.cp_1}',
    '${POST_ENDUSER_QUERY.cp1_hp}',
    '${POST_ENDUSER_QUERY.cp1_jpos}',
    '${POST_ENDUSER_QUERY.cp_2}',
    '${POST_ENDUSER_QUERY.cp2_hp}',
    '${POST_ENDUSER_QUERY.cp2_jpos}',
    '${POST_ENDUSER_QUERY.quot_num}',
    '${POST_ENDUSER_QUERY.quot_date}',
    '${POST_ENDUSER_QUERY.note}',
    '${POST_ENDUSER_QUERY.image}',
    '${POST_ENDUSER_QUERY.estimated_value}'
    )`;
  dbConn.query(query, ( err, results) => {
    if(err) throw err;
    return res.status(200).json({"status": 200, "err" : null, "data": results});
  });
});

</code>```

and the error came :

also in terminal when I test it with some kind of data, appears like this:

答:
You didn't add body data to your POST in React :

```<code>fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
</code>```

Try to change it to :

```<code> fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(this.state)
        })
</code>```

Body:
I am working on ReactJs and NodeJS in sending data to MySql, in my frontPage.js The problem is I already tested the API to post data using Postman and no error appears. And the problem comes when I tried in ReactJs, I coded this :

class InputEndUser extends Component {
    constructor(props){
        super(props);

        this.state = {
            project_type: '',
            status : '',
            subject : '',
            enduser_name : '',
            location : '',
            cp_1 : '',
            cp1_hp : '',
            cp1_jpos: '',
            cp_2 : '',
            cp2_hp : '',
            cp2_jpos : '',
            quot_num : '',
            quot_date : '',
            note : ''

        }
        this.handleProject_type = this.handleProject_type.bind(this);
        this.handleStatus = this.handleStatus.bind(this);
        this.handleSubject = this.handleSubject.bind(this);
        this.handleEnduser_name = this.handleEnduser_name.bind(this);
        this.handleLocation = this.handleLocation.bind(this);
        this.handleCP1 = this.handleCP1.bind(this);
        this.handleCP1_hp = this.handleCP1_hp.bind(this);
        this.handleCP1_jpos = this.handleCP1_jpos.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2_hp = this.handleCP2_hp.bind(this);
        this.handleCP2_jpos = this.handleCP2_jpos.bind(this);
        this.handleQuot_num = this.handleQuot_num.bind(this);
        this.handleQuot_date = this.handleQuot_date.bind (this);
        this.handleNotes = this.handleNotes.bind(this);
    }

    handleProject_type(event){
        this.setState ({
            project_type : event.target.value
        })
    }

    handleStatus(event){
        this.setState({
            status: event.target.value
        })
    }

    handleSubject(event){
        this.setState({
            subject: event.target.value
        })
    }

    handleEnduser_name (event) {
        this.setState({
            enduser_name: event.target.value
        })
    }

    handleLocation(event){
        this.setState({
            location: event.target.value
        })
    }

    handleCP1(event){
        this.setState({
            cp_1: event.target.value
        })
    }

    handleCP1_hp(event){
        this.setState ({
            cp1_hp : event.target.value
        })
    }

    handleCP1_jpos(event){
        this.setState ({
            cp1_jpos : event.target.value
        })
    }

    handleCP2(event){
        this.setState({
            cp_2: event.target.value
        })
    }

    handleCP2_hp(event){
        this.setState ({
            cp2_hp : event.target.value
        })
    }

    handleCP2_jpos(event){
        this.setState ({
            cp2_jpos : event.target.value
        })
    }

    handleQuot_num(event) {
        this.setState ({
            quot_num : event.target.value
        })
    }

    handleQuot_date (event) {
        this.setState({
            quot_date : event.target.value
        })
    }

    handleNotes(event) {
        this.setState({
            note : event.target.value
        })
    }

    submitEndUser(event){
        event.preventDefault();
        fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then ((response) => {
            return response.json;
        })
        .then ((body) => {
            console.log(body);
        })
        .catch((error) => {
            console.log(error)
        })
    }

and My API in server.js :

app.post('/enduser', (req, res) => {
  let POST_ENDUSER_QUERY =  {
    project_id: req.body.project_id,
    project_type: req.body.project_type,
    status: req.body.status,
    subject: req.body.subject,
    endUser_name: req.body.endUser_name,
    location: req.body.location,
    cp_1: req.body.cp_1,
    cp1_hp: req.body.cp1_hp,
    cp1_jpos: req.body.cp1_jpos,
    cp_2: req.body.cp_1,
    cp2_hp: req.body.cp1_hp,
    cp2_jpos: req.body.cp1_jpos,
    quot_num: req.body.quot_num,
    quot_date: req.body.quot_date,
    note: req.body.note,
    image: req.body.image,
    estimated_value: req.body.estimated_value
  };
  if (!POST_ENDUSER_QUERY) {
    return res.status(400).send({ err: true, message: 'Please project name' });
  }

  let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
    '${POST_ENDUSER_QUERY.project_id}',
    '${POST_ENDUSER_QUERY.project_type}',
    '${POST_ENDUSER_QUERY.status}',
    '${POST_ENDUSER_QUERY.subject}',
    '${POST_ENDUSER_QUERY.endUser_name}',
    '${POST_ENDUSER_QUERY.location}',
    '${POST_ENDUSER_QUERY.cp_1}',
    '${POST_ENDUSER_QUERY.cp1_hp}',
    '${POST_ENDUSER_QUERY.cp1_jpos}',
    '${POST_ENDUSER_QUERY.cp_2}',
    '${POST_ENDUSER_QUERY.cp2_hp}',
    '${POST_ENDUSER_QUERY.cp2_jpos}',
    '${POST_ENDUSER_QUERY.quot_num}',
    '${POST_ENDUSER_QUERY.quot_date}',
    '${POST_ENDUSER_QUERY.note}',
    '${POST_ENDUSER_QUERY.image}',
    '${POST_ENDUSER_QUERY.estimated_value}'
    )`;
  dbConn.query(query, ( err, results) => {
    if(err) throw err;
    return res.status(200).json({"status": 200, "err" : null, "data": results});
  });
});

and the error came :

also in terminal when I test it with some kind of data, appears like this:

Body:
You didn't add body data to your POST in React :

fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })

Try to change it to :

 fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(this.state)
        })


问:
"Cannot assign to var because it is a read-only property." in angular test using Jasmine Test Framework
I have a readonly property in one of the service in angular :

```<code>@Injectable({
  providedIn: 'root'
})

export class MyService {
  private readonly timeIntervals: any;
}

constructor(private readonly config: AppConfig) {
    this.timeIntervals = this.config.getResourceByKey(this.timeIntervalString);
}

getTimeIntervalMenuItem(): Array<IElementData>{
    const menuListItems = new Array<IElementData>();
    let index = 0;
    for (const item of Object.keys(this.timeIntervals)) {
      menuListItems.push({
        id: this.menuItem + index.toString(),
        label: this.timeIntervals[item].toString()
      });
      index++;
    }
    return menuListItems;
  }

export interface IElementData {
    label?: string;
    value?: string;
    id?: string;
    active?: string;
}
</code>```

While writing test for the same service, how will I assign value to timeIntervals?

What I did was:

```<code>beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService,
      ]
    });
    service = TestBed.get(MyService);
  });

it('should generate total 7 menu items for dropdown', () => {
    const timeIntervals = 'timeIntervals';
    service[timeIntervals] = timeLists;
    const generatedMenu = service.getTimeIntervalMenuItem();
    expect(generatedMenu.length).toBe(7);
  });

const timeLists = {
  3: '3',
  5: '5',
  10: '10',
  15: '15',
  20: '20',
  30: '30',
  60: '60'
};
</code>```

I am getting error as:

Cannot assign to 'timeIntervals' because it is a read-only property.

How to assign value to timeIntervals so that I can test my method

答:
I figured out solution by using

Object.defineProperty

Code:

```<code>beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService
      ]
    });
    service = TestBed.get(MyService);
    const timeIntervals = 'timeIntervals';
    Object.defineProperty(service, timeIntervals, { value: timeLists });
  });
</code>```

Body:
I have a readonly property in one of the service in angular :

@Injectable({
  providedIn: 'root'
})

export class MyService {
  private readonly timeIntervals: any;
}

constructor(private readonly config: AppConfig) {
    this.timeIntervals = this.config.getResourceByKey(this.timeIntervalString);
}

getTimeIntervalMenuItem(): Array<IElementData>{
    const menuListItems = new Array<IElementData>();
    let index = 0;
    for (const item of Object.keys(this.timeIntervals)) {
      menuListItems.push({
        id: this.menuItem + index.toString(),
        label: this.timeIntervals[item].toString()
      });
      index++;
    }
    return menuListItems;
  }

export interface IElementData {
    label?: string;
    value?: string;
    id?: string;
    active?: string;
}

While writing test for the same service, how will I assign value to timeIntervals?

What I did was:

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService,
      ]
    });
    service = TestBed.get(MyService);
  });

it('should generate total 7 menu items for dropdown', () => {
    const timeIntervals = 'timeIntervals';
    service[timeIntervals] = timeLists;
    const generatedMenu = service.getTimeIntervalMenuItem();
    expect(generatedMenu.length).toBe(7);
  });

const timeLists = {
  3: '3',
  5: '5',
  10: '10',
  15: '15',
  20: '20',
  30: '30',
  60: '60'
};

I am getting error as:

Cannot assign to 'timeIntervals' because it is a read-only property.

How to assign value to timeIntervals so that I can test my method

Body:
I figured out solution by using

Object.defineProperty

Code:

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService
      ]
    });
    service = TestBed.get(MyService);
    const timeIntervals = 'timeIntervals';
    Object.defineProperty(service, timeIntervals, { value: timeLists });
  });


问:
How to add button for "Send Transcript" to Directline WebChat
I would like customers to be able to click a button to send themselves a transcript at any point in the conversation. This button should essentially send a message to the bot which would initiate an “email transcript" dialog to prompt for their email and send the transcript. I was able to add a button to the directline webchat client (in my title bar) but I can't figure out how to have it create an activity for the bot. I have a custom store that sends an "inactive" activity but I wasn't able to use this same method to make the button send an activity. Can this be achieved? Or is there another way for customers to get a copy of their transcript?

I have achieved the actual transcript retrieval and emailing in code, initiates by a LUIS intent, I just want to provide an intuitive "always there" option to do this.

答:
The WebChat offers a simple sample that shows you how to send activities programmatically to the bot. In this sample they are creating a separate button with an Event Listener, which will sent your message as a message activity.

If you would like to sent it as an event in the background, you could have a look at this sample, which you could combine with the event listener of the first example.

How to send a message programmatically

How to send welcome event

Note: you need to use the JavaScript WebChat, it is not possible to add this functionality to the iFrame version of the Bot Service.


问:
ReactJS call parent method
I'm making my first step in ReactJS and trying to understand communication between parent and children.
I'm making form, so I have the component for styling fields. And also I have parent component that includes field and checking it. Example:

```<code>var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
        ...
    },
    handleChange: function(event) {
        // call parent!
    }
})
</code>```

Is there any way to do it. And is my logic is good in reactjs "world"? Thanks for your time.

答:
Using Function || stateless component

Parent Component

```<code> import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

     const handleParentFun = (value) =>{
       console.log("Call to Parent Component!",value);
     }

     return (
         <>
             This is Parent Component
             <ChildComponent
                 handleParentFun = {(value) => {
                     console.log("your value -->",value);
                     handleParentFun(value);
                 }}
             />
         </>
     );
 }
</code>```

Child Component

```<code>import React from "react";

export default function ChildComponent(props){
    return(
        <>
           This is Child Component
           <button onClick={props.handleParentFun("Your Value")}>
               Call to Parent Component Function
           </button>
        </>
    );
}
</code>```

Title: ReactJS call parent method

Body:
I'm making my first step in ReactJS and trying to understand communication between parent and children.
I'm making form, so I have the component for styling fields. And also I have parent component that includes field and checking it. Example:

var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
        ...
    },
    handleChange: function(event) {
        // call parent!
    }
})

Is there any way to do it. And is my logic is good in reactjs "world"? Thanks for your time.

Body:
Using Function || stateless component

Parent Component

 import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

     const handleParentFun = (value) =>{
       console.log("Call to Parent Component!",value);
     }

     return (
         <>
             This is Parent Component
             <ChildComponent
                 handleParentFun = {(value) => {
                     console.log("your value -->",value);
                     handleParentFun(value);
                 }}
             />
         </>
     );
 }

Child Component

import React from "react";

export default function ChildComponent(props){
    return(
        <>
           This is Child Component
           <button onClick={props.handleParentFun("Your Value")}>
               Call to Parent Component Function
           </button>
        </>
    );
}


问:
How to fetch Authorisation Bearer to test APIs from website which needs username and password?
I want to extract the Authorisation Bearer from my website after logging in by the help of python.

I have username,password and two factor authentication

Please suggest me piece of code by which i can print the authorization bearer token and save it in a variable.

I tried using requests library but it is not giving authorisation bearer in the header

答:
By default, you cannot get the Authorization header from the response which is what you are trying to do. The server needs to expose it by setting the response header Access-Control-Expose-Headers: authorization.

My suggestion is to use selenium instead and get it from the logged request headers after you're logged in.

```<code>from selenium import webdriver
import json
driver = webdriver.PhantomJS(executable_path=r"your_path")
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('headers: ', har['log']['entries'][0]['request']['headers'])
</code>```

Body:
By default, you cannot get the Authorization header from the response which is what you are trying to do. The server needs to expose it by setting the response header Access-Control-Expose-Headers: authorization.

My suggestion is to use selenium instead and get it from the logged request headers after you're logged in.

from selenium import webdriver
import json
driver = webdriver.PhantomJS(executable_path=r"your_path")
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('headers: ', har['log']['entries'][0]['request']['headers'])


问:
Mocking __init__ of a class imported in file
I have a file copy_x_to_y.py which goes like this:

```<code>from abcd import F

def function_to_be_tested():
     F()
</code>```

in abcd.py file, i have something like this:

```<code>from xyz import XY

class F():
   def __init__(self, arg1):
       self.xy = XY(arg1)
</code>```

I want to mock init of XY in my test case.
I have tried mocking F's init with:

```<code>def mock_func(*args, **kwargs):
    pass

@patch('path/to/copy_x_to_y.F.__init__', mock_func)
def test():
    assert function_to_be_tested() is None
</code>```

but it always happens to call XY's init, resulting in error as its initialization calls
to connect with S3 with arg1. How to test this kind of structure?

答:
What is the reason for wanting to mock __init__ of XY? Do you want it to return a specific object of XY, do you want to check if XY.__init__ was called with specific arguments or something else?

A possible solution to your problem would be to mock the entire class, but have it return a "normal" object. Here's an example:

```<code>>>> from unittest.mock import patch
>>> class MyClass:
...   def __init__(self, val):
...     self._val = val
...   def foo(self):
...     print(self._val)
...
>>> a = MyClass(1)
>>> a.foo()
1
>>> patcher = patch('__main__.MyClass', return_value=a)
>>> mock_class = patcher.start()
>>> b = MyClass(2)  # This will return a.
>>> b.foo()
1
>>> mock_class.call_args_list
[call(2)]
>>> patcher.stop()
</code>```

Which in your case would be:

```<code>from xyz import XY
from path/to/copy_x_to_y import function_to_be_tested
def test():
  arg1 = ...
  a = XY(arg1)  # Has to be called before the patch to get a "normal" object.
  with patch('xyz.XY', return_value=a) as mock_xy:
    # Run funcion to be tested here and check results.
    function_to_be_tested()
    assert ...
</code>```

Some side notes:

It is possible to mock __init__ directly though, if that's really what you need to do.

```<code>>>> def my_init(self, *args, **kwargs):
...   self._val = 1
>>> patcher = patch.object(MyClass, '__init__', my_init)
>>> mock_init = patcher.start()
>>> a = MyClass(2)
>>> a.foo()
1
</code>```

If you use the patch decorator, you have to supply the decorated function with one extra argument that is the mock of the class or object.
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch

```<code>@patch('path/to/SomeClass', ...)
def test(mock_class):
...
</code>```

Also patch is typically (exclusively?) used to patch a class while patch.object is used to patch a member inside a class or module. https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch.object

Body:
I have a file copy_x_to_y.py which goes like this:

from abcd import F

def function_to_be_tested():
     F()

in abcd.py file, i have something like this:

from xyz import XY

class F():
   def __init__(self, arg1):
       self.xy = XY(arg1)

I want to mock init of XY in my test case.
I have tried mocking F's init with:

def mock_func(*args, **kwargs):
    pass

@patch('path/to/copy_x_to_y.F.__init__', mock_func)
def test():
    assert function_to_be_tested() is None

but it always happens to call XY's init, resulting in error as its initialization calls
to connect with S3 with arg1. How to test this kind of structure?

Body:
What is the reason for wanting to mock __init__ of XY? Do you want it to return a specific object of XY, do you want to check if XY.__init__ was called with specific arguments or something else?

A possible solution to your problem would be to mock the entire class, but have it return a "normal" object. Here's an example:

>>> from unittest.mock import patch
>>> class MyClass:
...   def __init__(self, val):
...     self._val = val
...   def foo(self):
...     print(self._val)
...
>>> a = MyClass(1)
>>> a.foo()
1
>>> patcher = patch('__main__.MyClass', return_value=a)
>>> mock_class = patcher.start()
>>> b = MyClass(2)  # This will return a.
>>> b.foo()
1
>>> mock_class.call_args_list
[call(2)]
>>> patcher.stop()

Which in your case would be:

from xyz import XY
from path/to/copy_x_to_y import function_to_be_tested
def test():
  arg1 = ...
  a = XY(arg1)  # Has to be called before the patch to get a "normal" object.
  with patch('xyz.XY', return_value=a) as mock_xy:
    # Run funcion to be tested here and check results.
    function_to_be_tested()
    assert ...

Some side notes:

It is possible to mock __init__ directly though, if that's really what you need to do.

>>> def my_init(self, *args, **kwargs):
...   self._val = 1
>>> patcher = patch.object(MyClass, '__init__', my_init)
>>> mock_init = patcher.start()
>>> a = MyClass(2)
>>> a.foo()
1

If you use the patch decorator, you have to supply the decorated function with one extra argument that is the mock of the class or object.
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch

@patch('path/to/SomeClass', ...)
def test(mock_class):
...

Also patch is typically (exclusively?) used to patch a class while patch.object is used to patch a member inside a class or module. https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch.object


问:
Does Android HoneyComb support multiuser restricted account?
a customer ordered us a tablet application, but they need a lot of access restriction to lock device functions such as:

Permit datas transfer only inside the application not outside

Restricted user access on the device (something close to admin and normal user permissions)

A framework/API that permit to create an internal mail reader/sender

Public API of iOS makes impossible to fulfill those requirements. I was wondering if Android makes life easier when there are those kind of restriction.

UPDATE: To make understand better the field of use. I'm talking about an application that "force" the device to be used just only with that application for an Enterprise use. The app is just like a CRM but the device should be blocked in some functions to make users only work with them and NOT playing or use facebook, market etc.

答:
Permit datas transfer only inside the application not outside

Do not request the INTERNET permission.

Restricted user access on the device (something close to admin and normal user permissions)

You would have to implement this yourself.

A framework/API that permit to create an internal mail reader/sender

I have no idea what this means.


问:
Can not install processr and procesR on Windows
Following this question, I am trying to install the package (running R64 as admin on Windows):

```<code>devtools::install_github("markhwhiteii/processr")
</code>```

or

```<code>devtools::install_github("cardiomoon/processR")
</code>```

However, I get the error message:

Error: Failed to install 'processr' from GitHub:
    (converted from warning) cannot remove prior installation of package 'digest'

no matter which update option I select. Running the command .libPaths() I found the packages installation folder C:/Program Files/R/R-3.6.2/library and manually deleted the digest package and reinstalled it with package.install("digest").  But I still get the same error! I would appreciate it if you could help me understand what is the problem and how I can resolve it.

答:
The steps to install the markhwhiteii/processr package:

install.packages("devtools")

library(devtools)

install.packages("https://github.com/markhwhiteii/processr/archive/master.tar.gz")

for testing the instalation:

library(processr)

processr::model1

Sent a PR on the GitHub repo.

and if you want to run R in the Jupyter environment just follow the instructions to install and regsiter the kernel:

install.packages('IRkernel')

IRkernel::installspec()

Body:
Following this question, I am trying to install the package (running R64 as admin on Windows):

devtools::install_github("markhwhiteii/processr")

or

devtools::install_github("cardiomoon/processR")

However, I get the error message:

Error: Failed to install 'processr' from GitHub:
    (converted from warning) cannot remove prior installation of package 'digest'

no matter which update option I select. Running the command .libPaths() I found the packages installation folder C:/Program Files/R/R-3.6.2/library and manually deleted the digest package and reinstalled it with package.install("digest").  But I still get the same error! I would appreciate it if you could help me understand what is the problem and how I can resolve it.


问:
Akka Typed Actors and AKka Http - cannot find ActorRefFactory
I am trying to work with typed actors version 2.6.3 and akka http version 10.1.11
while all worked fine in non typed actors , now I am getting compilation error

```<code>object Main extends App {

   def createServer(implicit system: ActorSystem[IdentityCalculated]) = {

implicit val materializer = ActorMaterializer()

 }
 def apply(): Behavior[IdentityCalculated] = {
Behaviors.setup { context =>

  val identityManager = context.spawn(IdentityManager(), "identity-manager")

  implicit val timeout = Timeout(10, TimeUnit.SECONDS)
  implicit val scheduler = context.system.scheduler

  identityManager.tell(CalculateIdentity(context.self))

  Behaviors.receiveMessage{
    case IdentityCalculated(_,_,_) =>
      println("got response")
      Behaviors.same
  }
}

}
ActorSystem(Main(), "credentials-manager")

}
</code>```

what am I missing?
I want to create http server when I get the message that the identity was calculated how ever i am getting compilation error in the materializer
creation

Main.scala:19:50: implicit ActorRefFactory required: if outside of an Actor you need an implicit ActorSystem, inside of an actor this should be the implicit ActorContext
  [error]     implicit val materializer = ActorMaterializer()
  [error]                                                  ^
  [error] one error found

thanks

答:
In Akka 2.6 the ActorMaterializer API has been deprecated and a new system wide materializer that is always available have been introduced. To run a stream you should only need the implicit ActorSystem[T] in scope.

akka-stream-typed is only needed if you want to use the specific stream operators for interacting with Akka typed actors (ActorSource, ActorFlow and ActorSink)

However the Akka HTTP APIs is still depending on the classic APIs so you may need to adapt them to be able to bind a HTTP endpoint for example.

If that is your issue, you can see how to do that in the Akka HTTP quickstart guide here: https://developer.lightbend.com/guides/akka-http-quickstart-scala/http-server.html

Body:
I am trying to work with typed actors version 2.6.3 and akka http version 10.1.11
while all worked fine in non typed actors , now I am getting compilation error

object Main extends App {

   def createServer(implicit system: ActorSystem[IdentityCalculated]) = {

implicit val materializer = ActorMaterializer()

 }
 def apply(): Behavior[IdentityCalculated] = {
Behaviors.setup { context =>

  val identityManager = context.spawn(IdentityManager(), "identity-manager")

  implicit val timeout = Timeout(10, TimeUnit.SECONDS)
  implicit val scheduler = context.system.scheduler

  identityManager.tell(CalculateIdentity(context.self))

  Behaviors.receiveMessage{
    case IdentityCalculated(_,_,_) =>
      println("got response")
      Behaviors.same
  }
}

}
ActorSystem(Main(), "credentials-manager")

}

what am I missing?
I want to create http server when I get the message that the identity was calculated how ever i am getting compilation error in the materializer
creation

Main.scala:19:50: implicit ActorRefFactory required: if outside of an Actor you need an implicit ActorSystem, inside of an actor this should be the implicit ActorContext
  [error]     implicit val materializer = ActorMaterializer()
  [error]                                                  ^
  [error] one error found

thanks


问:
on Android, is onStopJob always called?
I am trying to implement my first JobService. I understand that a call to onStartJob is practically guaranteed (yes there are some edges if I specify some outrageous requirements without an expiration time). But how about onStopJob? Is it guaranteed to be called?

To be specific I have a job that will be performed in the background. But I have a way to know when the job is done (e.g. sharedPrefs). I was hoping to rely on when onStopJob is called to send a Notification to the user that the job is done.

Note: onStopJob is a convenient place for sending the notification since I am already checking whether the job is done so to know if I should retry.

p.s. Something to consider that might help (I am considering it too): If my onStartJob returns true, how does the system know when my job stops running unless it calls onStopJob?

答:
When u return true in onstartjob()

```<code> public boolean onStartJob(JobParameters jobParameters) {
        Toast.makeText(getApplicationContext(),
               "MyJobService.onStartJob()",
                Toast.LENGTH_SHORT).show();
        Log.d("KRN","KRANTHU: ");
        /*
         * True - if your service needs to process
         * the work (on a separate thread).
         * False - if there's no more work to be done for this job.
         */
        return true;
    }
</code>```

Only then the api will call onstop() function. While when u return false in onstartjob
(), it considers that the job is completed and doesnt calls onstopjob().

You question- > how does the system know when my job stops

When the constraint(condition) that u hv set in your jobinfo doesnt meets or the conditions is not meeting anymore than the app knows that the job has stopped.

Title: on Android, is onStopJob always called?

Body:
When u return true in onstartjob()

 public boolean onStartJob(JobParameters jobParameters) {
        Toast.makeText(getApplicationContext(),
               "MyJobService.onStartJob()",
                Toast.LENGTH_SHORT).show();
        Log.d("KRN","KRANTHU: ");
        /*
         * True - if your service needs to process
         * the work (on a separate thread).
         * False - if there's no more work to be done for this job.
         */
        return true;
    }

Only then the api will call onstop() function. While when u return false in onstartjob
(), it considers that the job is completed and doesnt calls onstopjob().

You question- > how does the system know when my job stops

When the constraint(condition) that u hv set in your jobinfo doesnt meets or the conditions is not meeting anymore than the app knows that the job has stopped.