问:
Why SparseCategoricalCrossentropy is not working with this machine learning model?
I have a .csv database file which looks like this:

```<code>              Day   Hour  N1  N2  N3  N4  N5  ...  N14  N15  N16  N17  N18  N19  N20
0      1996-03-18  15:00   4   9  10  16  21  ...   48   62   66   68   73   76   78
1      1996-03-19  15:00   6  12  15  19  28  ...   63   64   67   69   71   75   77
2      1996-03-21  15:00   2   4   6   7  15  ...   52   54   69   72   73   75   77
3      1996-03-22  15:00   3   8  15  17  19  ...   49   60   61   64   67   68   75
4      1996-03-25  15:00   2  10  11  14  18  ...   55   60   61   66   67   75   79
...           ...    ...  ..  ..  ..  ..  ..  ...  ...  ...  ...  ...  ...  ...  ...
13596  2022-01-04  22:50  17  18  22  26  27  ...   64   65   71   72   73   76   80
13597  2022-01-05  15:00   1   5   8  14  15  ...   47   54   59   67   70   72   76
13598  2022-01-05  22:50   6   7  14  15  16  ...   54   55   59   61   70   71   80
13599  2022-01-06  15:00   9  10  11  17  28  ...   51   55   65   67   72   76   78
13600  2022-01-06  22:50   1   2   6   9  11  ...   51   52   54   67   68   73   75
</code>```

I have found this article:
https://machinelearningmastery.com/how-to-develop-convolutional-neural-network-models-for-time-series-forecasting/

But I am trying to develop a modified version of that 1D CNN model by using softmax function on the last layer and SparseCategoricalCrossentropy() as loss function and also by adding new functions to that code making it different.

This is my code so far and the model I am trying to build and use:

```<code># multivariate output 1d cnn example
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # or any {'0', '1', '2'}
import warnings

warnings.filterwarnings('ignore')
import pandas as pd
# multivariate output 1d cnn example
from numpy import array
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import *
from tensorflow.keras.losses import *
from tensorflow.keras.layers import *
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.callbacks import ModelCheckpoint

# Define the Required Callback Function
class printlearningrate(tf.keras.callbacks.Callback):
    def on_epoch_end (self, epoch, logs={}):
        optimizer = self.model.optimizer
        lr = K.eval(optimizer.lr)
        Epoch_count = epoch + 1
        print('\n', "Epoch:", Epoch_count, ', Learning Rate: {:.7f}'.format(lr))

printlr = printlearningrate()

# split a multivariate sequence into samples
def split_sequences (sequences, n_steps):
    X, y = list(), list()
    for i in range(len(sequences)):
        # find the end of this pattern
        end_ix = i + n_steps
        # check if we are beyond the dataset
        if end_ix > len(sequences) - 1:
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix, :]
        X.append(seq_x)
        y.append(seq_y)
    return array(X), array(y)

df = pd.read_csv('DrawsDB.csv')

print(df)
# df['Time'] = df[['Day', 'Hour']].agg(' '.join, axis=1)
df.insert(0, 'Time', df[['Day', 'Hour']].agg(' '.join, axis=1))
df.drop(columns=['Day', 'Hour'], inplace=True)
df.set_index('Time', inplace=True)
print(df)

numpy_array = df.to_numpy()

print(type(numpy_array))
print(numpy_array)

# choose a number of time steps
n_steps = 10
# convert into input/output
X, y = split_sequences(numpy_array, n_steps)
print(X.shape, y.shape)

# the dataset knows the number of features, e.g. 2
n_features = X.shape[2]
# Reduce learning rate when nothing happens to lower more the loss:
reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.9888888888888889,
                              patience=10, min_lr=0.0000001, verbose=1)

epochs = 10
# saving best model every epoch with ModelCheckpoint:
checkpoint_filepath = 'C:\\Path\\To\\Saved\\CheckPoint\\model\\'
model_checkpoint_callback = ModelCheckpoint(
    filepath=checkpoint_filepath,
    monitor='loss',
    save_best_only=True,
    save_weights_only=True,
    verbose=1)

# define model
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=2, activation=LeakyReLU(), input_shape=(n_steps, n_features)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation=LeakyReLU()))
model.add(Dense(n_features))
model.compile(optimizer=Nadam(lr=0.09), loss=SparseCategoricalCrossentropy(),
              metrics=['accuracy', mean_squared_error, mean_absolute_error, mean_absolute_percentage_error])

# fit model
model.fit(X, y, epochs=10, verbose=2, callbacks=[printlr, reduce_lr, model_checkpoint_callback])
</code>```

split_sequences function like its name says it is splitting the database by taking just N rows from it as input and trying to predict the all N+1 row from the database as the output.

However, I think there is a problem because I am getting this error every time I am trying to run the python script:

```<code>tensorflow.python.framework.errors_impl.InvalidArgumentError:  logits and labels must have the same first dimension, got logits shape [32,20] and labels shape [640]
     [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits
 (defined at C:\Users\UserName\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\backend.py:5114)
]] [Op:__inference_train_function_1228]
</code>```

Any idea on how to fix this problem, please?

Thank you in advance!

答:
Assuming the labels are integers, they have the wrong shape for SparseCategoricalCrossentropy. Check the docs.
Try converting your y to one-hot encoded labels:

```<code>y = tf.keras.utils.to_categorical(y, num_classes=20)
</code>```

and change your loss function to CategoricalCrossentropy:

```<code>model.compile(optimizer=Nadam(lr=0.09), loss=tf.keras.losses.CategoricalCrossentropy(),
              metrics=['accuracy', mean_squared_error, mean_absolute_error, mean_absolute_percentage_error])
</code>```

and it should work.

Body:
I have a .csv database file which looks like this:

              Day   Hour  N1  N2  N3  N4  N5  ...  N14  N15  N16  N17  N18  N19  N20
0      1996-03-18  15:00   4   9  10  16  21  ...   48   62   66   68   73   76   78
1      1996-03-19  15:00   6  12  15  19  28  ...   63   64   67   69   71   75   77
2      1996-03-21  15:00   2   4   6   7  15  ...   52   54   69   72   73   75   77
3      1996-03-22  15:00   3   8  15  17  19  ...   49   60   61   64   67   68   75
4      1996-03-25  15:00   2  10  11  14  18  ...   55   60   61   66   67   75   79
...           ...    ...  ..  ..  ..  ..  ..  ...  ...  ...  ...  ...  ...  ...  ...
13596  2022-01-04  22:50  17  18  22  26  27  ...   64   65   71   72   73   76   80
13597  2022-01-05  15:00   1   5   8  14  15  ...   47   54   59   67   70   72   76
13598  2022-01-05  22:50   6   7  14  15  16  ...   54   55   59   61   70   71   80
13599  2022-01-06  15:00   9  10  11  17  28  ...   51   55   65   67   72   76   78
13600  2022-01-06  22:50   1   2   6   9  11  ...   51   52   54   67   68   73   75

I have found this article:
https://machinelearningmastery.com/how-to-develop-convolutional-neural-network-models-for-time-series-forecasting/

But I am trying to develop a modified version of that 1D CNN model by using softmax function on the last layer and SparseCategoricalCrossentropy() as loss function and also by adding new functions to that code making it different.

This is my code so far and the model I am trying to build and use:

# multivariate output 1d cnn example
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # or any {'0', '1', '2'}
import warnings

warnings.filterwarnings('ignore')
import pandas as pd
# multivariate output 1d cnn example
from numpy import array
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import *
from tensorflow.keras.losses import *
from tensorflow.keras.layers import *
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.callbacks import ModelCheckpoint

# Define the Required Callback Function
class printlearningrate(tf.keras.callbacks.Callback):
    def on_epoch_end (self, epoch, logs={}):
        optimizer = self.model.optimizer
        lr = K.eval(optimizer.lr)
        Epoch_count = epoch + 1
        print('\n', "Epoch:", Epoch_count, ', Learning Rate: {:.7f}'.format(lr))

printlr = printlearningrate()

# split a multivariate sequence into samples
def split_sequences (sequences, n_steps):
    X, y = list(), list()
    for i in range(len(sequences)):
        # find the end of this pattern
        end_ix = i + n_steps
        # check if we are beyond the dataset
        if end_ix > len(sequences) - 1:
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix, :]
        X.append(seq_x)
        y.append(seq_y)
    return array(X), array(y)

df = pd.read_csv('DrawsDB.csv')

print(df)
# df['Time'] = df[['Day', 'Hour']].agg(' '.join, axis=1)
df.insert(0, 'Time', df[['Day', 'Hour']].agg(' '.join, axis=1))
df.drop(columns=['Day', 'Hour'], inplace=True)
df.set_index('Time', inplace=True)
print(df)

numpy_array = df.to_numpy()

print(type(numpy_array))
print(numpy_array)

# choose a number of time steps
n_steps = 10
# convert into input/output
X, y = split_sequences(numpy_array, n_steps)
print(X.shape, y.shape)

# the dataset knows the number of features, e.g. 2
n_features = X.shape[2]
# Reduce learning rate when nothing happens to lower more the loss:
reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.9888888888888889,
                              patience=10, min_lr=0.0000001, verbose=1)

epochs = 10
# saving best model every epoch with ModelCheckpoint:
checkpoint_filepath = 'C:\\Path\\To\\Saved\\CheckPoint\\model\\'
model_checkpoint_callback = ModelCheckpoint(
    filepath=checkpoint_filepath,
    monitor='loss',
    save_best_only=True,
    save_weights_only=True,
    verbose=1)

# define model
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=2, activation=LeakyReLU(), input_shape=(n_steps, n_features)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation=LeakyReLU()))
model.add(Dense(n_features))
model.compile(optimizer=Nadam(lr=0.09), loss=SparseCategoricalCrossentropy(),
              metrics=['accuracy', mean_squared_error, mean_absolute_error, mean_absolute_percentage_error])

# fit model
model.fit(X, y, epochs=10, verbose=2, callbacks=[printlr, reduce_lr, model_checkpoint_callback])

split_sequences function like its name says it is splitting the database by taking just N rows from it as input and trying to predict the all N+1 row from the database as the output.

However, I think there is a problem because I am getting this error every time I am trying to run the python script:

tensorflow.python.framework.errors_impl.InvalidArgumentError:  logits and labels must have the same first dimension, got logits shape [32,20] and labels shape [640]
     [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits
 (defined at C:\Users\UserName\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\backend.py:5114)
]] [Op:__inference_train_function_1228]

Any idea on how to fix this problem, please?

Thank you in advance!

Body:
Assuming the labels are integers, they have the wrong shape for SparseCategoricalCrossentropy. Check the docs.
Try converting your y to one-hot encoded labels:

y = tf.keras.utils.to_categorical(y, num_classes=20)

and change your loss function to CategoricalCrossentropy:

model.compile(optimizer=Nadam(lr=0.09), loss=tf.keras.losses.CategoricalCrossentropy(),
              metrics=['accuracy', mean_squared_error, mean_absolute_error, mean_absolute_percentage_error])

and it should work.


来源: stackexchange

问:
Different results between clang/gcc and MSVC for templated constructor in base class
I stumbled over the following piece of code. The "DerivedFoo" case produces different results on MSVC than on clang or gcc. Namely, clang 13 and gcc 11.2 call the copy constructor of Foo while MSVC v19.29 calls the templated constructor. I am using C++17.

Considering the non-derived case ("Foo") where all compilers agree to call the templated constructor, I think that this is a bug in clang and gcc and that MSVC is correct? Or am I interpreting things wrong and clang/gcc are correct? Can anyone shed some light on what might be going on?

Code (https://godbolt.org/z/bbjasrraj):

```<code>#include <iostream>
using namespace std;

struct Foo {
  Foo() {
    cout << "\tFoo default constructor\n";
  }

  Foo(Foo const &) { cout << "\tFoo COPY constructor\n";
  }

  Foo(Foo &&) {
    cout << "\tFoo move constructor\n";
  }

  template <class U>
  Foo(U &&) {
    cout << "\tFoo TEMPLATED constructor\n";
  }
};

struct DerivedFoo : Foo {
   using Foo::Foo;
};

int main() {
  cout << "Foo:\n";
  Foo f1;
  Foo f2(f1);

  cout << "\nConst Foo:\n";
  Foo const cf1;
  Foo cf2(cf1);

  cout << "\nDerivedFoo:\n";
  DerivedFoo d1;
  DerivedFoo d2(d1);

  cout << "\nConst DerivedFoo:\n";
  DerivedFoo const cd1;
  DerivedFoo cd2(cd1);
}
</code>```

Result for clang and gcc:

```<code>Foo:
    Foo default constructor
    Foo TEMPLATED constructor

Const Foo:
    Foo default constructor
    Foo COPY constructor

DerivedFoo:
    Foo default constructor
    Foo COPY constructor  <<<<< This is different

Const DerivedFoo:
    Foo default constructor
    Foo COPY constructor
</code>```

Result for MSVC:

```<code>Foo:
        Foo default constructor
        Foo TEMPLATED constructor

Const Foo:
        Foo default constructor
        Foo COPY constructor

DerivedFoo:
        Foo default constructor
        Foo TEMPLATED constructor  <<<<< This is different

Const DerivedFoo:
        Foo default constructor
        Foo COPY constructor
</code>```

答:
It is correct that the constructor template is generally a better match for the constructor call with argument of type DerivedFoo& or Foo& than the copy constructors are, since it doesn't require a const conversion.

However, [over.match.funcs.general]/8 essentially (almost) says, in more general wording, that an inherited constructor that would have the form of a move or copy constructor is excluded from overload resolution, even if it is instantiated from a constructor template. Therefore the template constructor will not be considered.

Therefore the implicit copy constructor of DerivedFoo will be chosen by overload resolution for

```<code>DerivedFoo d2(d1);
</code>```

and this will call Foo(Foo const &); to construct the base class subobject.

This wording is a consequence of CWG 2356, which was resolved after C++17, but I think it is supposed to be a defect report against older versions as well. (I don't really know though.)

So GCC and Clang are correct here. Also note that MSVC behaves according to the defect report as well since version 19.30 if the conformance mode (/permissive-) is used.

ContentLicense: CC BY-SA 4.0

Body:
I stumbled over the following piece of code. The "DerivedFoo" case produces different results on MSVC than on clang or gcc. Namely, clang 13 and gcc 11.2 call the copy constructor of Foo while MSVC v19.29 calls the templated constructor. I am using C++17.

Considering the non-derived case ("Foo") where all compilers agree to call the templated constructor, I think that this is a bug in clang and gcc and that MSVC is correct? Or am I interpreting things wrong and clang/gcc are correct? Can anyone shed some light on what might be going on?

Code (https://godbolt.org/z/bbjasrraj):

#include <iostream>
using namespace std;

struct Foo {
  Foo() {
    cout << "\tFoo default constructor\n";
  }

  Foo(Foo const &) { cout << "\tFoo COPY constructor\n";
  }

  Foo(Foo &&) {
    cout << "\tFoo move constructor\n";
  }

  template <class U>
  Foo(U &&) {
    cout << "\tFoo TEMPLATED constructor\n";
  }
};

struct DerivedFoo : Foo {
   using Foo::Foo;
};

int main() {
  cout << "Foo:\n";
  Foo f1;
  Foo f2(f1);

  cout << "\nConst Foo:\n";
  Foo const cf1;
  Foo cf2(cf1);

  cout << "\nDerivedFoo:\n";
  DerivedFoo d1;
  DerivedFoo d2(d1);

  cout << "\nConst DerivedFoo:\n";
  DerivedFoo const cd1;
  DerivedFoo cd2(cd1);
}

Result for clang and gcc:

Foo:
    Foo default constructor
    Foo TEMPLATED constructor

Const Foo:
    Foo default constructor
    Foo COPY constructor

DerivedFoo:
    Foo default constructor
    Foo COPY constructor  <<<<< This is different

Const DerivedFoo:
    Foo default constructor
    Foo COPY constructor

Result for MSVC:

Foo:
        Foo default constructor
        Foo TEMPLATED constructor

Const Foo:
        Foo default constructor
        Foo COPY constructor

DerivedFoo:
        Foo default constructor
        Foo TEMPLATED constructor  <<<<< This is different

Const DerivedFoo:
        Foo default constructor
        Foo COPY constructor

Body:
It is correct that the constructor template is generally a better match for the constructor call with argument of type DerivedFoo& or Foo& than the copy constructors are, since it doesn't require a const conversion.

However, [over.match.funcs.general]/8 essentially (almost) says, in more general wording, that an inherited constructor that would have the form of a move or copy constructor is excluded from overload resolution, even if it is instantiated from a constructor template. Therefore the template constructor will not be considered.

Therefore the implicit copy constructor of DerivedFoo will be chosen by overload resolution for

DerivedFoo d2(d1);

and this will call Foo(Foo const &); to construct the base class subobject.

This wording is a consequence of CWG 2356, which was resolved after C++17, but I think it is supposed to be a defect report against older versions as well. (I don't really know though.)

So GCC and Clang are correct here. Also note that MSVC behaves according to the defect report as well since version 19.30 if the conformance mode (/permissive-) is used.


问:
Code using RISC-V a program that finds the smallest value in the sequence and swaps it with the first value
The question is :  Given a sequence of non-zero integers followed by 0, find the smallest
integer in the sequence then swap it with the integer in the beginning of the sequence. Use the
DD assembler command to store in the beginning of the memory the initial test sequence of
121, 33, -5, 242, -45, -12, 0. Save your solution as a file named bex2b.asm for
possible future use

Problem: I understand how to find the smallest value but I am stuck on how to swap the value with the first value of the sequence.

```<code>src:     DD -1, 5, -3, 7, 0

         add x6, x0, x0
         ld x7, src(x6)
         addi x5, x7, 0

        beq x5, x0, end

loop:   blt x7, x5, skip
        addi x7, x5, 0

skip:   addi x6, x6, 8
        ld x5, src(x6)
        bne x5, x0, loop

end:    addi x5, x7, 0
        ebreak x0, x0, 0
</code>```

some help on this would be appreciated

答:
You will have to write to memory.  The instruction set does not offer a single "swap the values of two memory locations" instruction, and whenever you cannot do something in one, you compose a sequence to do it in more.

Capture both values from memory into CPU registers, then write the first value into the location where you got the second one, and vice versa: write the second value into the location where you got the first one.

You'll need to manipulate both the values and their storage locations to accomplish that, so you'll have to know or remember what the first value is, as well as where the first value is located, and know or remember what the smallest value is, as well as where the smallest value is located.

There is no need to think in assembly for this algorithm.  It can be worked out in C with pointers or in C with indexes, and in other languages with indexes.  (Pointers would be natural to use for this.)  Working this out in C and then translating to assembly would be easier than thinking in assembly when you don't know the language yet.

Body:
The question is :  Given a sequence of non-zero integers followed by 0, find the smallest
integer in the sequence then swap it with the integer in the beginning of the sequence. Use the
DD assembler command to store in the beginning of the memory the initial test sequence of
121, 33, -5, 242, -45, -12, 0. Save your solution as a file named bex2b.asm for
possible future use

Problem: I understand how to find the smallest value but I am stuck on how to swap the value with the first value of the sequence.

src:     DD -1, 5, -3, 7, 0

         add x6, x0, x0
         ld x7, src(x6)
         addi x5, x7, 0

        beq x5, x0, end

loop:   blt x7, x5, skip
        addi x7, x5, 0

skip:   addi x6, x6, 8
        ld x5, src(x6)
        bne x5, x0, loop

end:    addi x5, x7, 0
        ebreak x0, x0, 0

some help on this would be appreciated


问:
PHP binding method to another class
Can i bind method of class Foo to class Bar? And why the code below throws a warning "Cannot bind method Foo::say() to object of class Bar"? With function instead of method code works fine.

P.S. I know about extending)  it is not practical question, just want to know is it real to bind non-static method to another class

```<code>class Foo {

    public $text = 'Hello World!';

    public function say() {
        echo $this->text;
    }

}

class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable(array(new Foo, 'say'));
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();
</code>```

Code below works fine

```<code> function say(){
    echo $this->text;
 }
 class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable('say');
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();
</code>```

答:
It is not supported by PHP. However in PHP 7.0 it was kinda possible. Consider this example:

class Foo {
    private $baz = 1;

    public function baz() {
        var_dump('Foo');
        var_dump($this->baz);
    }
}

class Bar {
    public $baz = 2;

    public function baz() {
        var_dump('Bar');
        var_dump($this->baz);
    }
}

$fooClass = new ReflectionClass('Foo');
$method = $fooClass->getMethod('baz');

$foo = new Foo;
$bar = new Bar;

$closure = $method->getClosure($foo);

$closure2 = $closure->bindTo($bar);

$closure2();
```
<p>The output of foregoing code is:</p>
```string(3) "Foo"
int(2)
```
<p>And this means method <code>Foo::baz</code> was called on object <code>$bar</code> and has accessed its <code>$baz</code> property rather than <code>Foo::$baz</code>.</p>
<p>Also, please note that <code>Bar::$baz</code> is public property. If it was private, php would throw Fatal error cannot access private property. This could've be fixed up by changing the scope of closure <code>$closure->bindTo($bar, $bar);</code>, however doing this was already prohibited in php7.0 and would lead to a following warning: <code>Cannot rebind scope of closure created by ReflectionFunctionAbstract::getClosure()</code>.</p>
<p><strong>There's workaround however</strong>, which will work for latest versions of php. Laravel created a splendid package called <code>laravel/serializable-closure</code>. What it does is simple - it reads source code of closure in order to serialize it and be able to unserialize it later with all necessary context.</p>
<p>So basically the functionality of unserialized closure remains the same, however it is different from PHP's perspective. PHP doesn't know it was created from class method and therefore allows to bind any <code>$this</code>.</p>
<p>Final variant will look like this:</p>
<pre class="lang-php prettyprint-override"><code>$callback = [$foo, 'baz'];

$closure = unserialize(
    serialize(new SerializableClosure(Closure::fromCallable($callback)))
)->getClosure();

$closure->call($bar);
</code>```

Please, note that serialization and unserialization are expensive operations, so do not use provided solution unless there's no other solution.

ContentLicense: CC BY-SA 3.0

Title: PHP binding method to another class

Body:
Can i bind method of class Foo to class Bar? And why the code below throws a warning "Cannot bind method Foo::say() to object of class Bar"? With function instead of method code works fine.

P.S. I know about extending)  it is not practical question, just want to know is it real to bind non-static method to another class

class Foo {

    public $text = 'Hello World!';

    public function say() {
        echo $this->text;
    }

}

class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable(array(new Foo, 'say'));
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();

Code below works fine

 function say(){
    echo $this->text;
 }
 class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable('say');
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();

Body:
It is not supported by PHP. However in PHP 7.0 it was kinda possible. Consider this example:

class Foo {
    private $baz = 1;

    public function baz() {
        var_dump('Foo');
        var_dump($this->baz);
    }
}

class Bar {
    public $baz = 2;

    public function baz() {
        var_dump('Bar');
        var_dump($this->baz);
    }
}

$fooClass = new ReflectionClass('Foo');
$method = $fooClass->getMethod('baz');

$foo = new Foo;
$bar = new Bar;

$closure = $method->getClosure($foo);

$closure2 = $closure->bindTo($bar);

$closure2();

The output of foregoing code is:

string(3) "Foo"
int(2)

And this means method Foo::baz was called on object $bar and has accessed its $baz property rather than Foo::$baz.

Also, please note that Bar::$baz is public property. If it was private, php would throw Fatal error cannot access private property. This could've be fixed up by changing the scope of closure $closure->bindTo($bar, $bar);, however doing this was already prohibited in php7.0 and would lead to a following warning: Cannot rebind scope of closure created by ReflectionFunctionAbstract::getClosure().

There's workaround however, which will work for latest versions of php. Laravel created a splendid package called laravel/serializable-closure. What it does is simple - it reads source code of closure in order to serialize it and be able to unserialize it later with all necessary context.

So basically the functionality of unserialized closure remains the same, however it is different from PHP's perspective. PHP doesn't know it was created from class method and therefore allows to bind any $this.

Final variant will look like this:

$callback = [$foo, 'baz'];

$closure = unserialize(
    serialize(new SerializableClosure(Closure::fromCallable($callback)))
)->getClosure();

$closure->call($bar);

Please, note that serialization and unserialization are expensive operations, so do not use provided solution unless there's no other solution.


问:
String representation of chess board
I need to print a chess board. In this example I create a board with for in for and did a for each where take chess pieces and put in it's places:

```<code>StringBuilder stringBuilder = new StringBuilder();
        for (int number = 8; number >= 1; number--) {
            for (char letter = 'H'; letter >= 'A'; letter--) {

                for (ChessPiece chessPiece : pieces) {
                    if (chessPiece.getCell().letter == letter && chessPiece.getCell().number == number) {
                        stringBuilder.append(chessPiece.toChar());
                    }
                }
                }
                stringBuilder.append("\n");
            }
            String string = String.valueOf(stringBuilder);

            return string;
        }
</code>```

The result is:

```<code>RNBQKBNR
PPPPPPPP

pppppppp
rnbqkbnr
</code>```

but need to be:

```<code>RNBQKBNR
PPPPPPPP
........
........
........
........
pppppppp
rnbqkbnr
</code>```

I do not understand how to put '.' char in my StringBuilder. Please help me.

答:
You don't seem to be appending "." in any point in your code.
While not the smartest thing you can do, one possible way would be to

```<code>for (int number = 8; number >= 1; number--) {
  if(number > 2 && number < 7){ //if between 3 and 6
    for (char letter = 'H'; letter >= 'A'; letter--) {
      stringBuilder.append(".");
    }
  }
}
</code>```

Note that this code only works for the original disposition of pieces in the beginning of the game. If you want to make it dynamic, you will have to check (for every location in the board) if there is a piece in that position, and the code would be

```<code>if( there is piece){
   stringBuilder.append(chessPiece.toChar());
}
else
   stringBuilder.append(".");
</code>```

Title: String representation of chess board

Body:
I need to print a chess board. In this example I create a board with for in for and did a for each where take chess pieces and put in it's places:

StringBuilder stringBuilder = new StringBuilder();
        for (int number = 8; number >= 1; number--) {
            for (char letter = 'H'; letter >= 'A'; letter--) {

                for (ChessPiece chessPiece : pieces) {
                    if (chessPiece.getCell().letter == letter && chessPiece.getCell().number == number) {
                        stringBuilder.append(chessPiece.toChar());
                    }
                }
                }
                stringBuilder.append("\n");
            }
            String string = String.valueOf(stringBuilder);

            return string;
        }

The result is:

RNBQKBNR
PPPPPPPP

pppppppp
rnbqkbnr

but need to be:

RNBQKBNR
PPPPPPPP
........
........
........
........
pppppppp
rnbqkbnr

I do not understand how to put '.' char in my StringBuilder. Please help me.

Body:
You don't seem to be appending "." in any point in your code.
While not the smartest thing you can do, one possible way would be to

for (int number = 8; number >= 1; number--) {
  if(number > 2 && number < 7){ //if between 3 and 6
    for (char letter = 'H'; letter >= 'A'; letter--) {
      stringBuilder.append(".");
    }
  }
}

Note that this code only works for the original disposition of pieces in the beginning of the game. If you want to make it dynamic, you will have to check (for every location in the board) if there is a piece in that position, and the code would be

if( there is piece){
   stringBuilder.append(chessPiece.toChar());
}
else
   stringBuilder.append(".");


问:
How do I make an html link look like a button?
I'm using ASP.NET, some of my buttons just do redirects.  I'd rather they were ordinary links, but I don't want my users to notice much difference in the appearance.  I considered images wrapped by anchors, i.e.  tags, but I don't want to have to fire up an image editor every time I change the text on a button.</p>

答:
Apply this class to it

.button {
  font: bold 11px Arial;
  text-decoration: none;
  background-color: #EEEEEE;
  color: #333333;
  padding: 2px 6px 2px 6px;
  border-top: 1px solid #CCCCCC;
  border-right: 1px solid #333333;
  border-bottom: 1px solid #333333;
  border-left: 1px solid #CCCCCC;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Example</code>```

OwnerDisplayName: MatthewMartin

ContentLicense: CC BY-SA 2.5

Body:
Apply this class to it

.button {
  font: bold 11px Arial;
  text-decoration: none;
  background-color: #EEEEEE;
  color: #333333;
  padding: 2px 6px 2px 6px;
  border-top: 1px solid #CCCCCC;
  border-right: 1px solid #333333;
  border-bottom: 1px solid #333333;
  border-left: 1px solid #CCCCCC;
}

<a href="#" class="button">Example</a>

OwnerDisplayName: TStamper


问:
Hidden bugs with given-when and for-match. Is Perl truly cross-platform?
I have been trying to make a relatively large Perl program that has been working perfectly fine on CentOS for many years to work on Ubuntu and this has become a huge nightmare. CentOS uses Perl built for x86_64-linux-thread-multi and Ubuntu uses the x86_64-linux-gnu-thread-multi build. AFAIK, the interpreter behavior should be the same in both environments when the program invokes the same previous version v5.10.1. However I have been getting very different behavior, including warnings about given/when and smartmatch being experimental and, most importantly, a set of nasty bugs that are hard to trace and resolve. A particular problem occurs when a given statement shown below (form 1) matches and calls a function. Then suddenly the value of the switch variable (called $ailtype) that is never otherwise touched gets erased from memory! If I simply call that function nothing obnoxious happens. So, I replaced the given/when usage with a for statement (form 2) and my question is why does the the problem still occur?! The only form that truly avoids the problem is a simple chain of if/elsifs (form 3) and this clearly shows that the problem is with forms 1 and 2 and the perl interpreter being inconsistent and bug-ridden: it does not even produce an "experimental" warning for form 2.

Here is form 1 (original):

```<code>print "ailtype is $ailtype \n"; # prints "ailtype is 8"

given ($ailtype) {
    when (4) { &parse_mascot}
    when (5) { &parse_sequest}
    when (8) { &parse_spectrast($ms2_results, $rttemp)}
    when (9) { &parse_cnstab($ms2_results, $rttemp)}
    default { STDOUT->autoflush(1) and die "ailtype=|$ailtype| unknown.\n"; }
}

print "ailtype is $ailtype \n"; # prints "ailtype is ". $ailtype got destroyed!

</code>```

The prints are for debug. I can put them inside the when block and confirm that $ailtype gets destroyed after the &parse_spectrast function call. However, the function does not read or touch $ailtype at all! (Interestingly, if I go inside the function and print the value of $ailtype to find exactly where it gets messed up, I see that it occurs within a while loop parsing the lines of an input file. Printing $ailtype somehow returns the lines of that file!)

The program consists of several large perl files with many given/when statements and re-writing all of them by hand would be tedious. I have to make sure that the alternative form works. So I tried form 2 (suggested here):

```<code>print "ailtype is $ailtype \n"; # prints "ailtype is 8"

for ($ailtype) {
    /4/ and do { &parse_mascot; last};
    /5/ and do { &parse_sequest; last};
    /8/ and do { &parse_spectrast($ms2_results, $rttemp); last};
    /9/ and do { &parse_cnstab($ms2_results, $rttemp); last};
    do { STDOUT->autoflush(1) and die "ailtype=|$ailtype| unknown.\n"; }
}

print "ailtype is $ailtype \n"; # prints "ailtype is ". $ailtype still gets destroyed!
</code>```

The problem still occurs in this form, and I really don't understand why?! The interpreter no longer warns about experimental given/when here (they're still used elsewhere in the code though. I ensured they didn't occur before the problematic block and that didn't help).

Surprising or not, a chain of if/elsifs (form 3) works fine:

```<code>print "ailtype is $ailtype \n"; # prints "ailtype is 8"

if    (4 == $ailtype) {
    &parse_mascot;
}
elsif (5 == $ailtype) {
    &parse_sequest;
}
elsif (8 == $ailtype) {
    &parse_spectrast($ms2_results, $rttemp);
}
elsif (9 == $ailtype) {
    &parse_cnstab($ms2_results, $rttemp);
}
else {
    STDOUT->autoflush(1) and die "ailtype=|$ailtype| unknown.\n";
}

print "ailtype is $ailtype \n"; # prints "ailtype is 8". It was never changed.

</code>```

But I thought the powers of Perl were there to save us from having to code all of this. I would be willing to do so if I was sure I had an otherwise reliable interpreter. Changing the version to v5.16.3 (the latest installed on both platforms) only produces new errors regarding declarations, "bareword STDOUT not allowed", etc. Having fought with this bug alone for 10 hours, I am seriously in doubt.

答:
for aliases $_ for each value in the loop. If the called function changes the value of $_, the original variable will be changed, as well. The diamond operator used in a while loop changes the global $_ and it becomes undef on the eof.

#!/usr/bin/perl
use warnings;
use strict;

sub f {
    while (<DATA>) {
        warn "read:\t$_";
    }
}

my $x = 8;

print "Before:<<$x>>\n";

for ($x) {
    &f();
}

print "After:<<$x>>\n";

__DATA__
A
B
```
<p>Solution:
Insert the following line before the <code>while (<>) {</code>:</p>
<pre class="lang-perl prettyprint-override"><code>    local $_;
</code>```

This will restore the original value of $_ when leaving the scope of the local statement.

Body:
I have been trying to make a relatively large Perl program that has been working perfectly fine on CentOS for many years to work on Ubuntu and this has become a huge nightmare. CentOS uses Perl built for x86_64-linux-thread-multi and Ubuntu uses the x86_64-linux-gnu-thread-multi build. AFAIK, the interpreter behavior should be the same in both environments when the program invokes the same previous version v5.10.1. However I have been getting very different behavior, including warnings about given/when and smartmatch being experimental and, most importantly, a set of nasty bugs that are hard to trace and resolve. A particular problem occurs when a given statement shown below (form 1) matches and calls a function. Then suddenly the value of the switch variable (called $ailtype) that is never otherwise touched gets erased from memory! If I simply call that function nothing obnoxious happens. So, I replaced the given/when usage with a for statement (form 2) and my question is why does the the problem still occur?! The only form that truly avoids the problem is a simple chain of if/elsifs (form 3) and this clearly shows that the problem is with forms 1 and 2 and the perl interpreter being inconsistent and bug-ridden: it does not even produce an "experimental" warning for form 2.

Here is form 1 (original):

print "ailtype is $ailtype \n"; # prints "ailtype is 8"

given ($ailtype) {
    when (4) { &parse_mascot}
    when (5) { &parse_sequest}
    when (8) { &parse_spectrast($ms2_results, $rttemp)}
    when (9) { &parse_cnstab($ms2_results, $rttemp)}
    default { STDOUT->autoflush(1) and die "ailtype=|$ailtype| unknown.\n"; }
}

print "ailtype is $ailtype \n"; # prints "ailtype is ". $ailtype got destroyed!

The prints are for debug. I can put them inside the when block and confirm that $ailtype gets destroyed after the &parse_spectrast function call. However, the function does not read or touch $ailtype at all! (Interestingly, if I go inside the function and print the value of $ailtype to find exactly where it gets messed up, I see that it occurs within a while loop parsing the lines of an input file. Printing $ailtype somehow returns the lines of that file!)

The program consists of several large perl files with many given/when statements and re-writing all of them by hand would be tedious. I have to make sure that the alternative form works. So I tried form 2 (suggested here):

print "ailtype is $ailtype \n"; # prints "ailtype is 8"

for ($ailtype) {
    /4/ and do { &parse_mascot; last};
    /5/ and do { &parse_sequest; last};
    /8/ and do { &parse_spectrast($ms2_results, $rttemp); last};
    /9/ and do { &parse_cnstab($ms2_results, $rttemp); last};
    do { STDOUT->autoflush(1) and die "ailtype=|$ailtype| unknown.\n"; }
}

print "ailtype is $ailtype \n"; # prints "ailtype is ". $ailtype still gets destroyed!

The problem still occurs in this form, and I really don't understand why?! The interpreter no longer warns about experimental given/when here (they're still used elsewhere in the code though. I ensured they didn't occur before the problematic block and that didn't help).

