问:
How to convert a database data in predefined format and generate output in text format
I am having a SQL database having the attributes:

First_Name

Last_Name

Sex

Address

For reporting to the authority I have a fixed format like

For the First name:
FN(no of characters in the first name)First_Name

For example the first name Daniel should be like: FN05Daniel

For Bose, it should be: LN04Bose

Is there any way using SSIS the same can be accomplished and the output can be generated in text format?

If not SSIS please suggest any probable mechanism to get the result. I am just learning to code so please don't mind if it's a silly question.

答:
I don't get what you mean but this is how i use sqlite3

class Database():
    def __init__(self, path = ""):
        try:
            if path == "":
                with open("Database.db", "r") as Database:
                    pass
                self.path = "Database.db"
            else:
                with open(path + "/Database.db", "r") as Database:
                    pass
                self.path = path + "/Database.db"
        except:
            if path == "":
                with open("Database.db", "x") as Database:
                    pass
                self.path = "Database.db"
            else:
                if not os.path.exists(path):
                    os.mkdir(path)
                with open(path + "/Database.db", "x") as Database:
                    pass
                self.path = path + "/Database.db"
        self.Database = sqlite3.connect(self.path)
        self.Cursor = self.Database.cursor()
    def createSheet(self, name):
        self.Database.execute(
          f'''CREATE TABLE IF NOT EXISTS {name}(
          ID INT PRIMARY KEY
          );
          '''
        )
    def setVar(self, Sheet, Var, Value):
        try:
          self.Cursor.execute(
            f'''ALTER TABLE {Sheet} ADD COLUMN {Var} TEXT'''
          )
        except:
          pass
        self.Cursor.execute(
          f'''INSERT OR IGNORE INTO {Sheet} ({Var}) VALUES ("{Value}")'''
        )
        self.Cursor.execute(
          f'''UPDATE {Sheet} SET {Var} = "{Value}"'''
        )
        self.Database.commit()
    def readVar(self, Sheet, Var, Convert = str):
        DataGet = self.Database.execute(f'SELECT {Var} from {Sheet}').fetchone()
        return Convert(DataGet[0])
```

So imagine sqlite3 as Excel

The createSheet function actually creates a sheet in Excel (in sqlite3 is table)

The addVar function creates a column (which is the variable name, this variable is empty, which mean it doesn't have value) if not exists then it's will insert (put a value into the variable) or update (same as insert but it's update, insert function only work when you add an empty variable), value in sqlite3 is row

The readVar function read the value base on the variable name

Body:
I don't get what you mean but this is how i use sqlite3

class Database():
    def __init__(self, path = ""):
        try:
            if path == "":
                with open("Database.db", "r") as Database:
                    pass
                self.path = "Database.db"
            else:
                with open(path + "/Database.db", "r") as Database:
                    pass
                self.path = path + "/Database.db"
        except:
            if path == "":
                with open("Database.db", "x") as Database:
                    pass
                self.path = "Database.db"
            else:
                if not os.path.exists(path):
                    os.mkdir(path)
                with open(path + "/Database.db", "x") as Database:
                    pass
                self.path = path + "/Database.db"
        self.Database = sqlite3.connect(self.path)
        self.Cursor = self.Database.cursor()
    def createSheet(self, name):
        self.Database.execute(
          f'''CREATE TABLE IF NOT EXISTS {name}(
          ID INT PRIMARY KEY
          );
          '''
        )
    def setVar(self, Sheet, Var, Value):
        try:
          self.Cursor.execute(
            f'''ALTER TABLE {Sheet} ADD COLUMN {Var} TEXT'''
          )
        except:
          pass
        self.Cursor.execute(
          f'''INSERT OR IGNORE INTO {Sheet} ({Var}) VALUES ("{Value}")'''
        )
        self.Cursor.execute(
          f'''UPDATE {Sheet} SET {Var} = "{Value}"'''
        )
        self.Database.commit()
    def readVar(self, Sheet, Var, Convert = str):
        DataGet = self.Database.execute(f'SELECT {Var} from {Sheet}').fetchone()
        return Convert(DataGet[0])

So imagine sqlite3 as Excel

The createSheet function actually creates a sheet in Excel (in sqlite3 is table)

The addVar function creates a column (which is the variable name, this variable is empty, which mean it doesn't have value) if not exists then it's will insert (put a value into the variable) or update (same as insert but it's update, insert function only work when you add an empty variable), value in sqlite3 is row

The readVar function read the value base on the variable name


来源: stackexchange

问:
Using System.Json for non-Silverlight projects?
Any idea on how to do it? If not possible, what's a good JSON library for C#?</p>

答:
System.Json is now available in non-Silverlight projects via NuGet (.Net's package management system) and is hopefully going to be released as part of the core framework in vnext.  The NuGet package is named JsonValue.

Imagine that we have the following JSON in the string variable json:

```<code>[{"a":"foo","b":"bar"},{"a":"another foo","b":"another bar"}]
</code>```

We can get write the value "another bar" to the console using the following code:

```<code>using System.Json;
dynamic jsonObj = JsonValue.Parse(json);
var node = jsonObj[1].b;
System.Console.WriteLine(node.Value);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
System.Json is now available in non-Silverlight projects via NuGet (.Net's package management system) and is hopefully going to be released as part of the core framework in vnext.  The NuGet package is named JsonValue.

Imagine that we have the following JSON in the string variable json:

[{"a":"foo","b":"bar"},{"a":"another foo","b":"another bar"}]

We can get write the value "another bar" to the console using the following code:

using System.Json;
dynamic jsonObj = JsonValue.Parse(json);
var node = jsonObj[1].b;
System.Console.WriteLine(node.Value);

ContentLicense: CC BY-SA 3.0


问:
error: cannot shadow already defined class `Error` after adding console_error_panic_hook::set_once();
Simply adding console_error_panic_hook::set_once() causes the error:

```<code>[WARN]: :-) origin crate has no README
[INFO]: Installing wasm-bindgen...
error: cannot shadow already defined class `Error`
Error: Running the wasm-bindgen CLI
Caused by: failed to execute `wasm-bindgen`: exited with exit code: 1
</code>```

And yes, I do have my own Error struct, but why does using this function cause a "shadow" error?

The error only happens if I export the Error struct with [wasm_bindgen].

The error occurs after running wasm-pack build --target web

Reproduction

```<code># cargo.toml
[package]
name = "testing"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
console_error_panic_hook = "0.1.7"
wasm-bindgen = { version = "0.2.76" }
</code>```

// lib.rs

use wasm_bindgen::prelude::wasm_bindgen;
// Adding this does not help:
// extern crate console_error_panic_hook;

#[wasm_bindgen] // Works if either this line is remove...
struct Error {}

#[wasm_bindgen]
pub fn main() {
    console_error_panic_hook::set_once(); // ... or this one
    println!("Hello, world!");
}
```
<h1>Versions</h1>
```wasm-pack 0.10.2
cargo 1.58.0 (f01b232bc 2022-01-19)
rustc 1.58.1 (db9d1b20b 2022-01-20)
```

答:
This code:

```<code>#[wasm_bindgen]
struct Error {}
</code>```

...means that you want your own struct Error to be treated as WASM-binding to the JavaScript Error type. Since console_error_panic_hook needs to bind to JavaScript Error too, this generates a conflict - with multiple bindings, it's unclear what struct should be created in Rust, when JavaScript passes its Error to WASM function.

ContentLicense: CC BY-SA 4.0

Body:
Simply adding console_error_panic_hook::set_once() causes the error:

[WARN]: :-) origin crate has no README
[INFO]: Installing wasm-bindgen...
error: cannot shadow already defined class `Error`
Error: Running the wasm-bindgen CLI
Caused by: failed to execute `wasm-bindgen`: exited with exit code: 1

And yes, I do have my own Error struct, but why does using this function cause a "shadow" error?

The error only happens if I export the Error struct with [wasm_bindgen].

The error occurs after running wasm-pack build --target web

Reproduction

# cargo.toml
[package]
name = "testing"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
console_error_panic_hook = "0.1.7"
wasm-bindgen = { version = "0.2.76" }

// lib.rs

use wasm_bindgen::prelude::wasm_bindgen;
// Adding this does not help:
// extern crate console_error_panic_hook;

#[wasm_bindgen] // Works if either this line is remove...
struct Error {}

#[wasm_bindgen]
pub fn main() {
    console_error_panic_hook::set_once(); // ... or this one
    println!("Hello, world!");
}

Versions

wasm-pack 0.10.2
cargo 1.58.0 (f01b232bc 2022-01-19)
rustc 1.58.1 (db9d1b20b 2022-01-20)

Body:
This code:

#[wasm_bindgen]
struct Error {}

...means that you want your own struct Error to be treated as WASM-binding to the JavaScript Error type. Since console_error_panic_hook needs to bind to JavaScript Error too, this generates a conflict - with multiple bindings, it's unclear what struct should be created in Rust, when JavaScript passes its Error to WASM function.


问:
How to auto append new column everyday to a google sheet via google script and add data via gmail attachment?
I am getting an email every day with 3 attachments (xlsx). I want the last column of the second tab of the 2nd attachment to be appended to an existing google sheet (in the column next to the last one). I have done some research and came up with a code to export the xlsx file to google drive, then convert it to CSV. I am able to update the whole google sheet with the data in the second attachment, but I am not able to copy the last column of the sheet and append it to an existing sheet. The destination sheet has 4 columns as of now, and I want a new column to be added every day along with the latest data from the attachment in my Gmail. Below is the code which I am using:

function importCSVFromGmail() {

  var thread = GmailApp.search("Scheduled Reports from RingCentral"); // enter search criteria here
  var messages = thread[0].getMessages();
  var len = messages.length;
  var message=messages[len-1] //get last message
  var attachments = message.getAttachments(); // Get attachment of first message
  var xlsxBlob = attachments[1]; // Is supposes that attachments[1] is the blob of xlsx file. I get 3 attachments in gmail, and I am using the 2nd one, so using attachment[1]
  var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
  var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[2]; // There is the data in 1st tab.
  var data = sheet.getDataRange().getValues();
  var sheet2 = SpreadsheetApp.openByUrl("link to the existing google sheet").getSheetByName("Test"); //add the URL of the google sheet along with the tab name, in this case, "Test"
  sheet2.clearContents();
  var copyColumn = sheet.getRange("D1:D21"); //copying the column which I need to paste
  var range = sheet2.getRange(5, 5, data.length, data[0].length); //5 is the column where I was testing to paste the data
  var lastColumn = sheet2.getLastColumn();
  copyColumn.copyValuesToRange(sheet2, lastColumn+1, lastColumn+1, 1, 23); // there are 23 rows
  Drive.Files.remove(convertedSpreadsheetId); // Remove the converted file.
}
```
<p>I am pretty sure I am doing some blunder in this code, also I am getting this exception and the code is not working:</p>
```Exception: Target sheet and source range must be on the same spreadsheet. (line 23, file "AP Script")
```

Please let me know if my requirements are not clear.

答:
try this:</p>
```<code>function importCSVFromGmail() {
  var thread = GmailApp.search("Scheduled Reports from RingCentral"); // enter search criteria here
  var messages = thread[0].getMessages();
  var len = messages.length;
  var message=messages[len-1] //get last message
  var attachments = message.getAttachments(); // Get attachment of first message
  var xlsxBlob = attachments[1]; // Is supposes that attachments[1] is the blob of xlsx file. I get 3 attachments in gmail, and I am using the 2nd one, so using attachment[1]
  var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
  var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[2]; // There is the data in 1st tab.
  var data = sheet.getDataRange().getValues();
  var sheet2 = SpreadsheetApp.openByUrl("link to the existing google sheet").getSheetByName("Test"); //add the URL of the google sheet along with the tab name, in this case, "Test"
  sheet2.clearContents();
  var vs = sheet.getRange("D1:D21").getValues();
  var range = sheet2.getRange(5, 5, data.length, data[0].length); //5 is the column where I was testing to paste the data
  var lastColumn = sheet2.getLastColumn();
  sheet2.getRange(sheet2.getLastRow() + 1,1,vs.length,vs[0].length).setValues(vs);
  Drive.Files.remove(convertedSpreadsheetId);
}
</code>```

Body:
I am getting an email every day with 3 attachments (xlsx). I want the last column of the second tab of the 2nd attachment to be appended to an existing google sheet (in the column next to the last one). I have done some research and came up with a code to export the xlsx file to google drive, then convert it to CSV. I am able to update the whole google sheet with the data in the second attachment, but I am not able to copy the last column of the sheet and append it to an existing sheet. The destination sheet has 4 columns as of now, and I want a new column to be added every day along with the latest data from the attachment in my Gmail. Below is the code which I am using:

function importCSVFromGmail() {

  var thread = GmailApp.search("Scheduled Reports from RingCentral"); // enter search criteria here
  var messages = thread[0].getMessages();
  var len = messages.length;
  var message=messages[len-1] //get last message
  var attachments = message.getAttachments(); // Get attachment of first message
  var xlsxBlob = attachments[1]; // Is supposes that attachments[1] is the blob of xlsx file. I get 3 attachments in gmail, and I am using the 2nd one, so using attachment[1]
  var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
  var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[2]; // There is the data in 1st tab.
  var data = sheet.getDataRange().getValues();
  var sheet2 = SpreadsheetApp.openByUrl("link to the existing google sheet").getSheetByName("Test"); //add the URL of the google sheet along with the tab name, in this case, "Test"
  sheet2.clearContents();
  var copyColumn = sheet.getRange("D1:D21"); //copying the column which I need to paste
  var range = sheet2.getRange(5, 5, data.length, data[0].length); //5 is the column where I was testing to paste the data
  var lastColumn = sheet2.getLastColumn();
  copyColumn.copyValuesToRange(sheet2, lastColumn+1, lastColumn+1, 1, 23); // there are 23 rows
  Drive.Files.remove(convertedSpreadsheetId); // Remove the converted file.
}

I am pretty sure I am doing some blunder in this code, also I am getting this exception and the code is not working:

Exception: Target sheet and source range must be on the same spreadsheet. (line 23, file "AP Script")

Please let me know if my requirements are not clear.

Body:
try this:

function importCSVFromGmail() {
  var thread = GmailApp.search("Scheduled Reports from RingCentral"); // enter search criteria here
  var messages = thread[0].getMessages();
  var len = messages.length;
  var message=messages[len-1] //get last message
  var attachments = message.getAttachments(); // Get attachment of first message
  var xlsxBlob = attachments[1]; // Is supposes that attachments[1] is the blob of xlsx file. I get 3 attachments in gmail, and I am using the 2nd one, so using attachment[1]
  var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
  var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[2]; // There is the data in 1st tab.
  var data = sheet.getDataRange().getValues();
  var sheet2 = SpreadsheetApp.openByUrl("link to the existing google sheet").getSheetByName("Test"); //add the URL of the google sheet along with the tab name, in this case, "Test"
  sheet2.clearContents();
  var vs = sheet.getRange("D1:D21").getValues();
  var range = sheet2.getRange(5, 5, data.length, data[0].length); //5 is the column where I was testing to paste the data
  var lastColumn = sheet2.getLastColumn();
  sheet2.getRange(sheet2.getLastRow() + 1,1,vs.length,vs[0].length).setValues(vs);
  Drive.Files.remove(convertedSpreadsheetId);
}


问:
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)

