问:
Cannot see expected PRINT or RAISERROR output when a later error is raised
I'm getting an error message in a stored procedure, saying that I can't insert a NULL value into a table, when I should be getting errors earlier in the code if the value is null.

Here's the relevant part of the stored procedure:

```<code>CREATE PROCEDURE [dbo].[udp_AddUpdateStaffVariable]
    -- Add the parameters for the stored procedure here
    @StaffID int=null,
    @VariableTypeID int,
    @VariableIntValue int=null,
    @VariableVarcharValue varchar(max)=null,
    @VariableDatetimeValue datetime=null,
    @VariableDecimalValue decimal=null
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
BEGIN TRY
    DECLARE @PrintOutput varchar(150)
    SET @PrintOutput = '@StaffID = ' + CASE WHEN @StaffID = NULL THEN 'Null' ELSE CONVERT(varchar(20), @StaffID) END
    RAISERROR (@PrintOutput, 10, 1) WITH NOWAIT

    IF (@StaffID = NULL)    -- If the staffid of the current user was not supplied, find it in the Staff table
    BEGIN
        DECLARE @CurrentUser nvarchar(255) = SUSER_SNAME();
        SELECT @StaffID = [StaffID] FROM [dbo].[Staff] WHERE [UserName] = @CurrentUser;
        SET @PrintOutput = '@StaffID = ' + CASE WHEN @StaffID = NULL THEN 'Null' ELSE CONVERT(varchar(20), @StaffID) END
        RAISERROR (@PrintOutput, 10, 1) WITH NOWAIT
        IF @StaffID = NULL -- raise error if staffid wasn't found
        BEGIN
            RAISERROR (50001 --error number
                , 16 -- severity
                , 1 --state
                , @CurrentUser -- parameter
                )
        END
    END

    -- Get the variable data type (used to determine where the variable is stored)
    DECLARE @VarDataTypeDesc varchar(20)
    DECLARE @StaffVarID int

    SELECT @VarDataTypeDesc = dt.[StaffVariableDataType]
    FROM [list].[DataTypes] dt INNER JOIN [list].[StaffVariableTypes] svt ON dt.DataTypeID = svt.DataTypeID
    WHERE svt.VariableTypeID = @VariableTypeID

    -- update or add the staff variable
    IF EXISTS (SELECT 1 FROM [dbo].[StaffVariables] WHERE StaffID = @StaffID AND [VariableTypeID] = @VariableTypeID) -- update
    BEGIN
        IF @VarDataTypeDesc = 'int'
        BEGIN -- only update here - other data types are updated further down
            UPDATE [dbo].[StaffVariables] SET VariableIntValue = @VariableIntValue WHERE StaffID = @StaffID AND VariableTypeID = @VariableTypeID
        END
        ELSE -- StaffVariableID is only needed if the variable type is not int
        BEGIN
            SELECT @StaffVarID = StaffVariableID FROM [dbo].[StaffVariables] WHERE StaffID = @StaffID AND [VariableTypeID] = @VariableTypeID
        END
    END
    ELSE -- insert
    BEGIN
        IF @VarDataTypeDesc = 'int'
        BEGIN
            INSERT INTO [dbo].[StaffVariables] (StaffID, VariableTypeID, VariableIntValue)
            VALUES (@StaffID, @VariableTypeID, @VariableIntValue)
        END
        ELSE -- StaffVariableID is only needed if the variable type is not int
        BEGIN
            DECLARE @StaffVarIDTbl table(ID int)
            INSERT INTO [dbo].[StaffVariables] (StaffID, VariableTypeID, VariableIntValue)
            OUTPUT INSERTED.[StaffVariableID] INTO @StaffVarIDTbl
            VALUES (@StaffID, @VariableTypeID, @VariableIntValue)

            SELECT @StaffVarID = ID FROM @StaffVarIDTbl
        END
    END

-- Cutting out the section where I deal with other variable types besides int here - not relevant to this problem

END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;
END
</code>```

Here's the test procedure run code:

```<code>DECLARE @return_value int

EXEC    @return_value = [dbo].[udp_AddUpdateStaffVariable]
        @VariableTypeID = 1,
        @VariableIntValue = 10

SELECT  'Return Value' = @return_value

GO
</code>```

...and here's the response:

```<code>Msg 50000, Level 16, State 2, Procedure dbo.udp_AddUpdateStaffVariable, Line 130 [Batch Start Line 2]
Cannot insert the value NULL into column 'StaffID', table 'SnippingDbName.dbo.StaffVariables'; column does not allow nulls. INSERT fails.

(1 row affected)

Completion time: 2020-06-01T21:17:08.2049072-05:00
</code>```

So... here's the question. The error seems to indicate that it either never ran the whole, if @StaffID = NULL portion of the code, or it did, and didn't find the StaffID and set the @StaffID variable. But if that were the case, why can't I see the results of my earlier RAISERROR statements?

I initially tried PRINT and switched to RAISERROR when PRINT wasn't working.

SQL Server 2017 Developer Edition, SSMS 15.0.18183.0

答: It was a syntax error, that people commenting on the question figured out. IF (@StaffID = NULL) should have been, IF (@StaffID IS NULL) Fixing that in all places in the procedure fixed the problem, and altering my test Staff record so UserName doesn't match SUSER_SNAME() resulted in the expected error.

Body:
I'm getting an error message in a stored procedure, saying that I can't insert a NULL value into a table, when I should be getting errors earlier in the code if the value is null.

Here's the relevant part of the stored procedure:

CREATE PROCEDURE [dbo].[udp_AddUpdateStaffVariable]
    -- Add the parameters for the stored procedure here
    @StaffID int=null,
    @VariableTypeID int,
    @VariableIntValue int=null,
    @VariableVarcharValue varchar(max)=null,
    @VariableDatetimeValue datetime=null,
    @VariableDecimalValue decimal=null
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
BEGIN TRY
    DECLARE @PrintOutput varchar(150)
    SET @PrintOutput = '@StaffID = ' + CASE WHEN @StaffID = NULL THEN 'Null' ELSE CONVERT(varchar(20), @StaffID) END
    RAISERROR (@PrintOutput, 10, 1) WITH NOWAIT

    IF (@StaffID = NULL)    -- If the staffid of the current user was not supplied, find it in the Staff table
    BEGIN
        DECLARE @CurrentUser nvarchar(255) = SUSER_SNAME();
        SELECT @StaffID = [StaffID] FROM [dbo].[Staff] WHERE [UserName] = @CurrentUser;
        SET @PrintOutput = '@StaffID = ' + CASE WHEN @StaffID = NULL THEN 'Null' ELSE CONVERT(varchar(20), @StaffID) END
        RAISERROR (@PrintOutput, 10, 1) WITH NOWAIT
        IF @StaffID = NULL -- raise error if staffid wasn't found
        BEGIN
            RAISERROR (50001 --error number
                , 16 -- severity
                , 1 --state
                , @CurrentUser -- parameter
                )
        END
    END

    -- Get the variable data type (used to determine where the variable is stored)
    DECLARE @VarDataTypeDesc varchar(20)
    DECLARE @StaffVarID int

    SELECT @VarDataTypeDesc = dt.[StaffVariableDataType]
    FROM [list].[DataTypes] dt INNER JOIN [list].[StaffVariableTypes] svt ON dt.DataTypeID = svt.DataTypeID
    WHERE svt.VariableTypeID = @VariableTypeID

    -- update or add the staff variable
    IF EXISTS (SELECT 1 FROM [dbo].[StaffVariables] WHERE StaffID = @StaffID AND [VariableTypeID] = @VariableTypeID) -- update
    BEGIN
        IF @VarDataTypeDesc = 'int'
        BEGIN -- only update here - other data types are updated further down
            UPDATE [dbo].[StaffVariables] SET VariableIntValue = @VariableIntValue WHERE StaffID = @StaffID AND VariableTypeID = @VariableTypeID
        END
        ELSE -- StaffVariableID is only needed if the variable type is not int
        BEGIN
            SELECT @StaffVarID = StaffVariableID FROM [dbo].[StaffVariables] WHERE StaffID = @StaffID AND [VariableTypeID] = @VariableTypeID
        END
    END
    ELSE -- insert
    BEGIN
        IF @VarDataTypeDesc = 'int'
        BEGIN
            INSERT INTO [dbo].[StaffVariables] (StaffID, VariableTypeID, VariableIntValue)
            VALUES (@StaffID, @VariableTypeID, @VariableIntValue)
        END
        ELSE -- StaffVariableID is only needed if the variable type is not int
        BEGIN
            DECLARE @StaffVarIDTbl table(ID int)
            INSERT INTO [dbo].[StaffVariables] (StaffID, VariableTypeID, VariableIntValue)
            OUTPUT INSERTED.[StaffVariableID] INTO @StaffVarIDTbl
            VALUES (@StaffID, @VariableTypeID, @VariableIntValue)

            SELECT @StaffVarID = ID FROM @StaffVarIDTbl
        END
    END

-- Cutting out the section where I deal with other variable types besides int here - not relevant to this problem

END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;
END

Here's the test procedure run code:

DECLARE @return_value int

EXEC    @return_value = [dbo].[udp_AddUpdateStaffVariable]
        @VariableTypeID = 1,
        @VariableIntValue = 10

SELECT  'Return Value' = @return_value

GO

...and here's the response:

Msg 50000, Level 16, State 2, Procedure dbo.udp_AddUpdateStaffVariable, Line 130 [Batch Start Line 2]
Cannot insert the value NULL into column 'StaffID', table 'SnippingDbName.dbo.StaffVariables'; column does not allow nulls. INSERT fails.

(1 row affected)

Completion time: 2020-06-01T21:17:08.2049072-05:00

So... here's the question. The error seems to indicate that it either never ran the whole, if @StaffID = NULL portion of the code, or it did, and didn't find the StaffID and set the @StaffID variable. But if that were the case, why can't I see the results of my earlier RAISERROR statements?

I initially tried PRINT and switched to RAISERROR when PRINT wasn't working.

SQL Server 2017 Developer Edition, SSMS 15.0.18183.0


来源: stackexchange

问:
Taking data out of JSONP
Using the url:
http://www.remote_host.com/feed.php?callback=jsonpCallback

I get back:

```<code>jsonpCallback({
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    } })
</code>```

