问:
Insert trigger doesnt do what i want it to do
i made a trigger which should avoid inserting a record  in the  rental 'uitlening' table if the person has an overdue payment (Boete). Unfortunately it doesnt work and i cant find the reason why. 'Boete' is an attribute of another table than rental. Can someone help me?

CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [dbo].[Uitlening]
FOR INSERT
AS
BEGIN
    DECLARE @Boete decimal(10, 2);

    SET @Boete = (SELECT Boete FROM Lid WHERE LidNr = (SELECT LidNr FROM inserted));
    IF @Boete = 0
    BEGIN
        INSERT INTO Uitlening
        SELECT *
        FROM inserted;
    END;
END;
```

答:
It sounds like what you actually need is a cross-table constraint.

You can either do this by throwing an error in the trigger:

CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [Rental]
AFTER INSERT
AS

SET NOCOUNT ON;

IF EXISTS (SELECT 1
    FROM inserted i
    INNER JOIN dbo.Person p ON i.[personID] = p.[personID]
    WHERE p.[PaymentDue] <= 0
)
    THROW 50001, 'PaymentDue is less than 0', 1;
```
<hr />
<p>A better solution is to utilize a trick with an indexed view. This is based on an article by spaghettidba.</p>
<p>We first create a dummy table of two rows</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE dbo.DummyTwoRows (dummy bit not null);
INSERT DummyTwoRows (dummy) VALUES(0),(1);
</code>```

Then we create the following view:

```<code>CREATE VIEW dbo.vwPaymentLessThanZero
WITH SCHEMBINDING  -- needs schema-binding
AS
SELECT 1 AS DummyOne
FROM dbo.Rental r
JOIN dbo.Person p ON p.personID = r.personID
CROSS JOIN dbo.DummyTwoRows dtr
WHERE p.PaymentDue <= 0;
</code>```

This view should in theory always have no rows in it. To enforce that, we create an index on it:

```<code>CREATE UNIQUE CLUSTERED INDEX CX_vwPaymentLessThanZero
  ON dbo.vwPaymentLessThanZero (DummyOne);
</code>```

Now if you try to add a row that qualifies for the view, it will fail with a unique violation, because the cross-join is doubling up the rows.

Note that in practice the view index takes up no space because there are never any rows in it.

Body:
It sounds like what you actually need is a cross-table constraint.

You can either do this by throwing an error in the trigger:

CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [Rental]
AFTER INSERT
AS

SET NOCOUNT ON;

IF EXISTS (SELECT 1
    FROM inserted i
    INNER JOIN dbo.Person p ON i.[personID] = p.[personID]
    WHERE p.[PaymentDue] <= 0
)
    THROW 50001, 'PaymentDue is less than 0', 1;

A better solution is to utilize a trick with an indexed view. This is based on an article by spaghettidba.

We first create a dummy table of two rows

CREATE TABLE dbo.DummyTwoRows (dummy bit not null);
INSERT DummyTwoRows (dummy) VALUES(0),(1);

Then we create the following view:

CREATE VIEW dbo.vwPaymentLessThanZero
WITH SCHEMBINDING  -- needs schema-binding
AS
SELECT 1 AS DummyOne
FROM dbo.Rental r
JOIN dbo.Person p ON p.personID = r.personID
CROSS JOIN dbo.DummyTwoRows dtr
WHERE p.PaymentDue <= 0;

This view should in theory always have no rows in it. To enforce that, we create an index on it:

CREATE UNIQUE CLUSTERED INDEX CX_vwPaymentLessThanZero
  ON dbo.vwPaymentLessThanZero (DummyOne);

Now if you try to add a row that qualifies for the view, it will fail with a unique violation, because the cross-join is doubling up the rows.

Note that in practice the view index takes up no space because there are never any rows in it.


来源: stackexchange

问:
how do i close firefox browsers window using javascript?
```<code>  function CloseWindow()
  {
        window.close();
  }
</code>```

The above code is working fine for IE but Firefox does not allows to close browsers window
any solution???

答:
similar post answer

```<code>function closeWindow() {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
    alert("This will close the window");
    window.open('','_self');
    window.close();
}

closeWindow();
</code>```

reason
For security reasons, your script cannot close a window/tab that it did not open.

The solution is to present the age prompt at an earlier point in the navigation history. Then, you can choose to allow them to enter your site or not based on their input.

Instead of closing the page that presents the prompt, you can simply say, "Sorry", or perhaps redirect the user to their homepage.

ContentLicense: CC BY-SA 3.0

Body:
  function CloseWindow()
  {
        window.close();
  }

The above code is working fine for IE but Firefox does not allows to close browsers window
any solution???

Body:
similar post answer

function closeWindow() {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
    alert("This will close the window");
    window.open('','_self');
    window.close();
}

closeWindow();

reason
For security reasons, your script cannot close a window/tab that it did not open.

The solution is to present the age prompt at an earlier point in the navigation history. Then, you can choose to allow them to enter your site or not based on their input.

Instead of closing the page that presents the prompt, you can simply say, "Sorry", or perhaps redirect the user to their homepage.


问:
Flutter can't recognize android sdk
I'm running Ubuntu 20 and trying to setup flutter enironment without android studio. Installed android sdk manually && it's path is $HOME/android.

here's a log of the directory

$ ls
# cmdline-tools  licenses
$ ls cmdline-tools/
# latest  tools
ls cmdline-tools/latest
bin  lib  NOTICE.txt  package.xml  source.properties
```
<p>And here's sys vars which are in <code>~/.bashrc</code></p>
<pre class="lang-sh prettyprint-override"><code>export ANDROID_SDK_ROOT="$HOME/android"
export ANDROID_HOME="$ANDROID_SDK_ROOT"
export PATH="$PATH:$ANDROID_SDK_ROOT"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/tools"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/tools/platform-tools"
export PATH="$PATH:$ANDROID_SDK_ROOT/platform-tools"
export PATH="$PATH:$ANDROID_SDK_ROOT/build-tools"
</code>```

And here's flutter doctor - v log

[!] Android toolchain - develop for Android devices
    • Android SDK at /home/aybak3k/android/
    ✗ Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, please use
      `flutter config --android-sdk` to update to that location.

    • ANDROID_HOME = /home/aybak3k/android/
    • ANDROID_SDK_ROOT = /home/aybak3k/android
    ✗ Android SDK file not found: adb.
    • Try re-installing or updating your Android SDK,
      visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions.
```

答:
flutter can't recognize the sdk unless you install the rest of the components

the following worked

# 30 is my physical device compatible version
sdkmanager --install "build-tools;30.0.2"
sdkmanager --install "platforms;android-30"
```

ContentLicense: CC BY-SA 4.0

Title: Flutter can't recognize android sdk

Body:
I'm running Ubuntu 20 and trying to setup flutter enironment without android studio. Installed android sdk manually && it's path is $HOME/android.

here's a log of the directory

$ ls
# cmdline-tools  licenses
$ ls cmdline-tools/
# latest  tools
ls cmdline-tools/latest
bin  lib  NOTICE.txt  package.xml  source.properties

And here's sys vars which are in ~/.bashrc

export ANDROID_SDK_ROOT="$HOME/android"
export ANDROID_HOME="$ANDROID_SDK_ROOT"
export PATH="$PATH:$ANDROID_SDK_ROOT"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/tools"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/tools/platform-tools"
export PATH="$PATH:$ANDROID_SDK_ROOT/platform-tools"
export PATH="$PATH:$ANDROID_SDK_ROOT/build-tools"

And here's flutter doctor - v log

[!] Android toolchain - develop for Android devices
    • Android SDK at /home/aybak3k/android/
    ✗ Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, please use
      `flutter config --android-sdk` to update to that location.

    • ANDROID_HOME = /home/aybak3k/android/
    • ANDROID_SDK_ROOT = /home/aybak3k/android
    ✗ Android SDK file not found: adb.
    • Try re-installing or updating your Android SDK,
      visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions.


问:
Is find_one_and_update() in pymongo atomic?
I couldn't find any documentation stating that find_one_and_update() in pymongo is atomic (i.e., no change on the document can appear between search and update). Can I rely on it being atomic? Or is there another way to perform the same operations in a guaranteed atomic way?

答:
PyMongo's find_one_and_update is atomic as it translates to server's findOneAndUpdate which is atomic (https://docs.mongodb.com/manual/core/write-operations-atomicity/#atomicity).

However, be aware of the "glitch" when upserting new documents. When not using a unique index on the query field(s), multiple instances of a findOneAndUpdate operation with similar query field(s) could result in duplicate documents being inserted in certain circumstances. (https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/#upsert-with-unique-index)


问:
can't connect to websocket (Mixed Content)
so i was trying to make web socket server

node js

```<code>const WebSocket = require("ws");
var porth = process.env.PORT || 80;
const wss = new WebSocket.Server({port:porth})

wss.on("connection", ws => {
    console.log("nowe połączenie");
    ws.on("message",  data => {
        console.log(data.toString());
    });
    ws.send("hej");
    ws.on("close", () =>
    {
        console.log("rozłączenie");
    });
})
</code>```

app.js

```<code>ws.addEventListener("open", () => {
  console.log("połączono")
  ws.send("test");
  ws.addEventListener("message", data => {
    console.log(data.data)
  })
})
</code>```

and when i host it on my pc it works but
when i upload it to github pages it keeps
sending me error:

Mixed Content: The page at 'https://*****.github.io/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://****.herokuapp.com/'. This request has been blocked; this endpoint must be available over WSS.

and i dont know what should i do about it

答: So from this error I assume that you are connecting between secure and not secure site. I'm not sure but if I can I would suggest you to see ws https server. Maybe this will help https://github.com/websockets/ws#external-https-server</p>

Body:
so i was trying to make web socket server

node js

const WebSocket = require("ws");
var porth = process.env.PORT || 80;
const wss = new WebSocket.Server({port:porth})

wss.on("connection", ws => {
    console.log("nowe połączenie");
    ws.on("message",  data => {
        console.log(data.toString());
    });
    ws.send("hej");
    ws.on("close", () =>
    {
        console.log("rozłączenie");
    });
})

app.js

ws.addEventListener("open", () => {
  console.log("połączono")
  ws.send("test");
  ws.addEventListener("message", data => {
    console.log(data.data)
  })
})

and when i host it on my pc it works but
when i upload it to github pages it keeps
sending me error:

Mixed Content: The page at 'https://*****.github.io/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://****.herokuapp.com/'. This request has been blocked; this endpoint must be available over WSS.

and i dont know what should i do about it


问:
there is some error in this recursive binarytree function type
I tried to check and fix the code but I just can't find what is the problem anywhere with this code

```<code>class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