答:
The one which you were trying shall render you only SUM of UNIQUE values i.e. for 1,2 or 3. However there is a workaround instead of using MATCH Function simply use the FREQUENCY Function with IF & ROW Function & wrap it within SUMPRODUCT!

Perhaps there is much easier way to of summing instead of using FREQUENCY Function, FREQUENCY Function also slows down the working functionality.

Using FREQUENCY Function --> Formula used in cell C8

```<code>=SUMPRODUCT(FREQUENCY(IF($B$1:$B$5=$A6,ROW($C$1:$C$5)),ROW($C$1:$C$5)),$C$1:$C$6)
</code>```

The easy way is using SUMPRODUCT Function this is because it multiplies ranges or arrays together and returns the sum of products. SUMPRODUCT is an incredibly versatile function which can be further used to count and sum like COUNTIFS or SUMIFS, but with more flexibility. Other functions can also easily be used inside SUMPRODUCT to extend functionality even further.

Formula used in cell C7

```<code>=SUMPRODUCT(($B$1:$B$5=$A$6)*($C$1:$C$5))
</code>```

Side Note: The SUMPRODUCT function can be used to create array formulas that don't require CTRL + SHIFT + ENTER. This is the most important reason why SUMPRODUCT is been so extensively used to create more advanced formulas.

One main issues with array formulas is that they usually return incorrect results if they are not entered with CTRL + SHIFT + ENTER. That said if someone forgets to confirm press CSE when entering a formula, the expected output may suddenly alter, nonetheless the actual formula did not change. Using SUMPRODUCT means the formulas will work in any version of Excel without special handling.

In O365, the formula engine handles arrays natively & can often use the SUM function in place of SUMPRODUCT in an array formula with the same desired output and you don't have to press CSE. If the same formula is opened in an earlier version of Excel, it will require CTRL + SHIFT + ENTER.

Fundamentally SUMPRODUCT is a much safer option if a worksheet is used any version of Excel before MS365, even if the worksheet was created in MS365.

Body:
The one which you were trying shall render you only SUM of UNIQUE values i.e. for 1,2 or 3. However there is a workaround instead of using MATCH Function simply use the FREQUENCY Function with IF & ROW Function & wrap it within SUMPRODUCT!

Perhaps there is much easier way to of summing instead of using FREQUENCY Function, FREQUENCY Function also slows down the working functionality.

Using FREQUENCY Function --> Formula used in cell C8

=SUMPRODUCT(FREQUENCY(IF($B$1:$B$5=$A6,ROW($C$1:$C$5)),ROW($C$1:$C$5)),$C$1:$C$6)