Surprising or not, a chain of if/elsifs (form 3) works fine:

print "ailtype is $ailtype \n"; # prints "ailtype is 8"

if    (4 == $ailtype) {
    &parse_mascot;
}
elsif (5 == $ailtype) {
    &parse_sequest;
}
elsif (8 == $ailtype) {
    &parse_spectrast($ms2_results, $rttemp);
}
elsif (9 == $ailtype) {
    &parse_cnstab($ms2_results, $rttemp);
}
else {
    STDOUT->autoflush(1) and die "ailtype=|$ailtype| unknown.\n";
}

print "ailtype is $ailtype \n"; # prints "ailtype is 8". It was never changed.

But I thought the powers of Perl were there to save us from having to code all of this. I would be willing to do so if I was sure I had an otherwise reliable interpreter. Changing the version to v5.16.3 (the latest installed on both platforms) only produces new errors regarding declarations, "bareword STDOUT not allowed", etc. Having fought with this bug alone for 10 hours, I am seriously in doubt.

Body:
for aliases $_ for each value in the loop. If the called function changes the value of $_, the original variable will be changed, as well. The diamond operator used in a while loop changes the global $_ and it becomes undef on the eof.

#!/usr/bin/perl
use warnings;
use strict;

sub f {
    while (<DATA>) {
        warn "read:\t$_";
    }
}