class BinaryTree:
    def __init__(self, root):
        self.key = root
        self.left_child = None
        self.right_child = None

    def insert_left(self, new_node):
        if self.left_child == None:
            self.left_child = BinaryTree(new_node)
        else:
            t = BinaryTree(new_node)
            t.left_child = self.left_child
            self.left_child = t

    def insert_right(self, new_node):
        if self.right_child == None:
            self.right_child = BinaryTree(new_node)
        else:
            t = BinaryTree(new_node)
            t.right_child = self.right_child
            self.right_child = t

    def get_right_child(self):
        return self.right_child

    def get_left_child(self):
        return self.left_child

    def set_root_val(self, obj):
        self.key = obj

    def get_root_val(self):
        return self.key

    def preorder(tree):
        if tree:
            print(tree.get_root_val())
            preorder(tree.get_left_child())
            preorder(tree.get_right_child())

    def postorder(tree):
        if tree != None:
            postorder(tree.get_left_child())
            postorder(tree.get_right_child())
            print(tree.get_root_val())

    def inorder(tree):
        if tree != None:
            inorder(tree.get_left_child())
            print(tree.get_root_val())
            inorder(tree.get_right_child())

def build_parse_tree(fp_exp):
    fp_list = fp_exp.split()
    p_stack = Stack()
    e_tree = BinaryTree('')
    p_stack.push(e_tree)
    current_tree = e_tree
    for i in fp_list:
        if i == '(':
            current_tree.insert_left('')
            p_stack.push(current_tree)
            current_tree = current_tree.get_left_child()
        elif i not in ['+', '-', '*', '/', ')']:
            current_tree.set_root_val(int(i))
            parent = p_stack.pop()
            current_tree = parent
        elif i in ['+', '-', '*', '/']:
            current_tree.set_root_val(i)
            current_tree.insert_right('')
            p_stack.push(current_tree)
            current_tree = current_tree.get_right_child()
        elif i == ')':
            current_tree = p_stack.pop()
        else:
            raise ValueError
    return e_tree

if __name__ == '__main__':
    pt = build_parse_tree("( ( 10 + 5 ) * ( 3 - 2 ) )")
    pt.postorder()
</code>```

I run the code and it's return me with this

```<code>name 'postorder' is not defined
  File "G:\VSCode\PythonVS\BinaryTree6Feb2022.py", line 63, in postorder
    postorder(tree.get_left_child())
  File "G:\VSCode\PythonVS\BinaryTree6Feb2022.py", line 102, in <module>
    pt.postorder()
</code>```

I tried to make it a recursive function but I don't know what am I doing wrong or what might I be missing.
I'm still checking the code but I just can't find missing things

答:
Your traversal methods preorder, postorder and inorder have declarations that you would expect for standalone functions, but they are indented to be part of the class and so they look like methods.

The easiest fix is to move them out of the class block and replace the call in your main program with postorder(pt), and it will work.

If you prefer to have them as methods on your class, so that you can make the call like pt.postorder(), then rename the parameter tree to self (as that is the common practice), make the recursive calls in method-notation, and move the if condition before the recursive calls:

```<code>    def postorder(self):
        print(self.get_root_val())
        if self.get_left_child():
            self.get_left_child().postorder()
        if self.get_right_child():
            self.get_right_child().postorder()
</code>```

For completeness sake, I provide also an alternative that leaves the if condition at the start, but then you must use another syntax on the recursive calls, as you cannot call a method on None:

```<code>    def postorder(self):
        if self:
            print(self.get_root_val())
            BinaryTree.postorder(self.get_left_child())
            BinaryTree.postorder(self.get_right_child())
</code>```

But this is not normal practice in Python.

Body:
I tried to check and fix the code but I just can't find what is the problem anywhere with this code

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

class BinaryTree:
    def __init__(self, root):
        self.key = root
        self.left_child = None
        self.right_child = None

    def insert_left(self, new_node):
        if self.left_child == None:
            self.left_child = BinaryTree(new_node)
        else:
            t = BinaryTree(new_node)
            t.left_child = self.left_child
            self.left_child = t

    def insert_right(self, new_node):
        if self.right_child == None:
            self.right_child = BinaryTree(new_node)
        else:
            t = BinaryTree(new_node)
            t.right_child = self.right_child
            self.right_child = t

    def get_right_child(self):
        return self.right_child

    def get_left_child(self):
        return self.left_child

    def set_root_val(self, obj):
        self.key = obj

    def get_root_val(self):
        return self.key

    def preorder(tree):
        if tree:
            print(tree.get_root_val())
            preorder(tree.get_left_child())
            preorder(tree.get_right_child())

    def postorder(tree):
        if tree != None:
            postorder(tree.get_left_child())
            postorder(tree.get_right_child())
            print(tree.get_root_val())

    def inorder(tree):
        if tree != None:
            inorder(tree.get_left_child())
            print(tree.get_root_val())
            inorder(tree.get_right_child())

def build_parse_tree(fp_exp):
    fp_list = fp_exp.split()
    p_stack = Stack()
    e_tree = BinaryTree('')
    p_stack.push(e_tree)
    current_tree = e_tree
    for i in fp_list:
        if i == '(':
            current_tree.insert_left('')
            p_stack.push(current_tree)
            current_tree = current_tree.get_left_child()
        elif i not in ['+', '-', '*', '/', ')']:
            current_tree.set_root_val(int(i))
            parent = p_stack.pop()
            current_tree = parent
        elif i in ['+', '-', '*', '/']:
            current_tree.set_root_val(i)
            current_tree.insert_right('')
            p_stack.push(current_tree)
            current_tree = current_tree.get_right_child()
        elif i == ')':
            current_tree = p_stack.pop()
        else:
            raise ValueError
    return e_tree

if __name__ == '__main__':
    pt = build_parse_tree("( ( 10 + 5 ) * ( 3 - 2 ) )")
    pt.postorder()

I run the code and it's return me with this

name 'postorder' is not defined
  File "G:\VSCode\PythonVS\BinaryTree6Feb2022.py", line 63, in postorder
    postorder(tree.get_left_child())
  File "G:\VSCode\PythonVS\BinaryTree6Feb2022.py", line 102, in <module>
    pt.postorder()

I tried to make it a recursive function but I don't know what am I doing wrong or what might I be missing.
I'm still checking the code but I just can't find missing things

Body:
Your traversal methods preorder, postorder and inorder have declarations that you would expect for standalone functions, but they are indented to be part of the class and so they look like methods.

The easiest fix is to move them out of the class block and replace the call in your main program with postorder(pt), and it will work.

If you prefer to have them as methods on your class, so that you can make the call like pt.postorder(), then rename the parameter tree to self (as that is the common practice), make the recursive calls in method-notation, and move the if condition before the recursive calls:

    def postorder(self):
        print(self.get_root_val())
        if self.get_left_child():
            self.get_left_child().postorder()
        if self.get_right_child():
            self.get_right_child().postorder()

For completeness sake, I provide also an alternative that leaves the if condition at the start, but then you must use another syntax on the recursive calls, as you cannot call a method on None:

    def postorder(self):
        if self:
            print(self.get_root_val())
            BinaryTree.postorder(self.get_left_child())
            BinaryTree.postorder(self.get_right_child())

But this is not normal practice in Python.


问:
CSS submit button weird on Iphone
A line like a border-right added on iPhone button submit, it's working fine on Android

I tried this property but it's still not working

```<code>-webkit-appearance: button;
</code>```

The HTML of the button

```<code><button
    id="ta-quantity-selector__custom-ok"
    className="QuantitySelectorCustomField__button-ok"
    type="button"
  >
    OK
  </button>
</code>```

Do you have any fix for this issue, please?

答:
I dunno the structure of your html. But can you try something like this?
The trick is first spacing them apart, then specifying the button width and finally, setting the input to take up the remaining space.

.field {
  display: flex;
  justify-content: space-between;
  width: 20rem;
  border: 1px solid grey;
  border-radius: 5px;
  overflow: hidden;
}
.text-field {
  flex: 1;
}
label {
  font-size: 0.7rem;
}
input {
  border: none;
  outline: none;
}
button {
  width: 5rem;
  border: none;
  background-color: green;
  outline: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="field">
  <div class="text-field">
    <label>Choose a quantity</label>
    <input type="text"/>
  </div>
  <button type="submit">OK</button>
</div></code>```

Title: CSS submit button weird on Iphone

Body:
A line like a border-right added on iPhone button submit, it's working fine on Android

I tried this property but it's still not working

-webkit-appearance: button;

The HTML of the button

<button
    id="ta-quantity-selector__custom-ok"
    className="QuantitySelectorCustomField__button-ok"
    type="button"
  >
    OK
  </button>

Do you have any fix for this issue, please?

Body:
I dunno the structure of your html. But can you try something like this?
The trick is first spacing them apart, then specifying the button width and finally, setting the input to take up the remaining space.

.field {
  display: flex;
  justify-content: space-between;
  width: 20rem;
  border: 1px solid grey;
  border-radius: 5px;
  overflow: hidden;
}
.text-field {
  flex: 1;
}
label {
  font-size: 0.7rem;
}
input {
  border: none;
  outline: none;
}
button {
  width: 5rem;
  border: none;
  background-color: green;
  outline: none;
}

<div class="field">
  <div class="text-field">
    <label>Choose a quantity</label>
    <input type="text"/>
  </div>
  <button type="submit">OK</button>
</div>


问:
Exploding not working in pandas as expected
I have a dataset like below:

```<code>Group   Attributes  S2SFlag
Age 1 to 5  Yes
Age 6 to 10 No
Channel DD  No
Channel Agency  Yes
Status  Lapse   Yes
Status  Active  Yes
</code>```

Now I want to explode the values of the 'Age' group by the range defined in the attributes column while retaining other column values.

The  expected output is as below:

Attempt so far:

```<code>df1 = pd.read_csv('')
df1 = df1[df1['Group'] == 'Age']
attrList = df1['Attributes'].tolist()
for i in attrList:
    start = i.split(" to ")[0]
    end = i.split(" to ")[1]
    for j in range(int(start), int(end) + 1):
        df1['Attributes'] = str(j)
</code>```

It is giving me output as below:

```<code> Group Attributes S2SFlag
0   Age         10     Yes
1   Age         10      No
</code>```

答:
You can use a custom function to replace the string with range, then explode:

```<code>import re

def to_range(s):
    m = re.match('(\d+) to (\d+)$', s)
    return range(int(m.group(1)), int(m.group(2))+1) if m else s

(df.assign(Attributes=[to_range(s) for s in df['Attributes']])
   .explode('Attributes')
)
</code>```

output:

```<code>     Group Attributes S2SFlag
0      Age          1     Yes
0      Age          2     Yes
0      Age          3     Yes
0      Age          4     Yes
0      Age          5     Yes
1      Age          6      No
1      Age          7      No
1      Age          8      No
1      Age          9      No
1      Age         10      No
2  Channel         DD      No
3  Channel     Agency     Yes
4   Status      Lapse     Yes
5   Status     Active     Yes
</code>```

Body:
I have a dataset like below:

Group   Attributes  S2SFlag
Age 1 to 5  Yes
Age 6 to 10 No
Channel DD  No
Channel Agency  Yes
Status  Lapse   Yes
Status  Active  Yes

Now I want to explode the values of the 'Age' group by the range defined in the attributes column while retaining other column values.

The  expected output is as below:

Attempt so far:

df1 = pd.read_csv('')
df1 = df1[df1['Group'] == 'Age']
attrList = df1['Attributes'].tolist()
for i in attrList:
    start = i.split(" to ")[0]
    end = i.split(" to ")[1]
    for j in range(int(start), int(end) + 1):
        df1['Attributes'] = str(j)

It is giving me output as below:

 Group Attributes S2SFlag
0   Age         10     Yes
1   Age         10      No

Body:
You can use a custom function to replace the string with range, then explode:

import re

def to_range(s):
    m = re.match('(\d+) to (\d+)$', s)
    return range(int(m.group(1)), int(m.group(2))+1) if m else s

(df.assign(Attributes=[to_range(s) for s in df['Attributes']])
   .explode('Attributes')
)

output:

     Group Attributes S2SFlag
0      Age          1     Yes
0      Age          2     Yes
0      Age          3     Yes
0      Age          4     Yes
0      Age          5     Yes
1      Age          6      No
1      Age          7      No
1      Age          8      No
1      Age          9      No
1      Age         10      No
2  Channel         DD      No
3  Channel     Agency     Yes
4   Status      Lapse     Yes
5   Status     Active     Yes


问:
find specific Byte in File and read until specific byte in Lua
Is it possible to search at first inside the file after an specific byte and find the position and read just the bytes from the file in until that specific byte?

At the moment it is just possible for me to read some bytes or the whole file in and afterwards search for that specific byte.
like this:

```<code>local function read_file(path)
  local file = open(path, "r") -- r read mode and b binary mode
  if not file then return nil end
  local content = file:read(64) -- reading 64 bytes
  file:close()
  return content
end

local fileContent = read_file("../test/l_0.dat");
print(fileContent)

function parse(line)
   if line then
     len = 1
     a = line:find("V", len +1) --find V in content
     return a
   else
     return false
   end
end

a = parse(fileContent) --position of V in content
print(a)
print(string.sub(fileContent, a)) -- content until first found V
</code>```

In this example i find at position 21 the first V. So it would be cool to read in only 21 bytes except of 64 bytes or the whole file. But then i need to find the position before reading something in. Is this possible ? (The 21byte are variable, it could be 20 or 50 or so on)

答:
(Or) Correct your code to...

```<code>local function read_file(path)
  local file = io.open(path, "r") -- r read mode and b binary mode
  if not file then return nil end
  local content = file:read(64) -- reading 64 bytes
  file:close()
  return content
end

local fileContent = read_file("test/l_0.dat") -- '../' causing error
print(fileContent)

local function parse(line)
   if line then
     local len = 1
     local a = line:find("V", len +1) --find V in content
     return a
   else
     return false
   end
end

print(fileContent:sub(1, parse(fileContent))) -- content until first found V
</code>```

That puts out...

```<code>0123456789VabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

0123456789V
</code>```

If you want that V is a (single) delimiter you probably dont want to put it out.

Meet the strength of string.sub(text, start, stop)...

```<code>print(fileContent:sub(1, parse(fileContent) - 1))  -- before V
-- 0123456789
print(fileContent:sub(parse(fileContent) + 1, -1)) -- after V
-- abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

Body:
Is it possible to search at first inside the file after an specific byte and find the position and read just the bytes from the file in until that specific byte?

At the moment it is just possible for me to read some bytes or the whole file in and afterwards search for that specific byte.
like this:

local function read_file(path)
  local file = open(path, "r") -- r read mode and b binary mode
  if not file then return nil end
  local content = file:read(64) -- reading 64 bytes
  file:close()
  return content
end

local fileContent = read_file("../test/l_0.dat");
print(fileContent)

function parse(line)
   if line then
     len = 1
     a = line:find("V", len +1) --find V in content
     return a
   else
     return false
   end
end

a = parse(fileContent) --position of V in content
print(a)
print(string.sub(fileContent, a)) -- content until first found V

In this example i find at position 21 the first V. So it would be cool to read in only 21 bytes except of 64 bytes or the whole file. But then i need to find the position before reading something in. Is this possible ? (The 21byte are variable, it could be 20 or 50 or so on)

Body:
(Or) Correct your code to...

local function read_file(path)
  local file = io.open(path, "r") -- r read mode and b binary mode
  if not file then return nil end
  local content = file:read(64) -- reading 64 bytes
  file:close()
  return content
end

local fileContent = read_file("test/l_0.dat") -- '../' causing error
print(fileContent)

local function parse(line)
   if line then
     local len = 1
     local a = line:find("V", len +1) --find V in content
     return a
   else
     return false
   end
end

print(fileContent:sub(1, parse(fileContent))) -- content until first found V

That puts out...

0123456789VabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

0123456789V

If you want that V is a (single) delimiter you probably dont want to put it out.

Meet the strength of string.sub(text, start, stop)...

print(fileContent:sub(1, parse(fileContent) - 1))  -- before V
-- 0123456789
print(fileContent:sub(parse(fileContent) + 1, -1)) -- after V
-- abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ


问:
Password expiration warnings with AIX Kerberos to Active Directory authentication
Our environment is AIX 7.1, having a mix of local accounts and accounts in Active Directory authenticated via Kerberos.

We have observed that for local accounts, successful authentication within the password warning period also issues the expected warning message, such as:

[compat]: 3004-328 Your password will expire: Fri Apr 15 12:59:33 CDT 2022

However the Active Directory accounts do not receive such warning messages.  Is it possible to configure AIX/Kerberos to issue these messages?  If so, will it use AIX's "Days to warn user before password expires", or Active Directory's?

Thanks

答:
•   No, you can’t configure AIX/Kerberos to issue this message to domain accounts as their password policy is managed by Active Directory Group policy and is a part of the Active Directory services. Thus, it is applicable to domain users only. And as these AD domain user accounts are not a part of AIX local user accounts, AIX server doesn’t have any authority over them due to which password expiration message regarding AIX local user accounts is not issued as same and equivalent to AD domain user accounts. Also, if you want to configure the password expiration prompt message for AD domain user accounts, you can surely do it as below: -

‘ Go to Group Policy Management -> Default Domain Policy -> Edit -> Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> Security Options -> Interactive logon: Prompt user to change password before expiration -> Set the number of days ’


问:
Heroku: python app works locally but does't on remote after git push
I'm trying to deploy a python app that supports redis and I'm currently facing a problem.
I have two git branches, one for production and one for dev and two different heroku apps (python-app, dev-python-app). My git repos are:

```<code>git remote
heroku
heroku-test
</code>```

I use the fallowing commands to deploy the heroku-test to check if the app works correctly before passing to prod:

```<code>git branch dev-python-app
git add .
git commit -m "commit msg"
git push heroku-test dev-python-app:master
</code>```

It says that everything's ok: "remote: Verifying deploy... done." but the app won't start.
If I check logs with: heroku logs --tail -a dev-python-app:

```<code>2022-02-09T10:36:29.000000+00:00 app[api]: Build started by user *****
2022-02-09T10:36:53.638128+00:00 app[api]: Deploy 267f3889 by user ****
2022-02-09T10:36:53.638128+00:00 app[api]: Release v21 created by user ****
2022-02-09T10:37:02.000000+00:00 app[api]: Build succeeded
</code>```

The stange thing is that if I run a one-off dyno using heroku run bash -a dev-python-app and than start the python app as: python3 main.py it works perfectly.

Moreover, It'd be useful to know that I tried this mentioned steps before introducing redis support to the app and It worked perfectly so could be redis the problem?

What do you think? Thank you

答:
I fixed that.
The problem was to scale the working process:</p>
```<code>heroku ps:scale worker=1 -a dev-python-app
</code>```

Body:
I'm trying to deploy a python app that supports redis and I'm currently facing a problem.
I have two git branches, one for production and one for dev and two different heroku apps (python-app, dev-python-app). My git repos are:

git remote
heroku
heroku-test

I use the fallowing commands to deploy the heroku-test to check if the app works correctly before passing to prod:

git branch dev-python-app
git add .
git commit -m "commit msg"
git push heroku-test dev-python-app:master

It says that everything's ok: "remote: Verifying deploy... done." but the app won't start.
If I check logs with: heroku logs --tail -a dev-python-app:

2022-02-09T10:36:29.000000+00:00 app[api]: Build started by user *****
2022-02-09T10:36:53.638128+00:00 app[api]: Deploy 267f3889 by user ****
2022-02-09T10:36:53.638128+00:00 app[api]: Release v21 created by user ****
2022-02-09T10:37:02.000000+00:00 app[api]: Build succeeded

The stange thing is that if I run a one-off dyno using heroku run bash -a dev-python-app and than start the python app as: python3 main.py it works perfectly.

Moreover, It'd be useful to know that I tried this mentioned steps before introducing redis support to the app and It worked perfectly so could be redis the problem?

What do you think? Thank you

Body:
I fixed that.
The problem was to scale the working process:

heroku ps:scale worker=1 -a dev-python-app


问:
NGCC failed. at NgccProcessor.process ( Angular\node_modules\@ngtools\webpack\src\ngcc_processor.js:139:19)
I have upgraded My Angular CLI project from 8 to 9.

Here are the current Angular CLI and other package versions:

```<code>Angular CLI: 9.1.15
Node: 14.17.0
OS: win32 x64

