问:
How Can I display only one column from a styled Pandas Dataframe?
So I am writing a python program that will pull in data and highlight rows based on a cell value. However, I want to only convert/show one of the highlighted columns(The name of the device) to HTML (and ultimately a pdf) which I can then display to a customer. How could I go about doing this?

Code:

```<code> df = pd.DataFrame(items)

 def highlightCritical(s,threshold,column):
    isSDT = pd.Series(data=False, index=s.index)
    isSDT[column] = s.loc[column] > threshold
    return ['background-color: red' if isSDT.any() else '' for v in isSDT]

 def highlightError(s,threshold,column):
     isSDT = pd.Series(data=False, index=s.index)
     isSDT[column] = s.loc[column] > threshold
     return ['background-color: orange' if isSDT.any() else '' for v in isSDT]

 def highlightWarning(s,threshold,column):
     isSDT = pd.Series(data=False, index=s.index)
     isSDT[column] = s.loc[column] > threshold
     return ['background-color: yellow' if isSDT.any() else '' for v in isSDT]

styled_df_a = df.style.apply(highlightWarning, threshold = 0, column = ['warnAlert' , 'confirmedWarnAlert'], axis=1)\
        .apply(highlightError, threshold = 0, column = ['errorAlert' , 'confirmedErrorAlert'],axis=1)\
        .apply(highlightCritical, threshold = 0, column = ['criticalAlert', 'confirmedCriticalAlert'], axis=1)

html = styled_df_a.hide_index().render()
with open("html_c.html","w") as fp:
   fp.write(html)
</code>```

答:
I fixed the issue. For anybody wondering, you can add the style.hide_columns(LIST OF COLUMNS) to the end of your Styler object.

Code:

```<code>styled_df_a = df.style.apply(highlightWarning, threshold = 0, column = ['warnAlert' , 'confirmedWarnAlert'], axis=1)\
    .apply(highlightError, threshold = 0, column = ['errorAlert' , 'confirmedErrorAlert'],axis=1)\
    .apply(highlightCritical, threshold = 0, column = ['criticalAlert', 'confirmedCriticalAlert'], axis=1)\
    .hide_columns(columnList)
</code>```

Body:
So I am writing a python program that will pull in data and highlight rows based on a cell value. However, I want to only convert/show one of the highlighted columns(The name of the device) to HTML (and ultimately a pdf) which I can then display to a customer. How could I go about doing this?

Code:

 df = pd.DataFrame(items)

 def highlightCritical(s,threshold,column):
    isSDT = pd.Series(data=False, index=s.index)
    isSDT[column] = s.loc[column] > threshold
    return ['background-color: red' if isSDT.any() else '' for v in isSDT]

 def highlightError(s,threshold,column):
     isSDT = pd.Series(data=False, index=s.index)
     isSDT[column] = s.loc[column] > threshold
     return ['background-color: orange' if isSDT.any() else '' for v in isSDT]

 def highlightWarning(s,threshold,column):
     isSDT = pd.Series(data=False, index=s.index)
     isSDT[column] = s.loc[column] > threshold
     return ['background-color: yellow' if isSDT.any() else '' for v in isSDT]

styled_df_a = df.style.apply(highlightWarning, threshold = 0, column = ['warnAlert' , 'confirmedWarnAlert'], axis=1)\
        .apply(highlightError, threshold = 0, column = ['errorAlert' , 'confirmedErrorAlert'],axis=1)\
        .apply(highlightCritical, threshold = 0, column = ['criticalAlert', 'confirmedCriticalAlert'], axis=1)

html = styled_df_a.hide_index().render()
with open("html_c.html","w") as fp:
   fp.write(html)

Body:
I fixed the issue. For anybody wondering, you can add the style.hide_columns(LIST OF COLUMNS) to the end of your Styler object.

Code:

styled_df_a = df.style.apply(highlightWarning, threshold = 0, column = ['warnAlert' , 'confirmedWarnAlert'], axis=1)\
    .apply(highlightError, threshold = 0, column = ['errorAlert' , 'confirmedErrorAlert'],axis=1)\
    .apply(highlightCritical, threshold = 0, column = ['criticalAlert', 'confirmedCriticalAlert'], axis=1)\
    .hide_columns(columnList)


来源: stackexchange

问:
SMS messages non ASCII characters encoding
I have a Nokia N900 phone, and when sending an SMS, the widget displays the number of characters left in the message (and the number of actual short messages needed to send the whole message).

I live in France, where I noticed the following odd thing when writing messages with non-ASCII characters:

some non-ASCII chars are encoded on one char/byte , e.g. "é", "è", "à", "ù"

the presence of some non-ASCII chars such as "ç", "ê", "ô" consumes a fixed amount of 90 char/bytes + 1 byte per character

the presence of a second "ç", "ê" etc. only consumes 1 additional byte.

So I'm wondering how the messages are encoded, because I can't see the above scheme matching the traditional encodings I know (iso-8859-1, UTF-8, UTF-16...).

答:
You already have the answer from @timdream, but just an additional point that some of the extended characters you mention are included in the GSM 7-bit alphabet as single characters, some are encoded in GSM 7-bit through an additional escape character (so two bytes to represent that character) and some can't be encoded at all in GSM 7-bit and need to be encoded as UTF-16 instead.

The full alphabet definition is here:
http://www.unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT

Note the particular peculiarity with c-cedilla - from that file,

The ETSI GSM 03.38 specification shows an uppercase C-cedilla
  glyph at 0x09. This may be the result of limited display
  capabilities for handling characters with descenders. However,
  the
  language coverage intent is clearly for the lowercase
  c-cedilla, as shown
  in the mapping below. The mapping for uppercase C-cedilla is
  shown
  in a commented line in the mapping table.

Some devices encode both upper and lower case c-cedilla as the same encoded character (0x09).

ContentLicense: CC BY-SA 3.0


问:
How to make fixed-content go above iOS keyboard?
I can only find questions where people have the opposite problem.

I want my fixed content to go above the iOS keyboard.
Image of the problem:

I want iOS to behave like Android.

Is there a simple way to achieve this?

Parent element css:

```<code>.parent{
    position:fixed;
    top: 0;
    left 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}
</code>```

Button css:

```<code>.button{
    position:fixed;
    left 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 5rem;
}
</code>```

答:
This is a well known problem, and unfortunately one must resort to hacky tricks like the accepted answer for now. The W3C is however in the process of specifying The VirtualKeyboard API.

Note: At the time of writing, this answer is not yet ready for prime time. It's important to understand that this specification must also be forward looking, to adapt to the myriad possible virtual keyboards of the future. It may be a few years before reliable cross platform browser support begins to appear and this answer becomes the correct one.

ContentLicense: CC BY-SA 4.0

Body:
I can only find questions where people have the opposite problem.

I want my fixed content to go above the iOS keyboard.
Image of the problem:

I want iOS to behave like Android.

Is there a simple way to achieve this?

Parent element css:

.parent{
    position:fixed;
    top: 0;
    left 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}

Button css:

.button{
    position:fixed;
    left 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 5rem;
}


问:
Create full screen image on Android to fill the splash screen
I'm new to Android programming, trying to create a splash screen with image. Currently I have this code :

```<code><?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque">

<item>
    <bitmap
        android:src="@drawable/splash"
        android:gravity="fill"/>
</item>

</layer-list>
</code>```

This result I get is a centered image with empty space top and bottom.

I tried multiple constants like center, fill, fill _horizontal, etc..
Also tried to replace bitmap with ImageView, but I think I need some more knowledge how to propely use it.

I'm trying to make the image fill the screen like this :

答:
I used android:dither="true" for bitmap, code like this :</p>
```<code><?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque">

<item>
    <bitmap
        android:src="@drawable/splash"
        android:dither="true"

        />
</item>

</layer-list>
</code>```

Body:
I'm new to Android programming, trying to create a splash screen with image. Currently I have this code :

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque">

<item>
    <bitmap
        android:src="@drawable/splash"
        android:gravity="fill"/>
</item>

</layer-list>

This result I get is a centered image with empty space top and bottom.

I tried multiple constants like center, fill, fill _horizontal, etc..
Also tried to replace bitmap with ImageView, but I think I need some more knowledge how to propely use it.

I'm trying to make the image fill the screen like this :

Body:
I used android:dither="true" for bitmap, code like this :

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque">

<item>
    <bitmap
        android:src="@drawable/splash"
        android:dither="true"

        />
</item>

</layer-list>


问:
Need help returning the input variable with an if statement
I am new to stackoverflow and python, is it possible to return the utility function within the class type function and then sort it by the class input? Let me know if you have any suggestions or help. Thanks

```<code>rates = pd.read_csv('data')

CNP_TDSP= rates.loc[(rates['TDSP'] == 'CNP')]
TNMP_TDSP= rates.loc[(rates['TDSP'] == 'TNMP')]
AEPC_TDSP= rates.loc[(rates['TDSP'] == 'AEPC')]
AEPN_TDSP= rates.loc[(rates['TDSP'] == 'AEPN')]
ONC_TDSP= rates.loc[(rates['TDSP'] == 'ONC')]

TDSP_OPTIONS = ['CNP', 'TNMP', 'AEPC', 'AEPN', 'ONC']
print(TDSP_OPTIONS)

userInput = input('Enter tdsp:')
class_input = input('Enter class type:')

def utility():
    if userInput == 'CNP':
        display(CNP_TDSP)
    if userInput == 'TNMP':
        display(TNMP_TDSP)
    if userInput == 'AEPC':
        display(AEPC_TDSP)
    if userInput == 'AEPN':
        display(AEPN_TDSP)
    if userInput == 'ONC':
        display(ONC_TDSP)

utility()

def class_type():
    if class_input == 'Resi':
        display(utility['Class'] == 'Resi)

class_type()
</code>```