The easy way is using SUMPRODUCT Function this is because it multiplies ranges or arrays together and returns the sum of products. SUMPRODUCT is an incredibly versatile function which can be further used to count and sum like COUNTIFS or SUMIFS, but with more flexibility. Other functions can also easily be used inside SUMPRODUCT to extend functionality even further.

Formula used in cell C7

=SUMPRODUCT(($B$1:$B$5=$A$6)*($C$1:$C$5))

Side Note: The SUMPRODUCT function can be used to create array formulas that don't require CTRL + SHIFT + ENTER. This is the most important reason why SUMPRODUCT is been so extensively used to create more advanced formulas.

One main issues with array formulas is that they usually return incorrect results if they are not entered with CTRL + SHIFT + ENTER. That said if someone forgets to confirm press CSE when entering a formula, the expected output may suddenly alter, nonetheless the actual formula did not change. Using SUMPRODUCT means the formulas will work in any version of Excel without special handling.

In O365, the formula engine handles arrays natively & can often use the SUM function in place of SUMPRODUCT in an array formula with the same desired output and you don't have to press CSE. If the same formula is opened in an earlier version of Excel, it will require CTRL + SHIFT + ENTER.

Fundamentally SUMPRODUCT is a much safer option if a worksheet is used any version of Excel before MS365, even if the worksheet was created in MS365.


问:
How to update a single column in a Pandas df with data from a second Pandas df using pd.merge function
Please see my code below.  I was stuck on this problem for a while and so thought I would share the solution I found in case it helps someone else.

The problem (now solved; see solution below) is as follows:

I have a "master" df, called df_master, that holds a large amount of information.

The data in column 'c' of df_master contains pricing data that must sometimes be updated with data found in column 'c' of a second, smaller df.  I call this smaller df 'df_updates'.

df_updates contains pricing updates for only a small portion of the rows in df_master, meaning that only a few updates to column 'c' of df_master need to be made.

The column names in df_updates are identical to the column names in df_master.

I wish to update the pricing data in col 'c' of df_master with the information in col 'c' of df_updates.

The solution I found is in the answer below.  Hopefully this helps someone facing this same problem.

答:
Please find below the code for my solution to this issue.  I've inserted explanatory comments in the code.</p>
```<code>import pandas as pd
import numpy as np

# Create the df_master, which will be updated by the df_updates dataframe.
df_master = pd.DataFrame(np.array([[1, 11, 111], [2, 22, 222], [3, 33, 333], [4, 44, 444]]),
                   columns=['a', 'b', 'c'])

# Create df_updates, which contains updates that need to be made to df_master.
df_updates = pd.DataFrame(np.array([[1, 11, 500], [2, 22, 600]]),
                   columns=['a', 'b', 'c'])

# View dfs prior to pd.merge function.
print('df_master')
display(df_master)
print('')
print('df_updates')
display(df_updates)

# Merge df_master and df_updates using all columns other than the column that is to be updated.
df_master_updated = pd.merge(df_master, df_updates, left_on=['a', 'b'], right_on=['a', 'b'], how='left', indicator=False)

# Display df_master_updated to show the unwanted columns 'c_x' and 'c_y' that need to be merged
# into new col and then deleted.
print('')
print('df_master_updated')
display(df_master_updated)

# Calculate a new column 'c' by using the values from df_updates, unless df_updates
# has NaN value, in which case we use .fillna() to pull value from column 'c' of df_master.
df_master_updated['c'] = df_master_updated['c_y'].fillna(df_master_updated['c_x'])

# Drop cols 'c_x' and 'c_y'
df_master_updated = df_master_updated.drop(['c_x', 'c_y'], axis=1)

# Display the final updated df_master_updated, where all col 'c' values have been udpated.
print('')
print('df_master_updated')
display(df_master_updated)
</code>```

Body:
Please find below the code for my solution to this issue.  I've inserted explanatory comments in the code.

import pandas as pd
import numpy as np

# Create the df_master, which will be updated by the df_updates dataframe.
df_master = pd.DataFrame(np.array([[1, 11, 111], [2, 22, 222], [3, 33, 333], [4, 44, 444]]),
                   columns=['a', 'b', 'c'])

# Create df_updates, which contains updates that need to be made to df_master.
df_updates = pd.DataFrame(np.array([[1, 11, 500], [2, 22, 600]]),
                   columns=['a', 'b', 'c'])

# View dfs prior to pd.merge function.
print('df_master')
display(df_master)
print('')
print('df_updates')
display(df_updates)

# Merge df_master and df_updates using all columns other than the column that is to be updated.
df_master_updated = pd.merge(df_master, df_updates, left_on=['a', 'b'], right_on=['a', 'b'], how='left', indicator=False)

# Display df_master_updated to show the unwanted columns 'c_x' and 'c_y' that need to be merged
# into new col and then deleted.
print('')
print('df_master_updated')
display(df_master_updated)

# Calculate a new column 'c' by using the values from df_updates, unless df_updates
# has NaN value, in which case we use .fillna() to pull value from column 'c' of df_master.
df_master_updated['c'] = df_master_updated['c_y'].fillna(df_master_updated['c_x'])

# Drop cols 'c_x' and 'c_y'
df_master_updated = df_master_updated.drop(['c_x', 'c_y'], axis=1)

# Display the final updated df_master_updated, where all col 'c' values have been udpated.
print('')
print('df_master_updated')
display(df_master_updated)


问:
List.stream().filter() vs removeIf
Please help me understand the difference.

I'm trying to remove elements from list. If I use stream().filter(), this works but when I use removeIf, it throws UnsupportedOperationException.

```<code>private void filterEmployees(EmployeeResponse employeeResponse) {
        List<Employee> employees = employeeResponse.getEmployees();
        List<Employee> employeesFiltered = employees
                .stream()
                .filter(employee -> employee.getRole().equals("01") || employee.getRole().equals("02") || employee.getRole().equals("03"))
                .collect(Collectors.toList());
        employeeResponse.setEmployees(employeesFiltered);
    }
</code>```

Below code throws UnsupportedOperationException.

```<code>private void filterEmployees(EmployeeResponse employeeResponse, List<String> rolesList) {
        List<Employee> employees = employeeResponse.getEmployees();
        employees.removeIf(employee -> !rolesList.contains(employee.getRole()));
        employeeResponse.setEmployees(employees);
    }
</code>```

Exception:

```<code>java.lang.UnsupportedOperationException: remove

    at java.base/java.util.Iterator.remove(Iterator.java:102)
    at java.base/java.util.Collection.removeIf(Collection.java:545)
</code>```

答:
Streaming list with a filter simply filters the current list, skipping the unwanted values, and creates a new one.  I would be equivalent to you iterating the list and when you see the value, skip it. Otherwise add it to the new list.

removeIf is a new method in Java 8.  It is in the Collections interface which List extends.  That method is not supported in any immutable collection or in List.of which creates an ImmutableCollection.

I can't tell if that is the problem so you may want to check if that instance is immutable by doing the following:

```<code>List<Employee> employees = employeeResponse.getEmployees();
System.out.println(employees.getClass().getName());
</code>```

One way to possibly solve that problem is to do the following:

```<code>List<Employee> employee = new ArrayList<>(employeeResponse.getEmployees());
</code>```

Which creates a mutable ArrayList and populates it with the employee list.  Then removeIf should work as expected.

Title: List.stream().filter() vs removeIf

Body:
Please help me understand the difference.

I'm trying to remove elements from list. If I use stream().filter(), this works but when I use removeIf, it throws UnsupportedOperationException.

private void filterEmployees(EmployeeResponse employeeResponse) {
        List<Employee> employees = employeeResponse.getEmployees();
        List<Employee> employeesFiltered = employees
                .stream()
                .filter(employee -> employee.getRole().equals("01") || employee.getRole().equals("02") || employee.getRole().equals("03"))
                .collect(Collectors.toList());
        employeeResponse.setEmployees(employeesFiltered);
    }

Below code throws UnsupportedOperationException.

private void filterEmployees(EmployeeResponse employeeResponse, List<String> rolesList) {
        List<Employee> employees = employeeResponse.getEmployees();
        employees.removeIf(employee -> !rolesList.contains(employee.getRole()));
        employeeResponse.setEmployees(employees);
    }

Exception:

java.lang.UnsupportedOperationException: remove

    at java.base/java.util.Iterator.remove(Iterator.java:102)
    at java.base/java.util.Collection.removeIf(Collection.java:545)

Body:
Streaming list with a filter simply filters the current list, skipping the unwanted values, and creates a new one.  I would be equivalent to you iterating the list and when you see the value, skip it. Otherwise add it to the new list.

removeIf is a new method in Java 8.  It is in the Collections interface which List extends.  That method is not supported in any immutable collection or in List.of which creates an ImmutableCollection.

I can't tell if that is the problem so you may want to check if that instance is immutable by doing the following:

List<Employee> employees = employeeResponse.getEmployees();
System.out.println(employees.getClass().getName());

One way to possibly solve that problem is to do the following:

List<Employee> employee = new ArrayList<>(employeeResponse.getEmployees());

Which creates a mutable ArrayList and populates it with the employee list.  Then removeIf should work as expected.


问:
Examples of compiled programming languages with modern features for the real world [please vote for reopen]
Apart from C, C++, Delphi, VB, can you put an example of a relatively "modern" COMPILED* programming language* supporting things like OO, collections, GUI libraries?
Please do not mention experimental or academic only languages, I'm looking for something used in the real world, for PCs 80x86, and I don't mind about the OS.

Thanks!

*UPDATED: Compiled to native code.

*DISCLAIMER:

For language understand language implementation.

For compiled to native code understand not interpreted.

答: Wikipedia has a lot: http://en.wikipedia.org/wiki/Comparison_of_programming_languages</p>


问:
autofill won't fill until last row
I have a code for inserting formula at some row in a module

Then I add a new module to autofill the formula depending on C column (if C 15 data then it autofill down 15)

The autofill works manually to what I expected, but when I set to Private Sub for Workbook_Open, the autofill doesn't fill the last row (if 15 data, the macro only fill until row 14)

Below is my autofill code

```<code>Sub AutoFill()

lr = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row

ThisWorkbook.Sheets(1).Range("A6:B6").AutoFill Destination:=ThisWorkbook.Sheets(1).Range("A6:B" & lr), Type:=xlFillDefault
ThisWorkbook.Sheets(1).Range("D6:S6").AutoFill Destination:=ThisWorkbook.Sheets(1).Range("D6:S" & lr), Type:=xlFillDefault

End Sub
</code>```

How do I make this code run until the last row when I set it to Private Sub?

答:
Range.AutoFill

The important difference is that in this solution the .Cells are qualified ws.Cells i.e. ThisWorkbook.Sheets(1).Cells and ThisWorkbook.Sheets(1).Cells(1, 1) to ensure that the correct worksheet is being searched. You can use variables to shorten the lines.

Option Explicit

Sub AutoFill()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets(1)

    Dim lrCell As Range
    Set lrCell = ws.Cells.Find("*", , xlFormulas, , xlByRows, xlPrevious)
    If lrCell Is Nothing Then Exit Sub ' empty worksheet

    Dim lr As Long: lr = lrCell.Row
    If lr < 7 Then Exit Sub ' no data below

    ws.Range("A6:B6").AutoFill Destination:=ws.Range("A6:B" & lr), Type:=xlFillDefault
    ws.Range("D6:S6").AutoFill Destination:=ws.Range("D6:S" & lr), Type:=xlFillDefault

End Sub
```

Title: autofill won't fill until last row

Body:
I have a code for inserting formula at some row in a module

Then I add a new module to autofill the formula depending on C column (if C 15 data then it autofill down 15)

The autofill works manually to what I expected, but when I set to Private Sub for Workbook_Open, the autofill doesn't fill the last row (if 15 data, the macro only fill until row 14)

Below is my autofill code

Sub AutoFill()

lr = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row

ThisWorkbook.Sheets(1).Range("A6:B6").AutoFill Destination:=ThisWorkbook.Sheets(1).Range("A6:B" & lr), Type:=xlFillDefault
ThisWorkbook.Sheets(1).Range("D6:S6").AutoFill Destination:=ThisWorkbook.Sheets(1).Range("D6:S" & lr), Type:=xlFillDefault

End Sub

How do I make this code run until the last row when I set it to Private Sub?


问:
Behaviour subject initial value null?
```<code>private customer: Subject<Object> = new BehaviorSubject<Object>(null);

setCustomer(id, accountClassCode) {
    this.customer.next({'id': id, 'accountClassCode': accountClassCode});
}

getCustomer() {
    return this.customer.asObservable();
}
</code>```

I'm using this part of code but I'm getting an error that can not find id of null. Is there any solution to get initial value that is not null?

答:
Another way is to use pipe to filter until a non-null value is received. It can be done with takeWhile also.

.pipe(filter(val => !!val)).subscribe(x => {});

Title: Behaviour subject initial value null?

Body:
private customer: Subject<Object> = new BehaviorSubject<Object>(null);

setCustomer(id, accountClassCode) {
    this.customer.next({'id': id, 'accountClassCode': accountClassCode});
}

getCustomer() {
    return this.customer.asObservable();
}

I'm using this part of code but I'm getting an error that can not find id of null. Is there any solution to get initial value that is not null?


问:
programatically seelect angular mat chip values
we have some selectable dropdowns using mat chip as a component. The requirement is that when there are some values in the Url query string, then those values should also be pre selected in the relevant multi select option.
am fairly new to angular. have been able to get values from the url into relevant property arrays but cant seem to figure out how to programatically select those values for each of the multi select dropdown.

code is as under:

mat chip component:

```<code><mat-expansion-panel class="shadow-none" style="box-shadow:none !important">
  <mat-expansion-panel-header>
    <mat-panel-title>
      {{label}}
    </mat-panel-title>
    <mat-panel-description>

    </mat-panel-description>
  </mat-expansion-panel-header>
  <div >
  <mat-chip-list>
    <mat-chip *ngFor="let option of selectedOptions" [selectable]="selectable" [removable]="removable"
    (removed)="remove(option)">
    {{option.name}}
    <button matChipRemove *ngIf="removable">
      <mat-icon>cancel</mat-icon>
    </button>
  </mat-chip>
  </mat-chip-list>
  <div class="w-full mt-2" style="border-width: 1px; border-radius: 6px; align-items: stretch;">
    <input class="w-full p-2" placeholder="Select options" #inputValue [formControl]="optionCtrl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option.id">
        <span class="multiLine">
          <p style="font-weight:bold">{{option.name}}</p>
          <p>{{option.description}}</p>
        </span>
      </mat-option>
    </mat-autocomplete>
  </div>

  </div>

</mat-expansion-panel>
</code>```

Typescript file:

```<code>@Component({
  selector: 'app-select-dropdown',
  templateUrl: './select-dropdown.component.html',
  styleUrls: ['./select-dropdown.component.scss']
})
export class SelectDropdownComponent implements AfterViewInit {

  @Input() options: any[];
  @Input() selection: any;
  @Input() label: string;
  @Output() selectionChange = new EventEmitter<any[]>();

  selectable = true;
  removable = true;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  optionCtrl = new FormControl();

  filteredOptions: Observable<any[]>;
  selectedOptions: any[];

  @ViewChild('inputValue') inputValue: ElementRef<HTMLInputElement>;

  constructor() {
    this.selectedOptions = [];
    this.filteredOptions = this.optionCtrl.valueChanges.pipe(
      startWith(null),
      map((option: any | null) => option ? this._filter(option) : this.options.slice())
    );
  }

  remove(option: any): void {
    const index = this.selectedOptions.indexOf(option);
    if (index >= 0) {
      this.selectedOptions.splice(index, 1);
    }
    this.inputValue.nativeElement.value = '';
    this.optionCtrl.setValue(null);
    this.selectionChange.emit(this.selectedOptions.map(function(a) { return a.id}))
  }

    selected(event: MatAutocompleteSelectedEvent): void {
    this.selectedOptions.push(this.options.find(x => x.id == event.option.value))
    this.inputValue.nativeElement.value = '';
        this.optionCtrl.setValue(null);
        this.selectionChange.emit(this.selectedOptions.map(function (a) { return a.id }));
        setTimeout(() => {
            this.inputValue.nativeElement.blur();
           // this.inputValue.nativeElement.focus();
        })

  }

 ngAfterViewInit(): void {
  }

}
</code>```

Filter page sample:

```<code><div class="mt-2 no-shadow" matTooltip="abc.">
                        <app-select-dropdown [options]="filterData.investmentProgramPeriods"
                                             [(selection)]="filters.investmentPeriodId" [label]="'label'">
                        </app-select-dropdown>
                    </div>
                    <div class="mt-2 no-shadow" matTooltip="tooltip.">
                        <app-select-dropdown [options]="filterData.utilityServiceAreas"
                                             [(selection)]="filters.untilityServiceId" [label]="'Utility Service Area'">
                        </app-select-dropdown>
                    </div>