Angular: 9.1.13
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.1202.1
@angular-devkit/build-angular     12.2.1
@angular-devkit/build-optimizer   0.1202.1
@angular-devkit/build-webpack     0.1202.1
@angular-devkit/core              9.1.15
@angular-devkit/schematics        9.1.15
@angular/cdk                      8.2.3
@angular/cli                      9.1.15
@ngtools/webpack                  12.2.1
@schematics/angular               9.1.15
@schematics/update                0.901.15
rxjs                              6.6.7
typescript                        3.8.3
webpack                           5.50.0
</code>```

I am receiving this below-given error when I am compiling the project.

```<code>Generating browser application bundles (phase: setup)...Options:
      --version                          Show version number           [boolean]
  -s, --source                           A path (relative to the working
                                         directory) of the `node_modules` folder
                                         to process. [default: "./node_modules"]
  -p, --properties                       An array of names of properties in
                                         package.json to compile (e.g. `module`
                                         or `es2015`)
                                         Each of these properties should hold
                                         the path to a bundle-format.
                                         If provided, only the specified
                                         properties are considered for
                                         processing.
                                         If not provided, all the supported
                                         format properties (e.g. fesm2015,
                                         fesm5, es2015, esm2015, esm5, main,
                                         module) in the package.json are
                                         considered.
                                         .......
                                         .......

Unknown arguments: use-program-dependencies, useProgramDependencies
C:\Users\x\Angular\node_modules\@ngtools\webpack\src\ngcc_processor.js:139
            throw new Error(errorMessage + `NGCC failed${errorMessage ? ', see above' : ''}.`);

Error: NGCC failed.
    at NgccProcessor.process (C:\Users\x\Angular\node_modules\@ngtools\webpack\src\ngcc_processor.js:139:19)
    at C:\Users\x\Angular\node_modules\@ngtools\webpack\src\ivy\plugin.js:129:27
</code>```

Can some guide me how I can resolve this issue?

答: I had similar issue with Angular 12 and Node 17.4.0. I changed Node to v16.13.2 and now it works fine.

Body:
I have upgraded My Angular CLI project from 8 to 9.

Here are the current Angular CLI and other package versions:

Angular CLI: 9.1.15
Node: 14.17.0
OS: win32 x64

Angular: 9.1.13
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.1202.1
@angular-devkit/build-angular     12.2.1
@angular-devkit/build-optimizer   0.1202.1
@angular-devkit/build-webpack     0.1202.1
@angular-devkit/core              9.1.15
@angular-devkit/schematics        9.1.15
@angular/cdk                      8.2.3
@angular/cli                      9.1.15
@ngtools/webpack                  12.2.1
@schematics/angular               9.1.15
@schematics/update                0.901.15
rxjs                              6.6.7
typescript                        3.8.3
webpack                           5.50.0

I am receiving this below-given error when I am compiling the project.

Generating browser application bundles (phase: setup)...Options:
      --version                          Show version number           [boolean]
  -s, --source                           A path (relative to the working
                                         directory) of the `node_modules` folder
                                         to process. [default: "./node_modules"]
  -p, --properties                       An array of names of properties in
                                         package.json to compile (e.g. `module`
                                         or `es2015`)
                                         Each of these properties should hold
                                         the path to a bundle-format.
                                         If provided, only the specified
                                         properties are considered for
                                         processing.
                                         If not provided, all the supported
                                         format properties (e.g. fesm2015,
                                         fesm5, es2015, esm2015, esm5, main,
                                         module) in the package.json are
                                         considered.
                                         .......
                                         .......

Unknown arguments: use-program-dependencies, useProgramDependencies
C:\Users\x\Angular\node_modules\@ngtools\webpack\src\ngcc_processor.js:139
            throw new Error(errorMessage + `NGCC failed${errorMessage ? ', see above' : ''}.`);

Error: NGCC failed.
    at NgccProcessor.process (C:\Users\x\Angular\node_modules\@ngtools\webpack\src\ngcc_processor.js:139:19)
    at C:\Users\x\Angular\node_modules\@ngtools\webpack\src\ivy\plugin.js:129:27

Can some guide me how I can resolve this issue?


问:
ModuleNotFoundError: No module named '_overlapped'
I am just trying to run a python file and this error shows up. I tried installing the 'trollius' package and the 'overlap' package if those are related to this error but none of them seems to work.

答:
It is about python access modifiers. You can try to remove underscore at the beginning. For further knowledge you may look at this link
enter link description here</p>


问:
Why does this for loop in C program print Hi 11 times?
```<code>#include <stdio.h>
int main()
{
int i = 1024;
for (; i; i >>= 1)
printf("Hi");
return 0;
}
</code>```

Why does the for loop print Hi 11 times? I don't understand.

答:
Example of bitwise right shift operator:

```<code>int x = 1024
int z = x >>=1 # right shift operator
// then printing z will print 512, i.e. x/2
</code>```

So, now if you keep on updating the value of z using a for loop as you are updating the value of 'i' in your example you will see that 'i' or 'z' will go as low as 1 (because 'i' is int type)

```<code># include <stdio.h>
# include <iostream>
int main()
{
    int i = 1024;
    for (; i; i >>= 1)
        std::cout << "\n" << i;

    return 0;
}
</code>```

In your code, because i = 1024 (2^10) can be divided maximum of 11 times by 2 hence the loop prints "Hi" 11 times where i = [1024, 512, ....2, 1].

Check this link for more details:
https://en.cppreference.com/w/cpp/language/operator_assignment

Body:
#include <stdio.h>
int main()
{
int i = 1024;
for (; i; i >>= 1)
printf("Hi");
return 0;
}

Why does the for loop print Hi 11 times? I don't understand.

Body:
Example of bitwise right shift operator:

int x = 1024
int z = x >>=1 # right shift operator
// then printing z will print 512, i.e. x/2

So, now if you keep on updating the value of z using a for loop as you are updating the value of 'i' in your example you will see that 'i' or 'z' will go as low as 1 (because 'i' is int type)

# include <stdio.h>
# include <iostream>
int main()
{
    int i = 1024;
    for (; i; i >>= 1)
        std::cout << "\n" << i;

    return 0;
}

In your code, because i = 1024 (2^10) can be divided maximum of 11 times by 2 hence the loop prints "Hi" 11 times where i = [1024, 512, ....2, 1].

Check this link for more details:
https://en.cppreference.com/w/cpp/language/operator_assignment


问:
Excel: combining IF formula with FREQUENCIES and MATCH
I'm trying to compbine an if-then and a frequency formula in Excel:

I need to get the sum of the values in column C1:C5 in cell C6, but only there is a match with the value in B1:B5 and A6.

So in the picture below, the result should be 25 (Tthe formula is in Dutch, but I'm using IF, SUM, FREQUENCY, MATCH)

答: Enter =SUMIF($B$1:$B$5,A6,$C$1:$C$5) or the Dutch equivalent into C6 and fill down.


问:
How to combine/join two results tables by the grouped by column?
How can the two individual tables be combined into one results table?

The first query gives the results table
| company_id| Number products sold (2022) |
|-----------|-----------------------------|
| 1         | 151513                      |
| ...       | ...                         |
| 958       | 11156                       |

```<code>SELECT company_id, COUNT(product_id) AS 'Number products sold (2022)'
FROM Sales
WHERE sales_year = 2022
GROUP BY company_id;
</code>```

And the second query gives the results table
| company_id| Number products sold (2021) |
|-----------|-----------------------------|
| 1         | 81513                       |
| ...       | ...                         |
| 958       | 10167                       |

```<code>SELECT company_id, COUNT(product_id) AS 'Number products sold (2021)'
FROM Sales
WHERE sales_year = 2021
GROUP BY company_id;
</code>```

However, both tables should be combined to the following table
| company_id| Number products sold (2022) | Number products sold (2021) |
|-----------|-----------------------------|-----------------------------|
| 1         | 151513                      | 81513                       |
| ...       | ...                         | ...                         |
| 958       | 11156                       | 10167                       |

答:
use join in subquery  to put them in front of each other

company_id
Number_products_sold_(2022)
Number_products_sold_(2021)

Ids
Values(2022)
Values(2021)

```<code>select a.company_id,'Number products sold (2022)','Number products sold (2021)' from
(SELECT company_id, COUNT(product_id) AS 'Number products sold (2022)'
FROM Sales
WHERE sales_year = 2022
GROUP BY company_id) a
join
(SELECT company_id, COUNT(product_id) AS 'Number products sold (2021)'
FROM Sales
WHERE sales_year = 2021
GROUP BY company_id) b
on a.company_id=b.company_id
</code>```

if you want to put sales_year = 2022 followed by sales_year = 2021 use union

company_id
Number_products_sold

Ids
Values(2022)

Ids
Values(2021)

```<code>SELECT company_id, COUNT(product_id) AS 'Number products sold (2022)'
FROM Sales
WHERE sales_year = 2022
GROUP BY company_id;
union all
SELECT company_id, COUNT(product_id) AS 'Number products sold (2021)'
FROM Sales
WHERE sales_year = 2021
GROUP BY company_id;
</code>```

Body:
How can the two individual tables be combined into one results table?

The first query gives the results table
| company_id| Number products sold (2022) |
|-----------|-----------------------------|
| 1         | 151513                      |
| ...       | ...                         |
| 958       | 11156                       |

SELECT company_id, COUNT(product_id) AS 'Number products sold (2022)'
FROM Sales
WHERE sales_year = 2022
GROUP BY company_id;

And the second query gives the results table
| company_id| Number products sold (2021) |
|-----------|-----------------------------|
| 1         | 81513                       |
| ...       | ...                         |
| 958       | 10167                       |

SELECT company_id, COUNT(product_id) AS 'Number products sold (2021)'
FROM Sales
WHERE sales_year = 2021
GROUP BY company_id;

However, both tables should be combined to the following table
| company_id| Number products sold (2022) | Number products sold (2021) |
|-----------|-----------------------------|-----------------------------|
| 1         | 151513                      | 81513                       |
| ...       | ...                         | ...                         |
| 958       | 11156                       | 10167                       |

Body:
use join in subquery  to put them in front of each other

company_id
Number_products_sold_(2022)
Number_products_sold_(2021)

Ids
Values(2022)
Values(2021)

select a.company_id,'Number products sold (2022)','Number products sold (2021)' from
(SELECT company_id, COUNT(product_id) AS 'Number products sold (2022)'
FROM Sales
WHERE sales_year = 2022
GROUP BY company_id) a
join
(SELECT company_id, COUNT(product_id) AS 'Number products sold (2021)'
FROM Sales
WHERE sales_year = 2021
GROUP BY company_id) b
on a.company_id=b.company_id

if you want to put sales_year = 2022 followed by sales_year = 2021 use union

company_id
Number_products_sold

Ids
Values(2022)

Ids
Values(2021)

SELECT company_id, COUNT(product_id) AS 'Number products sold (2022)'
FROM Sales
WHERE sales_year = 2022
GROUP BY company_id;
union all
SELECT company_id, COUNT(product_id) AS 'Number products sold (2021)'
FROM Sales
WHERE sales_year = 2021
GROUP BY company_id;


问:
How to wirte a part of <fo:table> in a function
I have to create many <fo:table-row> in a  <fo:table-body>. I think it's not nice if I write almost 5 lines of code several times (Maybe 50 times) to create the rows.

Like this:

```<code><fo:table-body>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row1"/>
   </fo:table-cell>