output: File "/tmp/ipykernel_28447/2787243890.py", line 37
display(utility['Class'] == 'Resi) SyntaxError: EOL while scanning string literal

答:
def class_type():
    if class_input == 'Resi':
        display(utility['Class'] == 'Resi)
```

Add a quote after 'Resi

Body:
I am new to stackoverflow and python, is it possible to return the utility function within the class type function and then sort it by the class input? Let me know if you have any suggestions or help. Thanks

rates = pd.read_csv('data')

CNP_TDSP= rates.loc[(rates['TDSP'] == 'CNP')]
TNMP_TDSP= rates.loc[(rates['TDSP'] == 'TNMP')]
AEPC_TDSP= rates.loc[(rates['TDSP'] == 'AEPC')]
AEPN_TDSP= rates.loc[(rates['TDSP'] == 'AEPN')]
ONC_TDSP= rates.loc[(rates['TDSP'] == 'ONC')]

TDSP_OPTIONS = ['CNP', 'TNMP', 'AEPC', 'AEPN', 'ONC']
print(TDSP_OPTIONS)

userInput = input('Enter tdsp:')
class_input = input('Enter class type:')

def utility():
    if userInput == 'CNP':
        display(CNP_TDSP)
    if userInput == 'TNMP':
        display(TNMP_TDSP)
    if userInput == 'AEPC':
        display(AEPC_TDSP)
    if userInput == 'AEPN':
        display(AEPN_TDSP)
    if userInput == 'ONC':
        display(ONC_TDSP)

utility()

def class_type():
    if class_input == 'Resi':
        display(utility['Class'] == 'Resi)

class_type()

output: File "/tmp/ipykernel_28447/2787243890.py", line 37
display(utility['Class'] == 'Resi) SyntaxError: EOL while scanning string literal

Body:
def class_type():
    if class_input == 'Resi':
        display(utility['Class'] == 'Resi)

Add a quote after 'Resi


问:
When using Entity Framework 6 Code-First approach, can I create index directly from database?
I have a recommendation from Azure to create the following index:

CREATE NONCLUSTERED INDEX [nci_wi_Transactions_71EA7D20388C3F47A9B9EBF2A1C7BA0C] ON [dbo].[Transactions] ([Client_Id]) INCLUDE ([Date], [Description], [Size], [Type]) WITH (ONLINE = ON)

Is it possible to execute this SQL directly from MSSQL without affecting my applications work?
Or do I need to apply some migrations from code-first to keep database context with the correct state anyway?

答:
Actually, @Steve in comment answered and I checked in runtime and
Yes, it is safe to create an index directly from a database, which will not affect applications, used not changed DbContext.</p>


问:
Selecting multiple radio buttons (through jquery, javasscript?)
I currently have a form with lets say 5 radio button entries (see below).
What im looking archive is the following:
- Being able to choose multiple radio buttons - lets say 3 and submit the form.

Currently I got it working fine with PHP, SQL, but im only able to choose one radiobutton and submit that.

I figure it would also come in handy being able to deselect a radio button in case you wrongly click one.

My guess is that this can be done through some javascript? Any suggestions? Online examples perhaps?

```<code><form id="pollform" action="poll.php" method="post">
<input id="option-1" type="radio" value="1" name="poll">
<label for="option-1">Select option 1</label>

<input id="option-2" type="radio" value="2" name="poll">
<label for="option-2">Select option 2</label>

<input id="option-3" type="radio" value="3" name="poll">
<label for="option-3">Select option 3</label>

<input id="option-4" type="radio" value="4" name="poll">
<label for="option-4">Select option 4</label>

<input id="option-5" type="radio" value="5" name="poll">
<label for="option-5">Select option 5</label>
</form>
</code>```

答:
Radio buttons are designed so that only one option from each group (as designated by their shared name) can be selected at once (just like you can only tune a radio to one station).

The input control which allows any number of options to be selected is the checkbox. If you append [] to their names, then the selected options will arrive on the PHP side as an array.

```<code><input type="checkbox" value="1" name="poll[]" />
<input type="checkbox" value="2" name="poll[]" />
</code>```

Body:
I currently have a form with lets say 5 radio button entries (see below).
What im looking archive is the following:
- Being able to choose multiple radio buttons - lets say 3 and submit the form.

Currently I got it working fine with PHP, SQL, but im only able to choose one radiobutton and submit that.

I figure it would also come in handy being able to deselect a radio button in case you wrongly click one.

My guess is that this can be done through some javascript? Any suggestions? Online examples perhaps?

<form id="pollform" action="poll.php" method="post">
<input id="option-1" type="radio" value="1" name="poll">
Select option 1

<input id="option-2" type="radio" value="2" name="poll">
Select option 2

<input id="option-3" type="radio" value="3" name="poll">
Select option 3

<input id="option-4" type="radio" value="4" name="poll">
Select option 4

<input id="option-5" type="radio" value="5" name="poll">
Select option 5
</form>

Body:
Radio buttons are designed so that only one option from each group (as designated by their shared name) can be selected at once (just like you can only tune a radio to one station).

The input control which allows any number of options to be selected is the checkbox. If you append [] to their names, then the selected options will arrive on the PHP side as an array.

<input type="checkbox" value="1" name="poll[]" />
<input type="checkbox" value="2" name="poll[]" />


问:
Extract file during installation
I'm trying to extract a file using 7zip in the [Codes] section as I want to extract before any files get copied by the [Files] section.

With the code below I am not getting it, I tried and changed it, but it appears that The system cannot find the specified file

Am I doing something wrong?

[Files]

// Copy 7za.exe to {tmp} folder
Source: "tools\7zip\7za.exe"; DestDir: "{tmp}\7zip"; Flags: deleteafterinstall;

Source: "{tmp}\launchers\Launcher1"; DestDir: "{app}"; Flags: onlyifdoesntexist external; BeforeInstall: ExtractLauncher
Source: "{tmp}\launchers\Launcher2"; DestDir: "{app}"; Flags: onlyifdoesntexist external; BeforeInstall: ExtractLauncher

// --------------------------- Extract Launcher --------------------------- \\

[Code]
var
 ResultCode: integer;

procedure ExtractLauncher();
begin
  Exec(ExpandConstant('{tmp}\7zip\7za.exe'), 'x "{tmp}\launchers\launcher.zip" -o"{tmp}\launchers" * -r -aoa', '', SW_SHOW, ewWaitUntilTerminated, ResultCode)
  MsgBox(SysErrorMessage(ResultCode), mbError, MB_OK);
end;
```

The launcher.zip file is downloaded during installation to the {tmp}\launchers folder

I kept looking at the {tmp} folder, and the launcher.zip file and 7za.exe are created before running my [Codes], I did this to make sure they were there when run the code.
And yes, they were there before running the code.

答:
Thanks to Martin's Prikryl comment, I just added ExpandConstant to the rest of the command line and the code worked!

It was like this:

[Files]

// Copy 7za.exe to {tmp} folder
Source: "tools\7zip\7za.exe"; DestDir: "{tmp}\7zip"; Flags: deleteafterinstall;

Source: "{tmp}\launchers\Launcher1"; DestDir: "{app}"; Flags: onlyifdoesntexist external; BeforeInstall: ExtractLauncher
Source: "{tmp}\launchers\Launcher2"; DestDir: "{app}"; Flags: onlyifdoesntexist external; BeforeInstall: ExtractLauncher

// --------------------------- Extract Launcher ---------------------------

[Code]
var
 ResultCode: integer;

procedure ExtractLauncher();
begin
  Exec(ExpandConstant('{tmp}\7zip\7za.exe'), ' x ' + ExpandConstant('{tmp}\launchers\launcher.zip') + ' -o' + ExpandConstant('{tmp}\launchers') + ' * -r -aoa', '', SW_SHOW, ewWaitUntilTerminated, ResultCode)
  MsgBox(SysErrorMessage(ResultCode), mbError, MB_OK);
end;
```

Title: Extract file during installation

Body:
I'm trying to extract a file using 7zip in the [Codes] section as I want to extract before any files get copied by the [Files] section.

With the code below I am not getting it, I tried and changed it, but it appears that The system cannot find the specified file

Am I doing something wrong?

[Files]

// Copy 7za.exe to {tmp} folder
Source: "tools\7zip\7za.exe"; DestDir: "{tmp}\7zip"; Flags: deleteafterinstall;

Source: "{tmp}\launchers\Launcher1"; DestDir: "{app}"; Flags: onlyifdoesntexist external; BeforeInstall: ExtractLauncher
Source: "{tmp}\launchers\Launcher2"; DestDir: "{app}"; Flags: onlyifdoesntexist external; BeforeInstall: ExtractLauncher

// --------------------------- Extract Launcher --------------------------- \\

[Code]
var
 ResultCode: integer;

procedure ExtractLauncher();
begin
  Exec(ExpandConstant('{tmp}\7zip\7za.exe'), 'x "{tmp}\launchers\launcher.zip" -o"{tmp}\launchers" * -r -aoa', '', SW_SHOW, ewWaitUntilTerminated, ResultCode)
  MsgBox(SysErrorMessage(ResultCode), mbError, MB_OK);
end;

The launcher.zip file is downloaded during installation to the {tmp}\launchers folder

I kept looking at the {tmp} folder, and the launcher.zip file and 7za.exe are created before running my [Codes], I did this to make sure they were there when run the code.
And yes, they were there before running the code.


问:
Beginning at the end of 'a', insert 'b' after every 3rd character of 'a'
I've been trying to solve this challenge (found at jschallenger.com):

Write a function that takes two strings (a and b) as arguments

Beginning at the end of 'a', insert 'b' after every 3rd character of
'a'

Return the resulting string

This is my solution so far (Which I was sure would work):

function insertEveryThree(a, b) {
  let arr = a.split('')

  for (let i = arr.length - 3; i > 0; i -= 3) {

    arr.splice(i, 0, b)

  }
  return arr.join('')
}

console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz```

Where am I failing at?

答:
You need to push into a new array, splicing mutates the array and causes problems with indexes:</p>
```<code>function insertEveryThree(str, character, index = 3) {
  const strArr = str.split("");
  const newArr = [];

  for (const i = 0; i < str.length; i++) {
    newArr.push(strArr[i]);

    if ((i + 1) % index === 0 && i !== 0 && i + 1 < str.length) {
      newArr.push(character);
    }
  }

  return newArr.join("");
}
console.log(insertEveryThree("actionable", "-")); // act-ion-abl-e
console.log(insertEveryThree("1234567", ".")); // 123.456.7
console.log(insertEveryThree("abcde", "$")); // abc$de
console.log(insertEveryThree("zxyzxyzxyzxyzxyz", "w")); // zxywzxywzxywzxywzxywz
</code>```

Body:
I've been trying to solve this challenge (found at jschallenger.com):

Write a function that takes two strings (a and b) as arguments

Beginning at the end of 'a', insert 'b' after every 3rd character of
'a'

Return the resulting string

This is my solution so far (Which I was sure would work):

function insertEveryThree(a, b) {
  let arr = a.split('')

  for (let i = arr.length - 3; i > 0; i -= 3) {

    arr.splice(i, 0, b)

  }
  return arr.join('')
}

console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz

Where am I failing at?

Body:
You need to push into a new array, splicing mutates the array and causes problems with indexes:

function insertEveryThree(str, character, index = 3) {
  const strArr = str.split("");
  const newArr = [];

  for (const i = 0; i < str.length; i++) {
    newArr.push(strArr[i]);

    if ((i + 1) % index === 0 && i !== 0 && i + 1 < str.length) {
      newArr.push(character);
    }
  }

  return newArr.join("");
}
console.log(insertEveryThree("actionable", "-")); // act-ion-abl-e
console.log(insertEveryThree("1234567", ".")); // 123.456.7
console.log(insertEveryThree("abcde", "$")); // abc$de
console.log(insertEveryThree("zxyzxyzxyzxyzxyz", "w")); // zxywzxywzxywzxywzxywz


问:
How does the C++ compiler decide which of these functions is called?
Consider the following setup:

I am given an interface

```<code>template<class T>
  void FooClass<T>::foo(boost::function<double (int)> f)
{...}
</code>```

I want to implement f using a Functor:

```<code>class MyFun {
    public: double operator()(int a) {do something...;}
}
</code>```

However there is another function defined in the interface

```<code>template<class T>
  template <class FunPtr>
    void FooClass<T>::foo(const FunPtr& f)
{...}
</code>```

When a FooClass object is called,

```<code>MyFun f;
FooClass<double> fooclass;
fooclass.foo(f);
</code>```

it uses the second definition, while I want it to call the first one - can this be changed somehow?

答:
The compiler 'preferres' the second definition because the template version results in an exact match for the function object parameter, whereas the boost::function parameter needs an implicit conversion to be accepted (and implicit conversions are considered after direct overload resolution). You can achieve what you want just by constructing a boost::function object, and then passing it to the function (note that you can do this in the same line, I'm just doing it separately for clarity):

```<code>boost::function<double (int)> bMyFun(myFunInstance);
fooClassInstance.foo(bMyFun);
</code>```

Body:
Consider the following setup:

I am given an interface

template<class T>
  void FooClass<T>::foo(boost::function<double (int)> f)
{...}

I want to implement f using a Functor:

class MyFun {
    public: double operator()(int a) {do something...;}
}

However there is another function defined in the interface

template<class T>
  template <class FunPtr>
    void FooClass<T>::foo(const FunPtr& f)
{...}

When a FooClass object is called,

MyFun f;
FooClass<double> fooclass;
fooclass.foo(f);

it uses the second definition, while I want it to call the first one - can this be changed somehow?

Body:
The compiler 'preferres' the second definition because the template version results in an exact match for the function object parameter, whereas the boost::function parameter needs an implicit conversion to be accepted (and implicit conversions are considered after direct overload resolution). You can achieve what you want just by constructing a boost::function object, and then passing it to the function (note that you can do this in the same line, I'm just doing it separately for clarity):

boost::function<double (int)> bMyFun(myFunInstance);
fooClassInstance.foo(bMyFun);


问:
How to set validation based on field selection in angular reactive form array
i try to implement angular reactive form array validation on based on other filed

```<code>    private addUserFormGroup(): FormGroup {
            return new FormGroup({
                'name': new FormControl('', Validators.required),
                'emailAddress': new FormControl('', Validators.required),
                'admin': new FormControl(false, Validators.required),
                'role': new FormControl(''),
            });
        }

         ngOnInit(): void {
            this.addUserForm = this.formBuilder.group({
                userList: this.formBuilder.array([this.addUserFormGroup()]),
            });

            this.addUserForm.valueChanges.subscribe((c) => {
                c.userList.forEach((x) => {
                    console.log(x.admin);
                    x['role'].validator = Validators.required;
                    // x.role.setValidators(Validators.required);
                });

            }

</code>```

basically admin formcontrol as a checkbox, if i select admin checkbox i need to apply Validators.required to role filed.

could you please he me on this

答:
You can subscribe to valueChanges of FormControl "admin" only so that it wont trigger on any other value changes.

And in subscribed method based on value true or false you can set the validator with setValidators function.

Inside value changes subscribed method you can either find the FormControl "role" using parent property of FormControl "admin"

or

if the structure is fixed you can get FormControl "role" with path also, like this.addUserForm.get("userList").get("0").get("role").setValidators(Validators.required);

Body:
i try to implement angular reactive form array validation on based on other filed

    private addUserFormGroup(): FormGroup {
            return new FormGroup({
                'name': new FormControl('', Validators.required),
                'emailAddress': new FormControl('', Validators.required),
                'admin': new FormControl(false, Validators.required),
                'role': new FormControl(''),
            });
        }

         ngOnInit(): void {
            this.addUserForm = this.formBuilder.group({
                userList: this.formBuilder.array([this.addUserFormGroup()]),
            });

            this.addUserForm.valueChanges.subscribe((c) => {
                c.userList.forEach((x) => {
                    console.log(x.admin);
                    x['role'].validator = Validators.required;
                    // x.role.setValidators(Validators.required);
                });

            }

basically admin formcontrol as a checkbox, if i select admin checkbox i need to apply Validators.required to role filed.

could you please he me on this


问:
Break line when string reaches X characters
I created this function below to calculate when a string (name) reaches more than 35 characters then it break a line.

function getName(name) {
      let newName = name
      for (let i = 0; i < name.length; i += 1) {
        if (i % 35 === 0) {
          newName = `${newName.substr(0, i)}\n${newName.substr(i)}`
        }
      }
      return newName
}

console.log(getName("Please note that popular names below"))```
</div>
</div>
</p>
<p>Eg output:</p>
```Name = "Please note that popular names below"
function output:

Please note that popular names bel
ow
```

What I want is to instead of break a line of these two last characters "ow", I put "below" in the next line.

答:
You can I guess keep track of the last white space index, and then when reaching 35, break the line at the white space index</p>
```<code>function getName(name) {
  let newName = name
  let wsIndex = 0
  for (let i = 0; i < name.length; i += 1) {
    if (name.charAt(i) == ' ') wsIndex = i;
    if (i % 35 === 0) {
      newName = `${newName.substr(0, wsIndex)}\n${newName.substr(wsIndex+1)}`
    }
  }
  return newName
}
</code>```

Body:
I created this function below to calculate when a string (name) reaches more than 35 characters then it break a line.

function getName(name) {
      let newName = name
      for (let i = 0; i < name.length; i += 1) {
        if (i % 35 === 0) {
          newName = `${newName.substr(0, i)}\n${newName.substr(i)}`
        }
      }
      return newName
}

console.log(getName("Please note that popular names below"))

Eg output:

Name = "Please note that popular names below"
function output:

Please note that popular names bel
ow

What I want is to instead of break a line of these two last characters "ow", I put "below" in the next line.

Body:
You can I guess keep track of the last white space index, and then when reaching 35, break the line at the white space index

function getName(name) {
  let newName = name
  let wsIndex = 0
  for (let i = 0; i < name.length; i += 1) {
    if (name.charAt(i) == ' ') wsIndex = i;
    if (i % 35 === 0) {
      newName = `${newName.substr(0, wsIndex)}\n${newName.substr(wsIndex+1)}`
    }
  }
  return newName
}


问:
Convert a comma-delimited string into array of integers?
The following code:

```<code>$string = "1,2,3"
$ids = explode(',', $string);
var_dump($ids);
</code>```

Returns the array:

```<code>array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
</code>```

I need for the values to be of type int instead of type string. Is there a better way of doing this than looping through the array with foreach and converting each string to int?

答:
I'm surprised no one proposed filter_var method, I'm not sure how well it performs on huge datasets, but if your key is validity over performance here is an example:

$sampleString = '1,2 3, 4, 6, 5 , a';
$filteredValues = filter_var(
     explode(',', $sampleString),
     FILTER_VALIDATE_INT,
     FILTER_NULL_ON_FAILURE | FILTER_FORCE_ARRAY
);
```
```array (size=6)
  0 => int 1
  1 => null
  2 => int 4
  3 => int 6
  4 => int 5
  5 => null
```
<p>As you can see <code>2 3</code> is not a valid number same as <code>a</code> and were replaced by <code>null</code></p>
<p>To get rid of empty values you can apply <code>array_filter</code></p>
<pre class="lang-php prettyprint-override"><code>$filteredValues = array_filter($filteredValues);
</code>```

which would produce following result:

```<code>array (size=4)
  0 => int 1
  2 => int 4
  3 => int 6
  4 => int 5
</code>```

Body:
The following code:

$string = "1,2,3"
$ids = explode(',', $string);
var_dump($ids);

Returns the array:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}

I need for the values to be of type int instead of type string. Is there a better way of doing this than looping through the array with foreach and converting each string to int?

Body:
I'm surprised no one proposed filter_var method, I'm not sure how well it performs on huge datasets, but if your key is validity over performance here is an example:

$sampleString = '1,2 3, 4, 6, 5 , a';
$filteredValues = filter_var(
     explode(',', $sampleString),
     FILTER_VALIDATE_INT,
     FILTER_NULL_ON_FAILURE | FILTER_FORCE_ARRAY
);

array (size=6)
  0 => int 1
  1 => null
  2 => int 4
  3 => int 6
  4 => int 5
  5 => null

As you can see 2 3 is not a valid number same as a and were replaced by null

To get rid of empty values you can apply array_filter

$filteredValues = array_filter($filteredValues);

which would produce following result:

array (size=4)
  0 => int 1
  2 => int 4
  3 => int 6
  4 => int 5


问:
In ggplot2, how do I make a faceted plot have min heights and share the same ticks?
I'm producing a faceted plot like this:

This is accomplished with:

```<code>df = data.frame(val=rnorm(2005), class=c(rep(c('a','b'), 1000), rep('c', 5)))
qplot(val, ..count.., data=df, geom='density', fill=I('black')) +
  opts(strip.text.y = theme_text()) +
  # scale_y_continuous(breaks=seq(0, 999, by=50)) +
  facet_grid(class ~ ., scale = "free", space = "free")
</code>```

I intentionally do want the facets to be differently sized (taking up only as much vertical space as necessary) but maintain the same scale.

Now, there are some problems with this plot:

I'd like to impose a min height on each facet so that you can at least see the right label text and recognize the display as an empty density plot - currently, if I didn't know how I generated this plot, I would never have guessed what that artifact at the bottom was.

While the facets share the same scale, the y-axes don't share the same grids/ticks. I can force them to share the same grid by uncommenting the commented line, but then I'm manually calculating this - is there some way to just use the coarsest grid among any of the density plots?

Thanks in advance for any answers.

答:
Edited

I don't think that this is possible using an elegant parameter of ggplot, but will be happy to be proved wrong.

However, here is a workaround that has the desired effect.  The idea is to add an invisible layer to the plot with a single point that is high enough on the y-axis to force each panel to be a minimum size.  In this case I have manually selected this value as 50, but you should be able to create an algorithm that is based on a percentage of maximum count or similar:

```<code>df = data.frame(val=rnorm(2005), class=c(rep(c('a','b'), 1000), rep('c', 5)))
dg <- data.frame(class=c("a","b","c"), value=rep(50,3))
qplot(val, ..count.., data=df, geom='density', fill=I('black')) +
    opts(strip.text.y = theme_text()) +
    facet_grid(class ~ ., scales="free", space="free") +
    geom_blank(data=dg, aes(x=0, y=value))
</code>```

Edit 2 Thanks to @Thierry for the tip to use geom_blank rather than geom_point with invisible points.

Body:
I'm producing a faceted plot like this:

This is accomplished with:

df = data.frame(val=rnorm(2005), class=c(rep(c('a','b'), 1000), rep('c', 5)))
qplot(val, ..count.., data=df, geom='density', fill=I('black')) +
  opts(strip.text.y = theme_text()) +
  # scale_y_continuous(breaks=seq(0, 999, by=50)) +
  facet_grid(class ~ ., scale = "free", space = "free")

I intentionally do want the facets to be differently sized (taking up only as much vertical space as necessary) but maintain the same scale.

Now, there are some problems with this plot:

I'd like to impose a min height on each facet so that you can at least see the right label text and recognize the display as an empty density plot - currently, if I didn't know how I generated this plot, I would never have guessed what that artifact at the bottom was.

While the facets share the same scale, the y-axes don't share the same grids/ticks. I can force them to share the same grid by uncommenting the commented line, but then I'm manually calculating this - is there some way to just use the coarsest grid among any of the density plots?

Thanks in advance for any answers.

Body:
Edited

I don't think that this is possible using an elegant parameter of ggplot, but will be happy to be proved wrong.

However, here is a workaround that has the desired effect.  The idea is to add an invisible layer to the plot with a single point that is high enough on the y-axis to force each panel to be a minimum size.  In this case I have manually selected this value as 50, but you should be able to create an algorithm that is based on a percentage of maximum count or similar:

df = data.frame(val=rnorm(2005), class=c(rep(c('a','b'), 1000), rep('c', 5)))
dg <- data.frame(class=c("a","b","c"), value=rep(50,3))
qplot(val, ..count.., data=df, geom='density', fill=I('black')) +
    opts(strip.text.y = theme_text()) +
    facet_grid(class ~ ., scales="free", space="free") +
    geom_blank(data=dg, aes(x=0, y=value))

Edit 2 Thanks to @Thierry for the tip to use geom_blank rather than geom_point with invisible points.


问:
Unable to import module 'lambda_function': No module named 'pandas'

START RequestId: 3d5691d9-ad79-4eed-a26c-5bc3f1a23a99 Version: $LATEST
  Unable to import module 'lambda_function': No module named 'pandas'

  END RequestId: 3d5691d9-ad79-4eed-a26c-5bc3f1a23a99

I'm using Windows 7 64-bit as the host OS.

What I want to do

I simply want to use pandas in AWS-Lambda environment. Just like I use it in windows environment, I am looking for a simple solution for Lambda.

What I have tried so far

Installed Xubuntu on a virtual box.

Create a virtual environment called myvenv in Xubuntu on virtual-box.

Then I installed pandas3.6 in myvenv.

Thereafter, I copied the folder contents in myvenv at location '/usr/local/lib/python3.6/site-packages/' to my host OS.

In the host OS (windows 7), I created a folder called packs, pasted the contents of myvenv.

created a lambda_function.py script in packs in host OS (windows 7)

I then zipped the folder packs using 7zip software and upload it as zip in Lambda

In Lambda, the lambda function handler name is, lambda_handler(). The code snippet looks like,

import pandas as pd

```<code>def lambda_handler(event, context):

    dates = pd.date_range('2019001', periods=6)

    df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
    print(df)
</code>```

The handler is named as lambda_function.lambda_handler. I have given the lambda-role AWSLambdaFullAccess permission.

The time out is set to 4 min and 3 sec.

The test event looks like

{
  "key1": "This will be printed if all OK"
}

I have tried the following solutions:

Tried precompiled linux-compatible binaries for pandas & numpy from here -- no luck.

In Lambda, changed the Handler info to python_filename.function_name. For my case, it was lambda_function.lambda_handler -- failed with no module named 'pandas' error.

placed the lambda function in the root folder, zipped the folder using 7zip software and upload the folder to the S3 bucket. For my case, I placed the function at location python\lib\python3.6\site_packages\lambda_function.pyfailed with no module named 'pandas' error.

Already tried these related solutions posted on SO, 1, 2, 3, 4, 5, 6

Note: I do not want to use Docker, because I do not know how to use it and I'm not willing to learn it as I'm exasperated now. I'm coming from a windows environment (it sucks, I now know.)

Any ideas on how to get this to work.

答:
I found this github repo that has pre-built package ARNs. Find the one you want for your AWS region, and then choose "Specify an ARN" when creating the layer and paste in the layer ARN from this github repo:

https://github.com/keithrozario/Klayers

Body:
START RequestId: 3d5691d9-ad79-4eed-a26c-5bc3f1a23a99 Version: $LATEST
  Unable to import module 'lambda_function': No module named 'pandas'

  END RequestId: 3d5691d9-ad79-4eed-a26c-5bc3f1a23a99

I'm using Windows 7 64-bit as the host OS.

What I want to do

I simply want to use pandas in AWS-Lambda environment. Just like I use it in windows environment, I am looking for a simple solution for Lambda.

What I have tried so far

Installed Xubuntu on a virtual box.

Create a virtual environment called myvenv in Xubuntu on virtual-box.

Then I installed pandas3.6 in myvenv.

Thereafter, I copied the folder contents in myvenv at location '/usr/local/lib/python3.6/site-packages/' to my host OS.

In the host OS (windows 7), I created a folder called packs, pasted the contents of myvenv.

created a lambda_function.py script in packs in host OS (windows 7)

I then zipped the folder packs using 7zip software and upload it as zip in Lambda

In Lambda, the lambda function handler name is, lambda_handler(). The code snippet looks like,

import pandas as pd

def lambda_handler(event, context):

    dates = pd.date_range('2019001', periods=6)

    df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
    print(df)

The handler is named as lambda_function.lambda_handler. I have given the lambda-role AWSLambdaFullAccess permission.

The time out is set to 4 min and 3 sec.

The test event looks like

{
  "key1": "This will be printed if all OK"
}

I have tried the following solutions:

Tried precompiled linux-compatible binaries for pandas & numpy from here -- no luck.

In Lambda, changed the Handler info to python_filename.function_name. For my case, it was lambda_function.lambda_handler -- failed with no module named 'pandas' error.

placed the lambda function in the root folder, zipped the folder using 7zip software and upload the folder to the S3 bucket. For my case, I placed the function at location python\lib\python3.6\site_packages\lambda_function.pyfailed with no module named 'pandas' error.

Already tried these related solutions posted on SO, 1, 2, 3, 4, 5, 6

Note: I do not want to use Docker, because I do not know how to use it and I'm not willing to learn it as I'm exasperated now. I'm coming from a windows environment (it sucks, I now know.)

Any ideas on how to get this to work.


问:
VBA Array repetition
I am trying to make a function that takes in 3 values, and outputs that many of three different numbers in array format (in this case 1,2,4). For example: EntryArray(1,2,1) would output vertically: 1,1,2,2,2,4,4. However, it should repeat this array a certain number of times (given as the last value), and this part I can't get to work. For example: EntryArray(2,1,1,4) should give:
1,1,2,4,1,1,2,4,1,1,2,4,1,1,2,4

My code as follows:

```<code>Function EntryArray(One As Integer, Two As Integer, Four As Integer, Rept As Integer) As Integer()

Dim Length As Integer
Length = One + Two + Four

Dim entry() As Integer
ReDim entry(0 To Length, 0)

For i = 1 To Length
entry(i, 0) = 1
If i > One Then entry(i, 0) = 2
If i > Two + One Then entry(i, 0) = 4
Next i

EntryArray = entry

End Function
</code>```

答:
Simply create the loop that enters 1, 2, 4 and loop that Rept times.  Use a seperate counter to track where to insert the value into entry

I've simplified the logic of inserting 1, 2, 4 and switched to type Long.  There's no advantage in using Integer

Also, you have some "off by one" issues.  Using 1 based array is easier

Function EntryArray(One As Long, Two As Long, Four As Long, Rept As Long) As Long()
    Dim i As Long, j As Long, n As Long
    Dim Length As Long
    Length = One + Two + Four

    Dim entry() As Long
    ReDim entry(1 To Length * Rept, 1 To 1)

    n = 1
    For j = 1 to Rept
        For i = 1 To One
            entry(n, 1) = 1
            n= n + 1
        Next
        For i = 1 To Two
            entry(n, 1) = 2
            n= n + 1
        Next
        For i = 1 To Four
            entry(n, 1) = 4
            n= n + 1
        Next
    Next

    EntryArray = entry

End Function
```

Title: VBA Array repetition

Body:
I am trying to make a function that takes in 3 values, and outputs that many of three different numbers in array format (in this case 1,2,4). For example: EntryArray(1,2,1) would output vertically: 1,1,2,2,2,4,4. However, it should repeat this array a certain number of times (given as the last value), and this part I can't get to work. For example: EntryArray(2,1,1,4) should give:
1,1,2,4,1,1,2,4,1,1,2,4,1,1,2,4

My code as follows:

Function EntryArray(One As Integer, Two As Integer, Four As Integer, Rept As Integer) As Integer()

Dim Length As Integer
Length = One + Two + Four

Dim entry() As Integer
ReDim entry(0 To Length, 0)

For i = 1 To Length
entry(i, 0) = 1
If i > One Then entry(i, 0) = 2
If i > Two + One Then entry(i, 0) = 4
Next i

EntryArray = entry

End Function


问:
Python list - adding elements to the list
I am trying to add two elements to the list but only one of them gets listed but the previous one is not getting appended at all

```<code>choice = [[1, 2], [3, 5]]
c = 5
for loop in range(n):
    diff = choice[loop][1]-choice[loop][0]
    choice_variant = []
    print(diff)
    for item_c in range(c):
        if(item_c+1+diff>c):
            break
        si,ei = item_c+1,item_c+1+diff
        print([si,ei])
        choice_variant.append([si,ei])
</code>```

Output is coming as below

```<code> - 1
[1, 2]
[2, 3]
[3, 4]
[4, 5]
- 2
[1, 3]
[2, 4]
[3, 5]
</code>```

when I try to iterate through the list - choice_variant , it shows me this [[1, 3], [2, 4], [3, 5]] which is the second set but misses the first set

```<code> - 1
[1, 2]
[2, 3]
[3, 4]
[4, 5]
</code>```

答:
declare choice_variant = [] outside of the for loop

EDIT:

sorry forgot the explain: declaring it inside of the for loop reinitializes the empty list for each iteration.

As for your comment: to get nested lists. Keep choice_variant = [] where it is and initialize an outer list that will consist of the choice_variant lists. So you'll have:

```<code>result = []
c = 5
for loop in range(n):
    diff = choice[loop][1]-choice[loop][0]
    choice_variant = []
    print(diff)
    for item_c in range(c):
        if(item_c+1+diff>c):
            break
        si,ei = item_c+1,item_c+1+diff
        print([si,ei])
        choice_variant.append([si,ei])
    result.append(choice_variant)

</code>```

Body:
I am trying to add two elements to the list but only one of them gets listed but the previous one is not getting appended at all

choice = [[1, 2], [3, 5]]
c = 5
for loop in range(n):
    diff = choice[loop][1]-choice[loop][0]
    choice_variant = []
    print(diff)
    for item_c in range(c):
        if(item_c+1+diff>c):
            break
        si,ei = item_c+1,item_c+1+diff
        print([si,ei])
        choice_variant.append([si,ei])

Output is coming as below

 - 1
[1, 2]
[2, 3]
[3, 4]
[4, 5]
- 2
[1, 3]
[2, 4]
[3, 5]

when I try to iterate through the list - choice_variant , it shows me this [[1, 3], [2, 4], [3, 5]] which is the second set but misses the first set

 - 1
[1, 2]
[2, 3]
[3, 4]
[4, 5]

Body:
declare choice_variant = [] outside of the for loop

EDIT:

sorry forgot the explain: declaring it inside of the for loop reinitializes the empty list for each iteration.

As for your comment: to get nested lists. Keep choice_variant = [] where it is and initialize an outer list that will consist of the choice_variant lists. So you'll have:

result = []
c = 5
for loop in range(n):
    diff = choice[loop][1]-choice[loop][0]
    choice_variant = []
    print(diff)
    for item_c in range(c):
        if(item_c+1+diff>c):
            break
        si,ei = item_c+1,item_c+1+diff
        print([si,ei])
        choice_variant.append([si,ei])
    result.append(choice_variant)


问:
Electron.js NSIS installer - "oneClick": false has no effect. Keeps building one click installers
I want to make a Windows installer with electron.js,
I referred to nsis config

I have set "oneClick": false

However, whenever I build the app with: npm run build

The option always shows as oneClick=true on build.

Have also tried npm run build-installer, to no avail. Same one click output :-(

I dont understand why is wouldnt accept the oneClick option, it had worked before, now I cant figure out why it just stopped working.

Here is an excerpt from package.json

```<code>"scripts": {
    "start": "electron-forge start",
    "package": "electron-forge package",
    "make": "electron-forge make",
    "publish": "electron-forge publish",
    "lint": "echo \"No linting configured\"",
    "build-installer": "electron-builder",
    "build": "electron-builder"
  },

  "build": {
    "appId": "apppppppp",
    "win": {
      "target": [
        {
          "target": "nsis",
          "arch": [
            "x64"
          ]
        }
      ],
      "icon": "/src/images/icons/manifest-icon-512.maskable.png"
    }
  },
  "nsis": {
    "oneClick": false,
    "perMachine": false,
    "allowElevation": true,
    "allowToChangeInstallationDirectory": true
  },
  "dependencies": {},
  "devDependencies": {
    "@electron-forge/cli": "^6.0.0-beta.63",
    "@electron-forge/maker-deb": "^6.0.0-beta.63",
    "@electron-forge/maker-rpm": "^6.0.0-beta.63",
    "@electron-forge/maker-squirrel": "^6.0.0-beta.63",
    "@electron-forge/maker-zip": "^6.0.0-beta.63",
    "electron": "16.0.7",
    "build-installer": "electron-builder",
    "build": "electron-builder"
  }
}
</code>```

答: I put the "nsis" options inside the "build" options and it worked.</p>

Body:
I want to make a Windows installer with electron.js,
I referred to nsis config

I have set "oneClick": false

However, whenever I build the app with: npm run build

The option always shows as oneClick=true on build.

Have also tried npm run build-installer, to no avail. Same one click output :-(

I dont understand why is wouldnt accept the oneClick option, it had worked before, now I cant figure out why it just stopped working.

Here is an excerpt from package.json

"scripts": {
    "start": "electron-forge start",
    "package": "electron-forge package",
    "make": "electron-forge make",
    "publish": "electron-forge publish",
    "lint": "echo \"No linting configured\"",
    "build-installer": "electron-builder",
    "build": "electron-builder"
  },

  "build": {
    "appId": "apppppppp",
    "win": {
      "target": [
        {
          "target": "nsis",
          "arch": [
            "x64"
          ]
        }
      ],
      "icon": "/src/images/icons/manifest-icon-512.maskable.png"
    }
  },
  "nsis": {
    "oneClick": false,
    "perMachine": false,
    "allowElevation": true,
    "allowToChangeInstallationDirectory": true
  },
  "dependencies": {},
  "devDependencies": {
    "@electron-forge/cli": "^6.0.0-beta.63",
    "@electron-forge/maker-deb": "^6.0.0-beta.63",
    "@electron-forge/maker-rpm": "^6.0.0-beta.63",
    "@electron-forge/maker-squirrel": "^6.0.0-beta.63",
    "@electron-forge/maker-zip": "^6.0.0-beta.63",
    "electron": "16.0.7",
    "build-installer": "electron-builder",
    "build": "electron-builder"
  }
}


问:
mysql, ifnull vs coalesce, which is faster?
if it's known that there are only two values to candidate for the result of a column,

```<code>ifnull(a, b) as a_or_b_1
</code>```

and

```<code>coalesce(a, b) as a_or_b_2
</code>```

will give the same result. but which is faster? when searching i found this article, which says ifnull is faster. but it was the only article i found. any views on this?

thanks in advance :)

答:
Since an answer was never given for MySQL, here's a custom procedure that shows IFNULL is about 10% slower than COALESCE for larger datasets.

```<code>CREATE PROCEDURE `compare_ifnull_coalesce`(max_var INT)
BEGIN
    DECLARE COALESCE_BOTH_NOT_NULL INT(11);
    DECLARE IFNULL_BOTH_NOT_NULL INT(11);
    DECLARE COALESCE_FIRST_NULL INT(11);
    DECLARE IFNULL_FIRST_NULL INT(11);
    DECLARE i INT DEFAULT 1;
    DECLARE StartDate DATETIME DEFAULT SYSDATE(3);
    WHILE i <= max_var DO
        IF (SELECT COALESCE('a', 'b') = 'b') THEN
            SELECT 1;
        END IF;
        SET i = i + 1;
    END WHILE;
    SET COALESCE_BOTH_NOT_NULL = FLOOR(TIMESTAMPDIFF(MICROSECOND, StartDate, SYSDATE(3))/1000);
    SET i = 1;
    SET StartDate = SYSDATE(3);
    WHILE i <= max_var DO
        IF (SELECT IFNULL('a', 'b') = 'b') THEN
            SELECT 1;
        END IF;
        SET i = i + 1;
    END WHILE;
    SET IFNULL_BOTH_NOT_NULL = FLOOR(TIMESTAMPDIFF(MICROSECOND, StartDate, SYSDATE(3))/1000);
    SET i = 1;
    SET StartDate = SYSDATE(3);
    WHILE i <= max_var DO
        IF (SELECT COALESCE(null, 'b') = 'a') THEN
            SELECT 1;
        END IF;
        SET i = i + 1;
    END WHILE;
    SET COALESCE_FIRST_NULL = FLOOR(TIMESTAMPDIFF(MICROSECOND, StartDate, SYSDATE(3))/1000);
    SET i = 1;
    SET StartDate = SYSDATE(3);
    WHILE i <= max_var DO
        IF (SELECT COALESCE(null, 'b') = 'a') THEN
            SELECT 1;
        END IF;
        SET i = i + 1;
    END WHILE;
    SET IFNULL_FIRST_NULL = FLOOR(TIMESTAMPDIFF(MICROSECOND, StartDate, SYSDATE(3))/1000);
    SELECT
        'both columns not null' AS `SCENARIO`,
        CONCAT('Total milliseconds: ', COALESCE_BOTH_NOT_NULL) AS `COALESCE`,
        CONCAT('Total milliseconds: ', IFNULL_BOTH_NOT_NULL) AS `IFNULL`
    UNION
    SELECT
        'first column null' AS `SCENARIO`,
        CONCAT('Total milliseconds: ', COALESCE_FIRST_NULL) AS `COALESCE`,
        CONCAT('Total milliseconds: ', IFNULL_FIRST_NULL) AS `IFNULL`
    ;
END;
</code>```

Then, to get the results, just run:

```<code>CALL compare_ifnull_coalesce(1000000);
</code>```

SCENARIO
COALESCE
IFNULL

both columns not null
Total milliseconds: 5175
Total milliseconds: 5687

first column null
Total milliseconds: 5185
Total milliseconds: 5793

ContentLicense: CC BY-SA 2.5

Body:
if it's known that there are only two values to candidate for the result of a column,

ifnull(a, b) as a_or_b_1

and

coalesce(a, b) as a_or_b_2

will give the same result. but which is faster? when searching i found this article, which says ifnull is faster. but it was the only article i found. any views on this?

thanks in advance :)

Body:
Since an answer was never given for MySQL, here's a custom procedure that shows IFNULL is about 10% slower than COALESCE for larger datasets.

CREATE PROCEDURE `compare_ifnull_coalesce`(max_var INT)
BEGIN
    DECLARE COALESCE_BOTH_NOT_NULL INT(11);
    DECLARE IFNULL_BOTH_NOT_NULL INT(11);
    DECLARE COALESCE_FIRST_NULL INT(11);
    DECLARE IFNULL_FIRST_NULL INT(11);
    DECLARE i INT DEFAULT 1;
    DECLARE StartDate DATETIME DEFAULT SYSDATE(3);
    WHILE i <= max_var DO
        IF (SELECT COALESCE('a', 'b') = 'b') THEN
            SELECT 1;
        END IF;
        SET i = i + 1;
    END WHILE;
    SET COALESCE_BOTH_NOT_NULL = FLOOR(TIMESTAMPDIFF(MICROSECOND, StartDate, SYSDATE(3))/1000);
    SET i = 1;
    SET StartDate = SYSDATE(3);
    WHILE i <= max_var DO
        IF (SELECT IFNULL('a', 'b') = 'b') THEN
            SELECT 1;
        END IF;
        SET i = i + 1;
    END WHILE;
    SET IFNULL_BOTH_NOT_NULL = FLOOR(TIMESTAMPDIFF(MICROSECOND, StartDate, SYSDATE(3))/1000);
    SET i = 1;
    SET StartDate = SYSDATE(3);
    WHILE i <= max_var DO
        IF (SELECT COALESCE(null, 'b') = 'a') THEN
            SELECT 1;
        END IF;
        SET i = i + 1;
    END WHILE;
    SET COALESCE_FIRST_NULL = FLOOR(TIMESTAMPDIFF(MICROSECOND, StartDate, SYSDATE(3))/1000);
    SET i = 1;
    SET StartDate = SYSDATE(3);
    WHILE i <= max_var DO
        IF (SELECT COALESCE(null, 'b') = 'a') THEN
            SELECT 1;
        END IF;
        SET i = i + 1;
    END WHILE;
    SET IFNULL_FIRST_NULL = FLOOR(TIMESTAMPDIFF(MICROSECOND, StartDate, SYSDATE(3))/1000);
    SELECT
        'both columns not null' AS `SCENARIO`,
        CONCAT('Total milliseconds: ', COALESCE_BOTH_NOT_NULL) AS `COALESCE`,
        CONCAT('Total milliseconds: ', IFNULL_BOTH_NOT_NULL) AS `IFNULL`
    UNION
    SELECT
        'first column null' AS `SCENARIO`,
        CONCAT('Total milliseconds: ', COALESCE_FIRST_NULL) AS `COALESCE`,
        CONCAT('Total milliseconds: ', IFNULL_FIRST_NULL) AS `IFNULL`
    ;
END;

Then, to get the results, just run:

CALL compare_ifnull_coalesce(1000000);

SCENARIO
COALESCE
IFNULL

both columns not null
Total milliseconds: 5175
Total milliseconds: 5687

first column null
Total milliseconds: 5185
Total milliseconds: 5793


问:
Can STRtOK function return a null/0 value?
I'm trying to use the strtok function to breakout a concatenated string.
This is what I have so far. My source tables are sitting in Teradata and I'm running the code via SAS.

```<code>proc sql;
connect to teradata as tera ( server='XXXXXX' authdomain='XXXXX';
execute(
         update DB.Table1
         from
       (
        select id, string_key
        from DB.Table2
        where date_time >= current_date
       ) c
set
       country = STRTOK (c.string_key,',',1),
       Expense      = STRTOK (c.string_key,',',2),
       First_Name    = STRTOK (c.string_key,',',3),

) by tera
disconnect from tera
quit;
</code>```

An example of a value in string_key is :

UK,244,Jack,Mathews

For the above example, my code has no problem creating the required output i.e:

Country
Expense
First name

UK
244
Jack

However in instances where a value in string_key has a null value after the delimiter, the strtok function returns the next available value in the wrong column.

for e.g when string_key is :

UK,244,,Mathews

then the output I get is

Country
Expense
First name

UK
244
Mathews

but what I want is that the First_name column should be empty as there is no value for it in the string_key.

i.e I want it is

Country
Expense
First name

UK
244

Could someone pls help tweak my code such that the column populates with a null value if the string has a null value?

Many thanks!

Body:
I'm trying to use the strtok function to breakout a concatenated string.
This is what I have so far. My source tables are sitting in Teradata and I'm running the code via SAS.

proc sql;
connect to teradata as tera ( server='XXXXXX' authdomain='XXXXX';
execute(
         update DB.Table1
         from
       (
        select id, string_key
        from DB.Table2
        where date_time >= current_date
       ) c
set
       country = STRTOK (c.string_key,',',1),
       Expense      = STRTOK (c.string_key,',',2),
       First_Name    = STRTOK (c.string_key,',',3),

) by tera
disconnect from tera
quit;

An example of a value in string_key is :

UK,244,Jack,Mathews

For the above example, my code has no problem creating the required output i.e:

Country
Expense
First name

UK
244
Jack

However in instances where a value in string_key has a null value after the delimiter, the strtok function returns the next available value in the wrong column.

for e.g when string_key is :

UK,244,,Mathews

then the output I get is

Country
Expense
First name

UK
244
Mathews

but what I want is that the First_name column should be empty as there is no value for it in the string_key.

i.e I want it is

Country
Expense
First name

UK
244

Could someone pls help tweak my code such that the column populates with a null value if the string has a null value?

Many thanks!

Body:
A RegEx should work:

SELECT 'UK,244,,Mathews' AS string_key
  ,REGEXP_SUBSTR(string_key, '(,|^)\K([^,]*)(?=,|$)',1,1)
  ,REGEXP_SUBSTR(string_key, '(,|^)\K([^,]*)(?=,|$)',1,2)
  ,REGEXP_SUBSTR(string_key, '(,|^)\K([^,]*)(?=,|$)',1,3)
  ,REGEXP_SUBSTR(string_key, '(,|^)\K([^,]*)(?=,|$)',1,4)
;

See RegEx101


问:
org.springframework.http.converter.HttpMessageNotWritableException No converter found for return value of type: class
I'm doing exercises with Spring-Boot, I tried to search, but nothing I've found worked for me. I'm trying to return a JSON converting a POJO, which SB is supposed to do it automatically, but it returns:

2018-11-05 13:26:36.090  WARN 1584 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.example.demo.pelis.Foo]

Here is my pom.xml:

```<code>  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</code>```

And my POJO:

```<code>public class Foo {

    private String bar;

    /**
     * @return the bar
     */
    public String getBar() {
        return bar;
    }

    /**
     * @param bar
     *            the bar to set
     */
    public void setBar(String bar) {
        this.bar = bar;
    }
}
</code>```

The controller:

```<code>@RestController
public class PelisController {
    @GetMapping(value = "/fooPoint")
    public Foo fooPoint() {
        Foo foo = new Foo();
        foo.setBar("smthng");
        return foo;
    }
}
</code>```

I don't know what I'm doing wrong, because I've tried getters/setters method, I tried to replace my pom with the one in the official guide. Nothing helped.

答:
As of Spring Boot 2.5.7 getters or fasterxml don't solve this problem, but setting produces in @RequestMapping does
try setting produces = { "application/json" }

```<code>@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
</code>```

Body:
I'm doing exercises with Spring-Boot, I tried to search, but nothing I've found worked for me. I'm trying to return a JSON converting a POJO, which SB is supposed to do it automatically, but it returns:

2018-11-05 13:26:36.090  WARN 1584 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.example.demo.pelis.Foo]

Here is my pom.xml:

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath />
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

And my POJO:

public class Foo {

    private String bar;

    /**
     * @return the bar
     */
    public String getBar() {
        return bar;
    }

    /**
     * @param bar
     *            the bar to set
     */
    public void setBar(String bar) {
        this.bar = bar;
    }
}

The controller:

@RestController
public class PelisController {
    @GetMapping(value = "/fooPoint")
    public Foo fooPoint() {
        Foo foo = new Foo();
        foo.setBar("smthng");
        return foo;
    }
}

I don't know what I'm doing wrong, because I've tried getters/setters method, I tried to replace my pom with the one in the official guide. Nothing helped.

Body:
As of Spring Boot 2.5.7 getters or fasterxml don't solve this problem, but setting produces in @RequestMapping does
try setting produces = { "application/json" }

@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })


问:
Get the next seven days of the week in views - Django
How to get seven consecutive days of the week in views using Django. I try this, but it returns an error.

```<code>from datetime import datetime

day = datetime.now()
day_1 = datetime.now() + datetime.timedelta(days=1)
day_2 = datetime.now() + datetime.timedelta(days=2)
day_3 = datetime.now() + datetime.timedelta(days=3)
day_4 = datetime.now() + datetime.timedelta(days=4)
day_5 = datetime.now() + datetime.timedelta(days=5)
day_6 = datetime.now() + datetime.timedelta(days=6)
day_7 = datetime.now() + datetime.timedelta(days=7)
</code>```

It returns:

```<code>type object 'datetime.datetime' has no attribute 'timedelta'
</code>```

答:
The datetime in datetime.timedelta is about the module not the class, since you here import the class, you can also import timedelta directly:

```from datetime import datetime, <strong>timedelta</strong>

day = datetime.now()
day<sub>1</sub> = day + <strong>timedelta(</strong>days=1<strong>)</strong>
day<sub>2</sub> = day + <strong>timedelta(</strong>days=2<strong>)</strong>
day<sub>3</sub> = day + <strong>timedelta(</strong>days=3<strong>)</strong>
day<sub>4</sub> = day + <strong>timedelta(</strong>days=4<strong>)</strong>
day<sub>5</sub> = day + <strong>timedelta(</strong>days=5<strong>)</strong>
day<sub>6</sub> = day + <strong>timedelta(</strong>days=6<strong>)</strong>
day<sub>7</sub> = day + <strong>timedelta(</strong>days=7<strong>)</strong>```

Body:
How to get seven consecutive days of the week in views using Django. I try this, but it returns an error.

from datetime import datetime

day = datetime.now()
day_1 = datetime.now() + datetime.timedelta(days=1)
day_2 = datetime.now() + datetime.timedelta(days=2)
day_3 = datetime.now() + datetime.timedelta(days=3)
day_4 = datetime.now() + datetime.timedelta(days=4)
day_5 = datetime.now() + datetime.timedelta(days=5)
day_6 = datetime.now() + datetime.timedelta(days=6)
day_7 = datetime.now() + datetime.timedelta(days=7)

It returns:

type object 'datetime.datetime' has no attribute 'timedelta'

Body:
The datetime in datetime.timedelta is about the module not the class, since you here import the class, you can also import timedelta directly:

from datetime import datetime, timedelta

day = datetime.now()
day1 = day + timedelta(days=1)
day2 = day + timedelta(days=2)
day3 = day + timedelta(days=3)
day4 = day + timedelta(days=4)
day5 = day + timedelta(days=5)
day6 = day + timedelta(days=6)
day7 = day + timedelta(days=7)


问:
Multiple Automapper Custom Resolvers Only One Is Called
I am using custom resolvers to fill up an Ids property in the destination class.  But, only one of the custom resolvers is getting called.  (I put a break point in each.)

So, in my Automapper (v 10.1.1) mappings, I have:

```<code>.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property1ToIdsResolver>())
.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property2ToIdsResolver>())
</code>```

I am doing this because I want to pull ids from Class1 and Class2 and put them all in the destination's Ids list.

They are setup as such:

```<code>public class Property1ToIdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)
</code>```

and

```<code>public class Property2ToIdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)
</code>```

In both, I check if Ids is null and if so, new up a List of Guids and fill it. If not, I append to it.

With the current .ForMember setup above, Property1ToIdsResolver's breakpoint does not get hit, but Property2ToIdsResolver does.

If I change it to:

```<code>.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property2ToIdsResolver>())
.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property1ToIdsResolver>())
</code>```

Property2ToIdsResolver's breakpoint does not get hit, but Property1ToIdsResolver does.

How can I get both resolvers to be called?

答:
As Lucian commented, it looks like you cannot have multiple resolvers to the same property.  So, to keep the logic separated, I kept the two resolvers, Property1ToIdsResolver and Property2ToIdsResolver.  I created a third encompassing resolver called IdsResolver which just calls the other two.

```<code>public class IdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    private IValueResolver<SrcClass, DestClass, List<Guid>> property1ToIdsResolver = new Property1ToIdsResolver();
    private IValueResolver<SrcClass, DestClass, List<Guid>> property2ToIdsResolver = new Property2ToIdsResolver();

    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)
    {
        var ids = property1ToIdsResolver.Resolve(src, dest, member, context);
        ids.AddRange(property2ToIdsResolver.Resolve(src, dest, member, context));

        return ids;
    }
}
</code>```

Other people may prefer to have a single resolver with private methods, up to you.  But, this is what I did.

Body:
I am using custom resolvers to fill up an Ids property in the destination class.  But, only one of the custom resolvers is getting called.  (I put a break point in each.)

So, in my Automapper (v 10.1.1) mappings, I have:

.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property1ToIdsResolver>())
.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property2ToIdsResolver>())