</code>```

any help appreciated..

答: I don't see where is the [] which holds the strings from url which are supposed to go into the chip list. But what if you push those received values to selectedOptions? Your chip-list should update. e.g this.selectedOptions = [...this.selectedOptions, ...urlStrings] cd will run and template will update.

Body:
we have some selectable dropdowns using mat chip as a component. The requirement is that when there are some values in the Url query string, then those values should also be pre selected in the relevant multi select option.
am fairly new to angular. have been able to get values from the url into relevant property arrays but cant seem to figure out how to programatically select those values for each of the multi select dropdown.

code is as under:

mat chip component:

<mat-expansion-panel class="shadow-none" style="box-shadow:none !important">
  <mat-expansion-panel-header>
    <mat-panel-title>
      {{label}}
    </mat-panel-title>
    <mat-panel-description>

    </mat-panel-description>
  </mat-expansion-panel-header>

  <mat-chip-list>
    <mat-chip *ngFor="let option of selectedOptions" [selectable]="selectable" [removable]="removable"
    (removed)="remove(option)">
    {{option.name}}
    <button matChipRemove *ngIf="removable">
      <mat-icon>cancel</mat-icon>
    </button>
  </mat-chip>
  </mat-chip-list>

    <input class="w-full p-2" placeholder="Select options" #inputValue [formControl]="optionCtrl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option.id">

{{option.name}}

{{option.description}}

      </mat-option>
    </mat-autocomplete>

</mat-expansion-panel>

Typescript file:

@Component({
  selector: 'app-select-dropdown',
  templateUrl: './select-dropdown.component.html',
  styleUrls: ['./select-dropdown.component.scss']
})
export class SelectDropdownComponent implements AfterViewInit {

  @Input() options: any[];
  @Input() selection: any;
  @Input() label: string;
  @Output() selectionChange = new EventEmitter<any[]>();

  selectable = true;
  removable = true;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  optionCtrl = new FormControl();

  filteredOptions: Observable<any[]>;
  selectedOptions: any[];

  @ViewChild('inputValue') inputValue: ElementRef<HTMLInputElement>;

  constructor() {
    this.selectedOptions = [];
    this.filteredOptions = this.optionCtrl.valueChanges.pipe(
      startWith(null),
      map((option: any | null) => option ? this._filter(option) : this.options.slice())
    );
  }

  remove(option: any): void {
    const index = this.selectedOptions.indexOf(option);
    if (index >= 0) {
      this.selectedOptions.splice(index, 1);
    }
    this.inputValue.nativeElement.value = '';
    this.optionCtrl.setValue(null);
    this.selectionChange.emit(this.selectedOptions.map(function(a) { return a.id}))
  }

    selected(event: MatAutocompleteSelectedEvent): void {
    this.selectedOptions.push(this.options.find(x => x.id == event.option.value))
    this.inputValue.nativeElement.value = '';
        this.optionCtrl.setValue(null);
        this.selectionChange.emit(this.selectedOptions.map(function (a) { return a.id }));
        setTimeout(() => {
            this.inputValue.nativeElement.blur();
           // this.inputValue.nativeElement.focus();
        })

  }

 ngAfterViewInit(): void {
  }

}

Filter page sample:

                        <app-select-dropdown [options]="filterData.investmentProgramPeriods"
                                             [(selection)]="filters.investmentPeriodId" [label]="'label'">
                        </app-select-dropdown>

                        <app-select-dropdown [options]="filterData.utilityServiceAreas"
                                             [(selection)]="filters.untilityServiceId" [label]="'Utility Service Area'">
                        </app-select-dropdown>

any help appreciated..


问:
Tkinter uninstalled, cannot reinstall due to PIP SSL ERROR
I am trying to make an installer for an application. I had it working last night, but now it fails. I am using Tkinter, Python 3.10, pip 22, and when I run this code:

import tkinter as tk
root = tk.Tk()
root.geometry("500x300")
top = tk.Frame(root)
bottom = tk.Frame(root)
top.pack(side=tk.TOP)
bottom.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
root.eval('tk::PlaceWindow . center')
root.resizable(False, False)
root.title("Kahoot bot INSTALLER")
installNoticeLabel = tk.Label(root, text="You are about to install FrederickAmpsUp's\nkahoot bot generator. Do you want to proceed?", font=("roboto", 15))
installNoticeLabel.pack()
def install ():
    yes.pack_forget()
    no.pack_forget()
    installNoticeLabel.config(text="Installing, please wait...")
def cancel ():
    root.destroy()
yes = tk.Button(root, text="Yes", font=("roboto", 15), command=install)
no = tk.Button(root, text="No", font=("roboto", 15), command=cancel)
yes.pack(in_=bottom, side=tk.RIGHT, fill=tk.BOTH, expand=True)
no.pack(in_=bottom, side=tk.LEFT, fill=tk.BOTH, expand=True)
root.mainloop()
```
<p>I get the error:</p>
```Traceback (most recent call last):
  File "/home/USER/VSCode/Kahoot bot app/installer.py", line 1, in <module>
    import tkinter as tk
  File "/usr/local/lib/python3.10/tkinter/__init__.py", line 37, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'
```
<p>So I ran the command <code>pip3.10 install tk</code>.
Running this, I get:</p>
```Defaulting to user installation because normal site-packages is not writeable
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
Could not fetch URL https://pypi.org/simple/tk/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/tk/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement tk (from versions: none)
ERROR: No matching distribution found for tk
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
```

I have tried setting --trusted-hosts for pip, but it does not make a difference.
Please help!
I am running Ubuntu 16.04. If it matters, I get internet through a Raspberry Pi 3 B+ and ethernet cable, as I don't have a wireless card.

答:
You have a Mac/Linux so I think this could help:

Change openssl version back from to older version:

```<code>brew switch openssl 1.0.2e
</code>```

or

Reinstall openssl by brew uninstall openssl; brew install openssl.
According to the hints given by Homebrew, do the following:

```<code>echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"
</code>```

For Linux use this post.

For Windows & Anaconda use this post

Body:
I am trying to make an installer for an application. I had it working last night, but now it fails. I am using Tkinter, Python 3.10, pip 22, and when I run this code:

import tkinter as tk
root = tk.Tk()
root.geometry("500x300")
top = tk.Frame(root)
bottom = tk.Frame(root)
top.pack(side=tk.TOP)
bottom.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
root.eval('tk::PlaceWindow . center')
root.resizable(False, False)
root.title("Kahoot bot INSTALLER")
installNoticeLabel = tk.Label(root, text="You are about to install FrederickAmpsUp's\nkahoot bot generator. Do you want to proceed?", font=("roboto", 15))
installNoticeLabel.pack()
def install ():
    yes.pack_forget()
    no.pack_forget()
    installNoticeLabel.config(text="Installing, please wait...")
def cancel ():
    root.destroy()
yes = tk.Button(root, text="Yes", font=("roboto", 15), command=install)
no = tk.Button(root, text="No", font=("roboto", 15), command=cancel)
yes.pack(in_=bottom, side=tk.RIGHT, fill=tk.BOTH, expand=True)
no.pack(in_=bottom, side=tk.LEFT, fill=tk.BOTH, expand=True)
root.mainloop()

I get the error:

Traceback (most recent call last):
  File "/home/USER/VSCode/Kahoot bot app/installer.py", line 1, in <module>
    import tkinter as tk
  File "/usr/local/lib/python3.10/tkinter/__init__.py", line 37, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'

So I ran the command pip3.10 install tk.
Running this, I get:

Defaulting to user installation because normal site-packages is not writeable
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tk/
Could not fetch URL https://pypi.org/simple/tk/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/tk/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement tk (from versions: none)
ERROR: No matching distribution found for tk
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping

I have tried setting --trusted-hosts for pip, but it does not make a difference.
Please help!
I am running Ubuntu 16.04. If it matters, I get internet through a Raspberry Pi 3 B+ and ethernet cable, as I don't have a wireless card.

Body:
You have a Mac/Linux so I think this could help:

Change openssl version back from to older version:

brew switch openssl 1.0.2e

or

Reinstall openssl by brew uninstall openssl; brew install openssl.
According to the hints given by Homebrew, do the following:

echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

For Linux use this post.

For Windows & Anaconda use this post


问:
BigQuery Storage Write / managedwriter api return error server_shutting_down
As we know, the advantage of BigQuery Storage Write API, one month ago, we replace insertAll with managedwriter API on our server. It seems to work well for one month, however, we met the following errors recently

```<code>rpc error: code = Unavailable desc = closing transport due to: connection error:
desc = "error reading from server: EOF", received prior goaway: code: NO_ERROR,
debug data: "server_shutting_down"
</code>```

The version of managedwriter API are:

```<code>cloud.google.com/go/bigquery v1.25.0
google.golang.org/protobuf v1.27.1
</code>```

There is a piece of retrying logic for storage write API that detects error messages on our server-side. We notice the response time of storage write API becomes longer after retrying, as a result, OOM is happening on our server. We also tried to increase the request timeout to 30 seconds, and most of those requests could not be completed within it.

How to handle the error server_shutting_down correctly?

Update 02/08/2022

The default stream of managedwrite API is used in our server. And server_shutting_down error comes up periodically. And this issue happened on 02/04/2022 12:00 PM UTC and the default stream of managedwrite API works well for over one month.

Here is one wrapper function of appendRow and we log the cost time of this function.