my $x = 8;

print "Before:<<$x>>\n";

for ($x) {
    &f();
}

print "After:<<$x>>\n";

__DATA__
A
B

Solution:
Insert the following line before the while (<>) {:

    local $_;

This will restore the original value of $_ when leaving the scope of the local statement.


问:
Splitting class functions across multiple cells in Jupyter?
Given the following code:

```<code>class DTC:
    def __init__(self):
        self.__root = None

    def unique(self,Y):
        d = {}
        for i in Y:
            if i not in d:
                d[i]=1
            else:
                d[i]+=1
        return d

    def ent(self,Y):
        freq = self.__count_unique(Y)
        ent_ = 0
        total = len(Y)
        for i in freq:
            p = freq[i]/total
            entropy_ += (-p)*math.log2(p)
        return ent_
</code>```

The above will run if it is place in a single cell in Jupyter Notebook. However, how can I make the class code work if I want it to be split into multiple cells like this:

Cell 1

```<code>class DTC:
    def __init__(self):
        self.__root = None
</code>```

Cell 2

```<code>    def unique(self,Y):
        d = {}
        for i in Y:
            if i not in d:
                d[i]=1
            else:
                d[i]+=1
        return d
</code>```

Cell 3

```<code>    def ent(self,Y):
        freq = self.__unique(Y)
        ent_ = 0
        total = len(Y)
        for i in freq:
            p = freq[i]/total
            ent_ += (-p)*math.log2(p)
        return ent_
</code>```

答:
A python-only solution:

class OutsourceMethods:
    @classmethod
    def method(cls, f):
        setattr(cls, f.__name__, f)

```
<p>Used as:</p>
<pre class="lang-py prettyprint-override"><code>class A(SuperA, OutsourceMethods):
    def __init__(self):
        self.x = 10

@A.method
def bar(self, y):
    print(self.x, y)

a = A()

a.bar(20)

> 10 20

b = A()
b.x = 3
b.bar()

> 3 20
</code>```

It's not 100% equivalent, but I haven't noticed a different so far.

Body:
Given the following code:

class DTC:
    def __init__(self):
        self.__root = None

    def unique(self,Y):
        d = {}
        for i in Y:
            if i not in d:
                d[i]=1
            else:
                d[i]+=1
        return d

    def ent(self,Y):
        freq = self.__count_unique(Y)
        ent_ = 0
        total = len(Y)
        for i in freq:
            p = freq[i]/total
            entropy_ += (-p)*math.log2(p)
        return ent_

The above will run if it is place in a single cell in Jupyter Notebook. However, how can I make the class code work if I want it to be split into multiple cells like this:

Cell 1

class DTC:
    def __init__(self):
        self.__root = None

Cell 2

    def unique(self,Y):
        d = {}
        for i in Y:
            if i not in d:
                d[i]=1
            else:
                d[i]+=1
        return d

Cell 3

    def ent(self,Y):
        freq = self.__unique(Y)
        ent_ = 0
        total = len(Y)
        for i in freq:
            p = freq[i]/total
            ent_ += (-p)*math.log2(p)
        return ent_

Body:
A python-only solution:

class OutsourceMethods:
    @classmethod
    def method(cls, f):
        setattr(cls, f.__name__, f)

Used as:

class A(SuperA, OutsourceMethods):
    def __init__(self):
        self.x = 10

@A.method
def bar(self, y):
    print(self.x, y)

a = A()

a.bar(20)

> 10 20

b = A()
b.x = 3
b.bar()

> 3 20

It's not 100% equivalent, but I haven't noticed a different so far.


问:
React Map is not reading properties
I am learning react. It is showing an error. I tried many time to solve it but failed. I tried changing this.state.article with this.article but in vein- I even tried to cover this in function but it didn't work.

```<code>constructor(){
    super();
    console.log("let see If this constructor is running");
        this.state = {
            article : [],
            loading : false
        }

}
 async componentDidMount(){
  let url = "https://newsapi.org/v2/everything?q=pakistan&apiKey=api-key"
  let data  = await fetch(url);
  let parsedData = await data.json()
  console.log(parsedData);
  this.setState({article: parsedData.article})
}
</code>```

render() {

```<code>return <div>
    <div className='justify-content-center container my-5'>
    <h1>Muzamil's News - Headlines</h1>
    <div className='container row'>
     {this.state.article.map((element)=>{
      console.log("why it is not working");
      return <div key={element.url} className="col-md-4">
        <NewsItem title={element.title} description={element.description}
        urlToImage={element.urlToImage} url={element.url}></NewsItem>
      </div>
    })}
    </div>
    </div>
</div>
</code>```

答: If your component  not showing anything its probably because article array is still empty . You can specify what is the error you are facing?</p>

Title: React Map is not reading properties

Body:
I am learning react. It is showing an error. I tried many time to solve it but failed. I tried changing this.state.article with this.article but in vein- I even tried to cover this in function but it didn't work.

constructor(){
    super();
    console.log("let see If this constructor is running");
        this.state = {
            article : [],
            loading : false
        }

}
 async componentDidMount(){
  let url = "https://newsapi.org/v2/everything?q=pakistan&apiKey=api-key"
  let data  = await fetch(url);
  let parsedData = await data.json()
  console.log(parsedData);
  this.setState({article: parsedData.article})
}

render() {

return

Muzamil's News - Headlines

     {this.state.article.map((element)=>{
      console.log("why it is not working");
      return

        <NewsItem title={element.title} description={element.description}
        urlToImage={element.urlToImage} url={element.url}></NewsItem>

    })}


问:
Convert a 1d array into an object in Google Apps script
I want to be able to convert an array of values like this : ["apple", "pear", "orange","banana" ]
into an array in this format

```<code>[
{"value": "apple"},
{"value": "pear"},
{"value": "orange"},
{"value": "banana"}
]
</code>```

I'd be grateful for any advice.

答:
Use .map :

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const input = ["apple", "pear", "orange","banana"],
  output = input.map(fruit => ({value: fruit}));
console.log(output);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script></code>```

Body:
I want to be able to convert an array of values like this : ["apple", "pear", "orange","banana" ]
into an array in this format

[
{"value": "apple"},
{"value": "pear"},
{"value": "orange"},
{"value": "banana"}
]

I'd be grateful for any advice.

Body:
Use .map :

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const input = ["apple", "pear", "orange","banana"],
  output = input.map(fruit => ({value: fruit}));
console.log(output);

<!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>


问:
Invalid Selector sent to instance - objectForKey:
I get an error when running my code.  The culprit is me accessing a string from a plist below:

```<code>    NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
    NSLog(@"%@",sImageFile);
</code>```

I have this in my cocos2d Init shown here:

```<code>-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value
    if( (self=[super init])) {

        NSUserDefaults *sud = [NSUserDefaults standardUserDefaults];
        NSString *ctlLang = [sud valueForKey:@"ctlLang"];
        NSNumber *questionState = [sud valueForKey:@"questionState"];
        NSNumber *scoreState = [sud valueForKey:@"scoreState"];
        gameArray = (NSMutableArray *)[sud valueForKey:@"gameArray"];
        for (NSString *element in gameArray) {
            NSLog(@"\nQL gameArray value=%d\n", [element intValue]);
        }
        NSString *path = [[NSBundle mainBundle] bundlePath];
        NSString *finalPath = [path stringByAppendingPathComponent:ctlLang];
        dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];

        NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
        NSLog(@"%@",sImageFile);
    }
}
</code>```

The printing of the string works fine in the init section of the scene.  The problem occurs in a method I define later.  For some reason it is not returning the string in the method shown here:

```<code>-(void) checkAnswer: (id) sender {

    CGSize size = [[CCDirector sharedDirector] winSize];
    CCMenuItemSprite *sAnswer = (CCMenuItemSprite *)sender;
    NSLog(@"Checking Answer Tag is ---> %d",sAnswer.tag);
    NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
    NSLog(@"%@",sImageFile);
    if ([question.answer integerValue] == sAnswer.tag) {
        //...
    }
}
</code>```

What am I missing here?  the program bombs at the NSLog statement.

答: I don't think you are retaining the autoreleased dictionary created in your init method. You set the dictionary ivar but don't retain it. When you access it later, it is likely not valid anymore</p>

Body:
I get an error when running my code.  The culprit is me accessing a string from a plist below:

    NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
    NSLog(@"%@",sImageFile);

I have this in my cocos2d Init shown here:

-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value
    if( (self=[super init])) {

        NSUserDefaults *sud = [NSUserDefaults standardUserDefaults];
        NSString *ctlLang = [sud valueForKey:@"ctlLang"];
        NSNumber *questionState = [sud valueForKey:@"questionState"];
        NSNumber *scoreState = [sud valueForKey:@"scoreState"];
        gameArray = (NSMutableArray *)[sud valueForKey:@"gameArray"];
        for (NSString *element in gameArray) {
            NSLog(@"\nQL gameArray value=%d\n", [element intValue]);
        }
        NSString *path = [[NSBundle mainBundle] bundlePath];
        NSString *finalPath = [path stringByAppendingPathComponent:ctlLang];
        dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];

        NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
        NSLog(@"%@",sImageFile);
    }
}

The printing of the string works fine in the init section of the scene.  The problem occurs in a method I define later.  For some reason it is not returning the string in the method shown here:

-(void) checkAnswer: (id) sender {

    CGSize size = [[CCDirector sharedDirector] winSize];
    CCMenuItemSprite *sAnswer = (CCMenuItemSprite *)sender;
    NSLog(@"Checking Answer Tag is ---> %d",sAnswer.tag);
    NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
    NSLog(@"%@",sImageFile);
    if ([question.answer integerValue] == sAnswer.tag) {
        //...
    }
}

What am I missing here?  the program bombs at the NSLog statement.


问:
Is there a way to pass an imported component through a function?
I'm using a library called SlidingPane, and each pane has the exact same styles, just different content depending on the page. So I want to put it into a separate page, and get the content through an argument:

export default function CustomSlidingPane(content){
    <SlidingPane
        className="slidingPanel"
        isOpen={state.isPaneOpen}
        onRequestClose={() => {
            setState({ isPaneOpen: false });
        }}
        >
        <Container>
            {content}
        </Container>
    </SlidingPane>
}
```
<p>All of the content is in separate <code>.js</code> pages that kind of look like this:</p>
<pre class="lang-js prettyprint-override"><code>export default function One() {
    return (
        <h1>Hello</h1>
    );
}
</code>```

So what I'm trying to do is pass one of the content functions through to the CustomSlidingPane like this:

import One from './One';
import CustomSlidingPane from './CustomSlidingPane';

export default function Main(){
    <Container>
        <CustomSlidingPane content={<One/>}>
    </Container>
}
```

Every thing I've tried always ends up in content being undefined. Is there any proper way to do this / is this even possible?

答:
A few things:

It looks like you mighthave forgotten a return in CustomSlidingPane

You need to destructure content from the props

Try this

```<code>export default function CustomSlidingPane({content}){
    return (
        <SlidingPane
        className="slidingPanel"
        isOpen={state.isPaneOpen}
        onRequestClose={() => {
            setState({ isPaneOpen: false });
        }}
        >
        <Container>
            {content}
        </Container>
    </SlidingPane>
    )
}
</code>```

Also, this pattern might be supported better with the children prop.

Body:
I'm using a library called SlidingPane, and each pane has the exact same styles, just different content depending on the page. So I want to put it into a separate page, and get the content through an argument:

export default function CustomSlidingPane(content){
    <SlidingPane
        className="slidingPanel"
        isOpen={state.isPaneOpen}
        onRequestClose={() => {
            setState({ isPaneOpen: false });
        }}
        >
        <Container>
            {content}
        </Container>
    </SlidingPane>
}

All of the content is in separate .js pages that kind of look like this:

export default function One() {
    return (

Hello

    );
}

So what I'm trying to do is pass one of the content functions through to the CustomSlidingPane like this:

import One from './One';
import CustomSlidingPane from './CustomSlidingPane';

export default function Main(){
    <Container>
        <CustomSlidingPane content={<One/>}>
    </Container>
}

Every thing I've tried always ends up in content being undefined. Is there any proper way to do this / is this even possible?

Body:
A few things:

It looks like you mighthave forgotten a return in CustomSlidingPane

You need to destructure content from the props

Try this

export default function CustomSlidingPane({content}){
    return (
        <SlidingPane
        className="slidingPanel"
        isOpen={state.isPaneOpen}
        onRequestClose={() => {
            setState({ isPaneOpen: false });
        }}
        >
        <Container>
            {content}
        </Container>
    </SlidingPane>
    )
}

Also, this pattern might be supported better with the children prop.


问:
Swap specific text in string
I need to write a function swapLetters that receives two strings. The function transforms the string received as the first parameter by replacing the first character from the string that is passed as the second parameter with the last character from the same string, the second with the previous one, etc. to the middle of the string. If the second parameter contains an odd number of characters, nothing needs to be done with the character in the middle. If one of the parameters is an empty string, the function does not need to do anything.

For example:

```<code>char text[9]="dobar dan", letters[5]="abcde";
</code>```

OUTPUT:

```<code>After transformation text is: 'doder den'
</code>```

Explanation: first character in the string letters is "a", and in the string text, character "a" is replaced by the last character of string letters, which is "e". The second charater from string letters is "b", and in the string text, charater "b" is replaced by the penultimate character of string letters, which is "d", while with the letter "c "nothing has been done because it is in the middle of the string letters and there the function stops.

The function should return the cursor to the beginning of a text string for easier chain calling.

*Note: Auxiliary strings are not allowed

```<code>#include <stdio.h>
#include <string.h>
char *swapLetters(char *s1, char *s2) {
  int lenght1 = 0, lenght2 = 0;
  char *q1 = s1, *q2 = s2;
  while (*q1 != '\0') {
    lenght1++;
    q1++;
  }
  while (*q2 != '\0') {
    lenght2++;
    q2++;
  }
  return s1;
}

int main() {
  char text[9] = "dobar dan", letters[5] = "abcde";
  swapLetters(text, letters);
  printf("After transformation text is: '%s'\n", text);
  return 0;
}
</code>```

Could you help me with this task? Strings are new to me.

答:
As others have pointed, you are not providing enough space for your strings to have '\0' terminator.

You need to change to:

```<code>char text[10] = "dobar dan";
char letters[6] = "abcde";
</code>```

But also, your function swapLetters is not swapping any characters:

A correct function would have been:

```<code>char *swapLetters(char *s1, char *s2) {
  int length2 = 0;

  char *q1 = s1, *q2 = s2;

  while (*q2 != '\0') {
    length2++;
    q2++;
  }

  while (*q1 != '\0') {
    // find the char in striong 'letters'
    for(int i=0; i<length2/2; i++){
        if(*q1 == s2[i]){
            *q1 = s2[length2-i-1];
        }
    }
    q1++;
  }

  return s1;
}
</code>```

Title: Swap specific text in string

Body:
I need to write a function swapLetters that receives two strings. The function transforms the string received as the first parameter by replacing the first character from the string that is passed as the second parameter with the last character from the same string, the second with the previous one, etc. to the middle of the string. If the second parameter contains an odd number of characters, nothing needs to be done with the character in the middle. If one of the parameters is an empty string, the function does not need to do anything.

For example:

char text[9]="dobar dan", letters[5]="abcde";

OUTPUT:

After transformation text is: 'doder den'

Explanation: first character in the string letters is "a", and in the string text, character "a" is replaced by the last character of string letters, which is "e". The second charater from string letters is "b", and in the string text, charater "b" is replaced by the penultimate character of string letters, which is "d", while with the letter "c "nothing has been done because it is in the middle of the string letters and there the function stops.

The function should return the cursor to the beginning of a text string for easier chain calling.

*Note: Auxiliary strings are not allowed

#include <stdio.h>
#include <string.h>
char *swapLetters(char *s1, char *s2) {
  int lenght1 = 0, lenght2 = 0;
  char *q1 = s1, *q2 = s2;
  while (*q1 != '\0') {
    lenght1++;
    q1++;
  }
  while (*q2 != '\0') {
    lenght2++;
    q2++;
  }
  return s1;
}

int main() {
  char text[9] = "dobar dan", letters[5] = "abcde";
  swapLetters(text, letters);
  printf("After transformation text is: '%s'\n", text);
  return 0;
}

Could you help me with this task? Strings are new to me.

Body:
As others have pointed, you are not providing enough space for your strings to have '\0' terminator.

You need to change to:

char text[10] = "dobar dan";
char letters[6] = "abcde";

But also, your function swapLetters is not swapping any characters:

A correct function would have been:

char *swapLetters(char *s1, char *s2) {
  int length2 = 0;

  char *q1 = s1, *q2 = s2;

  while (*q2 != '\0') {
    length2++;
    q2++;
  }

  while (*q1 != '\0') {
    // find the char in striong 'letters'
    for(int i=0; i<length2/2; i++){
        if(*q1 == s2[i]){
            *q1 = s2[length2-i-1];
        }
    }
    q1++;
  }

  return s1;
}


问:
Enable Angular button when radio is selected
I'm trying to enable a button when either one of two radio buttons have been selected. I have the button defaulted to disabled with both of the radios defaulted to being unselected. The button should become enabled when either one of the radios has been selected. How can I do this? Here is my HTML:

```<code>    <input
          id="regions"
          name="distribution"
          type="radio"
          (change)="toggleSelectedDistribution()"
        />
        <label
          for="regions"
          >
          {{ 'budgetOnboarding.welcomeScreen.regionsDistribution' | i18next }}
        </label>
      </div>
      <div>
        <input
          id="individual_account"
          name="distribution"
          type="radio"
          (change)="toggleSelectedDistribution()"
        />
        <label
          for="individual_account">
          {{ 'budgetOnboarding.welcomeScreen.individualDistribution' | i18next }}
        </label>
      </div>
    </div>
    <div>
      <button
        type="button"
        id="beginButton"
        (click)="beginWizard()"
        disabled
      >
        {{ 'budgetOnboarding.welcomeScreen.begin' | i18next }}
      </button>
</code>```

Here is my ts:

```<code>import { ChangeDetectorRef, Component, EventEmitter, Output } from '@angular/core';

import { DEFAULT_WELCOME_STEPS } from '../../constants';
import { BudgetHierarchy } from '../../enumerations';
import { ProgramBudgetFacade } from '../../facades';

@Component({
  selector: 'app-welcome-screen',
  templateUrl: './welcome-screen.component.html'
})
export class WelcomeScreenComponent {
  @Output() public readonly onScreenChange = new EventEmitter<boolean>();

  public steps: string[] = [...DEFAULT_WELCOME_STEPS];
  public isRegionHierarchy = true;

  constructor(
    private readonly _changeDetectorRef: ChangeDetectorRef,
    private readonly _budgetFacade: ProgramBudgetFacade
  ) {}

  public toggleSelectedDistribution(): void {
    this.isRegionHierarchy = !this.isRegionHierarchy;

    this.isRegionHierarchy
      ? (this.steps = [...DEFAULT_WELCOME_STEPS])
      : this.steps.splice(2, 2, 'budgetOnboarding.welcomeScreen.accountThirdStep');

    this._changeDetectorRef.detectChanges();
  }

  public beginWizard(): void {
    const budgetHierarchy = this.isRegionHierarchy ? BudgetHierarchy.regions : BudgetHierarchy.none;
    this.onScreenChange.emit(this.isRegionHierarchy);
    this._budgetFacade.setBudgetHierarchy({ budgetHierarchy });
  }
}
</code>```

答:
Use a variable an ngModel, not use "a toogle". Check how all is more "natural"

```<code><input [(ngModel)]="isRegionHierarchy " [value]="true"
    id="regions" name="distribution" type="radio"
/>
<input [(ngModel)]="isRegionHierarchy" [value]="false"
    id="regions" name="distribution" type="radio"
/>
<!--when you use "steps" you can to have some like-->
<div *ngFor="let step of (isRegionHierarchy?stepsOne:stepsTwo)>
   {{step}}
</div>
<button [disabled]="isRegionHierarchy===undefined">button</button>
</code>```

You define in .ts

```<code>isRegionHierarchy:any;
stepsOne=[...DEFAULT_WELCOME_STEPS]
stepsTwo=this.steps.splice(2, 2,'budgetOnboarding.welcomeScreen.accountThirdStep')
</code>```

See how using three variables you needn't write any code in .ts. See also how is easy understand the .html

NOTE: Is necesary the [ + in [value] because else your variable gets the strings "true" or "false" not the boolean value true/false

Body:
I'm trying to enable a button when either one of two radio buttons have been selected. I have the button defaulted to disabled with both of the radios defaulted to being unselected. The button should become enabled when either one of the radios has been selected. How can I do this? Here is my HTML:

    <input
          id="regions"
          name="distribution"
          type="radio"
          (change)="toggleSelectedDistribution()"
        />

          {{ 'budgetOnboarding.welcomeScreen.regionsDistribution' | i18next }}

        <input
          id="individual_account"
          name="distribution"
          type="radio"
          (change)="toggleSelectedDistribution()"
        />

          {{ 'budgetOnboarding.welcomeScreen.individualDistribution' | i18next }}

      <button
        type="button"
        id="beginButton"
        (click)="beginWizard()"
        disabled
      >
        {{ 'budgetOnboarding.welcomeScreen.begin' | i18next }}
      </button>

Here is my ts:

import { ChangeDetectorRef, Component, EventEmitter, Output } from '@angular/core';

import { DEFAULT_WELCOME_STEPS } from '../../constants';
import { BudgetHierarchy } from '../../enumerations';
import { ProgramBudgetFacade } from '../../facades';

@Component({
  selector: 'app-welcome-screen',
  templateUrl: './welcome-screen.component.html'
})
export class WelcomeScreenComponent {
  @Output() public readonly onScreenChange = new EventEmitter<boolean>();

  public steps: string[] = [...DEFAULT_WELCOME_STEPS];
  public isRegionHierarchy = true;

  constructor(
    private readonly _changeDetectorRef: ChangeDetectorRef,
    private readonly _budgetFacade: ProgramBudgetFacade
  ) {}

  public toggleSelectedDistribution(): void {
    this.isRegionHierarchy = !this.isRegionHierarchy;

    this.isRegionHierarchy
      ? (this.steps = [...DEFAULT_WELCOME_STEPS])
      : this.steps.splice(2, 2, 'budgetOnboarding.welcomeScreen.accountThirdStep');

    this._changeDetectorRef.detectChanges();
  }

  public beginWizard(): void {
    const budgetHierarchy = this.isRegionHierarchy ? BudgetHierarchy.regions : BudgetHierarchy.none;
    this.onScreenChange.emit(this.isRegionHierarchy);
    this._budgetFacade.setBudgetHierarchy({ budgetHierarchy });
  }
}

Body:
Use a variable an ngModel, not use "a toogle". Check how all is more "natural"

<input [(ngModel)]="isRegionHierarchy " [value]="true"
    id="regions" name="distribution" type="radio"
/>
<input [(ngModel)]="isRegionHierarchy" [value]="false"
    id="regions" name="distribution" type="radio"
/>
<!--when you use "steps" you can to have some like-->
<div *ngFor="let step of (isRegionHierarchy?stepsOne:stepsTwo)>
   {{step}}
</div>
<button [disabled]="isRegionHierarchy===undefined">button</button>

You define in .ts

isRegionHierarchy:any;
stepsOne=[...DEFAULT_WELCOME_STEPS]
stepsTwo=this.steps.splice(2, 2,'budgetOnboarding.welcomeScreen.accountThirdStep')

See how using three variables you needn't write any code in .ts. See also how is easy understand the .html

NOTE: Is necesary the [ + in [value] because else your variable gets the strings "true" or "false" not the boolean value true/false


问:
How to access a single result of a multi result query in KQL
Given the example query:

```<code>StormEvents | evaluate funnel_sequence(EpisodeId, StartTime, datetime(2007-01-01), datetime(2008-01-01), 1d,365d, EventType, dynamic(['Tornado', 'Hail']))
</code>```

Which returns 3 table results, PrevNext, Prev and Next, how do I access in KQL only one of the results?
I'm interested in something like:

```<code>let PrevNext, Prev, Next = StormEvents | funnel_sequence(...);
Next | where ...
</code>```

答: There's no way to do this in a single KQL query, unfortunately. The follow up text after the funnel_sequence plugin receives only the first table (PrevNext) as input. If it helps, you can find samples here of how to read the different tables programmatically.

Body:
Given the example query:

StormEvents | evaluate funnel_sequence(EpisodeId, StartTime, datetime(2007-01-01), datetime(2008-01-01), 1d,365d, EventType, dynamic(['Tornado', 'Hail']))

Which returns 3 table results, PrevNext, Prev and Next, how do I access in KQL only one of the results?
I'm interested in something like:

let PrevNext, Prev, Next = StormEvents | funnel_sequence(...);
Next | where ...


问:
separating a string column, converting sub values into float and assigning column labels
I have a table t and vector times.

```<code>sym vals
-------------------
A   "3.6, 2.1, 1.8"
B   "2.1, 1.8, 1.6"
C   "2.2, 1.9, 1.6"
D   "1.9, 1.5, 1.3"
E   "2.6, 2.1, 1.9"

times: `0`1`2

</code>```

I want to separate the comma separated string in each row and convert each value into float. The column labels then need to be times. I also want to then drop the column vals. The following statement does this.

```<code>t_out: delete vals from t, 'flip exec times!("FFF";",")0:vals from t

sym 1   2   3
---------------
A   3.6 2.1 1.8
B   2.1 1.8 1.6
C   2.2 1.9 1.6
D   1.9 1.5 1.3
E   2.6 2.1 1.9

</code>```

why does exec times!("FFF";",")0:vals from t transpose the table after converting the values to float? Why do we need 'flip and not just flip? I appreciate your help. Are there alternative methods to achieve this?

答:
(This is a bit of a guess here, since you're asking about q's design choices.)

0: is often used to read in CSV files, where you would store a row per line, separated by a comma. This row won't always have the same types, for instance, this could be a CSV file (building on your example):

```<code>3.6, 2.1, 1.8, 10
2.1, 1.8, 1.6, 20
2.2, 1.9, 1.6, 30
1.9, 1.5, 1.3, 40
2.6, 2.1, 1.9, 50
</code>```

So we have four columns, the first three are float columns, and the fourth is a long (int) column.

When you use 0: to read in the CSV (or in your case, just a list of strings that resemble a CSV), q will transpose the table so that you have a list containing four lists.

```<code>q)vals: ("3.6, 2.1, 1.8, 10"; "2.1, 1.8, 1.6, 20"; "2.2, 1.9, 1.6, 30"; "1.9, 1.5, 1.3, 40"; "2.6, 2.1, 1.9, 50")
q)vals
"3.6, 2.1, 1.8, 10"
"2.1, 1.8, 1.6, 20"
"2.2, 1.9, 1.6, 30"
"1.9, 1.5, 1.3, 40"
"2.6, 2.1, 1.9, 50"
q)("FFFJ"; ",") 0: vals
3.6 2.1 2.2 1.9 2.6
2.1 1.8 1.9 1.5 2.1
1.8 1.6 1.6 1.3 1.9
10  20  30  40  50
</code>```

Each of the four lists in this list will be correctly typed:

```<code>q)first ("FFFJ"; ",") 0: vals
3.6 2.1 2.2 1.9 2.6
q)type first ("FFFJ"; ",") 0: vals
9h
q)last ("FFFJ"; ",") 0: vals
10 20 30 40 50
q)type last ("FFFJ"; ",") 0: vals
7h
</code>```

This makes it easier to work with, as you don't have a list of mixed lists. The alternative would be:

```<code>q)flip ("FFFJ"; ",") 0: vals
3.6 2.1 1.8 10
2.1 1.8 1.6 20
2.2 1.9 1.6 30
1.9 1.5 1.3 40
2.6 2.1 1.9 50
q)first flip ("FFFJ"; ",") 0: vals
3.6
2.1
1.8
10
q)type first flip ("FFFJ"; ",") 0: vals
0h
</code>```

I'm guessing the reasoning for this is performance, as under the hood, tables are in fact column dictionaries, so actually look something like this:

```<code>q)`1`2`3`4 ! ("FFFJ"; ",") 0: vals
1| 3.6 2.1 2.2 1.9 2.6
2| 2.1 1.8 1.9 1.5 2.1
3| 1.8 1.6 1.6 1.3 1.9
4| 10  20  30  40  50
</code>```

But again, you're asking about q's design choices, so I'm just guessing.

The reason you need to use 'flip instead of just flip, is because you want to join each element of two tables (which are treated as lists of dictionaries) to each other, so you are using the each iterator. You can read about it here (if you scroll down just a bit to the "Advanced part, just above the each-left header, it explains it a bit better).

Just to make it clear that the iterator ' is changing , and not flip, I would write your query as:

```<code>... from t ,' flip exec ...
</code>```

Body:
I have a table t and vector times.

sym vals
-------------------
A   "3.6, 2.1, 1.8"
B   "2.1, 1.8, 1.6"
C   "2.2, 1.9, 1.6"
D   "1.9, 1.5, 1.3"
E   "2.6, 2.1, 1.9"

times: `0`1`2