</fo:table-row>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row2"/>
   </fo:table-cell>
</fo:table-row>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row3"/>
   </fo:table-cell>
</fo:table-row>
....
</fo:table-body>
</code>```

I tried to write a function that writes the <fo:table-row> for me. And I have to call the function every time and pass a parameter.

```<code><xsl:function name="fn:createRow">
    <xsl:param name="string1"/>

    <fo:table-row>
       <fo:table-cell padding-bottom="6pt">
           <fo:value-of select="$string1"/>
       </fo:table-cell>
    </fo:table-row>

  </xsl:function>
</code>```

And now my XSLT look like this.

```<code><fo:table-body>
    <fo:block>
           <fo:value-of select="fn:createRow('row1')"/>
           <fo:value-of select="fn:createRow('row2')"/>
   </fo:block>
</fo:table-body>
</code>```

But I get the error:

"fo:block" is not a valid child of "fo:table-body"!

But when I work without <fo:block> I get nothing in the PDF:

```<code><fo:table-body>
       <fo:value-of select="fn:createRow('row1')"/>
       <fo:value-of select="fn:createRow('row2')"/>
</fo:table-body>
</code>```

Is there any opportunity to do it?

Thanks!

答:
I think instead of <fo:value-of select="$string1"/> you want <xsl:value-of select="$string1"/>. I would also check whether a fo:table-cell allows inline content, it might be necessary to put a fo:block container in the cell which has the xsl:value-of element as a child.

Also, for the function calls, don't use <fo:value-of select="fn:createRow('row1')"/>, instead, use <xsl:sequence select="fn:createRow('row1')"/>.

Also, fn is a reserved prefix, for your own functions declare and use your own namespace (e.g. xmlns:mf="http://example.com/mf" and <xsl:function name="mf:createRow" ...>...</xsl:function>, then use <xsl:sequence select="mf:createRow('row1')"/>.

So an example of the function would be

```<code><xsl:function name="mf:createRow">
    <xsl:param name="input"/>

    <fo:table-row>
       <fo:table-cell padding-bottom="6pt">
           <fo:block>
             <xsl:value-of select="$input"/>
           </fo:block>
       </fo:table-cell>
    </fo:table-row>

</xsl:function>
</code>```

and you could call it as e.g.

```<code>  <fo:table-body>
    <xsl:sequence select="(1 to 3) ! ('Row ' || . ) ! mf:createRow(.)"/>
  </fo:table-body>
</code>```

Body:
I have to create many <fo:table-row> in a  <fo:table-body>. I think it's not nice if I write almost 5 lines of code several times (Maybe 50 times) to create the rows.

Like this:

<fo:table-body>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row1"/>
   </fo:table-cell>
</fo:table-row>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row2"/>
   </fo:table-cell>
</fo:table-row>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row3"/>
   </fo:table-cell>
</fo:table-row>
....
</fo:table-body>

I tried to write a function that writes the <fo:table-row> for me. And I have to call the function every time and pass a parameter.

<xsl:function name="fn:createRow">
    <xsl:param name="string1"/>

    <fo:table-row>
       <fo:table-cell padding-bottom="6pt">
           <fo:value-of select="$string1"/>
       </fo:table-cell>
    </fo:table-row>

  </xsl:function>

And now my XSLT look like this.

<fo:table-body>
    <fo:block>
           <fo:value-of select="fn:createRow('row1')"/>
           <fo:value-of select="fn:createRow('row2')"/>
   </fo:block>
</fo:table-body>

But I get the error:

"fo:block" is not a valid child of "fo:table-body"!

But when I work without <fo:block> I get nothing in the PDF:

<fo:table-body>
       <fo:value-of select="fn:createRow('row1')"/>
       <fo:value-of select="fn:createRow('row2')"/>
</fo:table-body>

Is there any opportunity to do it?

Thanks!

Body:
I think instead of <fo:value-of select="$string1"/> you want <xsl:value-of select="$string1"/>. I would also check whether a fo:table-cell allows inline content, it might be necessary to put a fo:block container in the cell which has the xsl:value-of element as a child.

Also, for the function calls, don't use <fo:value-of select="fn:createRow('row1')"/>, instead, use <xsl:sequence select="fn:createRow('row1')"/>.

Also, fn is a reserved prefix, for your own functions declare and use your own namespace (e.g. xmlns:mf="http://example.com/mf" and <xsl:function name="mf:createRow" ...>...</xsl:function>, then use <xsl:sequence select="mf:createRow('row1')"/>.

So an example of the function would be

<xsl:function name="mf:createRow">
    <xsl:param name="input"/>

    <fo:table-row>
       <fo:table-cell padding-bottom="6pt">
           <fo:block>
             <xsl:value-of select="$input"/>
           </fo:block>
       </fo:table-cell>
    </fo:table-row>

</xsl:function>

and you could call it as e.g.

  <fo:table-body>
    <xsl:sequence select="(1 to 3) ! ('Row ' || . ) ! mf:createRow(.)"/>
  </fo:table-body>


问:
Yaml - Swagger, Duplicate mapping key
I've created a simple API, however I am having problems documenting it with Swagger as I get error: Duplicate mapping key on line 200. It is the line which says: "INVALID TOKEN" on route to update a switch: api/switches/update/{id}
I've tried creating also definition specific for update, but it was the same as Create so I think its okay to use Create definition for update as well. Not sure, if this could be a part of the problem.

```<code>swagger: "2.0"
info:
version: "1.0.0"
title: Mechanical Switches API
host: localhost:4000
basePath: /
schemes:
  - http
  - https
consumes:
  - application/json
produces:
  - application/json
  - application/xml
  - text/xml
  - text/html
paths:
  /api/welcome:
    get:
      description: Sharing the love with welcome message
      summary: Welcome message
      operationId: getWelcomeMessage
      tags:
        - user
      responses:
        '200':
          description: "OK"
  /api/user/register:
    post:
      description: Register a new user
      summary: Create new user
      operationId: postNewUser
      tags:
        - user
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
      parameters:
        - in: body
          name: User registration
          description: The user to create
          schema:
            $ref: "#/definitions/userCreate"
  /api/user/login:
    post:
      description: Login as user
      summary: Login user
      operationId: loginExistingUser
      tags:
        - user
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
      parameters:
        - in: body
          name: User login
          description: The user to login
          schema:
            $ref: "#/definitions/userLogin"
  /api/switches/create:
    post:
      description: Create a new switch
      summary: New Switch
      operationId: postNewSwitch
      tags:
        - switches
      responses:
        '200':
          description: "OK"
        '400':
          description: "ACCESS DENIED"
        '401':
          description: "INVALID TOKEN"
      parameters:
        - in: body
          name: Create switch
          description: Create a new switch
          schema:
            $ref: "#/definitions/switchCreate"
  /api/switches:
    get:
      description: Get all the switches
      summary: All Switches
      operationId: getAllSwitches
      tags:
        - switches
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/{id}:
    get:
      parameters:
        - name: id
          in: path
          required: true
          type: integer
          format: int64
      description: Get a specific switch
      summary: Specific switch
      operationId: getSingleSwitch
      tags:
        - switches
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/type/linear:
    get:
      description: Get all linear switches
      summary: Linear switches
      operationId: getLinearSwitches
      tags:
        - switches
        - type linear
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/type/tactile:
    get:
      description: Get all tactile switches
      summary: Tactile switches
      operationId: getTactileSwitches
      tags:
        - switches
        - type tactile
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/type/clicky:
    get:
      description: Get all clicky switches
      summary: Clicky switches
      operationId: getClickySwitches
      tags:
        - switches
        - type clicky
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/mount/5pin:
    get:
      description: Get all switches with 5-pin mount
      summary: All 5-pin
      operationId: getAll5pin
      tags:
        - switches
        - 5pin
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/mount/3pin:
    get:
      description: Get all switches with 3-pin mount
      summary: All 3-pin
      operationId: getAll3pin
      tags:
        - switches
        - 3pin
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/update/{id}:
    put:
      parameters:
        - name: id
          in: path
          required: true
          type: integer
          format: int64
      description: Update a specific switch
      summary: Update switch
      operationId: updateSwitch
      tags:
        - switches
        - update
      responses:
        '200':
          description: "OK"
        '400':
          description: "ACCESS DENIED"
        '401':
          description: "INVALID TOKEN"
      parameters:
        - in: body
          name: Update existing switch
          description: Update a switch
          schema:
            $ref: "#/definitions/switchCreate"
  /api/switches/delete/{id}:
    delete:
      parameters:
        - name: id
          in: path
          required: true
          type: integer
          format: int64
      description: Delete a specific switch
      summary: Delete switch
      operationId: deleteSwitch
      tags:
        - switches
        - delete
      responses:
        '200':
          description: "OK"
        '400':
          description: "ACCESS DENIED"
        '401':
          description: "INVALID TOKEN"