At clientside, I have the following script:

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

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }
});
</code>```

How do I write some of the jsonp content to the screen, i.e.

```<code>channel title: title goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />
</code>```

instead of alerting "success"?

答:
You can reach the values in jsonp like this:

```<code>html = "channel title: "+jsonp.rss.channels[0].title+"<br /><br />";
for (x in jsonp.rss.channels[0].items)
{
    html += "item title: "+jsonp.rss.channels[0].items[x].title+"<br />";
    html += "item link: "+jsonp.rss.channels[0].items[x].link+"<br />";
    html += "item date: "+jsonp.rss.channels[0].items[x].pubDate+"<br />";
    html += "item description: "+jsonp.rss.channels[0].items[x].description+"<br /><br />";
}
</code>```

Then you can insert the html where erver you want in your site.

ContentLicense: CC BY-SA 3.0

Title: Taking data out of JSONP

Body:
Using the url:
http://www.remote_host.com/feed.php?callback=jsonpCallback

I get back:

jsonpCallback({
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    } })

At clientside, I have the following script:

$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }
});

How do I write some of the jsonp content to the screen, i.e.

channel title: title goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

instead of alerting "success"?

Body:
You can reach the values in jsonp like this:

html = "channel title: "+jsonp.rss.channels[0].title+"<br /><br />";
for (x in jsonp.rss.channels[0].items)
{
    html += "item title: "+jsonp.rss.channels[0].items[x].title+"<br />";
    html += "item link: "+jsonp.rss.channels[0].items[x].link+"<br />";
    html += "item date: "+jsonp.rss.channels[0].items[x].pubDate+"<br />";
    html += "item description: "+jsonp.rss.channels[0].items[x].description+"<br /><br />";
}

Then you can insert the html where erver you want in your site.


问:
Remove Decimal trailing zeros without using scientific form in Elixir
I'd like to remove trailing zeros from the decimal part and keep the integer part in the neutral form (so not changing its from 100 to 1e2. Using Decimal properly removes trailing zeros but it switches to scientific notation as well.

```<code>iex(30)> d = Decimal.new("1.00000")
#Decimal<1.00000>
iex(31)> Decimal.reduce(d)
#Decimal<1>
iex(32)> d = Decimal.new("100.00000")
#Decimal<100.00000>
iex(33)> Decimal.reduce(d)
#Decimal<1E+2>
</code>```

答:
From: https://hexdocs.pm/elixir/Kernel.html#trunc/1

```<code>trunc(number)
</code>```

Specs

```<code>trunc(number()) :: integer()
</code>```

Returns the integer part of number.

Allowed in guard tests. Inlined by the compiler.

Examples:

```<code>iex> trunc(5.4)
> 5

iex> trunc(-5.99)
> -5