I want to separate the comma separated string in each row and convert each value into float. The column labels then need to be times. I also want to then drop the column vals. The following statement does this.

t_out: delete vals from t, 'flip exec times!("FFF";",")0:vals from t

sym 1   2   3
---------------
A   3.6 2.1 1.8
B   2.1 1.8 1.6
C   2.2 1.9 1.6
D   1.9 1.5 1.3
E   2.6 2.1 1.9

why does exec times!("FFF";",")0:vals from t transpose the table after converting the values to float? Why do we need 'flip and not just flip? I appreciate your help. Are there alternative methods to achieve this?

Body:
(This is a bit of a guess here, since you're asking about q's design choices.)

0: is often used to read in CSV files, where you would store a row per line, separated by a comma. This row won't always have the same types, for instance, this could be a CSV file (building on your example):

3.6, 2.1, 1.8, 10
2.1, 1.8, 1.6, 20
2.2, 1.9, 1.6, 30
1.9, 1.5, 1.3, 40
2.6, 2.1, 1.9, 50

So we have four columns, the first three are float columns, and the fourth is a long (int) column.

When you use 0: to read in the CSV (or in your case, just a list of strings that resemble a CSV), q will transpose the table so that you have a list containing four lists.

q)vals: ("3.6, 2.1, 1.8, 10"; "2.1, 1.8, 1.6, 20"; "2.2, 1.9, 1.6, 30"; "1.9, 1.5, 1.3, 40"; "2.6, 2.1, 1.9, 50")
q)vals
"3.6, 2.1, 1.8, 10"
"2.1, 1.8, 1.6, 20"
"2.2, 1.9, 1.6, 30"
"1.9, 1.5, 1.3, 40"
"2.6, 2.1, 1.9, 50"
q)("FFFJ"; ",") 0: vals
3.6 2.1 2.2 1.9 2.6
2.1 1.8 1.9 1.5 2.1
1.8 1.6 1.6 1.3 1.9
10  20  30  40  50