definitions:
  userCreate:
    properties:
      userName:
        type: string
      email:
        type: string
      password:
        type: string
    required:
      - userName
      - email
      - password
  userLogin:
    properties:
      email:
        type: string
      password:
        type: string
    required:
      - email
      - password
  switchCreate:
    properties:
      model:
        type: string
      brand:
        type: string
      switchCollection:
        type: string
      switchType:
        type: string
      actuationForce:
        type: string
      preTravel:
        type: string
      totalTravel:
        type: string
      stemStructure:
        type: string
      mount:
        type: string
      lifespan:
        type: string
      colors:
        type: string
      manufacturer:
        type: string
    required:
      - model
      - brand
      - switchCollection
      - switchType
      - actuationForce
      - preTravel
      - totalTravel
      - stemStructure
      - mount
      - lifespan
      - colors
      - manufacturer
</code>```

答:
The "duplicate mapping key" error occurs because the /api/switches/update/{id} definition contains two parameters sections:

  /api/switches/update/{id}:
    put:
      parameters:    # <------
        - name: id
          in: path
          required: true
          type: integer
          format: int64
      description: Update a specific switch
      ...
      responses:
        ...
      parameters:    # <------
        - in: body
          name: Update existing switch
          description: Update a switch
          schema:
            $ref: "#/definitions/switchCreate"

```
<p>You need to merge the parameters into a single list:</p>
<pre class="lang-yaml prettyprint-override"><code>  /api/switches/update/{id}:
    put:
      parameters:
        - name: id
          in: path
          required: true
          type: integer
          format: int64
        - in: body
          name: Update existing switch
          description: Update a switch
          schema:
            $ref: "#/definitions/switchCreate"
</code>```

Title: Yaml - Swagger, Duplicate mapping key

Body:
I've created a simple API, however I am having problems documenting it with Swagger as I get error: Duplicate mapping key on line 200. It is the line which says: "INVALID TOKEN" on route to update a switch: api/switches/update/{id}
I've tried creating also definition specific for update, but it was the same as Create so I think its okay to use Create definition for update as well. Not sure, if this could be a part of the problem.

swagger: "2.0"
info:
version: "1.0.0"
title: Mechanical Switches API
host: localhost:4000
basePath: /
schemes:
  - http
  - https
consumes:
  - application/json
produces:
  - application/json
  - application/xml
  - text/xml
  - text/html
paths:
  /api/welcome:
    get:
      description: Sharing the love with welcome message
      summary: Welcome message
      operationId: getWelcomeMessage
      tags:
        - user
      responses:
        '200':
          description: "OK"
  /api/user/register:
    post:
      description: Register a new user
      summary: Create new user
      operationId: postNewUser
      tags:
        - user
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
      parameters:
        - in: body
          name: User registration
          description: The user to create
          schema:
            $ref: "#/definitions/userCreate"
  /api/user/login:
    post:
      description: Login as user
      summary: Login user
      operationId: loginExistingUser
      tags:
        - user
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
      parameters:
        - in: body
          name: User login
          description: The user to login
          schema:
            $ref: "#/definitions/userLogin"
  /api/switches/create:
    post:
      description: Create a new switch
      summary: New Switch
      operationId: postNewSwitch
      tags:
        - switches
      responses:
        '200':
          description: "OK"
        '400':
          description: "ACCESS DENIED"
        '401':
          description: "INVALID TOKEN"
      parameters:
        - in: body
          name: Create switch
          description: Create a new switch
          schema:
            $ref: "#/definitions/switchCreate"
  /api/switches:
    get:
      description: Get all the switches
      summary: All Switches
      operationId: getAllSwitches
      tags:
        - switches
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/{id}:
    get:
      parameters:
        - name: id
          in: path
          required: true
          type: integer
          format: int64
      description: Get a specific switch
      summary: Specific switch
      operationId: getSingleSwitch
      tags:
        - switches
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/type/linear:
    get:
      description: Get all linear switches
      summary: Linear switches
      operationId: getLinearSwitches
      tags:
        - switches
        - type linear
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/type/tactile:
    get:
      description: Get all tactile switches
      summary: Tactile switches
      operationId: getTactileSwitches
      tags:
        - switches
        - type tactile
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/type/clicky:
    get:
      description: Get all clicky switches
      summary: Clicky switches
      operationId: getClickySwitches
      tags:
        - switches
        - type clicky
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/mount/5pin:
    get:
      description: Get all switches with 5-pin mount
      summary: All 5-pin
      operationId: getAll5pin
      tags:
        - switches
        - 5pin
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/mount/3pin:
    get:
      description: Get all switches with 3-pin mount
      summary: All 3-pin
      operationId: getAll3pin
      tags:
        - switches
        - 3pin
      responses:
        '200':
          description: "OK"
        '400':
          description: "NOT OK"
  /api/switches/update/{id}:
    put:
      parameters:
        - name: id
          in: path
          required: true
          type: integer
          format: int64
      description: Update a specific switch
      summary: Update switch
      operationId: updateSwitch
      tags:
        - switches
        - update
      responses:
        '200':
          description: "OK"
        '400':
          description: "ACCESS DENIED"
        '401':
          description: "INVALID TOKEN"
      parameters:
        - in: body
          name: Update existing switch
          description: Update a switch
          schema:
            $ref: "#/definitions/switchCreate"
  /api/switches/delete/{id}:
    delete:
      parameters:
        - name: id
          in: path
          required: true
          type: integer
          format: int64
      description: Delete a specific switch
      summary: Delete switch
      operationId: deleteSwitch
      tags:
        - switches
        - delete
      responses:
        '200':
          description: "OK"
        '400':
          description: "ACCESS DENIED"
        '401':
          description: "INVALID TOKEN"
definitions:
  userCreate:
    properties:
      userName:
        type: string
      email:
        type: string
      password:
        type: string
    required:
      - userName
      - email
      - password
  userLogin:
    properties:
      email:
        type: string
      password:
        type: string
    required:
      - email
      - password
  switchCreate:
    properties:
      model:
        type: string
      brand:
        type: string
      switchCollection:
        type: string
      switchType:
        type: string
      actuationForce:
        type: string
      preTravel:
        type: string
      totalTravel:
        type: string
      stemStructure:
        type: string
      mount:
        type: string
      lifespan:
        type: string
      colors:
        type: string
      manufacturer:
        type: string
    required:
      - model
      - brand
      - switchCollection
      - switchType
      - actuationForce
      - preTravel
      - totalTravel
      - stemStructure
      - mount
      - lifespan
      - colors
      - manufacturer

Body:
The "duplicate mapping key" error occurs because the /api/switches/update/{id} definition contains two parameters sections:

  /api/switches/update/{id}:
    put:
      parameters:    # <------
        - name: id
          in: path
          required: true
          type: integer
          format: int64
      description: Update a specific switch
      ...
      responses:
        ...
      parameters:    # <------
        - in: body
          name: Update existing switch
          description: Update a switch
          schema:
            $ref: "#/definitions/switchCreate"

You need to merge the parameters into a single list:

  /api/switches/update/{id}:
    put:
      parameters:
        - name: id
          in: path
          required: true
          type: integer
          format: int64
        - in: body
          name: Update existing switch
          description: Update a switch
          schema:
            $ref: "#/definitions/switchCreate"


问:
Go update document using elastic search
I'm using go-elasticsearch as a elastic search client.

I tried to update document using code from here elastic/go-elasticsearch/api.update.go

However using the same code from GitHub I got:

[UpdateRequest] unknown field [Title]

So far I have only one document which looks like this

{
    "took": 3,
    "timed_out": false,
    "_shards": {
        "total": 4,
        "successful": 4,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "posts",
                "_type": "_doc",
                "_id": "fc87941f-dc82-4fdb-9e04-460830e5f3ab",
                "_score": 1.0,
                "_source": {
                    "Title": "one two three2",
                    "Done": false,
                    "Created": "2022-02-09T11:51:59.027356+01:00",
                    "Updated": null
                }
            }
        ]
    }
}
```
<p>My go function:</p>
<pre class="lang-golang prettyprint-override"><code>func (postRepository) Update(id uuid.UUID, input inputs.Post) error {
    channel := make(chan error)
    go func() {
        post := entities.Post{
            Title:   "title updated",
        }

        body, err := json.Marshal(post)
        if err != nil {
            channel <- err
        }

        request := esapi.UpdateRequest{
            Index:      index,
            DocumentID: id.String(),
            Body:       strings.NewReader(string(body)),
        }

        response, err := request.Do(context.Background(), data.ElasticSearchClient)
        if err != nil {
            channel <- err
        }
        defer response.Body.Close()

        if response.IsError() {
            var b map[string]interface{}
            e := json.NewDecoder(response.Body).Decode(&b)
            if e != nil {
                fmt.Println(fmt.Errorf("error parsing the response body: %s", err))
            }
            fmt.Println(fmt.Errorf("reason: %s", b["error"].(map[string]interface{})["reason"].(string)))
            channel <- fmt.Errorf("[%s] Error indexing document", response.Status())
        }

        channel <- nil
    }()
    return <-channel
}
</code>```

My entity:

type Post struct {
    Title   string
    Done    bool
    Created time.Time
    Updated *time.Time
}
```

In addition this is the only function which does not work, other function like: AddDocument, RemoveDocument, GetDocuments all works as expected.

答:
Found solution here: a-simple-elasticsearch-crud-example-in-golang

Instead of using:

request := esapi.UpdateRequest{
    Index:      index,
    DocumentID: id.String(),
    Body:       strings.NewReader(string(body)),
}
```
<p>use</p>
<pre class="lang-golang prettyprint-override"><code>request := esapi.UpdateRequest{
    Index:      index,
    DocumentID: id.String(),
    Body: bytes.NewReader([]byte(fmt.Sprintf(`{"doc":%s}`, body))),
}
</code>```

Title: Go update document using elastic search

Body:
I'm using go-elasticsearch as a elastic search client.