I am doing this because I want to pull ids from Class1 and Class2 and put them all in the destination's Ids list.

They are setup as such:

public class Property1ToIdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)

and

public class Property2ToIdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)

In both, I check if Ids is null and if so, new up a List of Guids and fill it. If not, I append to it.

With the current .ForMember setup above, Property1ToIdsResolver's breakpoint does not get hit, but Property2ToIdsResolver does.

If I change it to:

.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property2ToIdsResolver>())
.ForMember(dest => dest.Ids, opt => opt.MapFrom<Property1ToIdsResolver>())

Property2ToIdsResolver's breakpoint does not get hit, but Property1ToIdsResolver does.

How can I get both resolvers to be called?

Body:
As Lucian commented, it looks like you cannot have multiple resolvers to the same property.  So, to keep the logic separated, I kept the two resolvers, Property1ToIdsResolver and Property2ToIdsResolver.  I created a third encompassing resolver called IdsResolver which just calls the other two.

public class IdsResolver : IValueResolver<SrcClass, DestClass, List<Guid>>
{
    private IValueResolver<SrcClass, DestClass, List<Guid>> property1ToIdsResolver = new Property1ToIdsResolver();
    private IValueResolver<SrcClass, DestClass, List<Guid>> property2ToIdsResolver = new Property2ToIdsResolver();