Each of the four lists in this list will be correctly typed:

q)first ("FFFJ"; ",") 0: vals
3.6 2.1 2.2 1.9 2.6
q)type first ("FFFJ"; ",") 0: vals
9h
q)last ("FFFJ"; ",") 0: vals
10 20 30 40 50
q)type last ("FFFJ"; ",") 0: vals
7h

This makes it easier to work with, as you don't have a list of mixed lists. The alternative would be:

q)flip ("FFFJ"; ",") 0: vals
3.6 2.1 1.8 10
2.1 1.8 1.6 20
2.2 1.9 1.6 30
1.9 1.5 1.3 40
2.6 2.1 1.9 50
q)first flip ("FFFJ"; ",") 0: vals
3.6
2.1
1.8
10
q)type first flip ("FFFJ"; ",") 0: vals
0h

I'm guessing the reasoning for this is performance, as under the hood, tables are in fact column dictionaries, so actually look something like this:

q)`1`2`3`4 ! ("FFFJ"; ",") 0: vals
1| 3.6 2.1 2.2 1.9 2.6
2| 2.1 1.8 1.9 1.5 2.1
3| 1.8 1.6 1.6 1.3 1.9
4| 10  20  30  40  50

But again, you're asking about q's design choices, so I'm just guessing.

The reason you need to use 'flip instead of just flip, is because you want to join each element of two tables (which are treated as lists of dictionaries) to each other, so you are using the each iterator. You can read about it here (if you scroll down just a bit to the "Advanced part, just above the each-left header, it explains it a bit better).