func (cl *GBOutput) appendRows(ctx context.Context,datas [][]byte, schema *gbSchema) error {
    var result *managedwriter.AppendResult
    var err error
    if cl.schema != schema {
        cl.schema = schema
        result, err = cl.managedStream.AppendRows(ctx, datas, managedwriter.UpdateSchemaDescriptor(schema.descriptorProto))
    } else {
        result, err = cl.managedStream.AppendRows(ctx, datas)
    }
    if err != nil {
        return err
    }
    _, err = result.GetResult(ctx)
    return err
}
```

When the error server_shutting_down comes up, the cost time of this function could be several hundred seconds. It is so weird, and it seems to there is no way to handle the timeout of appendRow.

答:
Per the GCP support guy,

The issue is hit once 10MB has been sent over the connection, regardless of how long it takes or how much is inflight at that time. The BigQuery Engineering team has identified the root cause and the fix would be rolled out by Friday, Feb 11th, 2022.

Body:
As we know, the advantage of BigQuery Storage Write API, one month ago, we replace insertAll with managedwriter API on our server. It seems to work well for one month, however, we met the following errors recently

rpc error: code = Unavailable desc = closing transport due to: connection error:
desc = "error reading from server: EOF", received prior goaway: code: NO_ERROR,
debug data: "server_shutting_down"

The version of managedwriter API are:

cloud.google.com/go/bigquery v1.25.0
google.golang.org/protobuf v1.27.1

There is a piece of retrying logic for storage write API that detects error messages on our server-side. We notice the response time of storage write API becomes longer after retrying, as a result, OOM is happening on our server. We also tried to increase the request timeout to 30 seconds, and most of those requests could not be completed within it.

How to handle the error server_shutting_down correctly?

Update 02/08/2022

The default stream of managedwrite API is used in our server. And server_shutting_down error comes up periodically. And this issue happened on 02/04/2022 12:00 PM UTC and the default stream of managedwrite API works well for over one month.

Here is one wrapper function of appendRow and we log the cost time of this function.

func (cl *GBOutput) appendRows(ctx context.Context,datas [][]byte, schema *gbSchema) error {
    var result *managedwriter.AppendResult
    var err error
    if cl.schema != schema {
        cl.schema = schema
        result, err = cl.managedStream.AppendRows(ctx, datas, managedwriter.UpdateSchemaDescriptor(schema.descriptorProto))
    } else {
        result, err = cl.managedStream.AppendRows(ctx, datas)
    }
    if err != nil {
        return err
    }
    _, err = result.GetResult(ctx)
    return err
}

When the error server_shutting_down comes up, the cost time of this function could be several hundred seconds. It is so weird, and it seems to there is no way to handle the timeout of appendRow.


问:
Why am I getting these Oracle SQL Developer errors
I can't figure out what I am doing wrong here

enter image description here

--1.Create a unique Profile based on the following requirements

```<code>CREATE PROFILE PDylanReed LIMIT

  SESSIONS_PER_USER          3

  CPU_PER_SESSION            UNLIMITED

  CPU_PER_CALL               3000

  CONNECT_TIME               45

  LOGICAL_READS_PER_SESSION  DEFAULT

  LOGICAL_READS_PER_CALL     1000

  PRIVATE_SGA                15K

  COMPOSITE_LIMIT            5000000

  FAILED_LOGIN_ATTEMPTS   4

  PASSWORD_LIFE_TIME         120

  PASSWORD_LOCK_TIME         1/24

  PASSWORD_GRACE_TIME        110

  PASSWORD_REUSE_TIME        600

  PASSWORD_REUSE_MAX         5

  PASSWORD_VERIFY_FUNCTION   ora12c_verify_function;
</code>```

--2.Verify your Profile was successfully created by Creating and executing a SQL statement querying the appropriate Data Dictionary objects

```<code>SELECT * FROM DBA_SQL_PROFILES where name = PDylanReed;
</code>```

--3.Create 2 users assign them to the Permanent Tablespace of Users with a Quota of 30M

```<code>CREATE USER U1DylanReed

   IDENTIFIED BY temporary_password

   PERMANENT TABLESPACE Users

   QUOTA 30M ON Users

   PROFILE PDylanReed

   PASSWORD EXPIRE;

CREATE USER U2DylanReed

   IDENTIFIED BY temporary_password

   PERMANENT TABLESPACE Users

   QUOTA 30M ON Users

   PROFILE PDylanReed

   PASSWORD EXPIRE;
</code>```

--4.Create a role allowing users assigned to be able to connect to the database and create tables.

```<code>CREATE ROLE R1DylanReed;

GRANT CREATE SESSION, CREATE TABLE TO R1DylanReed;

SET ROLE R1DylanReed;  -> enables the role
</code>```

Errors I'm getting

enter image description here

enter image description here

```<code>Error starting at line : 3 in command -
CREATE PROFILE PDylanReed LIMIT
  SESSIONS_PER_USER          3
  CPU_PER_SESSION            UNLIMITED
  CPU_PER_CALL               3000
  CONNECT_TIME               45
  LOGICAL_READS_PER_SESSION  DEFAULT
  LOGICAL_READS_PER_CALL     1000
  PRIVATE_SGA                15K
  COMPOSITE_LIMIT            5000000
  FAILED_LOGIN_ATTEMPTS   4
  PASSWORD_LIFE_TIME         120
  PASSWORD_LOCK_TIME         1/24
  PASSWORD_GRACE_TIME        110
  PASSWORD_REUSE_TIME        600
  PASSWORD_REUSE_MAX         5
  PASSWORD_VERIFY_FUNCTION   ora12c_verify_function
Error report -
ORA-01031: insufficient privileges
01031. 00000 -  "insufficient privileges"
*Cause:    An attempt was made to perform a database operation without
           the necessary privileges.
*Action:   Ask your database administrator or designated security
           administrator to grant you the necessary privileges

Error starting at line : 23 in command -
SELECT * FROM DBA_SQL_PROFILES where name = PDylanReed
Error at Command Line : 23 Column : 15
Error report -
SQL Error: ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:

Error starting at line : 28 in command -
CREATE USER U1DylanReed
   IDENTIFIED BY temporary_password
   PERMANENT TABLESPACE Users
   QUOTA 30M ON Users
   PROFILE PDylanReed
   PASSWORD EXPIRE
Error report -
ORA-00922: missing or invalid option
00922. 00000 -  "missing or invalid option"
*Cause:
*Action:

Error starting at line : 35 in command -
CREATE USER U2DylanReed
   IDENTIFIED BY temporary_password
   PERMANENT TABLESPACE Users
   QUOTA 30M ON Users
   PROFILE PDylanReed
   PASSWORD EXPIRE
Error report -
ORA-00922: missing or invalid option
00922. 00000 -  "missing or invalid option"
*Cause:
*Action:

Error starting at line : 44 in command -
CREATE ROLE R1DylanReed
Error report -
ORA-01031: insufficient privileges
01031. 00000 -  "insufficient privileges"
*Cause:    An attempt was made to perform a database operation without
           the necessary privileges.
*Action:   Ask your database administrator or designated security
           administrator to grant you the necessary privileges

Error starting at line : 46 in command -
GRANT CREATE SESSION, CREATE TABLE TO R1DylanReed
Error report -
ORA-01031: insufficient privileges
01031. 00000 -  "insufficient privileges"
*Cause:    An attempt was made to perform a database operation without
           the necessary privileges.
*Action:   Ask your database administrator or designated security
           administrator to grant you the necessary privileges

Role R1DYLANREED succeeded.

Error starting at line : 48 in command -
  -> enables the role