    public List<Guid> Resolve(SrcClass src, DestClass dest, List<Guid> member, ResolutionContext context)
    {
        var ids = property1ToIdsResolver.Resolve(src, dest, member, context);
        ids.AddRange(property2ToIdsResolver.Resolve(src, dest, member, context));

        return ids;
    }
}

Other people may prefer to have a single resolver with private methods, up to you.  But, this is what I did.


问:
Visual Studio class/file templates: Is there a way to change their content automatically per project/solution?
I've updated my default templates in Visual Studio for classes, interfaces, code files, etc.  I removed the default namespaces and added a copyright header blurb.

Is there a way to use a variable or something in the template so I don't have to zip/unzip and re-run the vs installer to change the copyright header? (I'm a consultant, the code-owner isn't always me or my company).

答:
Yes, you can. The documentation for this sort of thing is part of the Visual Studio SDK. There are already many variables you can use.

If you find you want to get fancy, look into the Guidance Automation Toolkit. A template using GAT can accept user input as well as information from the project and environment, can unfold one or more templates, filling in placeholders with the data gathered, and then can execute various actions against the unfolded templates, the project, or whatever.

OwnerDisplayName: Zachary Yates

OwnerDisplayName: John Saunders


问:
Excel SQL Paste Formula down in column based on range of another column
I have a spreadsheet that will populate data in Column A beginning at A2 from a table.  Column A may be 10 rows or 150 Rows.  I have a calculation in column F.  I would like to Copy Down a formula in column F based on the number of Rows in Column A.