Just to make it clear that the iterator ' is changing , and not flip, I would write your query as:

... from t ,' flip exec ...


问:
(Building) OpenJDK 11 on Mac OS X 10.9.5?
Does anyone know of an OpenJDK 11 build for Mac OS X 10.9.5, or whether it's possible to build it on that OS version?

Having only an X11 GUI would be fine.

EDIT: I've only found binary installers that require at least OS X 10.10 and no information that is specific to the minimum required OS version for building from source independently from the minimum required clang version. OS version 12 is advised but that is presumably because Apple's xcode only contains a new enough clang version starting from that release: one can build for 10.9. Conversely, 10.9 does have a 10.10 SDK and it is no problem to install newer clang versions (I have clang 5.0.1 and 9.0.1 installed).
I did not find any information whatsoever on building for X11 instead of native graphics (IOW, treat the Mac as a regular BSD/Posix workstation). That should cut a large part of the "this requires a newer OS" code out of the equation but is evidently not something any of the regular vendors will consider.

答:
Not an actual answer to my question but a solution to the underlying problem:

SAP provide v11 JDK and JRE that still run on OS X 10.9.5 .

Certain features will not work, like those requiring "Apple EAWT" and (thus?) "Mac OS X GUI integration" but this seems to be handled gracefully enough. These most certainly wouldn't work with an X11 build either.


问:
array sort method doesn't work outside cypress each but works inside
Here is the program piece where you can see that:

var likes = [] is defined before cy.get:

likes is populated inside the each () method
I want to sort likes array as in the below code. But that is not getting sorted.
cy is cypress
The problem is that I like to sort this likes array outside cy.get(..).each() as next instruction not inside. But that is not working and I have no clue as to why. Please could you help in here ?

    var likes = []

    cy.get('.blogs').each(($el, index) => {
        const bcy = cy.wrap($el)
        bcy.get('#viewBlog').click()
        const like =  Math.floor(Math.random() * 10)
        likes[index] = like
        for(let i=like;i--; )
          bcy.get('.blogsDetail').eq(index).contains('likes').click()

      })

     likes.sort((a, b) => b - a)  //Sorting at this place doesn't work```

答:
Cypress commands are asynchronous. To sort the array after the each command, you have to use a then callback:

var likes = []
  cy.get('.blogs').each(($el, index) => {
    const bcy = cy.wrap($el)
    bcy.get('#viewBlog').click()
    const like =  Math.floor(Math.random() * 10)
    likes[index] = like
    for(let i=like;i--; )
      bcy.get('.blogsDetail').eq(index).contains('likes').click()
  }).then(() => {
    likes.sort((a, b) => b - a)
  })
```

Wheny you call the sort method out of a then, it's executed before any cypress command and you have an empty array at that moment. See it in debugger:

Body:
Cypress commands are asynchronous. To sort the array after the each command, you have to use a then callback:

var likes = []
  cy.get('.blogs').each(($el, index) => {
    const bcy = cy.wrap($el)
    bcy.get('#viewBlog').click()
    const like =  Math.floor(Math.random() * 10)
    likes[index] = like
    for(let i=like;i--; )
      bcy.get('.blogsDetail').eq(index).contains('likes').click()
  }).then(() => {
    likes.sort((a, b) => b - a)
  })

Wheny you call the sort method out of a then, it's executed before any cypress command and you have an empty array at that moment. See it in debugger:


问:
Deploying pwa to GH pages
I bumped into problems, trying to deploy my pwa to GH pages.
Service worker is not available.

I try to register it the following way

```<code> navigator.serviceWorker
                 .register("sw.js")
</code>```

The problems in the wrong path to sw.js

TIA

答:
Solution is to use full path to your gh page.</p>
```<code>username.github.io/repo/sw.js
</code>```

Title: Deploying pwa to GH pages

Body:
I bumped into problems, trying to deploy my pwa to GH pages.
Service worker is not available.

I try to register it the following way

 navigator.serviceWorker
                 .register("sw.js")

The problems in the wrong path to sw.js

TIA

Body:
Solution is to use full path to your gh page.

username.github.io/repo/sw.js


问:
Flutter doctor --> Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
I have a question so I think I dowlnloaded everything correctly but I still get this massage when I type in "flutter dictir" in cmd.
When I run "path/to/sdkmanager --install "cmdline-tools;latest" as recommended nothing happens.
So could you help me to download it anyways?

thecode

[!] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
X cmdline-tools component is missing
Run path/to/sdkmanager --install "cmdline-tools;latest"
See https://developer.android.com/studio/command-line for more details.
X Android license status unknown.
Run flutter doctor --android-licenses to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/windows#android-setup for more

! Doctor found issues in 1 category.

答: Open android studio then go to settings then SDK manager. Check the command line tools if it's not checked (most times it's not), then finish and let it download that plugin</p>


问:
What is datasource.url and datasource.driverClassName in application.properties in Spring Boot
I have some questions regarding the datasource in my application.properties

```<code>#Data Source properties
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/example
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

What exactly is the datasource.driver-class-name indicating?

答:
The url is the location of your database. Here you are saying my database is located at http://localhost:3306/example where example is the database name.

The DriverClassName is the name of the JDBC driver that you use to talk to your database. in case one of the Spring data libraries like JDBC or JPA is used you can omit that property.

Body:
I have some questions regarding the datasource in my application.properties

#Data Source properties
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/example
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

What exactly is the datasource.driver-class-name indicating?


问:
Dispatch is working but it is not updating the state
I am working on a application which uses redux for state management. There, at a some condition, I  want to update the state.

My initial state and reducer function looks like this:

```<code>import { createSlice } from '@reduxjs/toolkit';

const filterDataTemplate = {
  programId: '',
  year: '',
};

const initialState = {
   //some other state
  filterData: { ...filterDataTemplate },
};

const slice = createSlice({
  name: 'editFilterSlice',
  initialState: initialState,
  reducers: {
    updateFilterProgramId: (state, action) => {
      state.filterData.programId = action.payload;
    },
    updateFilterYear: (state, action) => {
      state.filterData.year = action.payload;
    },

  },
});

export const {
  updateFilterYear,
  updateFilterProgramId,
} = slice.actions;

export default slice.reducer;
</code>```

So filter details containg year and programId is obtained with the help of this code:

```<code>const filterDetails = useAppSelector(
   (state) => state.locationsFilter.filterData
 );
</code>```

Let's say I have filter data initially:

```<code>filterDetails: {year:2021, programId: "Ameria"}
</code>```

And i want to have my new filter data to be

```<code>filterDetails: {year: "", programId: "Ameria"}
</code>```

So for this what I am doing:

```<code>const handleDelete = (e) => {
    e.preventDefault();
    if (//some condition) {
      console.log("delete is called");
      dispatch(updateFilterYear(''));
    } else {
      dispatch(updateFilterProgramId(''));
    }
}
</code>```

handleDelete function is getting called properly when I am clicking a button because I am getting value inside console.

But after running this code my filter data is not updating. I am not sure what I am doing wrong.
Please help with this.

答:
I think the issue is because you are trying to mutate your state directly. This is bad practice, and Redux state (and more generally react) is intended to be immutable. Reducers should return a copy of the state, along with the updated values. Documentation linked below.

Redux Documentation

Try writing your reducers like the following

```<code>updateFilterYear: (state, action) => {
     return {
         ...state,
         filterData: {
            ...state.filterData,
            year: action.payload
        }
    },

updateFilterProgramId: (state, action) => {
      return {
         ...state,
         filterData: {
            ...state.filterData,
            programId: action.payload
        }
    },
</code>```

Body:
I am working on a application which uses redux for state management. There, at a some condition, I  want to update the state.

My initial state and reducer function looks like this:

import { createSlice } from '@reduxjs/toolkit';

const filterDataTemplate = {
  programId: '',
  year: '',
};

const initialState = {
   //some other state
  filterData: { ...filterDataTemplate },
};

const slice = createSlice({
  name: 'editFilterSlice',
  initialState: initialState,
  reducers: {
    updateFilterProgramId: (state, action) => {
      state.filterData.programId = action.payload;
    },
    updateFilterYear: (state, action) => {
      state.filterData.year = action.payload;
    },

  },
});

export const {
  updateFilterYear,
  updateFilterProgramId,
} = slice.actions;

export default slice.reducer;

So filter details containg year and programId is obtained with the help of this code:

const filterDetails = useAppSelector(
   (state) => state.locationsFilter.filterData
 );

Let's say I have filter data initially:

filterDetails: {year:2021, programId: "Ameria"}

And i want to have my new filter data to be

filterDetails: {year: "", programId: "Ameria"}

So for this what I am doing:

const handleDelete = (e) => {
    e.preventDefault();
    if (//some condition) {
      console.log("delete is called");
      dispatch(updateFilterYear(''));
    } else {
      dispatch(updateFilterProgramId(''));
    }
}

handleDelete function is getting called properly when I am clicking a button because I am getting value inside console.

But after running this code my filter data is not updating. I am not sure what I am doing wrong.
Please help with this.

Body:
I think the issue is because you are trying to mutate your state directly. This is bad practice, and Redux state (and more generally react) is intended to be immutable. Reducers should return a copy of the state, along with the updated values. Documentation linked below.

Redux Documentation

Try writing your reducers like the following

updateFilterYear: (state, action) => {
     return {
         ...state,
         filterData: {
            ...state.filterData,
            year: action.payload
        }
    },

updateFilterProgramId: (state, action) => {
      return {
         ...state,
         filterData: {
            ...state.filterData,
            programId: action.payload
        }
    },


答:
You can accomplish this issue using two nested loops. The outer loop should use two pointers to the characters in the s2 string that should be checked-for and changed-to, respectively; the inner loop should (repeatedly) run through the s1 string, looking for occurrences of the target character, and change that if found.

You haven't specified what to do if there is any "overlap" between the character(s) to change and those that should be substituted but, in the code below, I have included an array of 'flags' to prevent multiple substitutions, in such cases. If you don't want this behaviour, or if the values of the s2 string simply won't allow it, then you can remove all references to the done array.

I have included comments that explain (I hope) what the code does, and the two lines commented out with the /// triple-slash can be un-commented if you want to watch what the function does "on the fly".

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* swapLetters(char* s1, char* s2)
{
    // A quick sanity check ...
    if (!strlen(s1) || !strlen(s2)) return s1; // Zero-length strings!

    // First, let's get pointers to the first/last characters of s2...
    char* sub_beg = s2;
    char* sub_end = s2 + strlen(s2) - 1;

    size_t src_len = strlen(s1); // So we don't have to keep calling "strlen"

    // Now, we need an array to keep track of characters we've ALREADY changed...
    int* done = calloc(src_len, sizeof(int)); // calloc set all elements to ZERO
    if (!done) {
        puts("Cannot allocate workspace!");
        return s1;
    }

    // Outer loop: run until beginning and end meet or cross over...
    while (sub_beg < sub_end) {
    /// printf("Checking for %c change to %c ... \n", *sub_beg, *sub_end);
        // Inner loop: run through the source and change if found...
        for (size_t i = 0; i < src_len; ++i) {
            if (s1[i] == *sub_beg && !done[i]) {
            /// printf("Swapping %c for %c ... \n", s1[i], *sub_end);
                s1[i] = *sub_end; // Make change
                done[i] = 1;     // Flag that we've changed it
            }
        }
        ++sub_beg; // Increment beginning
        --sub_end; // Decrement end
    }

    // Clean-up ...
    free(done);

    return s1;
}

int main()
{
    char text[10] = "dobar dan", letters[6] = "abcde"; // NOTE: We need space for the NUL-terminator
    swapLetters(text, letters);
    printf("After transformation text is: '%s'\n", text);
    return 0;
}
```

Note also, that I have increased the sizes of your text and letters arrays (in main) to allow for the required nul-terminator in those strings. You could also just declare those arrays with empty square brackets (i.e. char text[] = ...) so that the compiler allocates the size automatically.

Title: Swap specific text in string

Body:
You can accomplish this issue using two nested loops. The outer loop should use two pointers to the characters in the s2 string that should be checked-for and changed-to, respectively; the inner loop should (repeatedly) run through the s1 string, looking for occurrences of the target character, and change that if found.

You haven't specified what to do if there is any "overlap" between the character(s) to change and those that should be substituted but, in the code below, I have included an array of 'flags' to prevent multiple substitutions, in such cases. If you don't want this behaviour, or if the values of the s2 string simply won't allow it, then you can remove all references to the done array.

I have included comments that explain (I hope) what the code does, and the two lines commented out with the /// triple-slash can be un-commented if you want to watch what the function does "on the fly".

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* swapLetters(char* s1, char* s2)
{
    // A quick sanity check ...
    if (!strlen(s1) || !strlen(s2)) return s1; // Zero-length strings!

    // First, let's get pointers to the first/last characters of s2...
    char* sub_beg = s2;
    char* sub_end = s2 + strlen(s2) - 1;

    size_t src_len = strlen(s1); // So we don't have to keep calling "strlen"

    // Now, we need an array to keep track of characters we've ALREADY changed...
    int* done = calloc(src_len, sizeof(int)); // calloc set all elements to ZERO
    if (!done) {
        puts("Cannot allocate workspace!");
        return s1;
    }

    // Outer loop: run until beginning and end meet or cross over...
    while (sub_beg < sub_end) {
    /// printf("Checking for %c change to %c ... \n", *sub_beg, *sub_end);
        // Inner loop: run through the source and change if found...
        for (size_t i = 0; i < src_len; ++i) {
            if (s1[i] == *sub_beg && !done[i]) {
            /// printf("Swapping %c for %c ... \n", s1[i], *sub_end);
                s1[i] = *sub_end; // Make change
                done[i] = 1;     // Flag that we've changed it
            }
        }
        ++sub_beg; // Increment beginning
        --sub_end; // Decrement end
    }

    // Clean-up ...
    free(done);

    return s1;
}

int main()
{
    char text[10] = "dobar dan", letters[6] = "abcde"; // NOTE: We need space for the NUL-terminator
    swapLetters(text, letters);
    printf("After transformation text is: '%s'\n", text);
    return 0;
}

Note also, that I have increased the sizes of your text and letters arrays (in main) to allow for the required nul-terminator in those strings. You could also just declare those arrays with empty square brackets (i.e. char text[] = ...) so that the compiler allocates the size automatically.