Error report -
Unknown Command
</code>```

答:
In line 3 you must place the word grant, to allow the profile to be created.

Ej: GRANT CREATE ...

Most of the time that solves the permissions issues...

Body:
I can't figure out what I am doing wrong here

enter image description here

--1.Create a unique Profile based on the following requirements

CREATE PROFILE PDylanReed LIMIT

  SESSIONS_PER_USER          3

  CPU_PER_SESSION            UNLIMITED

  CPU_PER_CALL               3000

  CONNECT_TIME               45

  LOGICAL_READS_PER_SESSION  DEFAULT

  LOGICAL_READS_PER_CALL     1000

  PRIVATE_SGA                15K

  COMPOSITE_LIMIT            5000000

  FAILED_LOGIN_ATTEMPTS   4

  PASSWORD_LIFE_TIME         120

  PASSWORD_LOCK_TIME         1/24

  PASSWORD_GRACE_TIME        110

  PASSWORD_REUSE_TIME        600

  PASSWORD_REUSE_MAX         5

  PASSWORD_VERIFY_FUNCTION   ora12c_verify_function;

--2.Verify your Profile was successfully created by Creating and executing a SQL statement querying the appropriate Data Dictionary objects

SELECT * FROM DBA_SQL_PROFILES where name = PDylanReed;

--3.Create 2 users assign them to the Permanent Tablespace of Users with a Quota of 30M

CREATE USER U1DylanReed

   IDENTIFIED BY temporary_password

   PERMANENT TABLESPACE Users

   QUOTA 30M ON Users

   PROFILE PDylanReed

   PASSWORD EXPIRE;

CREATE USER U2DylanReed

   IDENTIFIED BY temporary_password

   PERMANENT TABLESPACE Users

   QUOTA 30M ON Users

   PROFILE PDylanReed

   PASSWORD EXPIRE;

--4.Create a role allowing users assigned to be able to connect to the database and create tables.

CREATE ROLE R1DylanReed;

GRANT CREATE SESSION, CREATE TABLE TO R1DylanReed;

SET ROLE R1DylanReed;  -> enables the role

Errors I'm getting

enter image description here

enter image description here

Error starting at line : 3 in command -
CREATE PROFILE PDylanReed LIMIT
  SESSIONS_PER_USER          3
  CPU_PER_SESSION            UNLIMITED
  CPU_PER_CALL               3000
  CONNECT_TIME               45
  LOGICAL_READS_PER_SESSION  DEFAULT
  LOGICAL_READS_PER_CALL     1000
  PRIVATE_SGA                15K
  COMPOSITE_LIMIT            5000000
  FAILED_LOGIN_ATTEMPTS   4
  PASSWORD_LIFE_TIME         120
  PASSWORD_LOCK_TIME         1/24
  PASSWORD_GRACE_TIME        110
  PASSWORD_REUSE_TIME        600
  PASSWORD_REUSE_MAX         5
  PASSWORD_VERIFY_FUNCTION   ora12c_verify_function
Error report -
ORA-01031: insufficient privileges
01031. 00000 -  "insufficient privileges"
*Cause:    An attempt was made to perform a database operation without
           the necessary privileges.
*Action:   Ask your database administrator or designated security
           administrator to grant you the necessary privileges

Error starting at line : 23 in command -
SELECT * FROM DBA_SQL_PROFILES where name = PDylanReed
Error at Command Line : 23 Column : 15
Error report -
SQL Error: ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:

Error starting at line : 28 in command -
CREATE USER U1DylanReed
   IDENTIFIED BY temporary_password
   PERMANENT TABLESPACE Users
   QUOTA 30M ON Users
   PROFILE PDylanReed
   PASSWORD EXPIRE
Error report -
ORA-00922: missing or invalid option
00922. 00000 -  "missing or invalid option"
*Cause:
*Action:

Error starting at line : 35 in command -
CREATE USER U2DylanReed
   IDENTIFIED BY temporary_password
   PERMANENT TABLESPACE Users
   QUOTA 30M ON Users
   PROFILE PDylanReed
   PASSWORD EXPIRE
Error report -
ORA-00922: missing or invalid option
00922. 00000 -  "missing or invalid option"
*Cause:
*Action:

Error starting at line : 44 in command -
CREATE ROLE R1DylanReed
Error report -
ORA-01031: insufficient privileges
01031. 00000 -  "insufficient privileges"
*Cause:    An attempt was made to perform a database operation without
           the necessary privileges.
*Action:   Ask your database administrator or designated security
           administrator to grant you the necessary privileges

Error starting at line : 46 in command -
GRANT CREATE SESSION, CREATE TABLE TO R1DylanReed
Error report -
ORA-01031: insufficient privileges
01031. 00000 -  "insufficient privileges"
*Cause:    An attempt was made to perform a database operation without
           the necessary privileges.
*Action:   Ask your database administrator or designated security
           administrator to grant you the necessary privileges

Role R1DYLANREED succeeded.

Error starting at line : 48 in command -
  -> enables the role
Error report -
Unknown Command


问:
Typescript declarations file for Node C++ Addon
I have a Node C++ Addon that provides a wrapped class similar to the one in the Node documentation. I can require() my addon and then get the constructor for my class to create an instance.

```<code>const { MyClass } = require('myaddon');
const obj = new MyClass('data');
</code>```

Now I want to use TypeScript to do the same. I can't find the right combination of .d.ts file and import statement to make this work. I guess ideally I'd like to declare my class is in the module and has a constructor that takes a string. I could then just do:

```<code>import { MyClass } from 'myaddon';
const obj = new MyClass('data');
</code>```

Any examples of this that people have seen?

答:
Another way to do this is similiar to Nick Kallen's way.

You're basically using a naming trick. If you do:

```<code>import test = require("../test/build/Release/hello.node");
</code>```

When 'compiled' to javascript, it will see the file as hello.node. Typescript will see the file as its name + a typescript file extension.

So this is how your *.node directory should look:

-hello.node

-hello.node.d.ts

-if-windows-hello.dll

In my hello.node.d.ts file I have:

```<code>export const hello: () => string;
</code>```

Body:
I have a Node C++ Addon that provides a wrapped class similar to the one in the Node documentation. I can require() my addon and then get the constructor for my class to create an instance.

const { MyClass } = require('myaddon');
const obj = new MyClass('data');

Now I want to use TypeScript to do the same. I can't find the right combination of .d.ts file and import statement to make this work. I guess ideally I'd like to declare my class is in the module and has a constructor that takes a string. I could then just do:

import { MyClass } from 'myaddon';
const obj = new MyClass('data');

Any examples of this that people have seen?

Body:
Another way to do this is similiar to Nick Kallen's way.

You're basically using a naming trick. If you do:

import test = require("../test/build/Release/hello.node");

When 'compiled' to javascript, it will see the file as hello.node. Typescript will see the file as its name + a typescript file extension.

So this is how your *.node directory should look:

-hello.node

-hello.node.d.ts

-if-windows-hello.dll

In my hello.node.d.ts file I have:

export const hello: () => string;


问:
Animation not working correctly with data triggers
I have a combobox, which is bound to an enumeration of animations. We have the requirement such that if an animation style is selected in the combo box, the corresponding animation should be triggered on a textblock. i have 3 animations, namely fade, scale and blink. While blink is working fine, fade and scale doesnt work. it works only for the first time when the screen loads and then thereafter, even if the selection is changed to fade/scale, teh animation is not triggered. As if now, i have triggered the animation using a data trigger, and that is when this issue started coming, but the animation was triggered perfectly when we tried to use an event trigger. My code is as below. Could someone help me as to what is it that I am doing wrong and how it can be rectified.

Animations:

```<code>        <Storyboard x:Key="Fade">
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
        </ObjectAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
            <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
            <EasingDoubleKeyFrame KeyTime="0:0:2" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
    <Storyboard x:Key="Scale">
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
        </ObjectAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
            <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
            <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
            <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
<Storyboard x:Key="Blink">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
            </DoubleAnimationUsingKeyFrames>
            <ObjectAnimationUsingKeyFrames RepeatBehavior="3x" Storyboard.TargetProperty="(UIElement.Visibility)">
                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                <DiscreteObjectKeyFrame KeyTime="0:0:0.25" Value="{x:Static Visibility.Collapsed}"/>
                <DiscreteObjectKeyFrame KeyTime="0:0:0.5" Value="{x:Static Visibility.Visible}"/>
            </ObjectAnimationUsingKeyFrames>
        </Storyboard>
</code>```

The combobox, textblock and data triggers used to trigger the animation:

```<code>         <telerik:RadComboBox x:Name="animationTypeComboBox"
                                 Foreground="White"
                                 Width="180"
                                 ItemsSource="{Binding Source={StaticResource AnimationTypeEnumValues}}"
                                 SelectedItem="{Binding SelectedAnimationType, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
                                 VerticalAlignment="Center" >
            </telerik:RadComboBox>
            <TextBlock x:Name="testMsg" Text="Test message" VerticalAlignment="Center" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5">
                <TextBlock.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform/>
                            <SkewTransform/>
                            <RotateTransform/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </TextBlock.RenderTransform>
                 <TextBlock.Style>
                    <Style TargetType="TextBlock" BasedOn="{StaticResource Subheading}">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding SelectedAnimationType}" Value="{x:Static ent:AnimationType.Fade}">
                                <DataTrigger.EnterActions>
                                    <BeginStoryboard Storyboard="{StaticResource Fade}"/>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding SelectedAnimationType}" Value="{x:Static ent:AnimationType.Scale}">
                                <DataTrigger.EnterActions>
                                    <BeginStoryboard Storyboard="{StaticResource Scale}"/>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding SelectedAnimationType}" Value="{x:Static ent:AnimationType.Blink}">
                                <DataTrigger.EnterActions>
                                    <BeginStoryboard Storyboard="{StaticResource Blink}"/>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
</code>```

答:
I made few changes in your code to make it work in my local system.... here is a solution to your problem.. </p>

```<code><TextBlock x:Name="testMsg" Text="Test message" VerticalAlignment="Center" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5">
                <TextBlock.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform/>
                            <SkewTransform/>
                            <RotateTransform/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </TextBlock.RenderTransform>
                 <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding SelectedItem,ElementName=AnimStyles}" Value="Fade">
                                <DataTrigger.EnterActions>
                                      <RemoveStoryboard BeginStoryboardName="Scale"/>
                                    <RemoveStoryboard BeginStoryboardName="Blink"/>
                                    <BeginStoryboard  Name="Fade">
                                         <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:2" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                             </Storyboard>
                                    </BeginStoryboard>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding SelectedItem,ElementName=AnimStyles}" Value="Scale">
                                <DataTrigger.EnterActions>
                                     <RemoveStoryboard BeginStoryboardName="Fade"/>
                                    <RemoveStoryboard BeginStoryboardName="Blink"/>
                                    <BeginStoryboard Name="Scale">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                         </Storyboard>
                                    </BeginStoryboard>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding SelectedItem,ElementName=AnimStyles}" Value="Blink">
                                <DataTrigger.EnterActions>
                                    <RemoveStoryboard BeginStoryboardName="Fade"/>
                                    <RemoveStoryboard BeginStoryboardName="Scale"/>
                                    <BeginStoryboard Name="Blink">
                                         <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames RepeatBehavior="3x" Storyboard.TargetProperty="(UIElement.Visibility)">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0.25" Value="{x:Static Visibility.Collapsed}"/>
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0.5" Value="{x:Static Visibility.Visible}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </BeginStoryboard>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
        </TextBlock>
</code>```

<p>In the above code instead of taking story boards in resources i am taking then in line... and removing the other storyboards before starting the actual storyboard...
This means what ever be the behavior effected by the previous Storyboards will be removed and every time animation works as like a new one.. </p>

Body:
I have a combobox, which is bound to an enumeration of animations. We have the requirement such that if an animation style is selected in the combo box, the corresponding animation should be triggered on a textblock. i have 3 animations, namely fade, scale and blink. While blink is working fine, fade and scale doesnt work. it works only for the first time when the screen loads and then thereafter, even if the selection is changed to fade/scale, teh animation is not triggered. As if now, i have triggered the animation using a data trigger, and that is when this issue started coming, but the animation was triggered perfectly when we tried to use an event trigger. My code is as below. Could someone help me as to what is it that I am doing wrong and how it can be rectified.

Animations:

        <Storyboard x:Key="Fade">
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
        </ObjectAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
            <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
            <EasingDoubleKeyFrame KeyTime="0:0:2" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
    <Storyboard x:Key="Scale">
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
        </ObjectAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
            <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
            <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
            <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
<Storyboard x:Key="Blink">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
            </DoubleAnimationUsingKeyFrames>
            <ObjectAnimationUsingKeyFrames RepeatBehavior="3x" Storyboard.TargetProperty="(UIElement.Visibility)">
                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                <DiscreteObjectKeyFrame KeyTime="0:0:0.25" Value="{x:Static Visibility.Collapsed}"/>
                <DiscreteObjectKeyFrame KeyTime="0:0:0.5" Value="{x:Static Visibility.Visible}"/>
            </ObjectAnimationUsingKeyFrames>
        </Storyboard>

The combobox, textblock and data triggers used to trigger the animation:

         <telerik:RadComboBox x:Name="animationTypeComboBox"
                                 Foreground="White"
                                 Width="180"
                                 ItemsSource="{Binding Source={StaticResource AnimationTypeEnumValues}}"
                                 SelectedItem="{Binding SelectedAnimationType, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
                                 VerticalAlignment="Center" >
            </telerik:RadComboBox>
            <TextBlock x:Name="testMsg" Text="Test message" VerticalAlignment="Center" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5">
                <TextBlock.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform/>
                            <SkewTransform/>
                            <RotateTransform/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </TextBlock.RenderTransform>
                 <TextBlock.Style>

                    </Style>
                </TextBlock.Style>
            </TextBlock>

Body:
I made few changes in your code to make it work in my local system.... here is a solution to your problem..

<TextBlock x:Name="testMsg" Text="Test message" VerticalAlignment="Center" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5">
                <TextBlock.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform/>
                            <SkewTransform/>
                            <RotateTransform/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </TextBlock.RenderTransform>
                 <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding SelectedItem,ElementName=AnimStyles}" Value="Fade">
                                <DataTrigger.EnterActions>
                                      <RemoveStoryboard BeginStoryboardName="Scale"/>
                                    <RemoveStoryboard BeginStoryboardName="Blink"/>
                                    <BeginStoryboard  Name="Fade">
                                         <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:2" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                             </Storyboard>
                                    </BeginStoryboard>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding SelectedItem,ElementName=AnimStyles}" Value="Scale">
                                <DataTrigger.EnterActions>
                                     <RemoveStoryboard BeginStoryboardName="Fade"/>
                                    <RemoveStoryboard BeginStoryboardName="Blink"/>
                                    <BeginStoryboard Name="Scale">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                         </Storyboard>
                                    </BeginStoryboard>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding SelectedItem,ElementName=AnimStyles}" Value="Blink">
                                <DataTrigger.EnterActions>
                                    <RemoveStoryboard BeginStoryboardName="Fade"/>
                                    <RemoveStoryboard BeginStoryboardName="Scale"/>
                                    <BeginStoryboard Name="Blink">
                                         <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames RepeatBehavior="3x" Storyboard.TargetProperty="(UIElement.Visibility)">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0.25" Value="{x:Static Visibility.Collapsed}"/>
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0.5" Value="{x:Static Visibility.Visible}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </BeginStoryboard>
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
        </TextBlock>

In the above code instead of taking story boards in resources i am taking then in line... and removing the other storyboards before starting the actual storyboard...
This means what ever be the behavior effected by the previous Storyboards will be removed and every time animation works as like a new one..


问:
Leetcode - how to optimize my solution using sliding window approach for maximum number of vowels in a substring of k length?
I am doing leetcode 1456

I came up with a working solution but got "Time limit exceeded" for one of the tests. I used the sliding window approach and I believe my solution is O(n) (or am I wrong?).

```<code>var maxVowels = function(s, k) {
   let left = 0;
   let right = 0;
   let maxVowels = 0;
   let curVowels = 0;
   let vowels = ['a','e','i','o','u'];

   while (right < s.length) {
       let subStringLength = right - left + 1;
       if (vowels.includes(s[right])) curVowels++;

       if (subStringLength === k) {
           maxVowels = Math.max(maxVowels, curVowels);
           if (maxVowels === k) return maxVowels;
           curVowels = 0;
           left++;
           right = left - 1;
       }
       right++;
   }
   return maxVowels;
};
</code>```

I tried to see if it was because the vowels.includes(s[right]) method was somehow a really slow method but based on what I read that is not the case, especially since my array is only of length 5.

How can I optimize my solution such that it passes the test?

答:
Ended up fixing my code with the help @Bergi.

The problem with my original answer was that I kept RESETTING the right pointer via right = left - 1 rather than just "sliding the window" by incrementing the right pointer. My original solution did not work at scale. It was O(n*k) and not O(n) as I originally thought.

And because I kept resetting the right pointer to right = left - 1, I was actually doing a lot of re-checking of the same char.

My new solution (that passed) now looks like this:

```<code>/**
 * @param {string} s
 * @param {number} k
 * @return {number}
 */
 var maxVowels = function(s, k) {
    let left = 0;
    let right = 0;
    let maxVowels = 0;
    let curVowels = 0;
    let vowels = ['a','e','i','o','u'];

    while (right < s.length) {
        let subStringLength = right - left + 1;
        if (vowels.includes(s[right])) curVowels++;

        if (subStringLength === k) {
            maxVowels = Math.max(maxVowels, curVowels);
            if (vowels.includes(s[left])) curVowels--;
            left++;
        }

        right++;
        if (maxVowels === k) return maxVowels;
    }
    return maxVowels;
};
</code>```

Body:
I am doing leetcode 1456

I came up with a working solution but got "Time limit exceeded" for one of the tests. I used the sliding window approach and I believe my solution is O(n) (or am I wrong?).

var maxVowels = function(s, k) {
   let left = 0;
   let right = 0;
   let maxVowels = 0;
   let curVowels = 0;
   let vowels = ['a','e','i','o','u'];

   while (right < s.length) {
       let subStringLength = right - left + 1;
       if (vowels.includes(s[right])) curVowels++;

       if (subStringLength === k) {
           maxVowels = Math.max(maxVowels, curVowels);
           if (maxVowels === k) return maxVowels;
           curVowels = 0;
           left++;
           right = left - 1;
       }
       right++;
   }
   return maxVowels;
};

I tried to see if it was because the vowels.includes(s[right]) method was somehow a really slow method but based on what I read that is not the case, especially since my array is only of length 5.

How can I optimize my solution such that it passes the test?

Body:
Ended up fixing my code with the help @Bergi.

The problem with my original answer was that I kept RESETTING the right pointer via right = left - 1 rather than just "sliding the window" by incrementing the right pointer. My original solution did not work at scale. It was O(n*k) and not O(n) as I originally thought.

And because I kept resetting the right pointer to right = left - 1, I was actually doing a lot of re-checking of the same char.

My new solution (that passed) now looks like this:

/**
 * @param {string} s
 * @param {number} k
 * @return {number}
 */
 var maxVowels = function(s, k) {
    let left = 0;
    let right = 0;
    let maxVowels = 0;
    let curVowels = 0;
    let vowels = ['a','e','i','o','u'];

    while (right < s.length) {
        let subStringLength = right - left + 1;
        if (vowels.includes(s[right])) curVowels++;

        if (subStringLength === k) {
            maxVowels = Math.max(maxVowels, curVowels);
            if (vowels.includes(s[left])) curVowels--;
            left++;
        }

        right++;
        if (maxVowels === k) return maxVowels;
    }
    return maxVowels;
};