My code will copy a fixed range however I don't know how to make it dynamic based on the number of rows in column A.

```<code>Sheets("PriceAdjTemplate").Activate
Range("F2").Select
ActiveCell.Formula = "=(C2-E2)/C2"
Range("F2").Select
Selection.AutoFill Destination:=Range("F2:F350"), Type:=xlFillDefault
</code>```

I would need to replace F350 with F & Number of rows in Column A Beginning with A2
Selection.AutoFill Destination:=Range("F2:F350"), Type:=xlFillDefault

答:
using your coding approach, change the Selection.Autofill as follows:</p>
```<code>Sheets("PriceAdjTemplate").Activate
Range("F2").Formula = "=(C2-E2)/C2"
Range("F2").Select
Selection.AutoFill Destination:=Range("F2:F" & Range("A2").End(xlDown).Row), Type:=xlFillDefault
</code>```

Body:
I have a spreadsheet that will populate data in Column A beginning at A2 from a table.  Column A may be 10 rows or 150 Rows.  I have a calculation in column F.  I would like to Copy Down a formula in column F based on the number of Rows in Column A.

My code will copy a fixed range however I don't know how to make it dynamic based on the number of rows in column A.

Sheets("PriceAdjTemplate").Activate
Range("F2").Select
ActiveCell.Formula = "=(C2-E2)/C2"
Range("F2").Select
Selection.AutoFill Destination:=Range("F2:F350"), Type:=xlFillDefault