iex> trunc(-5)
> -5
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to remove trailing zeros from the decimal part and keep the integer part in the neutral form (so not changing its from 100 to 1e2. Using Decimal properly removes trailing zeros but it switches to scientific notation as well.

iex(30)> d = Decimal.new("1.00000")
#Decimal<1.00000>
iex(31)> Decimal.reduce(d)
#Decimal<1>
iex(32)> d = Decimal.new("100.00000")
#Decimal<100.00000>
iex(33)> Decimal.reduce(d)
#Decimal<1E+2>

Body:
From: https://hexdocs.pm/elixir/Kernel.html#trunc/1

trunc(number)

Specs

trunc(number()) :: integer()

Returns the integer part of number.

Allowed in guard tests. Inlined by the compiler.

Examples:

iex> trunc(5.4)
> 5

iex> trunc(-5.99)
> -5

iex> trunc(-5)
> -5


问:
Efficiently split a long document into multiple shorter documents based on whitespace characters and specified character length
I need to write a function to split long documents into shorter documents on whitespace characters (\s) based on pre-specified character length.

To illustrate, for example, I have a text document that has 175,000,000 characters (including all the punctuation and whitespace characters). I would like to split the document into shorter documents of roughly 100,000 characters each.

Of course, the spots where splits happen won't be exactly at the 100,000th/200,00th/300,000th... characters because a whitespace character might not be exactly at those spots. If a whitespace character is not at the desired splitting point (e.g., if the 100,000th character is not a whitespace character), the function will look for the closest whhitespace character to the left and split there. The following is my attempt at the function, but it seems that the function is very slow.

```<code>whitespace_regex = re.compile(r"\s")

def foo(text):
    # If a document is 100000 character long or shorter
    # no splitting is needed
    if len(text) <= 100000:
        yield text
    # Splitting if a document is longer than 100000 characters
    elif len(text) > 100000:
        # A while loop until there is nothing left to be split
        while len(text) > 100000:
            # Split a document into two segments:
            #     left: 100000 character long
            #     text: the rest of the document
            left, text = text[:100000], text[100000:]

            # Look for the rightmost whitespace character in the 'left'
            # segment by first reversing the string so that the whitespace
            # returned by the regex search is the rightmost whitespace
            whitespace = whitespace_regex.search(left[::-1])

            # Get the start index of the returned whitespace. If -index
            # is 0, then that means pro
            index = whitespace.start()
            index = -index
            # if the whitespace is not exactly at the desired position,
            # yield the part to the left of the whitespace character, and
            # combine the part of the left segment to the right of the
            # whitespace character with the rest of the remaining text
            if index < 0:
                text = left[index:] + text
                left = left[:index]
            yield left
        if text:
            yield text
</code>```

I tested the speed on a document with 175,000,000 characters, and it took almost 6 minutes to finish splitting the document:

```<code>a = "John did what others told him to do" * 5000000
print(f"Document's length is {len(a)}")
#Document's length is 175000000

start_time = time.time()
segs = [x for x in foo(a)]
print(time.time() - start_time)
#344.3530957698822
</code>```

I wonder if there is a way to write a much more efficient function to do this.

答:
The problem scales very badly with the size of a document. For example, 10 times smaller document ran on my machine in 0.3 seconds, your size did so in 144.8. I think the problem is that every time you chop off a chunk from the left, the remaining text moved. So one solution could be to actually start chopping your document from the back. Another solution could be just chop the array in smaller blocks and run the function on them:

```<code>a = "John did what others told him to do" * 5000000
print(f"Document's length is {len(a)}")
#Document's length is 1750000000

start_time = time()
segs = []
block_size = 17500000
start_ind = 0
num_blocks = int(len(a)/block_size) + 1
for i in range(num_blocks):
  if len(a)-start_ind > block_size:
      block = a[start_ind : start_ind + block_size]
  else:
      block = a[start_ind :]

  block_segs = [x for x in foo(block)]

  start_ind += block_size - len(block_segs[-1])

  segs += block_segs[:-1]
  if len(a)-start_ind > block_size: segs += block_segs[-1]

print(time() - start_time)
</code>```

This takes about 3.0 seconds. Fast and dirty, I suppose...

Body:
I need to write a function to split long documents into shorter documents on whitespace characters (\s) based on pre-specified character length.

To illustrate, for example, I have a text document that has 175,000,000 characters (including all the punctuation and whitespace characters). I would like to split the document into shorter documents of roughly 100,000 characters each.

Of course, the spots where splits happen won't be exactly at the 100,000th/200,00th/300,000th... characters because a whitespace character might not be exactly at those spots. If a whitespace character is not at the desired splitting point (e.g., if the 100,000th character is not a whitespace character), the function will look for the closest whhitespace character to the left and split there. The following is my attempt at the function, but it seems that the function is very slow.

whitespace_regex = re.compile(r"\s")

def foo(text):
    # If a document is 100000 character long or shorter
    # no splitting is needed
    if len(text) <= 100000:
        yield text
    # Splitting if a document is longer than 100000 characters
    elif len(text) > 100000:
        # A while loop until there is nothing left to be split
        while len(text) > 100000:
            # Split a document into two segments:
            #     left: 100000 character long
            #     text: the rest of the document
            left, text = text[:100000], text[100000:]

            # Look for the rightmost whitespace character in the 'left'
            # segment by first reversing the string so that the whitespace
            # returned by the regex search is the rightmost whitespace
            whitespace = whitespace_regex.search(left[::-1])

            # Get the start index of the returned whitespace. If -index
            # is 0, then that means pro
            index = whitespace.start()
            index = -index
            # if the whitespace is not exactly at the desired position,
            # yield the part to the left of the whitespace character, and
            # combine the part of the left segment to the right of the
            # whitespace character with the rest of the remaining text
            if index < 0:
                text = left[index:] + text
                left = left[:index]
            yield left
        if text:
            yield text

I tested the speed on a document with 175,000,000 characters, and it took almost 6 minutes to finish splitting the document:

a = "John did what others told him to do" * 5000000
print(f"Document's length is {len(a)}")
#Document's length is 175000000

start_time = time.time()
segs = [x for x in foo(a)]
print(time.time() - start_time)
#344.3530957698822

I wonder if there is a way to write a much more efficient function to do this.

Body:
The problem scales very badly with the size of a document. For example, 10 times smaller document ran on my machine in 0.3 seconds, your size did so in 144.8. I think the problem is that every time you chop off a chunk from the left, the remaining text moved. So one solution could be to actually start chopping your document from the back. Another solution could be just chop the array in smaller blocks and run the function on them:

a = "John did what others told him to do" * 5000000
print(f"Document's length is {len(a)}")
#Document's length is 1750000000

start_time = time()
segs = []
block_size = 17500000
start_ind = 0
num_blocks = int(len(a)/block_size) + 1
for i in range(num_blocks):
  if len(a)-start_ind > block_size:
      block = a[start_ind : start_ind + block_size]
  else:
      block = a[start_ind :]

  block_segs = [x for x in foo(block)]

  start_ind += block_size - len(block_segs[-1])

  segs += block_segs[:-1]
  if len(a)-start_ind > block_size: segs += block_segs[-1]

print(time() - start_time)

This takes about 3.0 seconds. Fast and dirty, I suppose...


问:
I am having issue with python, I am trying to make QRcode creating app
I am facing problem in the clicked() function which has to be executed when the button is pressed
I have defined the variables but it shows the error message of 'variable not defined'</p>

```<code>import tkinter as tk
import pyqrcode as qr
import png
from pyqrcode import QRCode
window = tk.Tk()
window.title("QR")
label = tk.Label(window,text="QR maker",font=("Helvetica",50)).pack()
label = tk.Label(window,text="Enter link",font=("Helvetica",10)).pack()
txt = tk.Entry(window,width=50).pack()
label = tk.Label(window,text="Enter size",font=("Helvetica",10)).pack()
txt2 = tk.Entry(window,width=10).pack()
label = tk.Label(window,text="enter name",font=("Helvetica",10)).pack()
txt3 = tk.Entry(window,width=50).pack()

def clicked():
Qstr = txt.get()
a = int(txt2.get())
b = txt3.get()
url = qr.create(Qstr)
url.png(b,scale=a)
but = tk.Button(window,text="fill",command=fill).pack()
but2 = tk.Button(window,text="press here",command=clicked).pack()
window.geometry('1920x1080')
window.mainloop()
</code>```

答:
As @acw1668 states, you need to spereate the txt = tk.Entry(...).pack() into two lines.

This would be your code:

import tkinter as tk
import pyqrcode as qr
import png
from pyqrcode import QRCode
window = tk.Tk()
window.title("QR")
label = tk.Label(window,text="QR maker",font=("Helvetica",50))
label.pack()
label = tk.Label(window,text="Enter link",font=("Helvetica",10))
label.pack()
txt = tk.Entry(window,width=50)
txt.pack()
label = tk.Label(window,text="Enter size",font=("Helvetica",10))
label.pack()
txt2 = tk.Entry(window,width=10)
txt2.pack()
label = tk.Label(window,text="enter name",font=("Helvetica",10)).pack()
txt3 = tk.Entry(window,width=50)
txt3.pack()

def clicked():
    Qstr = txt.get()
    a = int(txt2.get())
    b = txt3.get()
    url = qr.create(Qstr)
    url.png(b,scale=a)
    but = tk.Button(window,text="fill",command=fill)
    but.pack()
but2 = tk.Button(window,text="press here",command=clicked)
but2.pack()
window.geometry('1920x1080')
window.mainloop()
```

Hope this helps!

Body:
I am facing problem in the clicked() function which has to be executed when the button is pressed
I have defined the variables but it shows the error message of 'variable not defined'

import tkinter as tk
import pyqrcode as qr
import png
from pyqrcode import QRCode
window = tk.Tk()
window.title("QR")
label = tk.Label(window,text="QR maker",font=("Helvetica",50)).pack()
label = tk.Label(window,text="Enter link",font=("Helvetica",10)).pack()
txt = tk.Entry(window,width=50).pack()
label = tk.Label(window,text="Enter size",font=("Helvetica",10)).pack()
txt2 = tk.Entry(window,width=10).pack()
label = tk.Label(window,text="enter name",font=("Helvetica",10)).pack()
txt3 = tk.Entry(window,width=50).pack()

def clicked():
Qstr = txt.get()
a = int(txt2.get())
b = txt3.get()
url = qr.create(Qstr)
url.png(b,scale=a)
but = tk.Button(window,text="fill",command=fill).pack()
but2 = tk.Button(window,text="press here",command=clicked).pack()
window.geometry('1920x1080')
window.mainloop()

Body:
As @acw1668 states, you need to spereate the txt = tk.Entry(...).pack() into two lines.

This would be your code:

import tkinter as tk
import pyqrcode as qr
import png
from pyqrcode import QRCode
window = tk.Tk()
window.title("QR")
label = tk.Label(window,text="QR maker",font=("Helvetica",50))
label.pack()
label = tk.Label(window,text="Enter link",font=("Helvetica",10))
label.pack()
txt = tk.Entry(window,width=50)
txt.pack()
label = tk.Label(window,text="Enter size",font=("Helvetica",10))
label.pack()
txt2 = tk.Entry(window,width=10)
txt2.pack()
label = tk.Label(window,text="enter name",font=("Helvetica",10)).pack()
txt3 = tk.Entry(window,width=50)
txt3.pack()

def clicked():
    Qstr = txt.get()
    a = int(txt2.get())
    b = txt3.get()
    url = qr.create(Qstr)
    url.png(b,scale=a)
    but = tk.Button(window,text="fill",command=fill)
    but.pack()
but2 = tk.Button(window,text="press here",command=clicked)
but2.pack()
window.geometry('1920x1080')
window.mainloop()

Hope this helps!


问:
Should I make the method virtual or abstract?
I have an abstract class that does its own internal validation. It has another method that allows subclasses to do additional validation checks. Currently, I've made the method abstract.

```<code>protected abstract bool ValidateFurther();
</code>```

However, I'm seeing quite a number of subclasses being forced to override it just to return true. I'm considering to make the method virtual.

```<code>protected virtual bool ValidateFurther() => true;
</code>```

Is it bad to assume that validation is going to be fine in the abstract class? I'm worried that subclasses may not notice it and ended up not overriding it even when it is needed. Which is the more suitable approach here?

答:
You could add another layer into your design.

```<code>public abstract class Base
{
    protected abstract bool ValidateFurther();
}

public abstract class BaseWithValidation : Base
{
    protected override bool ValidateFurther() => true;
}
</code>```

If a significant subset of your inherited classes should just return true you can use BaseWithValidation to avoid having to repeat the code everywhere; for anything else use Base.

Body:
I have an abstract class that does its own internal validation. It has another method that allows subclasses to do additional validation checks. Currently, I've made the method abstract.

protected abstract bool ValidateFurther();

However, I'm seeing quite a number of subclasses being forced to override it just to return true. I'm considering to make the method virtual.

protected virtual bool ValidateFurther() => true;

Is it bad to assume that validation is going to be fine in the abstract class? I'm worried that subclasses may not notice it and ended up not overriding it even when it is needed. Which is the more suitable approach here?

Body:
You could add another layer into your design.

public abstract class Base
{
    protected abstract bool ValidateFurther();
}

public abstract class BaseWithValidation : Base
{
    protected override bool ValidateFurther() => true;
}

If a significant subset of your inherited classes should just return true you can use BaseWithValidation to avoid having to repeat the code everywhere; for anything else use Base.


问:
WCF Method returns 400 Bad Request on Production
Methods of WCF REST Service are working with C# WCFClient against Production-Server.
They are also working in Dev-Environment on localhost.
The Service and the wsdl are ok from browser access on production also.

Access to svc

Access to wsdl

But when I access any method from the service on Production-Server, 400 Bad Request will be returned.
IIS-log shows also 400: GET /WCD/WCF.svc/GetNextGuestNumber - 443 -  Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/83.0.4103.61+Safari/537.36 https://www.DS.XXX.com/qa/dLobby 400 0 0 46

Here is my web.config from Production:

```<code><?xml version="1.0"?>
  <configuration>
    <appSettings>
      <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
      <add key="WBCCNN" value="PQkSAXkRXNsanbA5xK1KBZZqu+oxrJbssQlEiM1Fi+N2Vnz0F5QfAetqILb0QeLwlF7jMZ57k9J8sIlAJ1TRjtfgwh0V88Q2Kl/20Cny2WCTawWyDSECKg=="/>
    </appSettings>
    <system.web>
      <compilation debug="false" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5"/>
    </system.web>
    <system.serviceModel>
      <services>
        <service name="DS.XXX.Services.WCF" behaviorConfiguration="DSServiceBehavior">
          <endpoint address=""
              binding="basicHttpBinding"
              bindingConfiguration="secureHttpBinding"
              contract="DS.XXX.Services.IWCF"/>
          <endpoint address="mex"
              binding="mexHttpsBinding"
              contract="IMetadataExchange" />
        </service>
      </services>
      <bindings>
        <basicHttpBinding>
          <binding name="secureHttpBinding">
            <security mode="Transport">
            </security>
          </binding>
        </basicHttpBinding>
      </bindings>
      <behaviors>
        <serviceBehaviors>
          <behavior name="DSServiceBehavior">
            <serviceMetadata httpsGetEnabled="true" httpsGetUrl="" />
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
  </configuration>
</code>```

The methods are called from a REACT JS App with Axios

```<code>const res = await API.get("/GetNextGuestNumber");
</code>```

The API from Axios is configured like so:

```<code>import axios from "axios";
import global from "../config";

export default axios.create({
  baseURL: global.webServicesUrl,
  headers: { "Content-Type": "application/json" }
});
</code>```

As the service is working on dev and the svc and the wsdl is reachable on prod, it must be something with the binding and endpoint configuration?

I am using a Certificate from a third party vendor which is working fine also.
I don't see it. Any help is appreciated. If you need any more details, pleas let me know.

Env.: Windows Server 2016, IIS

答:
There is an error in the binding. You should use webhttpbinding to build the WCF REST Service, but I see in the configuration file that you used basichttpbinding.In this case, when you use JS to access the service, you will receive 400 errors.

```<code>        <services>
        <service name="Demo_rest_IIS.Service1"
                 behaviorConfiguration="UserServiceBehavior">
            <endpoint address=""
                      binding="webHttpBinding"
                      contract="Demo_rest_IIS.IService1"
                      behaviorConfiguration="ESEndPointBehavior" bindingConfiguration="bind"/>
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="ESEndPointBehavior">
                <webHttp helpEnabled="true"/>
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="UserServiceBehavior">
                <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</code>```

This is the configuration file of WCF rest service that I deployed in IIS.

```<code>    [OperationContract]
    [WebGet(UriTemplate = "user/?name={name}",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result GetUserData(string name);
    [OperationContract]
    [WebInvoke(UriTemplate = "user", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result PostUserData(UserData user);
    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "user", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result PutUserData(UserData user);
    [OperationContract]
    [WebInvoke(Method = "DELETE", UriTemplate = "user", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result DeleteUserData(UserData user);
</code>```

This is the interface of the service.In the configuration file, I set the value of helpenabled to true. After deploying the service, we use the help document to see how to access it.

This is the help document for the service.

For more information about WCF REST Service, please refer to the following link:

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/wcf-web-http-programming-model

Body:
Methods of WCF REST Service are working with C# WCFClient against Production-Server.
They are also working in Dev-Environment on localhost.
The Service and the wsdl are ok from browser access on production also.

Access to svc

Access to wsdl

But when I access any method from the service on Production-Server, 400 Bad Request will be returned.
IIS-log shows also 400: GET /WCD/WCF.svc/GetNextGuestNumber - 443 -  Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/83.0.4103.61+Safari/537.36 https://www.DS.XXX.com/qa/dLobby 400 0 0 46

Here is my web.config from Production:

<?xml version="1.0"?>
  <configuration>
    <appSettings>
      <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
      <add key="WBCCNN" value="PQkSAXkRXNsanbA5xK1KBZZqu+oxrJbssQlEiM1Fi+N2Vnz0F5QfAetqILb0QeLwlF7jMZ57k9J8sIlAJ1TRjtfgwh0V88Q2Kl/20Cny2WCTawWyDSECKg=="/>
    </appSettings>
    <system.web>
      <compilation debug="false" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5"/>
    </system.web>
    <system.serviceModel>
      <services>
        <service name="DS.XXX.Services.WCF" behaviorConfiguration="DSServiceBehavior">
          <endpoint address=""
              binding="basicHttpBinding"
              bindingConfiguration="secureHttpBinding"
              contract="DS.XXX.Services.IWCF"/>
          <endpoint address="mex"
              binding="mexHttpsBinding"
              contract="IMetadataExchange" />
        </service>
      </services>
      <bindings>
        <basicHttpBinding>
          <binding name="secureHttpBinding">
            <security mode="Transport">
            </security>
          </binding>
        </basicHttpBinding>
      </bindings>
      <behaviors>
        <serviceBehaviors>
          <behavior name="DSServiceBehavior">
            <serviceMetadata httpsGetEnabled="true" httpsGetUrl="" />
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
  </configuration>

The methods are called from a REACT JS App with Axios

const res = await API.get("/GetNextGuestNumber");

The API from Axios is configured like so:

import axios from "axios";
import global from "../config";

export default axios.create({
  baseURL: global.webServicesUrl,
  headers: { "Content-Type": "application/json" }
});

As the service is working on dev and the svc and the wsdl is reachable on prod, it must be something with the binding and endpoint configuration?

I am using a Certificate from a third party vendor which is working fine also.
I don't see it. Any help is appreciated. If you need any more details, pleas let me know.

Env.: Windows Server 2016, IIS

Body:
There is an error in the binding. You should use webhttpbinding to build the WCF REST Service, but I see in the configuration file that you used basichttpbinding.In this case, when you use JS to access the service, you will receive 400 errors.

        <services>
        <service name="Demo_rest_IIS.Service1"
                 behaviorConfiguration="UserServiceBehavior">
            <endpoint address=""
                      binding="webHttpBinding"
                      contract="Demo_rest_IIS.IService1"
                      behaviorConfiguration="ESEndPointBehavior" bindingConfiguration="bind"/>
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="ESEndPointBehavior">
                <webHttp helpEnabled="true"/>
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="UserServiceBehavior">
                <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>

This is the configuration file of WCF rest service that I deployed in IIS.

    [OperationContract]
    [WebGet(UriTemplate = "user/?name={name}",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result GetUserData(string name);
    [OperationContract]
    [WebInvoke(UriTemplate = "user", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result PostUserData(UserData user);
    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "user", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result PutUserData(UserData user);
    [OperationContract]
    [WebInvoke(Method = "DELETE", UriTemplate = "user", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result DeleteUserData(UserData user);

This is the interface of the service.In the configuration file, I set the value of helpenabled to true. After deploying the service, we use the help document to see how to access it.

This is the help document for the service.

For more information about WCF REST Service, please refer to the following link:

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/wcf-web-http-programming-model


问:
Preparing JSON tree structure from a JSON javascript
am looking for a JSON tree from a plain JSON.
below is the Input and expected output json.
the input json doesnt have any order
There can be multiple items at each level and each item can have n number of childrens.
leafFlag = 0 means no children
leafFlag = 1 means has chidlren
path is the property which tells where the item will be placed
The expectedOutputJson needs to be placed in a table to display level wise data

var inputJson = [
  {
  "level": "1",
  "leafFlag": "1",
  "path":"p123",
  "name":"food"
},
  {
  "level": "1",
  "leafFlag": "1",
  "path":"r125",
  "name":"car"
},
  {
  "level": "2",
  "leafFlag": "0",
  "path":"p123/p345",
  "name":"apple"
},
 {
  "level": "2",
  "leafFlag": "1",
  "path":"p123/p095",
  "name":"banana"
},
{
  "level": "3",
  "leafFlag": "0",
  "path":"p123/p095/p546",
  "name":"grapes"
},
{
  "level": "2",
  "leafFlag": "1",
  "path":"r125/yhes",
  "name":"tata"
},

]

var expectedOutput = [
  {
    "level": "1",
    "leafFlag": "1",
    "path": "p123",
    "name": "food",
    "children": [
      {
        "level": "2",
        "leafFlag": "0",
        "path": "p123/p345",
        "name": "apple"
      },
      {
        "level": "2",
        "leafFlag": "1",
        "path": "p123/p095",
        "name": "banana",
        "children": [
          {
            "level": "3",
            "leafFlag": "0",
            "path": "p123/p095/p546",
            "name": "grapes"
          }
        ]
      }
    ]
  },
  {
    "level": "1",
    "leafFlag": "1",
    "path": "r125",
    "name": "car",
    "children": [
      {
        "level": "2",
        "leafFlag": "1",
        "path": "r125/yhes",
        "name": "tata",
        "children": [
          {
            "level": "3",
            "leafFlag": "0",
            "path": "r125/yhes/sdie",
            "name": "Range Rover"
          }
        ]
      },
      {
        "level": "2",
        "leafFlag": "0",
        "path": "r125/theys",
        "name": "suzuki"
      }
    ]
  }
]

i tried the below code but not able to proceed further

private prepareTreeStructure = (inputJson) => {
    const treeFormat = (key, index, result) => {
      if (key.indexOf('/') === -1) {
        result = [...result, ...d[key]];
      } else {
        result.forEach((item, index) => {
          let splitKeyArray = key.split('/');
          splitKeyArray.forEach((splitItem, splitIndex) => {
            if (splitKeyArray.indexOf(item.path) !== -1) {
              if (!item['children']) {
                item['children'] = [];
              }
              if (splitKeyArray.length === splitIndex + 1) {
                result[index]['children'] = [...result[index]['children'], ...d[key]];
              }
            }
          });
          if (splitKeyArray.indexOf(item.path) !== -1) {
            if (!result[index]['children']) {
              result[index]['children'] = [];
            }
            result[index]['children'] = [...result[index]['children'], ...d[key]];
          }
        });
      }
      return result;
    }

    const d = inputJson.reduce((acc, ele) => {
      if (!acc[ele.path]) {
        acc[ele.path] = [];
      }
      acc[ele.path].push(ele);
      return acc;
    }, {});
    console.log('dddd  ', d);
    this.result = [];
    Object.keys(d).forEach((key, index) => {
      this.result = treeFormat(key, index, this.result);
      console.log('out ', this.result);
    })

  }

  prepareTreeStructure(inputJson);```

答:
var inputJson = [
  {
  "level": "1",
  "leafFlag": "1",
  "path":"p123",
  "name":"food"
},
  {
  "level": "1",
  "leafFlag": "1",
  "path":"r125",
  "name":"car"
},
  {
  "level": "2",
  "leafFlag": "0",
  "path":"p123/p345",
  "name":"apple"
},
 {
  "level": "2",
  "leafFlag": "1",
  "path":"p123/p095",
  "name":"banana"
},
{
  "level": "3",
  "leafFlag": "0",
  "path":"p123/p095/p546",
  "name":"grapes"
},
{
  "level": "2",
  "leafFlag": "0",
  "path":"r125/yhes",
  "name":"tata"
},

]

var expectedOutput = [
  {
    "level": "1",
    "leafFlag": "1",
    "path": "p123",
    "name": "food",
    "children": [
      {
        "level": "2",
        "leafFlag": "0",
        "path": "p123/p345",
        "name": "apple"
      },
      {
        "level": "2",
        "leafFlag": "1",
        "path": "p123/p095",
        "name": "banana",
        "children": [
          {
            "level": "3",
            "leafFlag": "0",
            "path": "p123/p095/p546",
            "name": "grapes"
          }
        ]
      }
    ]
  },
  {
    "level": "1",
    "leafFlag": "1",
    "path": "r125",
    "name": "car",
    "children": [
      {
        "level": "2",
        "leafFlag": "1",
        "path": "r125/yhes",
        "name": "tata",
        "children": [
          {
            "level": "3",
            "leafFlag": "0",
            "path": "r125/yhes/sdie",
            "name": "Range Rover"
          }
        ]
      },
      {
        "level": "2",
        "leafFlag": "0",
        "path": "r125/theys",
        "name": "suzuki"
      }
    ]
  }
]

const groupByLevels = inputJson => {
 var levelsObj = {};
 inputJson.forEach(ele => {
  if (ele.level === "1") {
   if (!levelsObj["1"]) {
    levelsObj["1"] = [];
   }
   levelsObj["1"].push(ele)
  } else {
   if (!levelsObj[ele.level]) {
    levelsObj[ele.level] = {};
   }
   var parKey = ele.path.substr(0, ele.path.lastIndexOf('/'));
   if (!levelsObj[ele.level][parKey]) {
    levelsObj[ele.level][parKey] = [];
   }
   levelsObj[ele.level][parKey].push(ele);
  }
 })
 return levelsObj;
}

const mergeByGroups = (currLevelArr, groupJSON) => {
 currLevelArr.forEach(ele => {
  if (ele.leafFlag == "0") {
   return ele;
  }
  let nextLevel = parseInt(ele.level) + 1 + ""
  let nextLevelArr = groupJSON[nextLevel][ele.path];
  mergeByGroups(nextLevelArr, groupJSON)
  ele.children = nextLevelArr;
 })
}

const constructOutput = groupJSON => {
 mergeByGroups(groupJSON["1"], groupJSON);
 return groupJSON["1"];
}

console.log(JSON.stringify(constructOutput(groupByLevels(inputJson)), null, 4));```


问:
Using JEXL in Cloud Data Fusion
I'm using wrangler component of cloud data fusion. I want to set new column with current date.

```<code>set-column :current_date new("java.time.LocalDateTime.now()");
</code>```

Throws "The preview of the pipeline "test" has failed. Please check the logs for more information." error for me and many similar code doesn't work too. Logs show nothing code related, only messages like "Failed to add file to Spark environment" or "Aborting task". I'm sure that problem is in JEXL expression because without it or with simple expression like:

```<code>var a = 5+5; a
</code>```

it works fine.

Is it possible to set column with current date?

答:
To add a column with current date, you can use the Add Field transform plugin. It is available from the Hub > Field Adder Transform. For the Field Value property, you can set it as:

```<code>${logicalStartTime(yyyy-MM-dd'T'HH-mm-ss)}
</code>```

On what's possible with Wrangler, here is a cheat sheet blog post.

Title: Using JEXL in Cloud Data Fusion

Body:
I'm using wrangler component of cloud data fusion. I want to set new column with current date.

set-column :current_date new("java.time.LocalDateTime.now()");

Throws "The preview of the pipeline "test" has failed. Please check the logs for more information." error for me and many similar code doesn't work too. Logs show nothing code related, only messages like "Failed to add file to Spark environment" or "Aborting task". I'm sure that problem is in JEXL expression because without it or with simple expression like:

var a = 5+5; a

it works fine.

Is it possible to set column with current date?

Body:
To add a column with current date, you can use the Add Field transform plugin. It is available from the Hub > Field Adder Transform. For the Field Value property, you can set it as:

${logicalStartTime(yyyy-MM-dd'T'HH-mm-ss)}

On what's possible with Wrangler, here is a cheat sheet blog post.


问:
How to use pretrained weights of a model for initializing the weights in next iteration?
I have a model architecture. I have saved the entire model using torch.save() for some n number of iterations. I want to run another iteration of my code by using the pre-trained weights of the model I saved previously.

Edit: I want the weight initialization for the new iteration be done from the weights of the pretrained model

Edit 2: Just to add, I don't plan to resume training. I intend to save the model and use it for a separate training with same parameters. Think of it like using a saved model with weights etc. for a larger run and more samples (i.e. a complete new training job)

Right now, I do something like:

```<code># default_lr = 5
# default_weight_decay = 0.001
# model_io = the pretrained model
model = torch.load(model_io)
optim = torch.optim.Adam(model.parameters(),lr=default_lr, weight_decay=default_weight_decay)
loss_new = BCELoss()
epochs = default_epoch
.
.
training_loop():
....
outputs = model(input)
....
.
#similarly for test loop
</code>```

Am I missing something? I have to run for a very long epoch for a huge number of sample so can not afford to wait to see the results then figure out things.

Thank you!

答:
From the code that you have posted, I see that you are only loading the previous model parameters in order to restart your training from where you left it off. This is not sufficient to restart your training correctly. Along with your model parameters (weights), you also need to save and load your optimizer state, especially when your choice of optimizer is Adam which has velocity parameters for all your weights that help in decaying the learning rate.

In order to smoothly restart training, I would do the following:

```<code># For saving your model

state = {
    'model': model.state_dict(),
    'optimizer': optimizer.state_dict()
}
model_save_path = "Enter/your/model/path/here/model_name.pth"
torch.save(state, model_save_path)

# ------------------------------------------

# For loading your model
state = torch.load(model_save_path)

model = MyNetwork()
model.load_state_dict(state['model'])

optim = torch.optim.Adam(model.parameters(),lr=default_lr, weight_decay=default_weight_decay)
optim.load_state_dict(state['optimizer'])
</code>```

Besides these, you may also want to save your learning rate if you are using a learning rate decay strategy, your best validation accuracy so far which you may want for checkpointing purposes, and any other changeable parameter which might affect your training. But in most of the cases, saving and loading just the model weights and optimizer state should be sufficient.

EDIT: You may also want to look at this following answer which explains in detail how you should save your model in different scenarios.

Body:
I have a model architecture. I have saved the entire model using torch.save() for some n number of iterations. I want to run another iteration of my code by using the pre-trained weights of the model I saved previously.

Edit: I want the weight initialization for the new iteration be done from the weights of the pretrained model

Edit 2: Just to add, I don't plan to resume training. I intend to save the model and use it for a separate training with same parameters. Think of it like using a saved model with weights etc. for a larger run and more samples (i.e. a complete new training job)

Right now, I do something like:

# default_lr = 5
# default_weight_decay = 0.001
# model_io = the pretrained model
model = torch.load(model_io)
optim = torch.optim.Adam(model.parameters(),lr=default_lr, weight_decay=default_weight_decay)
loss_new = BCELoss()
epochs = default_epoch
.
.
training_loop():
....
outputs = model(input)
....
.
#similarly for test loop

Am I missing something? I have to run for a very long epoch for a huge number of sample so can not afford to wait to see the results then figure out things.

Thank you!

Body:
From the code that you have posted, I see that you are only loading the previous model parameters in order to restart your training from where you left it off. This is not sufficient to restart your training correctly. Along with your model parameters (weights), you also need to save and load your optimizer state, especially when your choice of optimizer is Adam which has velocity parameters for all your weights that help in decaying the learning rate.

In order to smoothly restart training, I would do the following:

# For saving your model

state = {
    'model': model.state_dict(),
    'optimizer': optimizer.state_dict()
}
model_save_path = "Enter/your/model/path/here/model_name.pth"
torch.save(state, model_save_path)

# ------------------------------------------

# For loading your model
state = torch.load(model_save_path)

model = MyNetwork()
model.load_state_dict(state['model'])

optim = torch.optim.Adam(model.parameters(),lr=default_lr, weight_decay=default_weight_decay)
optim.load_state_dict(state['optimizer'])

Besides these, you may also want to save your learning rate if you are using a learning rate decay strategy, your best validation accuracy so far which you may want for checkpointing purposes, and any other changeable parameter which might affect your training. But in most of the cases, saving and loading just the model weights and optimizer state should be sufficient.

EDIT: You may also want to look at this following answer which explains in detail how you should save your model in different scenarios.


问:
Cannot import name 'Imputer' from 'sklearn.preprocessing' from pandas_ml
I am working on a project for my master and I was trying to get some stats on my calculations. I found a very cool tool to do this, called panda_ml, but when I import it in my cell on jupyter like this:

```<code>from pandas_ml import *
</code>```

It gives me this output error:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-118-93009f7254d4> in <module>
      3 from sklearn import *
      4 from matplotlib.colors import LogNorm
----> 5 from pandas_ml import *
      6 import math
      7

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/__init__.py in <module>
      1 #!/usr/bin/env python
      2
----> 3 from pandas_ml.core import ModelFrame, ModelSeries       # noqa
      4 from pandas_ml.tools import info                         # noqa
      5 from pandas_ml.version import version as __version__     # noqa

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/core/__init__.py in <module>
      1 #!/usr/bin/env python
      2
----> 3 from pandas_ml.core.frame import ModelFrame       # noqa
      4 from pandas_ml.core.series import ModelSeries     # noqa

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/core/frame.py in <module>
      8
      9 import pandas_ml.imbaccessors as imbaccessors
---> 10 import pandas_ml.skaccessors as skaccessors
     11 import pandas_ml.smaccessors as smaccessors
     12 import pandas_ml.snsaccessors as snsaccessors

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/skaccessors/__init__.py in <module>
     17 from pandas_ml.skaccessors.neighbors import NeighborsMethods                      # noqa
     18 from pandas_ml.skaccessors.pipeline import PipelineMethods                        # noqa
---> 19 from pandas_ml.skaccessors.preprocessing import PreprocessingMethods              # noqa
     20 from pandas_ml.skaccessors.svm import SVMMethods                                  # noqa

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/skaccessors/preprocessing.py in <module>
     11     _keep_col_classes = [pp.Binarizer,
     12                          pp.FunctionTransformer,
---> 13                          pp.Imputer,
     14                          pp.KernelCenterer,
     15                          pp.LabelEncoder,

AttributeError: module 'sklearn.preprocessing' has no attribute 'Imputer'
</code>```

I am using Conda, I have my own env with all the packages, I have tried to install older versions of sklearn and pandas_ml but it did not solve the problem. I've searching around but it seems that no one had ever this problem...Do you have any suggestion?

答: I had scikit-learn version 0.22.1 installed recently and had a similar problem. Then I tried your solution under Python 3.7.2, maintained the versions for Pandas v0.25.1 and Pandas ML v0.6.1 and it work like a charm!. I wonder when would be it safe to turn to a newer version of scikit-learn

Body:
I am working on a project for my master and I was trying to get some stats on my calculations. I found a very cool tool to do this, called panda_ml, but when I import it in my cell on jupyter like this:

from pandas_ml import *

It gives me this output error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-118-93009f7254d4> in <module>
      3 from sklearn import *
      4 from matplotlib.colors import LogNorm
----> 5 from pandas_ml import *
      6 import math
      7

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/__init__.py in <module>
      1 #!/usr/bin/env python
      2
----> 3 from pandas_ml.core import ModelFrame, ModelSeries       # noqa
      4 from pandas_ml.tools import info                         # noqa
      5 from pandas_ml.version import version as __version__     # noqa

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/core/__init__.py in <module>
      1 #!/usr/bin/env python
      2
----> 3 from pandas_ml.core.frame import ModelFrame       # noqa
      4 from pandas_ml.core.series import ModelSeries     # noqa

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/core/frame.py in <module>
      8
      9 import pandas_ml.imbaccessors as imbaccessors
---> 10 import pandas_ml.skaccessors as skaccessors
     11 import pandas_ml.smaccessors as smaccessors
     12 import pandas_ml.snsaccessors as snsaccessors

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/skaccessors/__init__.py in <module>
     17 from pandas_ml.skaccessors.neighbors import NeighborsMethods                      # noqa
     18 from pandas_ml.skaccessors.pipeline import PipelineMethods                        # noqa
---> 19 from pandas_ml.skaccessors.preprocessing import PreprocessingMethods              # noqa
     20 from pandas_ml.skaccessors.svm import SVMMethods                                  # noqa

~/anaconda3/envs/Lab1_B/lib/python3.7/site-packages/pandas_ml/skaccessors/preprocessing.py in <module>
     11     _keep_col_classes = [pp.Binarizer,
     12                          pp.FunctionTransformer,
---> 13                          pp.Imputer,
     14                          pp.KernelCenterer,
     15                          pp.LabelEncoder,

AttributeError: module 'sklearn.preprocessing' has no attribute 'Imputer'

I am using Conda, I have my own env with all the packages, I have tried to install older versions of sklearn and pandas_ml but it did not solve the problem. I've searching around but it seems that no one had ever this problem...Do you have any suggestion?


问:
Override a method in a single object instance
Am not sure how to put this, and I couldn't find the answer because of my inability to find the words to express what am looking for. (!)

In Java, I used to do something like this (I don't remember):

```<code>JPanel myButton = new JPanel("Press me"){
    public void add(JComponent component){
        //override add method
    }
};
</code>```

But, i couldn't find how to do this in Objective-C .. What I found in my search was categories and weird ^{} symbols ...

So, how can I override method(s) in a newly created object?

(For example, override -(BOOL)isEqual; in a newly created NSString* ?)

Am sorry if the question is a bit vague..

EDIT:

Obviously, without subclassing :)

EDIT:

Might as well post my problem in case someone has a better idea:

I have a few CCTransitions in COCOS2D, and I want to be notified when the transition ends .. The thing is, as soon as the transition ends, the -(void)finish; method is invoked (which is part of the CCTransition class structure)

I would really want to avoid subclassing the CCTransition class, and override the finish method to do my logic when the transition ends :)

EDIT:

-(void)onEnterTransitionDidFinish; ... I can't believe something as awesome as that existed and I haven't came across it while searching......

Which means, instead of subclassing CCTransition, override this method in my CCNode subclass :D!

答:
It's still not going to be very clean, but assuming you're willing to concentrate the ugliness, you could do something like (untested):

```<code>Method methodToReplace =
          [targetClass instanceMethodSignatureForSelector:@selector(methodToReplace)];
IMP implementationToSet =
          [someProxyClass instanceMethodForSelector:@selector(implementationYouWant)];

method_setImplementation(methodToReplace, implementationToSet);
</code>```

Relevant reference documentation is the Objective-C Runtime Reference and, optionally, the NSObject Class Reference (because it makes a few things slightly neater, though e.g. you could use class_getInstanceMethod from the runtime rather than instanceMethodSigntureForSelector:).

Note that you'll have no way to call the original implementation if you use exactly that recipe. method_setImplementation returns the old implementation, it's generally wise to add that to the class under a brand new selector and call that instead.

For reference, I've had a legitimate reason to do this sort of thing only exactly once: when we implemented printing support in an iOS application with which needed to be compatible with both OS 3.2 and 4.0. You need to subclass a particular class, but the class isn't available in 3.2. So you sort of have to subclass at runtime (though the conceptually neater way would be to use a normal subclass, put that into a framework and weak link, but Apple's iOS SDK terms allow static libraries only, so...).

Body:
Am not sure how to put this, and I couldn't find the answer because of my inability to find the words to express what am looking for. (!)

In Java, I used to do something like this (I don't remember):

JPanel myButton = new JPanel("Press me"){
    public void add(JComponent component){
        //override add method
    }
};

But, i couldn't find how to do this in Objective-C .. What I found in my search was categories and weird ^{} symbols ...

So, how can I override method(s) in a newly created object?

(For example, override -(BOOL)isEqual; in a newly created NSString* ?)

Am sorry if the question is a bit vague..

EDIT:

Obviously, without subclassing :)

EDIT:

Might as well post my problem in case someone has a better idea:

I have a few CCTransitions in COCOS2D, and I want to be notified when the transition ends .. The thing is, as soon as the transition ends, the -(void)finish; method is invoked (which is part of the CCTransition class structure)

I would really want to avoid subclassing the CCTransition class, and override the finish method to do my logic when the transition ends :)

EDIT:

-(void)onEnterTransitionDidFinish; ... I can't believe something as awesome as that existed and I haven't came across it while searching......

Which means, instead of subclassing CCTransition, override this method in my CCNode subclass :D!

Body:
It's still not going to be very clean, but assuming you're willing to concentrate the ugliness, you could do something like (untested):

Method methodToReplace =
          [targetClass instanceMethodSignatureForSelector:@selector(methodToReplace)];
IMP implementationToSet =
          [someProxyClass instanceMethodForSelector:@selector(implementationYouWant)];

method_setImplementation(methodToReplace, implementationToSet);

Relevant reference documentation is the Objective-C Runtime Reference and, optionally, the NSObject Class Reference (because it makes a few things slightly neater, though e.g. you could use class_getInstanceMethod from the runtime rather than instanceMethodSigntureForSelector:).

Note that you'll have no way to call the original implementation if you use exactly that recipe. method_setImplementation returns the old implementation, it's generally wise to add that to the class under a brand new selector and call that instead.

For reference, I've had a legitimate reason to do this sort of thing only exactly once: when we implemented printing support in an iOS application with which needed to be compatible with both OS 3.2 and 4.0. You need to subclass a particular class, but the class isn't available in 3.2. So you sort of have to subclass at runtime (though the conceptually neater way would be to use a normal subclass, put that into a framework and weak link, but Apple's iOS SDK terms allow static libraries only, so...).


问:
What is proper way to detect device in Next.js SSR?
I have <MobileLayout />, <DesktopLayout />. I'm using Next.js for Server Side Rendering.
And I noticed there are many famous ui library has mobile detection components like <Respnosive /> component in Semantic-UI-React. But all of this is client side method, not working properly on SSR

I read some documents the conclusion is I should check user-agent of server side req.headers. In Next.js, What is proper way to detect device and conditonally render one of MobileLayout / DesktopLayout?

What I tried

in _app.js

```<code>import isMobile from 'ismobilejs'

...

function Homepage({ Component, pageProps, mobile }){
  return (
    mobile ?
      <MobileLayout><Component {...pageProps} /></MobileLayout> :
      <DesktopLayout><Component {...pageProps} /></DesktopLayout>
  )
}

HomePage.getInitialProps = async (appContext) => {
  const userAgent = appContext.ctx.req.headers['user-agent']
  const mobile = isMobile(userAgent).any
  const appProps = await App.getInitialProps(appContext)
  return { ...appProps, mobile }
}
</code>```

But the problem is getIntialProps on _app.js executed every page load. with moving page with client, the appContext.ctx is undefined so it will omit error. and I think this method might block some nextjs builtin optimizations.

Error in error page getInitialProps:  TypeError: Cannot read
  property 'headers' of undefined

So what is propery way to check device in Next.js?

答:
If you want to detect the user's device using userAgent, your best bet is this answer:

```<code>IndexPage.getInitialProps = ({ req }) => {
  let userAgent;
  if (req) { // if you are on the server and you get a 'req' property from your context
    userAgent = req.headers['user-agent'] // get the user-agent from the headers
  } else {
    userAgent = navigator.userAgent // if you are on the client you can access the navigator from the window object
  }
}
</code>```

(Note you should actually be using getServerSideProps or getStaticProps when possible, if you have Next 9.3 or newer, but sometimes there is no replacement for the getInitialProps functionality.)

However, the folks at Mozilla advise:

It's worth re-iterating: it's very rarely a good idea to use user
  agent sniffing. You can almost always find a better, more broadly
  compatible way to solve your problem!

The maker of the isMobile package you're importing even warns:

You might not need this library. In most cases, responsive design
  solves the problem of controlling how to render things across
  different screen sizes.

So, see if you can use CSS3 media queries to conditionally render certain elements or change their size, etc., rather than having completely separate mobile and desktop layout components. But it's possible you have an edge case where you can't make any alternative option work.

If you are going to keep your current setup and use your two layouts on other pages, you might consider combining them into a parent <Layout> component that conditionally renders one or the other so you don't have to copy that logic into every page:

```<code>export const Layout = (props) => {
      return (
          props.mobile ?
          <MobileLayout>{props.children}</MobileLayout> :
          <DesktopLayout>{props.children}</DesktopLayout>
      )
}
</code>```

Body:
I have <MobileLayout />, <DesktopLayout />. I'm using Next.js for Server Side Rendering.
And I noticed there are many famous ui library has mobile detection components like <Respnosive /> component in Semantic-UI-React. But all of this is client side method, not working properly on SSR

I read some documents the conclusion is I should check user-agent of server side req.headers. In Next.js, What is proper way to detect device and conditonally render one of MobileLayout / DesktopLayout?

What I tried

in _app.js

import isMobile from 'ismobilejs'

...

function Homepage({ Component, pageProps, mobile }){
  return (
    mobile ?
      <MobileLayout><Component {...pageProps} /></MobileLayout> :
      <DesktopLayout><Component {...pageProps} /></DesktopLayout>
  )
}

HomePage.getInitialProps = async (appContext) => {
  const userAgent = appContext.ctx.req.headers['user-agent']
  const mobile = isMobile(userAgent).any
  const appProps = await App.getInitialProps(appContext)
  return { ...appProps, mobile }
}

But the problem is getIntialProps on _app.js executed every page load. with moving page with client, the appContext.ctx is undefined so it will omit error. and I think this method might block some nextjs builtin optimizations.

Error in error page getInitialProps:  TypeError: Cannot read
  property 'headers' of undefined

So what is propery way to check device in Next.js?

Body:
If you want to detect the user's device using userAgent, your best bet is this answer:

IndexPage.getInitialProps = ({ req }) => {
  let userAgent;
  if (req) { // if you are on the server and you get a 'req' property from your context
    userAgent = req.headers['user-agent'] // get the user-agent from the headers
  } else {
    userAgent = navigator.userAgent // if you are on the client you can access the navigator from the window object
  }
}

(Note you should actually be using getServerSideProps or getStaticProps when possible, if you have Next 9.3 or newer, but sometimes there is no replacement for the getInitialProps functionality.)

However, the folks at Mozilla advise:

It's worth re-iterating: it's very rarely a good idea to use user
  agent sniffing. You can almost always find a better, more broadly
  compatible way to solve your problem!

The maker of the isMobile package you're importing even warns:

You might not need this library. In most cases, responsive design
  solves the problem of controlling how to render things across
  different screen sizes.

So, see if you can use CSS3 media queries to conditionally render certain elements or change their size, etc., rather than having completely separate mobile and desktop layout components. But it's possible you have an edge case where you can't make any alternative option work.

If you are going to keep your current setup and use your two layouts on other pages, you might consider combining them into a parent <Layout> component that conditionally renders one or the other so you don't have to copy that logic into every page:

export const Layout = (props) => {
      return (
          props.mobile ?
          <MobileLayout>{props.children}</MobileLayout> :
          <DesktopLayout>{props.children}</DesktopLayout>
      )
}


问:
boto3 Lambda create_function
I have a zip file containing my lambda handler, but I don't know how to specify it as part of the Code parameter. The documentation says to use a ZipFile entry in the Code dictionary parameter, but how am I supposed to convert the zip file I have into "the base64 encoded contents"?

Here is the link to the doc

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.create_function

Thanks for any help!

答:
No, you don't need to encode it yourself, boto3 handles it for you.

ZipFile (bytes) --
  The base64-encoded contents of the deployment package. AWS SDK and AWS CLI clients handle the encoding for you.

Check out some examples here.

Title: boto3 Lambda create_function


问:
How do you display legends to zero decimal places when rounding fails?
I can't create an MWE that is reproducible - this snapshot shows the output I am having trouble with.

I want to create labels for a plot legend (matplotlib) from this, but I need it to have zero decimal places.   Is there a more reliable form of round where you can force zero decimal places? Or, is there another way to get this working?  I don't want to create the list manually because the values I am plotting, and the functions that form them, will change.

I did try to assign the output of the plot_R(thetaValues[40])*1e6 and then round that, but that didn't work either.  I also tried calling round twice in case that would work.  Interestingly, it is rounding to 0 decimal place (if you round to 1 the output is 160.3), it's just still printing the ".0"

答:
If you want to truncate the decimal, you could do:

```<code>decimal_round = round(plot_R(thetaValues[40])*1e6)
str_decimal = str(decimal_round)
if "." in str_decimal:
    decimal_round = int(str_decimal[:str_decimal.index(".")])
</code>```

This finds the index of the decimal pt, slices the string representation to drop the decimal point and everything after, and then re-converts to an int.

Hope that helps, Happy Coding!

Body:
If you want to truncate the decimal, you could do:

decimal_round = round(plot_R(thetaValues[40])*1e6)
str_decimal = str(decimal_round)
if "." in str_decimal:
    decimal_round = int(str_decimal[:str_decimal.index(".")])

This finds the index of the decimal pt, slices the string representation to drop the decimal point and everything after, and then re-converts to an int.

Hope that helps, Happy Coding!


问:
How can I find the isnull() value in CSV file?
```<code>In[17]: train_data.isnull()
Out[17]:
       Category  Title
0         False  False
1         False  False
2         False  False
3         False  False
4         False  False
        ...    ...
98013     False  False
98014     False  False
98015     False  False
98016     False  False
98017     False  False

[98018 rows x 2 columns]

In [18]: print(train_data.isnull().sum())
Category    0
Title       1
dtype: int64
</code>```

In train_data, there is one null value in csv file.
I need to find a null value and remove it.

答:
If you know the NA value is in the field Title

```<code>train_data.dropna(subset=['Title'])
</code>```

If you want to remove all NAs

```<code>train_data.dropna()
</code>```

View columns with NA

```<code>train_data.isna().any()
</code>```

If you want to view the NA values

```<code>train_data[train_data.isna().any(axis=1)]
</code>```

Body:
In[17]: train_data.isnull()
Out[17]:
       Category  Title
0         False  False
1         False  False
2         False  False
3         False  False
4         False  False
        ...    ...
98013     False  False
98014     False  False
98015     False  False
98016     False  False
98017     False  False

[98018 rows x 2 columns]

In [18]: print(train_data.isnull().sum())
Category    0
Title       1
dtype: int64

In train_data, there is one null value in csv file.
I need to find a null value and remove it.

Body:
If you know the NA value is in the field Title

train_data.dropna(subset=['Title'])

If you want to remove all NAs

train_data.dropna()

View columns with NA

train_data.isna().any()

If you want to view the NA values

train_data[train_data.isna().any(axis=1)]


问:
crystal report use Maximum as Sum condition problem
I met a problem with sum function:
the data have a datetime column and I want to get sum of who's datetime is max. And also there's anoher group condition.
So I do like:

Add formula maxDatetime: Maximum({datetime}, {groupcondition})

Add new formula for sum ValueToSum: if({datetime} = {@maxDatetime}) then value else 0

Sum the value, add new formula totalValue: Sum({@valueToSum}, {groupcondition})

The result is the sum can't be processed, it says: 'valueToSum can't be sumed'.

I think the causor may be using a maximum value as a condition in step 2. Because when use 1 = 1 to replace the condition, there's no problem.

Can anyone give some advice?

答:
We usually solve such kind of problems by creating additional queries and linking them to main data. Because Crystal Reports does only two passes over data - record reading and aggregate calculation, it can't easily aggregate over already aggregated values.

Another possibility is to accumulate your 'totalvalue' into variable. Something like next may work (needs tweaking probably):

```<code>WhilePrintingRecords();
NumberVar totalvalue;
If ({datetime} = Maximum({datetime}, {groupcondition}))
then totalvalue:=totalvalue+value
else 0
</code>```

This formula (which displays totalvalue) needs to placed into group footer:

```<code>WhilePrintingRecords();
NumberVar totalvalue
</code>```

Somewhere in group header you need another one to reset totalvalue:

```<code>WhilePrintingRecords();
NumberVar totalvalue:=0
</code>```

Body:
We usually solve such kind of problems by creating additional queries and linking them to main data. Because Crystal Reports does only two passes over data - record reading and aggregate calculation, it can't easily aggregate over already aggregated values.

Another possibility is to accumulate your 'totalvalue' into variable. Something like next may work (needs tweaking probably):

WhilePrintingRecords();
NumberVar totalvalue;
If ({datetime} = Maximum({datetime}, {groupcondition}))
then totalvalue:=totalvalue+value
else 0

This formula (which displays totalvalue) needs to placed into group footer:

WhilePrintingRecords();
NumberVar totalvalue

Somewhere in group header you need another one to reset totalvalue:

WhilePrintingRecords();
NumberVar totalvalue:=0


问:
Find the count of IDs that have the same value
I'd like to get a count of all of the Ids that have have the same value (Drops) as other Ids. For instance, the illustration below shows you that ID 1 and 3 have A drops so the query would count them. Similarly, ID 7 & 18 have B drops so that's another two IDs that the query would count totalling in 4 Ids that share the same values so that's what my query would return.

```<code>+------+-------+
| ID   | Drops |
+------+-------+
|  1   |   A   |
|  2   |   C   |
|  3   |   A   |
|  7   |   B   |
| 18   |   B   |
+------+-------+
</code>```

I've tried the several approaches but the following query was my last attempt.

```<code>With cte1 (Id1, D1) as
(
    select Id, Drops
    from Posts
),
cte2 (Id2, D2) as
(
    select Id, Drops
    from Posts
)
Select count(distinct c1.Id1) newcnt, c1.D1
from cte1 c1
left outer join cte2 c2 on c1.D1 = c2.D2
group by c1.D1
</code>```

The result if written out in full would be a single value output but the records that the query should be choosing should look as follows:

```<code>    +------+-------+
    | ID   | Drops |
    +------+-------+
    |  1   |   A   |
    |  3   |   A   |
    |  7   |   B   |
    | 18   |   B   |
    +------+-------+
</code>```

Any advice would be great. Thanks

答:
You may use dense_rank() to resolve your problem. if drops has the same ID then dense_rank() will provide the same rank.

Here is the demo.

```<code>with cte as
(
  select
    drops,
    count(distinct rnk) as newCnt
  from
  ( select
        *,
        dense_rank() over (partition by drops order by id) as rnk
    from myTable
  ) t
  group by
    drops
  having count(distinct rnk) > 1
)

select
    sum(newCnt) as newCnt
from cte
</code>```

Output:

```<code>   |newcnt |
   |------ |
   | 4     |
</code>```

Body:
I'd like to get a count of all of the Ids that have have the same value (Drops) as other Ids. For instance, the illustration below shows you that ID 1 and 3 have A drops so the query would count them. Similarly, ID 7 & 18 have B drops so that's another two IDs that the query would count totalling in 4 Ids that share the same values so that's what my query would return.

+------+-------+
| ID   | Drops |
+------+-------+
|  1   |   A   |
|  2   |   C   |
|  3   |   A   |
|  7   |   B   |
| 18   |   B   |
+------+-------+

I've tried the several approaches but the following query was my last attempt.

With cte1 (Id1, D1) as
(
    select Id, Drops
    from Posts
),
cte2 (Id2, D2) as
(
    select Id, Drops
    from Posts
)
Select count(distinct c1.Id1) newcnt, c1.D1
from cte1 c1
left outer join cte2 c2 on c1.D1 = c2.D2
group by c1.D1

The result if written out in full would be a single value output but the records that the query should be choosing should look as follows:

    +------+-------+
    | ID   | Drops |
    +------+-------+
    |  1   |   A   |
    |  3   |   A   |
    |  7   |   B   |
    | 18   |   B   |
    +------+-------+

Any advice would be great. Thanks

Body:
You may use dense_rank() to resolve your problem. if drops has the same ID then dense_rank() will provide the same rank.

Here is the demo.

with cte as
(
  select
    drops,
    count(distinct rnk) as newCnt
  from
  ( select
        *,
        dense_rank() over (partition by drops order by id) as rnk
    from myTable
  ) t
  group by
    drops
  having count(distinct rnk) > 1
)

select
    sum(newCnt) as newCnt
from cte

Output:

   |newcnt |
   |------ |
   | 4     |


问:
How to reduce time taken by tooltipValueGetter in ag Grid?
```<code> var ColDef = [{
        headerName: "colA",
        field: 'colA',
        rowGroup: true
      },
      {
        headerName: "colB",
        field: 'colB',
        pivot: true,
        enablePivot: true
      },
      {
        headerName: "colC",
        field: 'colC',
        rowGroup: true
      },
      {
        field: 'colD',
        aggFunc: 'last',
    tooltipValueGetter: commentTooltipValueGetter
      },
      {
        field: 'comment'
      },
      {
        field: 'colF'
      }
    ];

    function commentTooltipValueGetter(params) {
    const colB = params.colDef.pivotKeys[0];
    var model = params.api.getDisplayedRowAtIndex(params.rowIndex);
    for (var i = 0; i < model.allLeafChildren.length ; i++) {
        if (model.allLeafChildren[i].data.colB=== colB) {
          return model.allLeafChildren[i].data.comments;
                                                       }
                                             }
  }
</code>```

<p>For me when i hover over colD i get the comments as tooltip. but they take like 2-3 seconds to come up. Any way to reduce this time? Also my agGrid is pivot and group ag Grid not the normal one. Please take that into consideration when suggesting answers.
I have been already using tooltipShowDelay before i asked this question, looks like sometimes its very fast and sometimes it takes couple of seconds hovering for the tooltipValueGetter to do its magic </p>

答:
It doesn't look like you are doing a lot of processing, so ideally it should take less time.

From v23.1.0, ag-grid has provided this gridOption,  tooltipShowDelay = 0;

AG-2968   [Feature Request]   23.1.0  Allow configuring how long it
  takes a tooltip to popup

From docs -

By default, when you hover on an item, it will take 2 seconds for the
  tooltip to be displayed. If you need to change this delay, the
  tooltipShowDelay config should be used, which is set in milliseconds.

https://www.ag-grid.com/javascript-grid-tooltip-component/#tooltip-show-delay

Body:
 var ColDef = [{
        headerName: "colA",
        field: 'colA',
        rowGroup: true
      },
      {
        headerName: "colB",
        field: 'colB',
        pivot: true,
        enablePivot: true
      },
      {
        headerName: "colC",
        field: 'colC',
        rowGroup: true
      },
      {
        field: 'colD',
        aggFunc: 'last',
    tooltipValueGetter: commentTooltipValueGetter
      },
      {
        field: 'comment'
      },
      {
        field: 'colF'
      }
    ];

    function commentTooltipValueGetter(params) {
    const colB = params.colDef.pivotKeys[0];
    var model = params.api.getDisplayedRowAtIndex(params.rowIndex);
    for (var i = 0; i < model.allLeafChildren.length ; i++) {
        if (model.allLeafChildren[i].data.colB=== colB) {
          return model.allLeafChildren[i].data.comments;
                                                       }
                                             }
  }

For me when i hover over colD i get the comments as tooltip. but they take like 2-3 seconds to come up. Any way to reduce this time? Also my agGrid is pivot and group ag Grid not the normal one. Please take that into consideration when suggesting answers.
I have been already using tooltipShowDelay before i asked this question, looks like sometimes its very fast and sometimes it takes couple of seconds hovering for the tooltipValueGetter to do its magic


问:
How to upload file in Sharepoint using .net core with C#?
I want to upload file in my sharepoint using .net core c#, but I would't find the microsoft dll or CSOM package in .net core. PLease let me know if you have something that can work in .net core with C#.</p>

答:
Microsoft haven't released official .NET Core CSOM Library, please see the UserVoice, the status is still "Working On it":

Support .NET Core with CSOM

Nowadays, it's suggested to use .NET Standard platform instead if possible


问:
Show tooltips when cell receives focus
Is there any way to have the tooltips display when a cell receives focus? If a user uses the keyboard exclusively to navigate then the tooltips do not display when the user tabs to a cell or navigates to it with the keyboard</p>

答:
The built-in tooltip functionality is pretty basic, and not really customizable.
The only solution that I can think of is to write custom cell renderers that handle tooltips the way that you want.</p>

Title: Show tooltips when cell receives focus


问:
Prohibit Office365 group members from editing SharePoint layouts on Sharepoint Teams and Microsoft Teams
How do we avoid Office 365 group based Team channel or SharePoint Team guests/members from editing the SharePoint UI side of things (pages, navigation) while still participating in document library etc?  I'm more worried about guests, but team members can cause havoc too.

Example 1: Guests are included in Azure AD.  You create a new SharePoint Team site, which creates a new O365 group.  When you add Azure AD members and guests to this group, they can all edit the navigation / pages etc.  But we just want them to use the site as is.

Example 2: Guest access is on for Microsoft Teams.  You create a new Team, guests in Azure AD are included.  They use the web app, open the General Team channel and choose "Open in SharePoint".  At this point top navigation has the gear for Office 365 to add a page, site contents, site settings, etc.  They can do a lot of damage.

What step is necessary to add this restriction?  This looks to be the solution:
https://sharepointmaven.com/how-to-prevent-team-site-members-from-editing-sharepoint-pages/
But this is from a while back, and not part of the new Microsoft 365 admin UI.  Since these are brand new sites, I'm trying to create them as simply as possible without any artifacts or messing up new integration features.

If you have any ideas or have dealt with a similar situation, please advise.

thanks!!

[Edit - here's what worked for me based on alphaz18 suggested answer]:

1) Directly on the entire site collection level eg tenant.sharepoint.com/sites/teamname/ edit site permission levels

2) Remove some list permissions from "Edit": [Manage, add, edit, delete]. Submit.

3) Go back into "Edit" permission, at the bottom of this cloned permission, choose "Copy Permission Level", call new version (e.g.) "EditLists". RE-check the [add, edit, delete] options for this cloned permission level. Submit.

4) Go to a page you want edits to occur in (e.g.) Documents view (/Shared%20Documents/Forms/AllItems.aspx). Click top right gear, choose "Library settings".  Click "Permissions for this document library".

5) Break inheritance.

6) For Members group edit user permissions, set to cloned permission (eg) "EditItems"

答:
You can absolutely change the permission levels for different users and groups in sharepoint online for msTeams Created Sharepoint sites and your own.

if you are a site collection owner, just click the gear on top, click site permissions.
then click advanced permissions, and you can have the classic permissions panel, then you click permission levels and create one that fits your needs, eg just allow them to add items from lists for example. or whatever it is you want to allow them to do.
as long as you dont allow them to edit pages and such should be fine.
then assign the permission level to either team members or add more groups or whatever you want.

Hopefully this is what you're after,
Regards,


问:
Typescript: how to stub function from imported namespace
I have the following files

```<code>// definition file
export namespace Foo {
  export function foo() {
    bar();
  }
  export function bar() {
    throw 'not implemented yet'
  }
}

// test file
import { Foo } from 'fooFile'
describe('', () => {
  it('', () => {
    const sandbox = sinon.createSandbox();
    sandbox.stub(Foo, 'bar');
    Foo.foo(); // expected not to throw since I stubbed bar
  });
});
</code>```

and I don't know why it still throws. so far I've been able to stub functions imported from file with no namespace (import * as Foo from), methods and static methods from class, but I can't find the syntax for this stub.

答:
Variable bar inside function foo() actually refers to local scope variable bar, but is undefined and then use global variable, which is defined. (Reference)

AFAIK, You can not create stub from variable inside function.

How to make sure that you call function bar() inside Foo namespace? Use this.bar() or Foo.bar(). Then now, your stub to method bar from namespace Foo can work in your test file (you have created stub correctly).

For example, file foo.ts

export namespace Foo {
  export function foo() {
    this.bar(); // Or use: Foo.bar().
  }
  export function bar() {
    throw 'not implemented yet'
  }
}
```

<p>test file: stackoverflow.test.ts</p>

<pre class="lang-js prettyprint-override"><code>import sinon from 'sinon';
import { expect } from 'chai';

import { Foo } from './foo';

describe('', function () {
  it('', function () {
    const stubFooBar = sinon.stub(Foo, 'bar');

    Foo.foo();

    expect(stubFooBar.calledOnce).to.equal(true);
    stubFooBar.restore();
  });
});

</code>```

When I run it using mocha.

```<code>$ npx ts-mocha stackoverflow.test.ts --exit

    ✓

  1 passing (6ms)

$
</code>```

Hope this helps.

Body:
I have the following files

// definition file
export namespace Foo {
  export function foo() {
    bar();
  }
  export function bar() {
    throw 'not implemented yet'
  }
}

// test file
import { Foo } from 'fooFile'
describe('', () => {
  it('', () => {
    const sandbox = sinon.createSandbox();
    sandbox.stub(Foo, 'bar');
    Foo.foo(); // expected not to throw since I stubbed bar
  });
});

and I don't know why it still throws. so far I've been able to stub functions imported from file with no namespace (import * as Foo from), methods and static methods from class, but I can't find the syntax for this stub.

Body:
Variable bar inside function foo() actually refers to local scope variable bar, but is undefined and then use global variable, which is defined. (Reference)

AFAIK, You can not create stub from variable inside function.

How to make sure that you call function bar() inside Foo namespace? Use this.bar() or Foo.bar(). Then now, your stub to method bar from namespace Foo can work in your test file (you have created stub correctly).

For example, file foo.ts

export namespace Foo {
  export function foo() {
    this.bar(); // Or use: Foo.bar().
  }
  export function bar() {
    throw 'not implemented yet'
  }
}

test file: stackoverflow.test.ts

import sinon from 'sinon';
import { expect } from 'chai';

import { Foo } from './foo';

describe('', function () {
  it('', function () {
    const stubFooBar = sinon.stub(Foo, 'bar');

    Foo.foo();

    expect(stubFooBar.calledOnce).to.equal(true);
    stubFooBar.restore();
  });
});

When I run it using mocha.

$ npx ts-mocha stackoverflow.test.ts --exit

    ✓

  1 passing (6ms)

$

Hope this helps.


问:
How to register new device on IoT hub using REST Api
I am developing mobile application (android).I want to register new device on IoT hub Using REST API or SDK.The registration process will done by mobile application.for ex smartband.
Most of available link on google showing azure CLI process to create device.but I want to create new device programatically using REST API.

Can we use device provision service for register new device ?

I am new in azure service.

答:
You could create or update the identity of a device in the identity registry of an IoT hub by following Service - Create Or Update Device.

```<code>PUT https://fully-qualified-iothubname.azure-devices.net/devices/{id}?api-version=2019-07-01-preview
Authorization: Token
{
  "deviceId": "{device id}"
}
</code>```

For how to get the Token, please refer to Authentication.

Body:
You could create or update the identity of a device in the identity registry of an IoT hub by following Service - Create Or Update Device.

PUT https://fully-qualified-iothubname.azure-devices.net/devices/{id}?api-version=2019-07-01-preview
Authorization: Token
{
  "deviceId": "{device id}"
}

For how to get the Token, please refer to Authentication.


问:
How long a rollbacked message is kept in a Kafka topic
I came across with this scenario when implementing a chained transaction manager inside our spring boot application interacting with consuming messages from JMS then publishing to a Kafka topic.
My testing strategy was explained on here:
Unable to synchronise Kafka and MQ transactions usingChainedKafkaTransaction

In short I threw a RuntimeException on purpose after consuming messages from MQ and writing them to Kafka just to test transaction behaviour.

However as the rollback functionality worked OK I could see the number of uncommitted messages in the Kafka topic growing forever even if a rollback was happening with each processing. In a few seconds I ended up with hundreds of uncommitted messages in the topic.

Naturally I asked myself if a message is rollbacked why would it still be there taking storage. I understand with transaction isolation set to read_committed they will never get consumed but the idea of a poison message being rollbacked again and again eating up your storage does not sound right to me.

So my question is:
Am I missing something? Is there a configuration in place for a "time to live" or similar for a message that was rollbacked. I tried to read the Kafka docs around this subject but I could not find anything. Is such a setting is not in place what would be a good practice to deal with situations like this and avoid wasting storage.

Thank you in advance for your inputs.

答:
That's just the way Kafka works.

Publishing a record always takes a slot in the partition log. Whether or not a consumer can see that record depends on whether it is committed or not (assuming the isolation level is read_committed).

Kafka achieves its extraordinary throughput because of its simple log architecture.

Rollback is assumed to be somewhat rare.

If you are getting so many rollbacks then your application architecture is probably at fault.

You should probably shut things down for a while if you keep rolling back.

To specifically answer your question, see log-rentention-hours.

The uncommitted records are kept for a week by default.