I tried to update document using code from here elastic/go-elasticsearch/api.update.go

However using the same code from GitHub I got:

[UpdateRequest] unknown field [Title]

So far I have only one document which looks like this

{
    "took": 3,
    "timed_out": false,
    "_shards": {
        "total": 4,
        "successful": 4,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "posts",
                "_type": "_doc",
                "_id": "fc87941f-dc82-4fdb-9e04-460830e5f3ab",
                "_score": 1.0,
                "_source": {
                    "Title": "one two three2",
                    "Done": false,
                    "Created": "2022-02-09T11:51:59.027356+01:00",
                    "Updated": null
                }
            }
        ]
    }
}

My go function:

func (postRepository) Update(id uuid.UUID, input inputs.Post) error {
    channel := make(chan error)
    go func() {
        post := entities.Post{
            Title:   "title updated",
        }

        body, err := json.Marshal(post)
        if err != nil {
            channel <- err
        }

        request := esapi.UpdateRequest{
            Index:      index,
            DocumentID: id.String(),
            Body:       strings.NewReader(string(body)),
        }

        response, err := request.Do(context.Background(), data.ElasticSearchClient)
        if err != nil {
            channel <- err
        }
        defer response.Body.Close()

        if response.IsError() {
            var b map[string]interface{}
            e := json.NewDecoder(response.Body).Decode(&b)
            if e != nil {
                fmt.Println(fmt.Errorf("error parsing the response body: %s", err))
            }
            fmt.Println(fmt.Errorf("reason: %s", b["error"].(map[string]interface{})["reason"].(string)))
            channel <- fmt.Errorf("[%s] Error indexing document", response.Status())
        }

        channel <- nil
    }()
    return <-channel
}

My entity:

type Post struct {
    Title   string
    Done    bool
    Created time.Time
    Updated *time.Time
}

In addition this is the only function which does not work, other function like: AddDocument, RemoveDocument, GetDocuments all works as expected.

Body:
Found solution here: a-simple-elasticsearch-crud-example-in-golang

Instead of using:

request := esapi.UpdateRequest{
    Index:      index,
    DocumentID: id.String(),
    Body:       strings.NewReader(string(body)),
}

use

request := esapi.UpdateRequest{
    Index:      index,
    DocumentID: id.String(),
    Body: bytes.NewReader([]byte(fmt.Sprintf(`{"doc":%s}`, body))),
}


问:
ESLint not working in VS Code?
ESLint is not working for me in VS Code. I have the plugin installed in VS Code, and ESLint itself as a developer dependency in my package.json, which I have installed as well.

I modified the following option in the VS Code User Settings:

```<code>{
  "eslint.options": { "configFile": "C:/mypath" }
}
</code>```

I have use the command eslint --init to add the basic .eslintrc.json to the main directory of my package.

Other people were able to get ESLint feedback from VS Code using the exact same package with the exact same ESLint config file.

I have received no feedback of any kind when directly breaking multiple rules that were all included in the recommended rule set that is by default inside of the .eslintrc.json file.

What am I missing?

Edit: I have tested using ESLint via command line, and everything worked as expected, with the errors found where they should have, however, these same errors never showed up in VS Code. The issue seems to be on VS Code's side and not ESLint.

答:
In my case ESLint was properly installed and enabled and working in another workspace with identical settings.

What helped was to disable the extension in the workspace where it was not working, reload VSCode and then enable the extension back. Then it immediately started working.

Title: ESLint not working in VS Code?

Body:
ESLint is not working for me in VS Code. I have the plugin installed in VS Code, and ESLint itself as a developer dependency in my package.json, which I have installed as well.

I modified the following option in the VS Code User Settings:

{
  "eslint.options": { "configFile": "C:/mypath" }
}

I have use the command eslint --init to add the basic .eslintrc.json to the main directory of my package.

Other people were able to get ESLint feedback from VS Code using the exact same package with the exact same ESLint config file.

I have received no feedback of any kind when directly breaking multiple rules that were all included in the recommended rule set that is by default inside of the .eslintrc.json file.

What am I missing?

Edit: I have tested using ESLint via command line, and everything worked as expected, with the errors found where they should have, however, these same errors never showed up in VS Code. The issue seems to be on VS Code's side and not ESLint.


问:
Optimizing Multiple SQL Queries
I have 2 queries that I want to optimize but I don't know how. The execution time is not acceptable for me.

I'm working with jira database and did query to show different tasks with some attributes.
The code is:

```<code>SET NOCOUNT ON
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2

SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
        ,concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка'
        ,p.[pname] AS 'П'
        ,users.[display_name] AS 'Исполнитель'
        ,CAST(ji.[CREATED] AS smalldatetime) AS 'Создан'
        ,CAST(ji.[RESOLUTIONDATE] AS smalldatetime) AS 'Дата резолюции'
        ,ji.[issuenum]
INTO #TT
  FROM
    [jiraissue] AS ji
    LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
    LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
    LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
    LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
    LEFT OUTER JOIN [priority] AS p ON (p.[ID] = ji.[PRIORITY])
    LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
    LEFT OUTER JOIN [cwd_user] as users ON (users.[user_name] = ji.[ASSIGNEE])

  WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
  AND itype.pname = 'Incident'

SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
        ,system_t.[NAME] AS 'Контур ИС'
        ,system_t_t.[NAME] AS 'Критичность системы'
INTO #TT1
  FROM
    [jiraissue] AS ji
    LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
    LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
    LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
    LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
    LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
    LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
    LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t ON (system_t.[ID] = substring(customfv.[STRINGVALUE], PatIndex('%[0-9]%', customfv.[STRINGVALUE]), len(customfv.[STRINGVALUE])))
    LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR] AS system_attr ON (system_t.[ID] = system_attr.[OBJECT_ID])
    LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR_VAL] AS system_attr_val ON (system_attr.[ID] = system_attr_val.[OBJECT_ATTRIBUTE_ID])
    LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t_t ON (system_attr_val.[REFERENCED_OBJECT_ID] = system_t_t.[ID])

  WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
  AND (customfv.[CUSTOMFIELD] = 21003 OR customfv.[CUSTOMFIELD] = 21005)
  AND (system_t.[OBJECT_TYPE_ID] = 136 OR system_t.[OBJECT_TYPE_ID] = 303 OR system_t.[OBJECT_TYPE_ID] = 143)
  AND system_attr.[OBJECT_TYPE_ATTRIBUTE_ID] = 461
  AND itype.pname = 'Incident'

SELECT ji.[issuenum]
    ,pr_pr.[pname] AS '(project) Project'

INTO #TT2
  FROM
    [jiraissue] AS ji
    LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
    LEFT OUTER JOIN [project] AS pr_pr ON (pr_pr.[ID] = CAST(customfv.[NUMBERVALUE] AS BIGINT))
    LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
    LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
    LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
    LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
  WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
  AND pr_pr.[pname] is not NULL

  SELECT CTE.[Ключ], CTE.[Ссылка], CTE.[П], CTE.[Исполнитель], CTE.[Создан], CTE.[Дата резолюции], CTE2.[(project) Project], CTE1.[Контур ИС], CTE1.[Критичность системы], CTE.[issuenum]
  FROM #TT CTE
  LEFT OUTER JOIN #TT1 CTE1 ON (CTE1.[Ключ] = CTE.[Ключ])
  LEFT OUTER JOIN #TT2 CTE2 ON (CTE2.[issuenum] = CTE.[issuenum])

DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
</code>```

There will be some information for the month before last.

summary of query

The next query is:

```<code>WITH CTE AS (
SELECT concat(p.pkey,'-',i.issuenum) AS 'Ключ',
       cf.cfname,
       cv.textvalue,
       ROW_NUMBER() OVER (PARTITION BY i.issuenum ORDER BY i.issuenum) AS RowNumber_SLA
FROM   customfield cf,
       customfieldvalue cv,
       jiraissue i,
       project p
WHERE  i.project = p.id
       AND cv.issue = i.id
       AND cv.customfield = cf.id
       AND cf.customfieldtypekey = 'com.atlassian.servicedesk:sd-sla-field'
       and i.issuenum IN ()
       and CHARINDEX('"succeeded":false', TEXTVALUE) >0
)

SELECT CTE.Ключ
FROM CTE
WHERE RowNumber_SLA = 1
</code>```

The goal is to get tasks where SLA has been failed.
So in and i.issuenum IN () my Python script is putting issue numbers that I got through previous query.
The average execution time is 3 minutes.
So, I want optimize this too, maybe join first query.
Sorry for my English. I'm not an English-speaking person.

P. S. Changing CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done' to ci.[NEWSTRING] = 'Done' causing the error The data types ntext and varchar are incompatible in the equal to operator. Workaround - ci.[NEWSTRING] LIKE 'Done' fixing this.

答:
The first query must be rewrite as :

```<code>SELECT DISTINCT
       concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ',
       concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка',
       p.[pname] AS 'П',
       users.[display_name] AS 'Исполнитель',
       CAST(ji.[CREATED] AS SMALLDATETIME) AS 'Создан',
       CAST(ji.[RESOLUTIONDATE] AS SMALLDATETIME) AS 'Дата резолюции',
       ji.[issuenum]
INTO #TT
FROM [jiraissue] AS ji
     INNER JOIN [changegroup] AS cg ON(cg.[issueid] = ji.[id])
     INNER JOIN [changeitem] AS ci ON(ci.[groupid] = cg.[id])
                                          AND ci.FIELDTYPE = 'jira'
                                          AND ci.FIELD = 'status'
     LEFT OUTER JOIN [app_user] AS au ON(au.[user_key] = cg.[AUTHOR])
     INNER JOIN [issuetype] AS itype ON(itype.[ID] = ji.[issuetype])
     LEFT OUTER JOIN [priority] AS p ON(p.[ID] = ji.[PRIORITY])
     LEFT OUTER JOIN [project] AS pr ON(pr.[ID] = ji.[PROJECT])
     LEFT OUTER JOIN [cwd_user] AS users ON(users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(DATETIME, '2021-12-01')
      AND cg.[CREATED] <= CONVERT(DATETIME, '2022-01-01')
      AND ci.[NEWSTRING] = 'Done'
      AND itype.pname = 'Incident';
</code>```

False outer joins are converted in INNER and I have aslo eliminate the ugly CONVERT to NVARCHAR(max)

Same troubles appears in the second query...

Title: Optimizing Multiple SQL Queries

Body:
I have 2 queries that I want to optimize but I don't know how. The execution time is not acceptable for me.

I'm working with jira database and did query to show different tasks with some attributes.
The code is:

SET NOCOUNT ON
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2

SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
        ,concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка'
        ,p.[pname] AS 'П'
        ,users.[display_name] AS 'Исполнитель'
        ,CAST(ji.[CREATED] AS smalldatetime) AS 'Создан'
        ,CAST(ji.[RESOLUTIONDATE] AS smalldatetime) AS 'Дата резолюции'
        ,ji.[issuenum]
INTO #TT
  FROM
    [jiraissue] AS ji
    LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
    LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
    LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
    LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
    LEFT OUTER JOIN [priority] AS p ON (p.[ID] = ji.[PRIORITY])
    LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
    LEFT OUTER JOIN [cwd_user] as users ON (users.[user_name] = ji.[ASSIGNEE])

  WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
  AND itype.pname = 'Incident'

SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
        ,system_t.[NAME] AS 'Контур ИС'
        ,system_t_t.[NAME] AS 'Критичность системы'
INTO #TT1
  FROM
    [jiraissue] AS ji
    LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
    LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
    LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
    LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
    LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
    LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
    LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t ON (system_t.[ID] = substring(customfv.[STRINGVALUE], PatIndex('%[0-9]%', customfv.[STRINGVALUE]), len(customfv.[STRINGVALUE])))
    LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR] AS system_attr ON (system_t.[ID] = system_attr.[OBJECT_ID])
    LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR_VAL] AS system_attr_val ON (system_attr.[ID] = system_attr_val.[OBJECT_ATTRIBUTE_ID])
    LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t_t ON (system_attr_val.[REFERENCED_OBJECT_ID] = system_t_t.[ID])

  WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
  AND (customfv.[CUSTOMFIELD] = 21003 OR customfv.[CUSTOMFIELD] = 21005)
  AND (system_t.[OBJECT_TYPE_ID] = 136 OR system_t.[OBJECT_TYPE_ID] = 303 OR system_t.[OBJECT_TYPE_ID] = 143)
  AND system_attr.[OBJECT_TYPE_ATTRIBUTE_ID] = 461
  AND itype.pname = 'Incident'

SELECT ji.[issuenum]
    ,pr_pr.[pname] AS '(project) Project'

INTO #TT2
  FROM
    [jiraissue] AS ji
    LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
    LEFT OUTER JOIN [project] AS pr_pr ON (pr_pr.[ID] = CAST(customfv.[NUMBERVALUE] AS BIGINT))
    LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
    LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
    LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
    LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
  WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
  AND pr_pr.[pname] is not NULL

  SELECT CTE.[Ключ], CTE.[Ссылка], CTE.[П], CTE.[Исполнитель], CTE.[Создан], CTE.[Дата резолюции], CTE2.[(project) Project], CTE1.[Контур ИС], CTE1.[Критичность системы], CTE.[issuenum]
  FROM #TT CTE
  LEFT OUTER JOIN #TT1 CTE1 ON (CTE1.[Ключ] = CTE.[Ключ])
  LEFT OUTER JOIN #TT2 CTE2 ON (CTE2.[issuenum] = CTE.[issuenum])

DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2

There will be some information for the month before last.

summary of query

The next query is:

WITH CTE AS (
SELECT concat(p.pkey,'-',i.issuenum) AS 'Ключ',
       cf.cfname,
       cv.textvalue,
       ROW_NUMBER() OVER (PARTITION BY i.issuenum ORDER BY i.issuenum) AS RowNumber_SLA
FROM   customfield cf,
       customfieldvalue cv,
       jiraissue i,
       project p
WHERE  i.project = p.id
       AND cv.issue = i.id
       AND cv.customfield = cf.id
       AND cf.customfieldtypekey = 'com.atlassian.servicedesk:sd-sla-field'
       and i.issuenum IN ()
       and CHARINDEX('"succeeded":false', TEXTVALUE) >0
)

SELECT CTE.Ключ
FROM CTE
WHERE RowNumber_SLA = 1

The goal is to get tasks where SLA has been failed.
So in and i.issuenum IN () my Python script is putting issue numbers that I got through previous query.
The average execution time is 3 minutes.
So, I want optimize this too, maybe join first query.
Sorry for my English. I'm not an English-speaking person.

P. S. Changing CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done' to ci.[NEWSTRING] = 'Done' causing the error The data types ntext and varchar are incompatible in the equal to operator. Workaround - ci.[NEWSTRING] LIKE 'Done' fixing this.

Body:
The first query must be rewrite as :

SELECT DISTINCT
       concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ',
       concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка',
       p.[pname] AS 'П',
       users.[display_name] AS 'Исполнитель',
       CAST(ji.[CREATED] AS SMALLDATETIME) AS 'Создан',
       CAST(ji.[RESOLUTIONDATE] AS SMALLDATETIME) AS 'Дата резолюции',
       ji.[issuenum]
INTO #TT
FROM [jiraissue] AS ji
     INNER JOIN [changegroup] AS cg ON(cg.[issueid] = ji.[id])
     INNER JOIN [changeitem] AS ci ON(ci.[groupid] = cg.[id])
                                          AND ci.FIELDTYPE = 'jira'
                                          AND ci.FIELD = 'status'
     LEFT OUTER JOIN [app_user] AS au ON(au.[user_key] = cg.[AUTHOR])
     INNER JOIN [issuetype] AS itype ON(itype.[ID] = ji.[issuetype])
     LEFT OUTER JOIN [priority] AS p ON(p.[ID] = ji.[PRIORITY])
     LEFT OUTER JOIN [project] AS pr ON(pr.[ID] = ji.[PROJECT])
     LEFT OUTER JOIN [cwd_user] AS users ON(users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(DATETIME, '2021-12-01')
      AND cg.[CREATED] <= CONVERT(DATETIME, '2022-01-01')
      AND ci.[NEWSTRING] = 'Done'
      AND itype.pname = 'Incident';

False outer joins are converted in INNER and I have aslo eliminate the ugly CONVERT to NVARCHAR(max)

Same troubles appears in the second query...


问:
Replace the image in "<input>" by a new one with the reduced size
First of all JS is not my usual language, sorry if the question is not very clear.

I have been testing a code to compress the images that users upload to an <input> the JS code of compression is working perfectly but I don't know how to do to replace the file that they have chosen in the "input" by the one that I have just generated compressed.

I want to do this because the <input> is inside a form so I can upload the image to the server compressed.

Here is the JS fot compression:

```<code>const MAX_WIDTH = 300;
const MAX_HEIGHT = 200;
const MIME_TYPE = "image/jpeg";
const QUALITY = 0.8;
const input = document.getElementById("img-1");

input.onchange = function (ev) {
    const file = ev.target.files[0]; // get the file
    const blobURL = URL.createObjectURL(file);
    const img = new Image();
    img.src = blobURL;
    img.onerror = function () {
        URL.revokeObjectURL(this.src);
        // Handle the failure properly
        console.log("Cannot load image");
    };
    img.onload = function () {
        URL.revokeObjectURL(this.src);
        const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT);
        const canvas = document.createElement("canvas");
        canvas.width = newWidth;
        canvas.height = newHeight;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, newWidth, newHeight);
        canvas.toBlob(
            blob => {
                // Do something with img in my case show in Frontend
                displayInfo('Original file', file);
                displayInfo('Compressed file', blob);
            },
            MIME_TYPE,
            QUALITY);

        // Only for testing and see results
        document.getElementById("pruebas-tam").append(canvas);
    };
};
</code>```

答:
After many tests I managed to find the solution, adding these lines just where we have the 'blob' we can replace the input with the new compressed image. The solution is based on creating a file using the Blob and then assigning it to a DataTransfer and finally assigning it back to the Input.</p>
```<code>displayInfo('Original file', file);
displayInfo('Compressed file', blob);

// Here is where we convert the blob into a file and put inside DataTransfer
let newfile = new File([blob], "filename.ext",{type:MIME_TYPE,
lastModified:new Date().getTime()});
let container = new DataTransfer();
container.items.add(newfile);
input.files = container.files;
</code>```

Body:
First of all JS is not my usual language, sorry if the question is not very clear.

I have been testing a code to compress the images that users upload to an <input> the JS code of compression is working perfectly but I don't know how to do to replace the file that they have chosen in the "input" by the one that I have just generated compressed.

I want to do this because the <input> is inside a form so I can upload the image to the server compressed.

Here is the JS fot compression:

const MAX_WIDTH = 300;
const MAX_HEIGHT = 200;
const MIME_TYPE = "image/jpeg";
const QUALITY = 0.8;
const input = document.getElementById("img-1");

input.onchange = function (ev) {
    const file = ev.target.files[0]; // get the file
    const blobURL = URL.createObjectURL(file);
    const img = new Image();
    img.src = blobURL;
    img.onerror = function () {
        URL.revokeObjectURL(this.src);
        // Handle the failure properly
        console.log("Cannot load image");
    };
    img.onload = function () {
        URL.revokeObjectURL(this.src);
        const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT);
        const canvas = document.createElement("canvas");
        canvas.width = newWidth;
        canvas.height = newHeight;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, newWidth, newHeight);
        canvas.toBlob(
            blob => {
                // Do something with img in my case show in Frontend
                displayInfo('Original file', file);
                displayInfo('Compressed file', blob);
            },
            MIME_TYPE,
            QUALITY);

        // Only for testing and see results
        document.getElementById("pruebas-tam").append(canvas);
    };
};

Body:
After many tests I managed to find the solution, adding these lines just where we have the 'blob' we can replace the input with the new compressed image. The solution is based on creating a file using the Blob and then assigning it to a DataTransfer and finally assigning it back to the Input.

displayInfo('Original file', file);
displayInfo('Compressed file', blob);

// Here is where we convert the blob into a file and put inside DataTransfer
let newfile = new File([blob], "filename.ext",{type:MIME_TYPE,
lastModified:new Date().getTime()});
let container = new DataTransfer();
container.items.add(newfile);
input.files = container.files;