I would need to replace F350 with F & Number of rows in Column A Beginning with A2
Selection.AutoFill Destination:=Range("F2:F350"), Type:=xlFillDefault

Body:
using your coding approach, change the Selection.Autofill as follows:

Sheets("PriceAdjTemplate").Activate
Range("F2").Formula = "=(C2-E2)/C2"
Range("F2").Select
Selection.AutoFill Destination:=Range("F2:F" & Range("A2").End(xlDown).Row), Type:=xlFillDefault


问:
Dynamic sheet name change bases on a range
I would like to get the current month weeks number on this range C3:C8. Based on that values, to rename the following tabs names: Sheet3, Sheet4, Sheet5, Sheet6, Sheet7, Sheet8

Also, I would like this script to work only on sheet name: Sheet1

Is there a google script that can acomplish this request?
I would really appreciate it.
Thank you very much!

function sheetsNames(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues()
  for (var i=values.length-1;i>=0;i--){
    ss.getSheets()[i+3].setName(values[i][0])
  }
}```

UPDATE: I'm trying to attach the function renameSheetTabs() into a drawing but for some reason I'm getting the following error.

答:
Answer

You can try this script structure below:

Script

```<code>function renameSheetTabs(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues();
  var startTab = 2; //first tab will be sheet #2 or the tab after "Sheet1"
  for (var i=0; i<startTab;i++){
    if(values.length == i)return; //loop will stop once all tabs have been renamed
      Logger.log(ss.getSheets()[i+2].getName()+" To \""+values[i] +"\"\nRenaming Done!");
      ss.getSheets()[i+2].setName(values[i]);
    }catch{
      return;
    }
    startTab += 1;
  }
}
</code>```

Sample Demonstration

Test Sheet:

After running the script:

Execution logs for review

Body:
I would like to get the current month weeks number on this range C3:C8. Based on that values, to rename the following tabs names: Sheet3, Sheet4, Sheet5, Sheet6, Sheet7, Sheet8

Also, I would like this script to work only on sheet name: Sheet1

Is there a google script that can acomplish this request?
I would really appreciate it.
Thank you very much!

function sheetsNames(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues()
  for (var i=values.length-1;i>=0;i--){
    ss.getSheets()[i+3].setName(values[i][0])
  }
}

UPDATE: I'm trying to attach the function renameSheetTabs() into a drawing but for some reason I'm getting the following error.

Body:
Answer

You can try this script structure below:

Script

function renameSheetTabs(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues();
  var startTab = 2; //first tab will be sheet #2 or the tab after "Sheet1"
  for (var i=0; i<startTab;i++){
    if(values.length == i)return; //loop will stop once all tabs have been renamed
      Logger.log(ss.getSheets()[i+2].getName()+" To \""+values[i] +"\"\nRenaming Done!");
      ss.getSheets()[i+2].setName(values[i]);
    }catch{
      return;
    }
    startTab += 1;
  }
}

Sample Demonstration

Test Sheet:

After running the script:

Execution logs for review


问:
Update Canvas on State Change React
I'm trying to implement a canvas on in my React project, essentially I need to be able to style text (font color, style, size) on top of an image. I have created a simple form for the styling attributes and the text to be entered.

When the user changes values within the form, I want the canvas to update the text accordingly and reflect the new text/style changes. Currently, i'm using useEffect with a blank array to trigger the writeFunction(). fontFamily, fontSize, colorCode, textA are all states that get changed when the user makes changes to the form.

I have tried changing the dependency array of the useEffect() to thefontFamily, fontSize, colorCode, textA but that has not worked successfully.

```<code>useEffect(() => {
    // dynamically assign the width and height to canvas
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;

    // get context of the canvas
    ctx = canvasEle.getContext("2d");
  }, []);

  useEffect(() => {
    writeText({
      text: textA,
      x: 350,
      y: 100,
    });
  }, []);

const writeText = (info) => {
const { text, x, y } = info;
    var imageObj = new Image();
    imageObj.onload = function () {
      ctx.drawImage(imageObj, 10, 10);
      ctx.beginPath();
      ctx.font = fontSize + "px " + fontFamily;
      ctx.textAlign = textAlign;
      ctx.textBaseline = "top";
      ctx.fillStyle = colorCode;
      ctx.fillText(text, x, y);
      ctx.stroke();
    };
    imageObj.src = imageAddress; //imageAddress is a predetermined URL
    imageObj.width = "600px";
    imageObj.height = "550px";
  };
</code>```

Here's what my form looks like:

```<code><Form>
          <Form.Group className="mb-3" controlId="formBasicEmail">
            <Form.Label>Text 1</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter Text"
              onChange={(e) => setTextA(e.target.value)}
              value={textA}
            />
          </Form.Group>
          <Form.Group className="mb-3" controlId="formBasicEmail">
            <Form.Label>Font Size</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter Font Size"
              onChange={(e) => {setsize(e.target.value)
              console.log(e.target.value,'sizein114')}}
              value={size}
            />
          </Form.Group>
          <Form.Group className="mt-3" controlId="formBasicEmail">
            <Form.Label>Font Style</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter Font Style"
              onChange={(e) => setfamily(e.target.value)}
              value={family}
            />
          </Form.Group>
          <Form.Group className="mt-3" controlId="formBasicEmail">
            <Form.Label>Font Color</Form.Label>
            <Form.Control
              type="color"
              placeholder="Enter Font Color"
              onChange={(e) => setcolorCode(e.target.value)}
              defaultValue="#fffff"
            />
          </Form.Group>
</Form>
</code>```

Update: This is the error I get when I pass the dependency array [fontFamily, fontSize, colorCode, textA]
Dependency array error

Update: useState code

```<code>function App() {
  const canvas = useRef();
  let ctx = null;
  const [fontSize, setFontSize] = useState("28");
  const [fontFamily, setFontFamily] = useState("Calibri");
  const [colorCode, setcolorCode] = useState("red");
  const [textAlign, settextAlign] = useState("center");
  const [textA, setTextA] = useState("Title Here");
</code>```

答:
If you put state values in the useEffect subscription array (e.g. [textA, size, family]), the effect function should run each time those values change. Make sure you use the right variables (you mention fontFamily but in your Form it says family).

If this doesn't work, omit the subscription array as a test – the effect should now run on all updates. Make sure the onload fires, too. If that does not work please include the useState code so we get the whole picture.

Title: Update Canvas on State Change React

Body:
I'm trying to implement a canvas on in my React project, essentially I need to be able to style text (font color, style, size) on top of an image. I have created a simple form for the styling attributes and the text to be entered.

When the user changes values within the form, I want the canvas to update the text accordingly and reflect the new text/style changes. Currently, i'm using useEffect with a blank array to trigger the writeFunction(). fontFamily, fontSize, colorCode, textA are all states that get changed when the user makes changes to the form.

I have tried changing the dependency array of the useEffect() to thefontFamily, fontSize, colorCode, textA but that has not worked successfully.

useEffect(() => {
    // dynamically assign the width and height to canvas
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;

    // get context of the canvas
    ctx = canvasEle.getContext("2d");
  }, []);

  useEffect(() => {
    writeText({
      text: textA,
      x: 350,
      y: 100,
    });
  }, []);

const writeText = (info) => {
const { text, x, y } = info;
    var imageObj = new Image();
    imageObj.onload = function () {
      ctx.drawImage(imageObj, 10, 10);
      ctx.beginPath();
      ctx.font = fontSize + "px " + fontFamily;
      ctx.textAlign = textAlign;
      ctx.textBaseline = "top";
      ctx.fillStyle = colorCode;
      ctx.fillText(text, x, y);
      ctx.stroke();
    };
    imageObj.src = imageAddress; //imageAddress is a predetermined URL
    imageObj.width = "600px";
    imageObj.height = "550px";
  };

Here's what my form looks like:

<Form>
          <Form.Group className="mb-3" controlId="formBasicEmail">
            <Form.Label>Text 1</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter Text"
              onChange={(e) => setTextA(e.target.value)}
              value={textA}
            />
          </Form.Group>
          <Form.Group className="mb-3" controlId="formBasicEmail">
            <Form.Label>Font Size</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter Font Size"
              onChange={(e) => {setsize(e.target.value)
              console.log(e.target.value,'sizein114')}}
              value={size}
            />
          </Form.Group>
          <Form.Group className="mt-3" controlId="formBasicEmail">
            <Form.Label>Font Style</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter Font Style"
              onChange={(e) => setfamily(e.target.value)}
              value={family}
            />
          </Form.Group>
          <Form.Group className="mt-3" controlId="formBasicEmail">
            <Form.Label>Font Color</Form.Label>
            <Form.Control
              type="color"
              placeholder="Enter Font Color"
              onChange={(e) => setcolorCode(e.target.value)}
              defaultValue="#fffff"
            />
          </Form.Group>
</Form>

Update: This is the error I get when I pass the dependency array [fontFamily, fontSize, colorCode, textA]
Dependency array error

Update: useState code

function App() {
  const canvas = useRef();
  let ctx = null;
  const [fontSize, setFontSize] = useState("28");
  const [fontFamily, setFontFamily] = useState("Calibri");
  const [colorCode, setcolorCode] = useState("red");
  const [textAlign, settextAlign] = useState("center");
  const [textA, setTextA] = useState("Title Here");


问:
Create a sample data set with selected columns
I have a large data set(csv) with 10 columns, I want create a sample dataset with 5 selected columns from large set.

Is there a hdfs command for the same.

答:
There is no hdfs cli command for this.

You'll need an external tool such as Apache Hive, Pig, Spark, Flink, Beam, Drill, etc. to read this CSV, and select out the specific columns.

If your file is only a few GB large, you could even just download the file and use awk or cut to get specific columns; don't need HDFS at all.


问:
reducing the If else condtion code in javascript
I wrote a code to fetch the data present and store it in Array format but I thing I have wrote code multiple times can It be possible to minimize the code as its too long

let topicsValue = ["requiredType.*", "Entry.*", "token.*", "RestAPI.*"];

let Topic = [],
  rest = ["required", "unrequired"],
  final = ["createInput", "mustPossible", "finalOutput"];
topicsValue.map((data) => {
  let requiredType, entries, token, restAPI;
  if (data.split(".")[1].includes("*")) {
    if (data.split(".")[0].includes("requiredType")) {
      for (const value of final) {
        requiredType = data
          .split(".")[0]
          .replace("requiredType", "required_type")
          .concat(`.${value}`);
        Topic.push(requiredType);
      }
    }
    if (data.split(".")[0].includes("Entry")) {
      for (const value of final) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${value}`);
        Topic.push(entries);
      }
      for (const value of rest) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${value}`);
        Topic.push(entries);
      }
    }
    if (data.split(".")[0].includes("token")) {
      for (const value of final) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${value}`);
        Topic.push(token);
      }
      for (const value of rest) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${value}`);
        Topic.push(token);
      }
    }
    if (
      data.split(".")[0].includes("RestAPI") &&
      !data.split(".")[0].includes("RestAPIAction")
    ) {
      restAPI = data
        .split(".")[0]
        .replace("RestAPI", "restAPI")
        .concat(`.deploy`);
      Topic.push(restAPI);
    }
  } else {
    if (data.split(".")[0].includes("requiredType")) {
      if (!rest.includes(data.split(".")[1])) {
        requiredType = data
          .split(".")[0]
          .replace("requiredType", "required_type")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(requiredType);
      }
    }
    if (data.split(".")[0].includes("Entry")) {
      if (rest.includes(data.split(".")[1])) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${data.split(".")[1]}.demo`);
        Topic.push(entries);
      } else {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${data.split(".")[1]}.demo`);
        Topic.push(entries);
      }
    }
    if (data.split(".")[0].includes("token")) {
      if (rest.includes(data.split(".")[1])) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(token);
      } else {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(token);
      }
    }
    if (
      data.split(".")[0].includes("RestAPI") &&
      !data.split(".")[0].includes("RestAPIAction")
    ) {
      restAPI = data
        .split(".")[0]
        .replace("RestAPI", "restAPI")
        .concat(`.deploy`);
      Topic.push(restAPI);
    }
  }
});

console.log(Topic);```

Is there any possible way I can reduce the code without effecting the output

As the requirement of the code is like if the topicValue contain * or the other value so I wrote this long code and now I am trying to minimize the code so its look short and effective.

答:
I made refactoring only if(true) part of your code. You can implement the else part by yourself. I didn't run the code, spend any time for proper naming, etc. So it was quick refactoring to give you an idea. I think there is a mistake in else block because both if and else parts of tokens and Entry are doing the same thing.

let replace = {
  requiredType: 'required_type',
  Entry: 'entries',
  token: 'tokens',
  RestAPI: 'restAPI'
}

const run = () => {
  topicsValue.map((data) => task(data));
}

const task = (data) => {
  data.split(".")[1].includes("*") ? funcIf(data) : funcElse(data);
}

const funcIf = (data) => {
  for (const key in replace) {
      if (data.split(".")[0].includes(key)) commonTask(key, data);
  }
}

const commonTask = (key, data) => {
  if (key == 'RestAPI' && data.split(".")[0].includes("RestAPIAction")) return;

  final.forEach(value => Topic.push(makeOutput(key, value, data)));
}

const makeOutput = (key, value, data) => {
  return data.split(".")[0]
    .replace(key, replace[key])
    .concat(key == 'restAPI' ? '.deploy' : `.${value}`);
}
```

Body:
I wrote a code to fetch the data present and store it in Array format but I thing I have wrote code multiple times can It be possible to minimize the code as its too long

let topicsValue = ["requiredType.*", "Entry.*", "token.*", "RestAPI.*"];

let Topic = [],
  rest = ["required", "unrequired"],
  final = ["createInput", "mustPossible", "finalOutput"];
topicsValue.map((data) => {
  let requiredType, entries, token, restAPI;
  if (data.split(".")[1].includes("*")) {
    if (data.split(".")[0].includes("requiredType")) {
      for (const value of final) {
        requiredType = data
          .split(".")[0]
          .replace("requiredType", "required_type")
          .concat(`.${value}`);
        Topic.push(requiredType);
      }
    }
    if (data.split(".")[0].includes("Entry")) {
      for (const value of final) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${value}`);
        Topic.push(entries);
      }
      for (const value of rest) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${value}`);
        Topic.push(entries);
      }
    }
    if (data.split(".")[0].includes("token")) {
      for (const value of final) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${value}`);
        Topic.push(token);
      }
      for (const value of rest) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${value}`);
        Topic.push(token);
      }
    }
    if (
      data.split(".")[0].includes("RestAPI") &&
      !data.split(".")[0].includes("RestAPIAction")
    ) {
      restAPI = data
        .split(".")[0]
        .replace("RestAPI", "restAPI")
        .concat(`.deploy`);
      Topic.push(restAPI);
    }
  } else {
    if (data.split(".")[0].includes("requiredType")) {
      if (!rest.includes(data.split(".")[1])) {
        requiredType = data
          .split(".")[0]
          .replace("requiredType", "required_type")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(requiredType);
      }
    }
    if (data.split(".")[0].includes("Entry")) {
      if (rest.includes(data.split(".")[1])) {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${data.split(".")[1]}.demo`);
        Topic.push(entries);
      } else {
        entries = data
          .split(".")[0]
          .replace("Entry", "entries")
          .concat(`.${data.split(".")[1]}.demo`);
        Topic.push(entries);
      }
    }
    if (data.split(".")[0].includes("token")) {
      if (rest.includes(data.split(".")[1])) {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(token);
      } else {
        token = data
          .split(".")[0]
          .replace("token", "tokens")
          .concat(`.${data.split(".")[1]}`);
        Topic.push(token);
      }
    }
    if (
      data.split(".")[0].includes("RestAPI") &&
      !data.split(".")[0].includes("RestAPIAction")
    ) {
      restAPI = data
        .split(".")[0]
        .replace("RestAPI", "restAPI")
        .concat(`.deploy`);
      Topic.push(restAPI);
    }
  }
});

console.log(Topic);

Is there any possible way I can reduce the code without effecting the output

As the requirement of the code is like if the topicValue contain * or the other value so I wrote this long code and now I am trying to minimize the code so its look short and effective.


问:
Can github master branch append data from other branch?
I am looking for a way that we have a global file on master branch. Every time when another branch merge to master, this global file will not be written; instead it can append data from another branch into this global file on master.</p>

答:
There is no simple way, you have to implement it yourself. Merge, restore the file from master before the merge, append new content from another branch. Something like this:

```<code>git checkout master
git merge another_branch
git checkout HEAD^1 -- global_file # restore from before merge
git show another_branch:global_file >> global_file # append from another_branch

git add global_file
git commit -m "Append to global_file"
</code>```

Body:
There is no simple way, you have to implement it yourself. Merge, restore the file from master before the merge, append new content from another branch. Something like this:

git checkout master
git merge another_branch
git checkout HEAD^1 -- global_file # restore from before merge
git show another_branch:global_file >> global_file # append from another_branch

git add global_file
git commit -m "Append to global_file"


问:
nodejs-16 dependency issue with libuv
This is what I'm getting on my Amazon Linux 2 instance while trying to run yum update.

Do you suggest I use --skip-broken or wait until AWS rolls out a fix?

```<code>--> Processing Dependency: libuv >= 1:1.42.0 for package: 1:nodejs-16.13.2-8.el7.x86_64
--> Finished Dependency Resolution
Error: Package: 1:nodejs-16.13.2-8.el7.x86_64 (epel-testing)
           Requires: libuv >= 1:1.42.0
           Installed: 1:libuv-1.39.0-1.amzn2.x86_64 (@amzn2-core)
               libuv = 1:1.39.0-1.amzn2
           Available: 1:libuv-1.23.2-1.amzn2.0.2.i686 (amzn2-core)
               libuv = 1:1.23.2-1.amzn2.0.2
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest
</code>```

答:
Yeah, plus 1 to this issue. OP, the --skip-broken flag will only temporarily fix your currently running servers though. If you're baking any new AMIs or spinning up any new EC2s with Terraform, CDK, etc, that --skip-broken flag won't work as its not available as part of the aws cloud.init script. This will cause any new AMI or EC2 creations to timeout and fail.

One potential work around is to try compiling libuv directly from source as > 1.39 sadly isn't currently available from any linux distro.

Title: nodejs-16 dependency issue with libuv

Body:
This is what I'm getting on my Amazon Linux 2 instance while trying to run yum update.

Do you suggest I use --skip-broken or wait until AWS rolls out a fix?

--> Processing Dependency: libuv >= 1:1.42.0 for package: 1:nodejs-16.13.2-8.el7.x86_64
--> Finished Dependency Resolution
Error: Package: 1:nodejs-16.13.2-8.el7.x86_64 (epel-testing)
           Requires: libuv >= 1:1.42.0
           Installed: 1:libuv-1.39.0-1.amzn2.x86_64 (@amzn2-core)
               libuv = 1:1.39.0-1.amzn2
           Available: 1:libuv-1.23.2-1.amzn2.0.2.i686 (amzn2-core)
               libuv = 1:1.23.2-1.amzn2.0.2
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest