问:
jQuery button don't change its class instantly because of AJAX call
When my button is clicked,I want to change it's class instantly,but it seems that the ajax call is not letting it to happen.It's happening 3-4 seconds later.Why?I tested with alerts and it's ok.

the button:

```<code>    $('#myButton').click(function() {
        alert("ok");//it will alert instantly
        $('#myButton').removeClass().addClass("btn btn-success"); //here, this code is running after 3-4 secs
    });
</code>```

ajax call:

```<code> $('button').click(function() {
     ...some code...
     $.ajax({
            async: false,
            type: 'POST',
            dataType: 'json',
            url: myUrl,
            data: myValue,
            success: function(data) {
                setTimeout(function() {
                    img.src = img.src;
                }, 10);
            }

        })

}
</code>```

Without the ajax call it works

答:
Remove this:

```<code>async: false
</code>```

Adding that makes the asynchronous operation artificially synchronous, blocking everything else from happening in the browser.  You're probably even getting a warning about deprecation in your browser's development console.

Never use async: false.  Keep asynchronous operations asynchronous.

Body:
When my button is clicked,I want to change it's class instantly,but it seems that the ajax call is not letting it to happen.It's happening 3-4 seconds later.Why?I tested with alerts and it's ok.

the button:

    $('#myButton').click(function() {
        alert("ok");//it will alert instantly
        $('#myButton').removeClass().addClass("btn btn-success"); //here, this code is running after 3-4 secs
    });

ajax call:

 $('button').click(function() {
     ...some code...
     $.ajax({
            async: false,
            type: 'POST',
            dataType: 'json',
            url: myUrl,
            data: myValue,
            success: function(data) {
                setTimeout(function() {
                    img.src = img.src;
                }, 10);
            }

        })

}

Without the ajax call it works

Body:
Remove this:

async: false

Adding that makes the asynchronous operation artificially synchronous, blocking everything else from happening in the browser.  You're probably even getting a warning about deprecation in your browser's development console.

Never use async: false.  Keep asynchronous operations asynchronous.


来源: stackexchange

问:
Filtering Dataframe based on many conditions
here is my problem:

I have a dataFrame that look like this :

```<code>Date  Name  Score  Country
2012  Paul    45    Mexico
2012  Mike    38    Sweden
2012  Teddy   62    USA
2012  Hilary  80    USA
2013  Ashley  42    France
2013  Temari  58    UK
2013  Harry   78    UK
2013  Silvia  55    Italy
</code>```

I want to select the two best scores, with a filter by date and also from a different country.

For example here : In 2012 Hilary has the best score (USA) so she will be selected.
Teddy has the second best score in 2012 but he won't be selected as he comes from the same country (USA)
So Paul will be selected instead as he comes from a different country (Mexico).

This is what I did :

```<code>df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2013","2013","2013","2013"],
     'Name': ["Paul", "Mike", "Teddy", "Hilary", "Ashley", "Temaru","Harry","Silvia"],
     'Score': [45, 38, 62, 80, 42, 58,78,55],
     "Country":["Mexico","Sweden","USA","USA","France","UK",'UK','Italy']})
</code>```

And then I made the filter by Date and by Score :

```<code>df1 = df.set_index('Name').groupby('Date')['Score'].apply(lambda grp: grp.nlargest(2))
</code>```

But I don't really know and to do the filter that takes into account that they have to come from a different country.

Does anyone have an idea on that ? Thank you so much

EDIT : The answer I am looking for should be something like that :

```<code>Date  Name  Score  Country
2012  Hilary  80    USA
2012  Paul    45    Mexico
2013  Harry   78    UK
2013  Silvia  55    Italy
</code>```

Filter two people by date, best score and from a different country

答:
I have used different longer approach, which anyone hasn't submitted so far.

```<code>df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2013","2013","2013","2013"],
     'Name': ["Paul", "Mike", "Teddy", "Hilary", "Ashley", "Temaru","Harry","Silvia"],
     'Score': [45, 38, 62, 80, 42, 58,78,55],
     "Country":["Mexico","Sweden","USA","USA","France","UK",'UK','Italy']})

df1=df.groupby(['Date','Country'])['Score'].max().reset_index()

df2=df.iloc[:,[1,2]]

df1.merge(df2)
</code>```

This is little convoluted but does the work.

ContentLicense: CC BY-SA 4.0

Body:
here is my problem:

I have a dataFrame that look like this :

Date  Name  Score  Country
2012  Paul    45    Mexico
2012  Mike    38    Sweden
2012  Teddy   62    USA
2012  Hilary  80    USA
2013  Ashley  42    France
2013  Temari  58    UK
2013  Harry   78    UK
2013  Silvia  55    Italy

I want to select the two best scores, with a filter by date and also from a different country.

For example here : In 2012 Hilary has the best score (USA) so she will be selected.
Teddy has the second best score in 2012 but he won't be selected as he comes from the same country (USA)
So Paul will be selected instead as he comes from a different country (Mexico).

This is what I did :

df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2013","2013","2013","2013"],
     'Name': ["Paul", "Mike", "Teddy", "Hilary", "Ashley", "Temaru","Harry","Silvia"],
     'Score': [45, 38, 62, 80, 42, 58,78,55],
     "Country":["Mexico","Sweden","USA","USA","France","UK",'UK','Italy']})

And then I made the filter by Date and by Score :

df1 = df.set_index('Name').groupby('Date')['Score'].apply(lambda grp: grp.nlargest(2))

But I don't really know and to do the filter that takes into account that they have to come from a different country.

Does anyone have an idea on that ? Thank you so much

EDIT : The answer I am looking for should be something like that :

Date  Name  Score  Country
2012  Hilary  80    USA
2012  Paul    45    Mexico
2013  Harry   78    UK
2013  Silvia  55    Italy

Filter two people by date, best score and from a different country

Body:
I have used different longer approach, which anyone hasn't submitted so far.

df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2013","2013","2013","2013"],
     'Name': ["Paul", "Mike", "Teddy", "Hilary", "Ashley", "Temaru","Harry","Silvia"],
     'Score': [45, 38, 62, 80, 42, 58,78,55],
     "Country":["Mexico","Sweden","USA","USA","France","UK",'UK','Italy']})

df1=df.groupby(['Date','Country'])['Score'].max().reset_index()

df2=df.iloc[:,[1,2]]

df1.merge(df2)

This is little convoluted but does the work.


问:
Can you modify a C struct from lua?
I want to be able to have this Lua code:

function myfunc(s)
    print(s.value)
    s.value = 7
end
```

<p>And it should work with this C(++) code:</p>

```struct MyStruct {
    float value;
};

void func() {
    MyStruct var;
    var.value = 5;

    lua_getglobal(L, "myfunc");
    // push `var` to lua, somehow

    lua_call(L, 1, 0); // prints "5"

    // now, var.value is 7
    assert(var.value == 7);
}
```

How would I push var onto the stack such that the lua code can modify its variables?

答:
Standard Lua doesn't have a built-in way to expose the contents of structs through tables, so doing so is a bit of a manual process. Here's an example of a complete program that does what you want:

#include <assert.h>
#include <string.h>

#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>

struct MyStruct {
    float value;
};

int MyStruct_index(lua_State *L) {
    struct MyStruct *t = (struct MyStruct *)luaL_checkudata(L, 1, "MyStruct");
    const char *k = luaL_checkstring(L, 2);
    if(!strcmp(k, "value")) {
        lua_pushnumber(L, t->value);
    } else {
        lua_pushnil(L);
    }
    return 1;
}

int MyStruct_newindex(lua_State *L) {
    struct MyStruct *t = (struct MyStruct *)luaL_checkudata(L, 1, "MyStruct");
    const char *k = luaL_checkstring(L, 2);
    if(!strcmp(k, "value")) {
        t->value = luaL_checknumber(L, 3);
        return 0;
    } else {
        return luaL_argerror(L, 2,
                             lua_pushfstring(L, "invalid option '%s'", k));
    }
}

struct MyStruct *MyStruct_new(lua_State *L) {
    struct MyStruct *var = (struct MyStruct *)lua_newuserdata(L, sizeof *var);
    luaL_setmetatable(L, "MyStruct");
    return var;
}

void func(lua_State *L) {
    // Since this is allocated inside of Lua, it will be garbage collected,
    // so we don't need to worry about freeing it
    struct MyStruct *var = MyStruct_new(L);
    var->value = 5;

    lua_getglobal(L, "myfunc");
    lua_pushvalue(L, -2); // push `var` to lua, somehow

    lua_call(L, 1, 0); // prints "5"

    // now, var->value is 7
    assert(var->value == 7);
}

int main(void) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    // One-time setup that needs to happen before you first call MyStruct_new
    luaL_newmetatable(L, "MyStruct");
    lua_pushcfunction(L, MyStruct_index);
    lua_setfield(L, -2, "__index");
    lua_pushcfunction(L, MyStruct_newindex);
    lua_setfield(L, -2, "__newindex");
    lua_pop(L, 1);

    luaL_dostring(L, "function myfunc(s) print(s.value) s.value = 7 end");
    func(L);

    lua_close(L);
    return 0;
}
```

<p>To support more fields, you'd have to add them to <code>MyStruct_index</code> and <code>MyStruct_newindex</code>. If you want <code>pairs</code> to work on it, then you'd need to add a <code>__pairs</code> metamethod too. In general, though, exposing getters and setters is usually preferred over an approach like this one.</p>

<p>If you want to allocate your <code>struct MyStruct</code> somewhere other than inside of Lua, then you could add an extra layer of indirection everywhere it's used, like this:</p>

```#include <assert.h>
#include <string.h>

#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>

struct MyStruct {
    float value;
};

int MyStruct_index(lua_State *L) {
    struct MyStruct **t = (struct MyStruct **)luaL_checkudata(L, 1, "MyStruct");
    const char *k = luaL_checkstring(L, 2);
    if(!strcmp(k, "value")) {
        lua_pushnumber(L, (*t)->value);
    } else {
        lua_pushnil(L);
    }
    return 1;
}

int MyStruct_newindex(lua_State *L) {
    struct MyStruct **t = (struct MyStruct **)luaL_checkudata(L, 1, "MyStruct");
    const char *k = luaL_checkstring(L, 2);
    if(!strcmp(k, "value")) {
        (*t)->value = luaL_checknumber(L, 3);
        return 0;
    } else {
        return luaL_argerror(L, 2,
                             lua_pushfstring(L, "invalid option '%s'", k));
    }
}

void MyStruct_push(lua_State *L, struct MyStruct *var) {
    struct MyStruct **t = (struct MyStruct **)lua_newuserdata(L, sizeof *t);
    *t = var;
    luaL_setmetatable(L, "MyStruct");
}

void func(lua_State *L) {
    struct MyStruct var;
    var.value = 5;

    lua_getglobal(L, "myfunc");
    MyStruct_push(L, &var); // push `var` to lua, somehow

    lua_call(L, 1, 0); // prints "5"

    // now, var.value is 7
    assert(var.value == 7);

    // WARNING! `var` is about to go out of scope! If Lua uses the userdata
    // that references it beyond this point, it's Undefined Behavior! Make
    // sure that it didn't keep a copy of it!
}

int main(void) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    // One-time setup that needs to happen before you first call MyStruct_new
    luaL_newmetatable(L, "MyStruct");
    lua_pushcfunction(L, MyStruct_index);
    lua_setfield(L, -2, "__index");
    lua_pushcfunction(L, MyStruct_newindex);
    lua_setfield(L, -2, "__newindex");
    lua_pop(L, 1);

    luaL_dostring(L, "function myfunc(s) print(s.value) s.value = 7 end");
    func(L);

    lua_close(L);
    return 0;
}
```

But this is dangerous! If the Lua userdata outlives the object that it points to, Undefined Behavior will result!

Title: Can you modify a C struct from lua?

Body:
I want to be able to have this Lua code:

function myfunc(s)
    print(s.value)
    s.value = 7
end

And it should work with this C(++) code:

struct MyStruct {
    float value;
};

void func() {
    MyStruct var;
    var.value = 5;

    lua_getglobal(L, "myfunc");
    // push `var` to lua, somehow

    lua_call(L, 1, 0); // prints "5"

    // now, var.value is 7
    assert(var.value == 7);
}

How would I push var onto the stack such that the lua code can modify its variables?

Body:
Standard Lua doesn't have a built-in way to expose the contents of structs through tables, so doing so is a bit of a manual process. Here's an example of a complete program that does what you want:

#include <assert.h>
#include <string.h>

#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>

struct MyStruct {
    float value;
};

int MyStruct_index(lua_State *L) {
    struct MyStruct *t = (struct MyStruct *)luaL_checkudata(L, 1, "MyStruct");
    const char *k = luaL_checkstring(L, 2);
    if(!strcmp(k, "value")) {
        lua_pushnumber(L, t->value);
    } else {
        lua_pushnil(L);
    }
    return 1;
}

int MyStruct_newindex(lua_State *L) {
    struct MyStruct *t = (struct MyStruct *)luaL_checkudata(L, 1, "MyStruct");
    const char *k = luaL_checkstring(L, 2);
    if(!strcmp(k, "value")) {
        t->value = luaL_checknumber(L, 3);
        return 0;
    } else {
        return luaL_argerror(L, 2,
                             lua_pushfstring(L, "invalid option '%s'", k));
    }
}

struct MyStruct *MyStruct_new(lua_State *L) {
    struct MyStruct *var = (struct MyStruct *)lua_newuserdata(L, sizeof *var);
    luaL_setmetatable(L, "MyStruct");
    return var;
}

void func(lua_State *L) {
    // Since this is allocated inside of Lua, it will be garbage collected,
    // so we don't need to worry about freeing it
    struct MyStruct *var = MyStruct_new(L);
    var->value = 5;

    lua_getglobal(L, "myfunc");
    lua_pushvalue(L, -2); // push `var` to lua, somehow

    lua_call(L, 1, 0); // prints "5"

    // now, var->value is 7
    assert(var->value == 7);
}

int main(void) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    // One-time setup that needs to happen before you first call MyStruct_new
    luaL_newmetatable(L, "MyStruct");
    lua_pushcfunction(L, MyStruct_index);
    lua_setfield(L, -2, "__index");
    lua_pushcfunction(L, MyStruct_newindex);
    lua_setfield(L, -2, "__newindex");
    lua_pop(L, 1);

    luaL_dostring(L, "function myfunc(s) print(s.value) s.value = 7 end");
    func(L);

    lua_close(L);
    return 0;
}

To support more fields, you'd have to add them to MyStruct_index and MyStruct_newindex. If you want pairs to work on it, then you'd need to add a __pairs metamethod too. In general, though, exposing getters and setters is usually preferred over an approach like this one.

If you want to allocate your struct MyStruct somewhere other than inside of Lua, then you could add an extra layer of indirection everywhere it's used, like this:

#include <assert.h>
#include <string.h>

#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>

struct MyStruct {
    float value;
};

int MyStruct_index(lua_State *L) {
    struct MyStruct **t = (struct MyStruct **)luaL_checkudata(L, 1, "MyStruct");
    const char *k = luaL_checkstring(L, 2);
    if(!strcmp(k, "value")) {
        lua_pushnumber(L, (*t)->value);
    } else {
        lua_pushnil(L);
    }
    return 1;
}

int MyStruct_newindex(lua_State *L) {
    struct MyStruct **t = (struct MyStruct **)luaL_checkudata(L, 1, "MyStruct");
    const char *k = luaL_checkstring(L, 2);
    if(!strcmp(k, "value")) {
        (*t)->value = luaL_checknumber(L, 3);
        return 0;
    } else {
        return luaL_argerror(L, 2,
                             lua_pushfstring(L, "invalid option '%s'", k));
    }
}

void MyStruct_push(lua_State *L, struct MyStruct *var) {
    struct MyStruct **t = (struct MyStruct **)lua_newuserdata(L, sizeof *t);
    *t = var;
    luaL_setmetatable(L, "MyStruct");
}

void func(lua_State *L) {
    struct MyStruct var;
    var.value = 5;

    lua_getglobal(L, "myfunc");
    MyStruct_push(L, &var); // push `var` to lua, somehow

    lua_call(L, 1, 0); // prints "5"

    // now, var.value is 7
    assert(var.value == 7);

    // WARNING! `var` is about to go out of scope! If Lua uses the userdata
    // that references it beyond this point, it's Undefined Behavior! Make
    // sure that it didn't keep a copy of it!
}

int main(void) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    // One-time setup that needs to happen before you first call MyStruct_new
    luaL_newmetatable(L, "MyStruct");
    lua_pushcfunction(L, MyStruct_index);
    lua_setfield(L, -2, "__index");
    lua_pushcfunction(L, MyStruct_newindex);
    lua_setfield(L, -2, "__newindex");
    lua_pop(L, 1);

    luaL_dostring(L, "function myfunc(s) print(s.value) s.value = 7 end");
    func(L);

    lua_close(L);
    return 0;
}

But this is dangerous! If the Lua userdata outlives the object that it points to, Undefined Behavior will result!


问:
How can i obtain/define input output names of my graph or freeze it in proper form
Hi everyone we have been trying to save our model in .bytes format so that we can use it in a c# script.
We are using tensorflow 1.7.0
Here is our model:

```<code>bsize=16

# define cnn model
def define_model():
    # load model
    model = VGG16(include_top=False, input_shape=(224, 224, 3))
    # mark loaded layers as not trainable
    for layer in model.layers:
        layer.trainable = False
    # add new classifier layers
    flat1 = Flatten()(model.layers[-1].output)
    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)
    output = Dense(2, activation='softmax')(class1)
    # define new model
    model = Model(inputs=model.inputs, outputs=output)
    # compile model
    # compile model
    opt = Adam(lr=0.001)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model
</code>```

Training:

```<code>sess=tf.Session()
tf.global_variables_initializer().run(session=sess)
model = define_model()
# create data generator
datagen = ImageDataGenerator(rescale=1.0/255.0)
# prepare iterators
train_it = datagen.flow_from_directory(mpath+'/train',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
test_it = datagen.flow_from_directory(mpath+'/test',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
# fit model
history = model.fit_generator(train_it, steps_per_epoch=len(train_it),
validation_data=test_it, validation_steps=len(test_it), epochs=1, verbose=0)
# evaluate model
_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)
print('> %.3f' % (acc * 100.0))

model.save_weights("weights.h5")
</code>```

Freeze:

```<code>K.clear_session()
K.set_learning_phase(0)
model = define_model()
model.load_weights("weights.h5")

save_dir = "./out"

tf.saved_model.simple_save(K.get_session(),
                           save_dir,
                           inputs={"input": model.inputs[0]},
                           outputs={"output": model.outputs[0]})

freeze_graph.freeze_graph(None,
                          None,
                          None,
                          None,
                          model.outputs[0].op.name,
                          None,
                          None,
                          os.path.join(save_dir, "frozen_model.bytes"),
                          False,
                          "",
                          input_saved_model_dir=save_dir)
</code>```

Then we try to see input and output names using:

```<code>    model.inputs[0].name
    model.ouputs[0].name
</code>```

Finally we would like to use this graph in c# as:

```<code>.AddInput(graph["input_1_1:0"][0], tensor).Fetch(graph["output"][0]);
</code>```

However, as we understand from the error input and output names are wrong. Moreover  whenever we call

```<code>model.inputs[0].name
model.ouputs[0].name
</code>```

they print different input and output names even if we define output name as name="output"

Do you have any suggestions about how to freeze this model, obtain input and output names etc

regards

答:
For those having similar issues:

```<code>model.inputs[0].name
model.ouputs[0].name
</code>```

yield sth like this:

```<code>input_1:0
dense_2/Softmax:0
</code>```

but you shouldnt use them directly in .AddInput so instead of:

```<code>.AddInput(graph["input_1:0"][0], tensor).Fetch(graph[dense_2/Softmax:0][0]);
</code>```

do it this way:

```<code>.AddInput(graph["input_1"][0], tensor).Fetch(graph[dense_2/Softmax][0]);
</code>```

So the code above actually works just omit the :0 part from the name strings and thats all :D

Body:
Hi everyone we have been trying to save our model in .bytes format so that we can use it in a c# script.
We are using tensorflow 1.7.0
Here is our model:

bsize=16

# define cnn model
def define_model():
    # load model
    model = VGG16(include_top=False, input_shape=(224, 224, 3))
    # mark loaded layers as not trainable
    for layer in model.layers:
        layer.trainable = False
    # add new classifier layers
    flat1 = Flatten()(model.layers[-1].output)
    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)
    output = Dense(2, activation='softmax')(class1)
    # define new model
    model = Model(inputs=model.inputs, outputs=output)
    # compile model
    # compile model
    opt = Adam(lr=0.001)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

Training:

sess=tf.Session()
tf.global_variables_initializer().run(session=sess)
model = define_model()
# create data generator
datagen = ImageDataGenerator(rescale=1.0/255.0)
# prepare iterators
train_it = datagen.flow_from_directory(mpath+'/train',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
test_it = datagen.flow_from_directory(mpath+'/test',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
# fit model
history = model.fit_generator(train_it, steps_per_epoch=len(train_it),
validation_data=test_it, validation_steps=len(test_it), epochs=1, verbose=0)
# evaluate model
_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)
print('> %.3f' % (acc * 100.0))

model.save_weights("weights.h5")

Freeze:

K.clear_session()
K.set_learning_phase(0)
model = define_model()
model.load_weights("weights.h5")

save_dir = "./out"

tf.saved_model.simple_save(K.get_session(),
                           save_dir,
                           inputs={"input": model.inputs[0]},
                           outputs={"output": model.outputs[0]})

freeze_graph.freeze_graph(None,
                          None,
                          None,
                          None,
                          model.outputs[0].op.name,
                          None,
                          None,
                          os.path.join(save_dir, "frozen_model.bytes"),
                          False,
                          "",
                          input_saved_model_dir=save_dir)

Then we try to see input and output names using:

    model.inputs[0].name
    model.ouputs[0].name

Finally we would like to use this graph in c# as:

.AddInput(graph["input_1_1:0"][0], tensor).Fetch(graph["output"][0]);

However, as we understand from the error input and output names are wrong. Moreover  whenever we call

model.inputs[0].name
model.ouputs[0].name

they print different input and output names even if we define output name as name="output"

Do you have any suggestions about how to freeze this model, obtain input and output names etc

regards

Body:
For those having similar issues:

model.inputs[0].name
model.ouputs[0].name

yield sth like this:

input_1:0
dense_2/Softmax:0

but you shouldnt use them directly in .AddInput so instead of:

.AddInput(graph["input_1:0"][0], tensor).Fetch(graph[dense_2/Softmax:0][0]);

do it this way:

.AddInput(graph["input_1"][0], tensor).Fetch(graph[dense_2/Softmax][0]);

So the code above actually works just omit the :0 part from the name strings and thats all :D


问:
How to edit an R markdown YAML header programmatically?
Take for example this Rmd file - https://github.com/rstudio/learnr/blob/master/inst/tutorials/ex-setup-r/ex-setup-r.Rmd

The YAML header has this -

```<code>output:
  learnr::tutorial:
    progressive: true
    allow_skip: true
</code>```

I would like to change this to -

```<code>output:
  ioslides_presentation:
    widescreen: true
</code>```

Is there a way to make this edit programmatically i.e. Can I write some function that takes an Rmd file as input, edits the YAML header, and produces a new Rmd file?

Thanks!

答:
I think a quick function could do this.

change_yaml_matter <- function(input_file, ..., output_file) {
  input_lines <- readLines(input_file)
  delimiters <- grep("^---\\s*$", input_lines)
  if (!length(delimiters)) {
    stop("unable to find yaml delimiters")
  } else if (length(delimiters) == 1L) {
    if (delimiters[1] == 1L) {
      stop("cannot find second delimiter, first is on line 1")
    } else {
      # found just one set, assume it is *closing* the yaml matter;
      # fake a preceding line of delimiter
      delimiters <- c(0L, delimiters[1])
    }
  }
  delimiters <- delimiters[1:2]
  yaml_list <- yaml::yaml.load(input_lines[ (delimiters[1]+1):(delimiters[2]-1) ])

  dots <- list(...)
  yaml_list <- c(yaml_list[ setdiff(names(yaml_list), names(dots)) ], dots)

  output_lines <- c(
    if (delimiters[1] > 0) input_lines[1:(delimiters[1])],
    strsplit(yaml::as.yaml(yaml_list), "\n")[[1]],
    input_lines[ -(1:(delimiters[2]-1)) ]
  )

  if (missing(output_file)) {
    return(output_lines)
  } else {
    writeLines(output_lines, con = output_file)
    return(invisible(output_lines))
  }
}
```

<p>Where <code>...</code> is <em>whatever you want it to be</em>. Meaning: if you want to replace the <code>output:</code> component of the yaml matter, then you give a named list as <code>output=list(...)</code>. </p>

<p>If I use the rmarkdown document I used in a previous answer, then <em>unchanged</em>, it looks like this:</p>

<pre class="lang-r prettyprint-override"><code>readLines("~/StackOverflow/1883604/62095186.Rmd")
#  [1] "---"
#  [2] "title: Hello"
#  [3] "output: html_document"
#  [4] "params:"
#  [5] "  intab: TRUE"
#  [6] "---"
#  [7] ""
#  [8] "# Headline 1"
#  [9] ""
# [10] "## Headline 2 `r if (params$intab) \"{.tabset}\"`"
# [11] ""
# [12] "### Headline 3 in a tab"
# [13] ""
# [14] "### Headline 4 in a tab"
# [15] ""
# [16] "### Headline 5 in a tab"
# [17] ""
# [18] ""
</code>```

And to change the output portion, I add a nested named list as:

change_yaml_matter("~/StackOverflow/1883604/62095186.Rmd",
                   output=list(ioslides_presentation=list(widescreen=TRUE)))
#  [1] "---"
#  [2] "title: Hello"
#  [3] "params:"
#  [4] "  intab: yes"
#  [5] "output:"
#  [6] "  ioslides_presentation:"
#  [7] "    widescreen: yes"
#  [8] "---"
#  [9] ""
# [10] "# Headline 1"
# [11] ""
# [12] "## Headline 2 `r if (params$intab) \"{.tabset}\"`"
# [13] ""
# [14] "### Headline 3 in a tab"
# [15] ""
# [16] "### Headline 4 in a tab"
# [17] ""
# [18] "### Headline 5 in a tab"
# [19] ""
# [20] ""
```

<p>You can change just about any portion of the yaml matter. (The only things you cannot change, I suspect, are if you happen to have yaml parameters named <code>input_file</code> or <code>output_file</code>. If you actually have Rmd files with those yaml top-level parameters, then you can easily rename the named arguments here to be something else, such as <code>Mxyzptlk</code> and something else ... you're unlikely to see those in production.)</p>

<p>Notes:</p>

<ul>
<li>This did not save anything to a file, you have to do that yourself. Add <code>output_file="path/to/new.RMd"</code> to your call, and it will write a new file.</li>
<li>When you do include <code>output_file=</code> in the arguments, if you choose to not catch the return value, it will <em>appear</em> to return nothing. This is due to <code>invisible</code> in my return; if you really want to see and save, either capture to a variable and look at that, or wrap the function call in parens, as in <code>(change_yaml_matter(...))</code>.</li>
</ul>

<p>The trick for YAML is to know that <code>yaml::</code> will treat every top-level as the named element of a list, and its contents are recursively lists in the same manner. For instance,</p>

<pre class="lang-r prettyprint-override"><code>str(yaml::yaml.load("
---
top1:
  level2a:
    level3a: 123
    level3b: 456
  level2b: 789
top2: quux
---"))
# List of 2
#  $ top1:List of 2
#   ..$ level2a:List of 2
#   .. ..$ level3a: int 123
#   .. ..$ level3b: int 456
#   ..$ level2b: int 789
#  $ top2: chr "quux"
</code>```

To assign new values, just provide nested named lists.

Body:
Take for example this Rmd file - https://github.com/rstudio/learnr/blob/master/inst/tutorials/ex-setup-r/ex-setup-r.Rmd

The YAML header has this -

output:
  learnr::tutorial:
    progressive: true
    allow_skip: true

I would like to change this to -

output:
  ioslides_presentation:
    widescreen: true

Is there a way to make this edit programmatically i.e. Can I write some function that takes an Rmd file as input, edits the YAML header, and produces a new Rmd file?

Thanks!

Body:
I think a quick function could do this.

change_yaml_matter <- function(input_file, ..., output_file) {
  input_lines <- readLines(input_file)
  delimiters <- grep("^---\\s*$", input_lines)
  if (!length(delimiters)) {
    stop("unable to find yaml delimiters")
  } else if (length(delimiters) == 1L) {
    if (delimiters[1] == 1L) {
      stop("cannot find second delimiter, first is on line 1")
    } else {
      # found just one set, assume it is *closing* the yaml matter;
      # fake a preceding line of delimiter
      delimiters <- c(0L, delimiters[1])
    }
  }
  delimiters <- delimiters[1:2]
  yaml_list <- yaml::yaml.load(input_lines[ (delimiters[1]+1):(delimiters[2]-1) ])

  dots <- list(...)
  yaml_list <- c(yaml_list[ setdiff(names(yaml_list), names(dots)) ], dots)

  output_lines <- c(
    if (delimiters[1] > 0) input_lines[1:(delimiters[1])],
    strsplit(yaml::as.yaml(yaml_list), "\n")[[1]],
    input_lines[ -(1:(delimiters[2]-1)) ]
  )

  if (missing(output_file)) {
    return(output_lines)
  } else {
    writeLines(output_lines, con = output_file)
    return(invisible(output_lines))
  }
}

Where ... is whatever you want it to be. Meaning: if you want to replace the output: component of the yaml matter, then you give a named list as output=list(...).

If I use the rmarkdown document I used in a previous answer, then unchanged, it looks like this:

readLines("~/StackOverflow/1883604/62095186.Rmd")
#  [1] "---"
#  [2] "title: Hello"
#  [3] "output: html_document"
#  [4] "params:"
#  [5] "  intab: TRUE"
#  [6] "---"
#  [7] ""
#  [8] "# Headline 1"
#  [9] ""
# [10] "## Headline 2 `r if (params$intab) \"{.tabset}\"`"
# [11] ""
# [12] "### Headline 3 in a tab"
# [13] ""
# [14] "### Headline 4 in a tab"
# [15] ""
# [16] "### Headline 5 in a tab"
# [17] ""
# [18] ""

And to change the output portion, I add a nested named list as:

change_yaml_matter("~/StackOverflow/1883604/62095186.Rmd",
                   output=list(ioslides_presentation=list(widescreen=TRUE)))
#  [1] "---"
#  [2] "title: Hello"
#  [3] "params:"
#  [4] "  intab: yes"
#  [5] "output:"
#  [6] "  ioslides_presentation:"
#  [7] "    widescreen: yes"
#  [8] "---"
#  [9] ""
# [10] "# Headline 1"
# [11] ""
# [12] "## Headline 2 `r if (params$intab) \"{.tabset}\"`"
# [13] ""
# [14] "### Headline 3 in a tab"
# [15] ""
# [16] "### Headline 4 in a tab"
# [17] ""
# [18] "### Headline 5 in a tab"
# [19] ""
# [20] ""

You can change just about any portion of the yaml matter. (The only things you cannot change, I suspect, are if you happen to have yaml parameters named input_file or output_file. If you actually have Rmd files with those yaml top-level parameters, then you can easily rename the named arguments here to be something else, such as Mxyzptlk and something else ... you're unlikely to see those in production.)

Notes:

This did not save anything to a file, you have to do that yourself. Add output_file="path/to/new.RMd" to your call, and it will write a new file.

When you do include output_file= in the arguments, if you choose to not catch the return value, it will appear to return nothing. This is due to invisible in my return; if you really want to see and save, either capture to a variable and look at that, or wrap the function call in parens, as in (change_yaml_matter(...)).

The trick for YAML is to know that yaml:: will treat every top-level as the named element of a list, and its contents are recursively lists in the same manner. For instance,

str(yaml::yaml.load("
---
top1:
  level2a:
    level3a: 123
    level3b: 456
  level2b: 789
top2: quux
---"))
# List of 2
#  $ top1:List of 2
#   ..$ level2a:List of 2
#   .. ..$ level3a: int 123
#   .. ..$ level3b: int 456
#   ..$ level2b: int 789
#  $ top2: chr "quux"

To assign new values, just provide nested named lists.


问:
Column names using Oracle reserved word
Inside my database I have some tables that use a column with a reserved word name for example user, I have created it using " as "USER" but when I want to get it I have realized that I have to put it in capital letters, I have already investigated and I obtained that when placing " oracle respects it as case sensitive, they somehow know how to avoid this and obtain my column without the need for it to be written as defined, that is, case insensitive.
I am working Oracle with Firedac, on the Firedac side, do you know if something can be done so that this can be solved by having to put the column name as it is?</p>

答:
No.

You chose to have a column that conflicts with a reserved word, so you had to quote it when you declared it. You also need to quote this identifier everytime you use it - and a quoted identifier is case-sensitive by design.

I would strongly suggest avoiding having column names that conflict with SQL reserved word (or keywords). There is no benefit, and many drawbacks. You could just rename that column to usr, username, userid, or else. Declare the new name as a unquoted identifier, and you will never need to worry about this all afterwards.

Title: Column names using Oracle reserved word


问:
Retry a command only once : when a command fails (in bash)
```<code> for ( i=3; i<5; i++)

 do

   execute some command 1

   if command 2 is successful then do not run the command 1 (the for loop should continue)

   if command 2 is not successful then run command 1 only once (like retry command 1 only once, after this the for loop should continue)

done
</code>```

This is to note that command 2 is dependent on command 1 and command 2 can only be executed after command 1

for example:

```<code> for ( i=3; i<5; i++)
 do
    echo "i" >> mytext.txt   ---> command 1
    if "check the content of mytext.txt file to see if the value of i is  actually added" ---> command 2
    if it is not added then execute echo "i" >> mytext.txt (command 1) again and only once.
    if i value is added to the file .. then exit and continue the loop
  done
</code>```

Since the "command 1" is quite big and not just an example echo statement here.I do not want to add "command 1" twice .. once outside and once inside the if condition. I want this logic in an optimized way with no redundancy of code.

答:
Per a comment it sounds like the OP may need to invoke command 1 up to 2 times for a given $i value, but only wants to type command 1 once in the script.

Siddhartha's suggestion to use a function is probably good enough but depending on the actual command 1 (OP mentions that it's 'quite big') I'm going to play devil's advocate and assume there could be additional issues with passing some args to the function (eg, a need to escape some characters ... ??).

The general idea is to have an internal loop that can be executed at most 2 times, with logic in the loop that will allow for an 'early' exit (eg, after just one pass through the loop).

Since we're using pseudo-code I'll use the same ...

```<code>for ( i=3; i<5; i++ )
do
    pass=1                                    # reset internal loop counter

    while ( pass -le 2 )
    do
        echo "i" >> mytext.txt                # command 1

        if ( pass -eq 1 )                     # after first 'command 1' execution
        && ( value of 'i' is in mytext.txt )  # command 2
        then
            break                             # break out of inner loop; alternatively ...
        #   pass=10                           # ensure pass >= 2 to force loop to exit on this pass
        fi

        pass=pass+1                           # on 1st pass set pass=2 => allows another pass through loop
                                              # on 2nd pass set pass=3 => will force loop to exit
    done
done
</code>```

Body:
 for ( i=3; i<5; i++)

 do

   execute some command 1

   if command 2 is successful then do not run the command 1 (the for loop should continue)

   if command 2 is not successful then run command 1 only once (like retry command 1 only once, after this the for loop should continue)

done

This is to note that command 2 is dependent on command 1 and command 2 can only be executed after command 1

for example:

 for ( i=3; i<5; i++)
 do
    echo "i" >> mytext.txt   ---> command 1
    if "check the content of mytext.txt file to see if the value of i is  actually added" ---> command 2
    if it is not added then execute echo "i" >> mytext.txt (command 1) again and only once.
    if i value is added to the file .. then exit and continue the loop
  done

Since the "command 1" is quite big and not just an example echo statement here.I do not want to add "command 1" twice .. once outside and once inside the if condition. I want this logic in an optimized way with no redundancy of code.

Body:
Per a comment it sounds like the OP may need to invoke command 1 up to 2 times for a given $i value, but only wants to type command 1 once in the script.

Siddhartha's suggestion to use a function is probably good enough but depending on the actual command 1 (OP mentions that it's 'quite big') I'm going to play devil's advocate and assume there could be additional issues with passing some args to the function (eg, a need to escape some characters ... ??).

The general idea is to have an internal loop that can be executed at most 2 times, with logic in the loop that will allow for an 'early' exit (eg, after just one pass through the loop).

Since we're using pseudo-code I'll use the same ...

for ( i=3; i<5; i++ )
do
    pass=1                                    # reset internal loop counter

    while ( pass -le 2 )
    do
        echo "i" >> mytext.txt                # command 1

        if ( pass -eq 1 )                     # after first 'command 1' execution
        && ( value of 'i' is in mytext.txt )  # command 2
        then
            break                             # break out of inner loop; alternatively ...
        #   pass=10                           # ensure pass >= 2 to force loop to exit on this pass
        fi

        pass=pass+1                           # on 1st pass set pass=2 => allows another pass through loop
                                              # on 2nd pass set pass=3 => will force loop to exit
    done
done


问:
MongoParseError: URI does not have hostname, domain name and tld
I'm getting this error when I try to connect my app(nodejs) to mongodb. I really appreciate your help here.

```<code>MongoParseError: URI does not have hostname, domain name and tld
    at parseSrvConnectionString (E:\Projects\NodeAPI\node_modules\mongodb-core\lib\uri_parser.js:41:21)
    at parseConnectionString (E:\Projects\NodeAPI\node_modules\mongodb-core\lib\uri_parser.js:509:12)
    at connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\operations\mongo_client_ops.js:195:3)
    at connectOp (E:\Projects\NodeAPI\node_modules\mongodb\lib\operations\mongo_client_ops.js:284:3)
    at executeOperation (E:\Projects\NodeAPI\node_modules\mongodb\lib\utils.js:416:24)
    at MongoClient.connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\mongo_client.js:175:10)
    at Function.MongoClient.connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\mongo_client.js:341:22)
    at Object.<anonymous> (E:\Projects\NodeAPI\server.js:12:13)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
  name: 'MongoParseError',
  [Symbol(mongoErrorContextSymbol)]: {} }
</code>```

My code:

db.js

```<code> module.exports = {
uri : "mongodb+srv://mithun:*******@cluster0-s089x.mongodb.net/test?retryWrites=true"}
</code>```

==================================================================

node_route.js

```<code> module.exports = function(app, db){
app.post('/notes', (req, res) => {
    const note = {text: req.body.body, title: req.body.title};
    db.collection('notes').insert(note, (err, results) => {
        if(err){
            res.send({'error': 'An error has occured'});
        } else {
            res.send(result.ops[0]);
        }
    });
 });
 };
</code>```

=======================================================================
index.js

```<code> const noteRoutes = require('./note_route');
 module.exports = function(app, db){
 noteRoutes(app, db);
}
</code>```

=========================================================================
server.js

```<code>       const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
 app.use(bodyParser.urlencoded({extended: true}));
  MongoClient.connect(db.uri,{ useNewUrlParser: true }, (err, database) =>
  {
     if (err) return console.log(err);
     require('./app/routes')(app, database);
      app.listen(port, () => {
           console.log("We are live on " +port);
  });
 });
</code>```

===========================================================================

```<code>module.exports = {
uri : "mongodb+srv://mithun:m3Thun#47@cluster0-s089x.mongodb.net/test?retryWrites=true&ssl=false"
</code>```

}

I've tried with ssl= false but the error remains same.

答:
I also faced this problem.

In my case, I was using npm dotenv package to get the username the password from a .env file.

When I logged the values from the .env file, I noticed it was not retrieving the password correctly.

It could be an issue with either the username or password.

Body:
I'm getting this error when I try to connect my app(nodejs) to mongodb. I really appreciate your help here.

MongoParseError: URI does not have hostname, domain name and tld
    at parseSrvConnectionString (E:\Projects\NodeAPI\node_modules\mongodb-core\lib\uri_parser.js:41:21)
    at parseConnectionString (E:\Projects\NodeAPI\node_modules\mongodb-core\lib\uri_parser.js:509:12)
    at connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\operations\mongo_client_ops.js:195:3)
    at connectOp (E:\Projects\NodeAPI\node_modules\mongodb\lib\operations\mongo_client_ops.js:284:3)
    at executeOperation (E:\Projects\NodeAPI\node_modules\mongodb\lib\utils.js:416:24)
    at MongoClient.connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\mongo_client.js:175:10)
    at Function.MongoClient.connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\mongo_client.js:341:22)
    at Object.<anonymous> (E:\Projects\NodeAPI\server.js:12:13)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
  name: 'MongoParseError',
  [Symbol(mongoErrorContextSymbol)]: {} }

My code:

db.js

 module.exports = {
uri : "mongodb+srv://mithun:*******@cluster0-s089x.mongodb.net/test?retryWrites=true"}

==================================================================

node_route.js

 module.exports = function(app, db){
app.post('/notes', (req, res) => {
    const note = {text: req.body.body, title: req.body.title};
    db.collection('notes').insert(note, (err, results) => {
        if(err){
            res.send({'error': 'An error has occured'});
        } else {
            res.send(result.ops[0]);
        }
    });
 });
 };

=======================================================================
index.js

 const noteRoutes = require('./note_route');
 module.exports = function(app, db){
 noteRoutes(app, db);
}

=========================================================================
server.js

       const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
 app.use(bodyParser.urlencoded({extended: true}));
  MongoClient.connect(db.uri,{ useNewUrlParser: true }, (err, database) =>
  {
     if (err) return console.log(err);
     require('./app/routes')(app, database);
      app.listen(port, () => {
           console.log("We are live on " +port);
  });
 });

===========================================================================

module.exports = {
uri : "mongodb+srv://mithun:m3Thun#47@cluster0-s089x.mongodb.net/test?retryWrites=true&ssl=false"

}

I've tried with ssl= false but the error remains same.


问:
How to create a file's path inside "~"
I have an issue with Capistrano where File.readlines and File.foreach claim a file doesn't exist, but it does. When the error occurs, I can copy the error returned and cat or nano the file correctly.

if File.readlines("#{fetch(:application)}/.git/config").grep(/#{fetch(:old_repo_url)}/).size > 0
```

<p>This outputs something like:</p>

```Errno::ENOENT: No such file or directory @ rb_sysopen - ~/Develop/homestead/code/projectname/.git/config
```

<p>I can copy that and the location though and it <em>does</em> exist. Can it not read it because there's no file extension? </p>

<p>If I can't grep a git config file, is there maybe some other way to check if the git config currently contains the old repo URL variable?</p>

<p>If I could save the output of:</p>

```execute "cd #{fetch(:homestead_path)}/#{fetch(:application)}; git remote get-url origin"
```

to a variable, even to check, that would be great.

答:
This isn't a Capistrano issue.

In a path being processed by the shell ~ is expanded to the full path to your $HOME.

Ruby doesn't know what that would be, and assumes that ~ is a literal directory name, tries to open the file and it fails because ~ doesn't exist.

And, when you copy and test it from the shell, again, it expands ~ and you're convinced Ruby is wrong.

Fixing it is easy:

```<code>File.expand_path('~/.vimrc')   #=> "/Users/ttm/.vimrc"
</code>```

Whatever is my current working directory will be used for relative files:

```<code>File.expand_path('.') #=> "/Users/ttm"
File.expand_path('..') #=> "/Users"
</code>```

The File class has several methods like expand_path that are used to expand and convert paths. I'd suggest studying the documentation as they've very powerful and quite useful.

Title: How to create a file's path inside "~"

Body:
I have an issue with Capistrano where File.readlines and File.foreach claim a file doesn't exist, but it does. When the error occurs, I can copy the error returned and cat or nano the file correctly.

if File.readlines("#{fetch(:application)}/.git/config").grep(/#{fetch(:old_repo_url)}/).size > 0

This outputs something like:

Errno::ENOENT: No such file or directory @ rb_sysopen - ~/Develop/homestead/code/projectname/.git/config

I can copy that and the location though and it does exist. Can it not read it because there's no file extension?

If I can't grep a git config file, is there maybe some other way to check if the git config currently contains the old repo URL variable?

If I could save the output of:

execute "cd #{fetch(:homestead_path)}/#{fetch(:application)}; git remote get-url origin"

to a variable, even to check, that would be great.

Body:
This isn't a Capistrano issue.

In a path being processed by the shell ~ is expanded to the full path to your $HOME.

Ruby doesn't know what that would be, and assumes that ~ is a literal directory name, tries to open the file and it fails because ~ doesn't exist.

And, when you copy and test it from the shell, again, it expands ~ and you're convinced Ruby is wrong.

Fixing it is easy:

File.expand_path('~/.vimrc')   #=> "/Users/ttm/.vimrc"

Whatever is my current working directory will be used for relative files:

File.expand_path('.') #=> "/Users/ttm"
File.expand_path('..') #=> "/Users"

The File class has several methods like expand_path that are used to expand and convert paths. I'd suggest studying the documentation as they've very powerful and quite useful.


问:
Biggest and smallest of four integers (No arrays, no functions, fewest 'if' statements)
You see, I've self-taught myself C++ (not completely, I'm still procrastinating -_-). So, now I started university and they're teaching C and they made us do a program of inputting four integers and we have to tell the largest and smallest out of them. Simple, no?

The thing is, I already have good understanding of functions and arrays. Yes, I CAN program this in arrays, no problem. But since this was the first lab, we haven't 'learned' that yet, so I can't use any of those, it'd be very simple with that.

This is what I wrote there (it feels wrong somehow).

```<code>#include<stdio.h>

int main(void)
{
    int first, second, third, fourth;
    printf("Enter four integers (separated by space): ");
    scanf("%d %d %d %d", &first, &second, &third, &fourth);

    if((first>second) && (first>third) && (first>fourth))
        printf("\nFirst number is largest");
    else if((second>first) && (second>third) && (second>fourth))
        printf("\nSecond number is largest");
    else if((third>second) && (third>first) && (third>fourth))
        printf("\nThird number is largest");
    else if((fourth>second) && (fourth>third) && (fourth>first))
        printf("\nFourth number is largest");

    if((first<second) && (first<third) && (first<fourth))
        printf("\nFirst number is smallest");
    else if((second<first) && (second<third) && (second<fourth))
        printf("\nSecond number is smallest");
    else if((third<second) && (third<first) && (third<fourth))
        printf("\nThird number is smallest");
    else if((fourth<second) && (fourth<third) && (fourth<first))
        printf("\nFourth number is smallest");

    printf("\n");
    return 0;
}
</code>```

As you can see, it's too long and boring and complex. But seeing that all we've covered in class for now are loops and decision statements. Is there a more elegant way of doing this? One which uses fewer ifs? Not that there is something wrong with this, but it could be better.

P.S. This isn't exactly 'homework' or anything. I made a program, I just wanted to know what I could have done to make it better and to learn better programming practices.

答:
We can make use of condition statements here.</p>

```<code>int max,max1,max2,min,min1,min2;
max = (max1 = a>b?a:b)>(max2 = c>d?c:d)?max1:max2 ;
min = (min1 = a<b?a:b)<(min2 = c<d?c:d)?min1:min2 ;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You see, I've self-taught myself C++ (not completely, I'm still procrastinating -_-). So, now I started university and they're teaching C and they made us do a program of inputting four integers and we have to tell the largest and smallest out of them. Simple, no?

The thing is, I already have good understanding of functions and arrays. Yes, I CAN program this in arrays, no problem. But since this was the first lab, we haven't 'learned' that yet, so I can't use any of those, it'd be very simple with that.

This is what I wrote there (it feels wrong somehow).

#include<stdio.h>

int main(void)
{
    int first, second, third, fourth;
    printf("Enter four integers (separated by space): ");
    scanf("%d %d %d %d", &first, &second, &third, &fourth);

    if((first>second) && (first>third) && (first>fourth))
        printf("\nFirst number is largest");
    else if((second>first) && (second>third) && (second>fourth))
        printf("\nSecond number is largest");
    else if((third>second) && (third>first) && (third>fourth))
        printf("\nThird number is largest");
    else if((fourth>second) && (fourth>third) && (fourth>first))
        printf("\nFourth number is largest");

    if((first<second) && (first<third) && (first<fourth))
        printf("\nFirst number is smallest");
    else if((second<first) && (second<third) && (second<fourth))
        printf("\nSecond number is smallest");
    else if((third<second) && (third<first) && (third<fourth))
        printf("\nThird number is smallest");
    else if((fourth<second) && (fourth<third) && (fourth<first))
        printf("\nFourth number is smallest");

    printf("\n");
    return 0;
}

As you can see, it's too long and boring and complex. But seeing that all we've covered in class for now are loops and decision statements. Is there a more elegant way of doing this? One which uses fewer ifs? Not that there is something wrong with this, but it could be better.

P.S. This isn't exactly 'homework' or anything. I made a program, I just wanted to know what I could have done to make it better and to learn better programming practices.

Body:
We can make use of condition statements here.

int max,max1,max2,min,min1,min2;
max = (max1 = a>b?a:b)>(max2 = c>d?c:d)?max1:max2 ;
min = (min1 = a<b?a:b)<(min2 = c<d?c:d)?min1:min2 ;


问:
How to count the comparisons made in Quick Sort
So I have a fully written and working code for quick sort but instead of returning the sorted list, I am trying to have it return the number of comparisons. I am not sure where I should put the counter to count the number of comparisons made. Any help is greatly appreciated!

def quickSort(alist):
   quickSortHelper(alist,0,len(alist)-1)

def quickSortHelper(alist,first,last):
   if first<last:

       splitpoint = partition(alist,first,last)

       quickSortHelper(alist,first,splitpoint-1)
       quickSortHelper(alist,splitpoint+1,last)

def partition(alist,first,last):
   pivotvalue = alist[first]

   leftmark = first+1
   rightmark = last

   done = False
   while not done:

       while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
           leftmark = leftmark + 1

       while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
           rightmark = rightmark -1

       if rightmark < leftmark:
           done = True
       else:
           temp = alist[leftmark]
           alist[leftmark] = alist[rightmark]
           alist[rightmark] = temp

   temp = alist[first]
   alist[first] = alist[rightmark]
   alist[rightmark] = temp

   return rightmark   #returns the sorted list
```

答:
Those two loops are the only places where you actually compare values from the array:

```<code>       while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
           leftmark = leftmark + 1

       while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
           rightmark = rightmark -1
</code>```

so you should add counter += 1 inside both loops. Remember to initialize the counter to 0 and to declare it as global.

BTW, leftmark = leftmark + 1 can be written as leftmark += 1
and this part:

```<code>           temp = alist[leftmark]
           alist[leftmark] = alist[rightmark]
           alist[rightmark] = temp
</code>```

doesn't require a temporary variable:

```<code>           alist[rightmark],alist[leftmark] = alist[leftmark],alist[rightmark]
</code>```

Body:
Those two loops are the only places where you actually compare values from the array:

       while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
           leftmark = leftmark + 1

       while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
           rightmark = rightmark -1

so you should add counter += 1 inside both loops. Remember to initialize the counter to 0 and to declare it as global.

BTW, leftmark = leftmark + 1 can be written as leftmark += 1
and this part:

           temp = alist[leftmark]
           alist[leftmark] = alist[rightmark]
           alist[rightmark] = temp

doesn't require a temporary variable:

           alist[rightmark],alist[leftmark] = alist[leftmark],alist[rightmark]


问:
How can I untar multiple tar files over ssh?
I am attempting to untar multiple tar files over ssh:

```<code>ssh user@hostname "cat /dir/file*.tgz" | tar xvzf -
</code>```

The above only works on the first file match on the remote server. The local (dest) server only receives one file. The wildcard has been verified to match multiple files though.

Is there another way to do this?

答:
(Edit after first try didn't work:)

Another idea, avoiding multiple ssh calls and also scp (since this needs at least one roundtrip between each file):

```<code>ssh user@hostname 'tar cf - /dir/file*.tgz' | tar xf - --to-command='tar xzvf -'
</code>```

We use one more tar call on the server side to wrap all the files together, a second tar call on the client side to unwrap them again, which will then be calling tar xzv for each entry once. This works similar to the base64-answer from sehe, but will be more efficient since it does not blow up the files.

Body:
I am attempting to untar multiple tar files over ssh:

ssh user@hostname "cat /dir/file*.tgz" | tar xvzf -

The above only works on the first file match on the remote server. The local (dest) server only receives one file. The wildcard has been verified to match multiple files though.

Is there another way to do this?

Body:
(Edit after first try didn't work:)

Another idea, avoiding multiple ssh calls and also scp (since this needs at least one roundtrip between each file):

ssh user@hostname 'tar cf - /dir/file*.tgz' | tar xf - --to-command='tar xzvf -'

We use one more tar call on the server side to wrap all the files together, a second tar call on the client side to unwrap them again, which will then be calling tar xzv for each entry once. This works similar to the base64-answer from sehe, but will be more efficient since it does not blow up the files.


问:
When using multiple databases with Spring Data JPA, No bean named "ConfigurationClassPostProcessor.importRegistry" exception occurs
In my spring boot(data) project, I am trying to set up and use multiple databases. One database is MySql and other database is H2. I defined custom JPA configurations as shown here. During application startup I get the exception

No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available exception occurs

I tried to follow the instructions from Baeldung blog.

Exception Log:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationAvailability' defined in class path resource [org/springframework/boot/autoconfigure/availability/ApplicationAvailabilityAutoConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' availableorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationAvailability' defined in class path resource [org/springframework/boot/autoconfigure/availability/ApplicationAvailabilityAutoConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:512) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:245) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:197) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:134) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.boot.availability.AvailabilityChangeEvent.publish(AvailabilityChangeEvent.java:81) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.availability.AvailabilityChangeEvent.publish(AvailabilityChangeEvent.java:67) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.doClose(ServletWebServerApplicationContext.java:167) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:978) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:814) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:325) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE] a
t org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at com.pj.multipledatabasesdemo.MultipleDatabasesDemoApplication.main(MultipleDatabasesDemoApplication.java:12) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.0.RELEASE.jar:2.3.0.RELEASE]

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:603) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:409) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:91) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:109) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at
org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator.java:92) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:101) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:251) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1141) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1114) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:506) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE] ... 23 common frames omitted

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:814) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1282) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:297) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor.postProcessBeforeInitialization(ConfigurationClassPostProcessor.java:456) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:416) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
</code>```

答:
Okay. This issue is caused by Redisson dependency that I use for cache. My primary database which is SQL server configured to use Redis as hibernate second level cache and second database(Oracle) is not. But for some reason second database also expecting Redisson configuration and throwing NullPointerException. Disabling cache on my second database fixed the issue

Note: The demo I added has MySql and H2 databases instead of SQL Server and Oracle databases

Body:
In my spring boot(data) project, I am trying to set up and use multiple databases. One database is MySql and other database is H2. I defined custom JPA configurations as shown here. During application startup I get the exception

No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available exception occurs

I tried to follow the instructions from Baeldung blog.

Exception Log:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationAvailability' defined in class path resource [org/springframework/boot/autoconfigure/availability/ApplicationAvailabilityAutoConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' availableorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationAvailability' defined in class path resource [org/springframework/boot/autoconfigure/availability/ApplicationAvailabilityAutoConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:512) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:245) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:197) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:134) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.boot.availability.AvailabilityChangeEvent.publish(AvailabilityChangeEvent.java:81) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.availability.AvailabilityChangeEvent.publish(AvailabilityChangeEvent.java:67) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.doClose(ServletWebServerApplicationContext.java:167) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:978) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:814) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:325) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE] a
t org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at com.pj.multipledatabasesdemo.MultipleDatabasesDemoApplication.main(MultipleDatabasesDemoApplication.java:12) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.0.RELEASE.jar:2.3.0.RELEASE]

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:603) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:409) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:91) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:109) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at
org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator.java:92) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:101) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:251) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1141) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1114) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:506) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE] ... 23 common frames omitted

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:814) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1282) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:297) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor.postProcessBeforeInitialization(ConfigurationClassPostProcessor.java:456) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:416) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]


问:
c++ Segmentation fault printing an unsigned char
I'm getting Segmentation Fault when trying to print a buffer that was filled up by a function:

```<code>    int ret = 0;
    unsigned char plaintext;

    /* ret will contain the length of the "plaintext" output buffer */
    ret = gcm_decrypt( &ciphertext[0], ciphertext_len, &aad[0], aad_len, &tag[0], (unsigned char*)decoded_key.c_str(), &iv[0], iv_len, &plaintext );

    /* This will segfault BUT it actually prints out the correct data */
    std::string sName(reinterpret_cast<char*>(&plaintext)
    cout << "ret: " << ret << endl;
    cout << "plaintext: " << sName << endl;
</code>```

I've tried many things to get a std::string from that plaintext buffer, but i can't figure it out.

the function requires an unsigned char *

```<code>int gcm_decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad, int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv, int iv_len, unsigned char *plaintext)
</code>```

答:
Following @drescherjm advice, i updated it to:

The end code is

```<code>int main(void)
{
    std::string key_encoded = "DgvkCrkyBNSy9yHP1Yznyc2DkHTIUXaO6NlEw4CSq0E=";
    std::string decoded_key = base64_decode(key_encoded);

    std::string token_encoded = "rj_ZkkZUOZMxZOfOmLpEUB3siU7u6RjZFeM9s-gb_xCR56WFKFAJiMyF2T6CBRmlh_Sy0i_lfyT9AI8sEif8MTIIszyzSl_aDnG48aO50yaHGuRSYbUbSYm9WIiQ0g==";
    std::string token_decoded_tmp = base64_decode( token_encoded );
    std::string token_decoded( token_decoded_tmp.begin()+32, token_decoded_tmp.end() );
    int ciphertext_len = token_decoded.size();

    std::string aad = "xxxxxxxxxxxxxxx";
    int aad_len = aad.size();

    std::string tag( token_decoded_tmp.begin()+16, token_decoded_tmp.end()+32 );
    std::string iv( token_decoded_tmp.begin(), token_decoded_tmp.begin()+16 );
    int iv_len = iv.size();

    int ret = 0;
    unsigned char plaintext[1024];
    ret = gcm_decrypt(
        (unsigned char*)token_decoded.c_str(),
        ciphertext_len,
        (unsigned char*)aad.c_str(),
        aad_len,
        (unsigned char*)tag.c_str(),
        (unsigned char*)decoded_key.c_str(),
        (unsigned char*)iv.c_str(),
        iv_len,
        plaintext
    );
    cout << "ret: " << ret << endl;
    cout << "plaintext: <" << plaintext << ">" << endl;

    return 0;
}
</code>```

And it's perfect now. Thanks!

@drescherjm i can't mark your answer as the right one.

Body:
I'm getting Segmentation Fault when trying to print a buffer that was filled up by a function:

    int ret = 0;
    unsigned char plaintext;

    /* ret will contain the length of the "plaintext" output buffer */
    ret = gcm_decrypt( &ciphertext[0], ciphertext_len, &aad[0], aad_len, &tag[0], (unsigned char*)decoded_key.c_str(), &iv[0], iv_len, &plaintext );

    /* This will segfault BUT it actually prints out the correct data */
    std::string sName(reinterpret_cast<char*>(&plaintext)
    cout << "ret: " << ret << endl;
    cout << "plaintext: " << sName << endl;

I've tried many things to get a std::string from that plaintext buffer, but i can't figure it out.

the function requires an unsigned char *

int gcm_decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad, int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv, int iv_len, unsigned char *plaintext)

Body:
Following @drescherjm advice, i updated it to:

The end code is

int main(void)
{
    std::string key_encoded = "DgvkCrkyBNSy9yHP1Yznyc2DkHTIUXaO6NlEw4CSq0E=";
    std::string decoded_key = base64_decode(key_encoded);

    std::string token_encoded = "rj_ZkkZUOZMxZOfOmLpEUB3siU7u6RjZFeM9s-gb_xCR56WFKFAJiMyF2T6CBRmlh_Sy0i_lfyT9AI8sEif8MTIIszyzSl_aDnG48aO50yaHGuRSYbUbSYm9WIiQ0g==";
    std::string token_decoded_tmp = base64_decode( token_encoded );
    std::string token_decoded( token_decoded_tmp.begin()+32, token_decoded_tmp.end() );
    int ciphertext_len = token_decoded.size();

    std::string aad = "xxxxxxxxxxxxxxx";
    int aad_len = aad.size();

    std::string tag( token_decoded_tmp.begin()+16, token_decoded_tmp.end()+32 );
    std::string iv( token_decoded_tmp.begin(), token_decoded_tmp.begin()+16 );
    int iv_len = iv.size();

    int ret = 0;
    unsigned char plaintext[1024];
    ret = gcm_decrypt(
        (unsigned char*)token_decoded.c_str(),
        ciphertext_len,
        (unsigned char*)aad.c_str(),
        aad_len,
        (unsigned char*)tag.c_str(),
        (unsigned char*)decoded_key.c_str(),
        (unsigned char*)iv.c_str(),
        iv_len,
        plaintext
    );
    cout << "ret: " << ret << endl;
    cout << "plaintext: <" << plaintext << ">" << endl;

    return 0;
}

And it's perfect now. Thanks!

@drescherjm i can't mark your answer as the right one.


问:
Can I make dataframes by for loop?
I want to make each 10 dataframes using a for loop.

But it just keeps being overwritten.

How can I make each dataframe using for loop?

```<code>for i in range(10):
    df = pd.DataFrame({'name' : list_name,
                       'year' : list_year,
                       'point' : list_point})
</code>```

答:
You can't define 10 separate dataframes that each have their own variable names, in any kind of loop.

What you can do though is instantiate something like a list of dataframes, which you can freely add to with a loop.

dfs = []
for _ in range(10):
    dfs.append(pd.Dataframe....)
```

Title: Can I make dataframes by for loop?

Body:
I want to make each 10 dataframes using a for loop.

But it just keeps being overwritten.

How can I make each dataframe using for loop?

for i in range(10):
    df = pd.DataFrame({'name' : list_name,
                       'year' : list_year,
                       'point' : list_point})


问:
brew install mariadb fails as system can not chown for auth_pam_tool

brew

brew install not work. this is the log.

```<code>% brew install mariadb
==> Downloading https://homebrew.bintray.com/bottles/mariadb-10.4.13.mojave.bottle.tar.gz
Already downloaded: /Users/shingo/Library/Caches/Homebrew/downloads/d56104142081a8230646ac3f245adf2414e515cd5f2aeeb0637614e9966e882c--mariadb-10.4.13.mojave.bottle.tar.gz
==> Pouring mariadb-10.4.13.mojave.bottle.tar.gz
==> /usr/local/Cellar/mariadb/10.4.13/bin/mysql_install_db --verbose --user=shingo --basedir=/usr/local/Cellar/mariadb/10.4.13 --datadir=/usr/local/var/mysql --tmpdir=/tmp
Last 15 lines from /Users/shingo/Library/Logs/Homebrew/mariadb/post_install.01.mysql_install_db:

    shell> /usr/local/Cellar/mariadb/10.4.13/bin/mysql -u root mysql
    mysql> show tables;

Try 'mysqld --help' if you have problems with paths.  Using
--general-log gives you a log in /usr/local/var/mysql that may be helpful.

The latest information about mysql_install_db is available at
https://mariadb.com/kb/en/installing-system-tables-mysql_install_db
You can find the latest source at https://downloads.mariadb.org and
the maria-discuss email list at https://launchpad.net/~maria-discuss

Please check all of the above before submitting a bug report
at http://mariadb.org/jira

Warning: The post-install step did not complete successfully
You can try again using `brew postinstall mariadb`
==> Caveats
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.

MySQL is configured to only allow connections from localhost by default

To start mariadb:
  brew services start mariadb
Or, if you don't want/need a background service you can just run:
  mysql.server start
==> Summary
  /usr/local/Cellar/mariadb/10.4.13: 744 files, 169.9MB
</code>```

I have tried to execute mysql_install_db

I have tried to execute mysql_install_db without brew. this is the log.
The brew displays only the last 15 lines, so I can't help it.

```<code>% /usr/local/Cellar/mariadb/10.4.13/bin/mysql_install_db --verbose --user=shingo --basedir=/usr/local/Cellar/mariadb/10.4.13 --datadir=/usr/local/var/mysql --tmpdir=/tmp
chown: /usr/local/Cellar/mariadb/10.4.13/lib/plugin/auth_pam_tool_dir/auth_pam_tool: Operation not permitted
Couldn't set an owner to '/usr/local/Cellar/mariadb/10.4.13/lib/plugin/auth_pam_tool_dir/auth_pam_tool'.
It must be root, the PAM authentication plugin doesn't work otherwise..

Installing MariaDB/MySQL system tables in '/usr/local/var/mysql' ...
2020-05-29 22:13:03 0 [Note] /usr/local/Cellar/mariadb/10.4.13/bin/mysqld (mysqld 10.4.13-MariaDB) starting as process 45440 ...
2020-05-29 22:13:03 0 [ERROR] /usr/local/Cellar/mariadb/10.4.13/bin/mysqld: option '--innodb-large-prefix' requires an argument
2020-05-29 22:13:03 0 [ERROR] Parsing options for plugin 'InnoDB' failed.
2020-05-29 22:13:03 0 [ERROR] /usr/local/Cellar/mariadb/10.4.13/bin/mysqld: unknown variable 'mysqlx-bind-address=127.0.0.1'
2020-05-29 22:13:03 0 [ERROR] Aborting

Installation of system tables failed!  Examine the logs in
/usr/local/var/mysql for more information.

The problem could be conflicting information in an external
my.cnf files. You can ignore these by doing:

    shell> /usr/local/Cellar/mariadb/10.4.13/bin/mysql_install_db --defaults-file=~/.my.cnf

You can also try to start the mysqld daemon with:

    shell> /usr/local/Cellar/mariadb/10.4.13/bin/mysqld --skip-grant-tables --general-log &

and use the command line tool /usr/local/Cellar/mariadb/10.4.13/bin/mysql
to connect to the mysql database and look at the grant tables:

    shell> /usr/local/Cellar/mariadb/10.4.13/bin/mysql -u root mysql
    mysql> show tables;

Try 'mysqld --help' if you have problems with paths.  Using
--general-log gives you a log in /usr/local/var/mysql that may be helpful.

The latest information about mysql_install_db is available at
https://mariadb.com/kb/en/installing-system-tables-mysql_install_db
You can find the latest source at https://downloads.mariadb.org and
the maria-discuss email list at https://launchpad.net/~maria-discuss

Please check all of the above before submitting a bug report
at http://mariadb.org/jira
</code>```

I noticed that the system can not chown for auth_pam_tool because Operation not permitted.

auth_pam_tool permission

this is my permission the directory.

```<code>% ls -l /usr/local/Cellar/mariadb/10.4.13/lib/plugin/auth_pam_tool_dir/auth_pam_tool
-r-xr-xr-x  1 shingo  staff  13608  5 10 04:28 /usr/local/Cellar/mariadb/10.4.13/lib/plugin/auth_pam_tool_dir/auth_pam_tool
</code>```

How to fix Operation not permitted?

Or is there any other reason why it cannot be installed?

答:
Self resolved.

Anyway I gave it try start

Even though the installation was not successful, anyway I gave it try % mysql.server start.

A error log file was created.

A error log file was created by starting mysql server.

the error log shows:

```<code>2020-05-30  8:47:10 0 [Warning] InnoDB: innodb_open_files 300 should not be greater than the open_files_limit 256
2020-05-30  8:47:10 0 [ERROR] /usr/local/Cellar/mariadb/10.4.13/bin/mysqld: unknown variable 'mysqlx-bind-address=127.0.0.1'
2020-05-30  8:47:10 0 [ERROR] Aborting
</code>```

An unknown value in the mysqlx-bind-address seems to be causing the error.

How to fix unknown variable

I found
the same error question. This question discussed a my.conf file.

~/.my.conf did not exist on my mac

/etc/my.conf did not exist on my mac

this question teach me the my.conf location.

Finally I found my.conf in /usr/local/etc/my.cnf.Certainly the settings for mysqlx-bind-address were written in my.conf.

So rm /usr/local/etc/my.cnf, then brew reinstall SUCCESS!.

The permission was irrelevant at all.

Body:
brew

brew install not work. this is the log.

% brew install mariadb
==> Downloading https://homebrew.bintray.com/bottles/mariadb-10.4.13.mojave.bottle.tar.gz
Already downloaded: /Users/shingo/Library/Caches/Homebrew/downloads/d56104142081a8230646ac3f245adf2414e515cd5f2aeeb0637614e9966e882c--mariadb-10.4.13.mojave.bottle.tar.gz
==> Pouring mariadb-10.4.13.mojave.bottle.tar.gz
==> /usr/local/Cellar/mariadb/10.4.13/bin/mysql_install_db --verbose --user=shingo --basedir=/usr/local/Cellar/mariadb/10.4.13 --datadir=/usr/local/var/mysql --tmpdir=/tmp
Last 15 lines from /Users/shingo/Library/Logs/Homebrew/mariadb/post_install.01.mysql_install_db:

    shell> /usr/local/Cellar/mariadb/10.4.13/bin/mysql -u root mysql
    mysql> show tables;

Try 'mysqld --help' if you have problems with paths.  Using
--general-log gives you a log in /usr/local/var/mysql that may be helpful.

The latest information about mysql_install_db is available at
https://mariadb.com/kb/en/installing-system-tables-mysql_install_db
You can find the latest source at https://downloads.mariadb.org and
the maria-discuss email list at https://launchpad.net/~maria-discuss

Please check all of the above before submitting a bug report
at http://mariadb.org/jira

Warning: The post-install step did not complete successfully
You can try again using `brew postinstall mariadb`
==> Caveats
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.

MySQL is configured to only allow connections from localhost by default

To start mariadb:
  brew services start mariadb
Or, if you don't want/need a background service you can just run:
  mysql.server start
==> Summary
  /usr/local/Cellar/mariadb/10.4.13: 744 files, 169.9MB

I have tried to execute mysql_install_db

I have tried to execute mysql_install_db without brew. this is the log.
The brew displays only the last 15 lines, so I can't help it.

% /usr/local/Cellar/mariadb/10.4.13/bin/mysql_install_db --verbose --user=shingo --basedir=/usr/local/Cellar/mariadb/10.4.13 --datadir=/usr/local/var/mysql --tmpdir=/tmp
chown: /usr/local/Cellar/mariadb/10.4.13/lib/plugin/auth_pam_tool_dir/auth_pam_tool: Operation not permitted
Couldn't set an owner to '/usr/local/Cellar/mariadb/10.4.13/lib/plugin/auth_pam_tool_dir/auth_pam_tool'.
It must be root, the PAM authentication plugin doesn't work otherwise..

Installing MariaDB/MySQL system tables in '/usr/local/var/mysql' ...
2020-05-29 22:13:03 0 [Note] /usr/local/Cellar/mariadb/10.4.13/bin/mysqld (mysqld 10.4.13-MariaDB) starting as process 45440 ...
2020-05-29 22:13:03 0 [ERROR] /usr/local/Cellar/mariadb/10.4.13/bin/mysqld: option '--innodb-large-prefix' requires an argument
2020-05-29 22:13:03 0 [ERROR] Parsing options for plugin 'InnoDB' failed.
2020-05-29 22:13:03 0 [ERROR] /usr/local/Cellar/mariadb/10.4.13/bin/mysqld: unknown variable 'mysqlx-bind-address=127.0.0.1'
2020-05-29 22:13:03 0 [ERROR] Aborting

Installation of system tables failed!  Examine the logs in
/usr/local/var/mysql for more information.

The problem could be conflicting information in an external
my.cnf files. You can ignore these by doing:

    shell> /usr/local/Cellar/mariadb/10.4.13/bin/mysql_install_db --defaults-file=~/.my.cnf

You can also try to start the mysqld daemon with:

    shell> /usr/local/Cellar/mariadb/10.4.13/bin/mysqld --skip-grant-tables --general-log &

and use the command line tool /usr/local/Cellar/mariadb/10.4.13/bin/mysql
to connect to the mysql database and look at the grant tables:

    shell> /usr/local/Cellar/mariadb/10.4.13/bin/mysql -u root mysql
    mysql> show tables;

Try 'mysqld --help' if you have problems with paths.  Using
--general-log gives you a log in /usr/local/var/mysql that may be helpful.

The latest information about mysql_install_db is available at
https://mariadb.com/kb/en/installing-system-tables-mysql_install_db
You can find the latest source at https://downloads.mariadb.org and
the maria-discuss email list at https://launchpad.net/~maria-discuss

Please check all of the above before submitting a bug report
at http://mariadb.org/jira

I noticed that the system can not chown for auth_pam_tool because Operation not permitted.

auth_pam_tool permission

this is my permission the directory.

% ls -l /usr/local/Cellar/mariadb/10.4.13/lib/plugin/auth_pam_tool_dir/auth_pam_tool
-r-xr-xr-x  1 shingo  staff  13608  5 10 04:28 /usr/local/Cellar/mariadb/10.4.13/lib/plugin/auth_pam_tool_dir/auth_pam_tool

How to fix Operation not permitted?

Or is there any other reason why it cannot be installed?

Body:
Self resolved.

Anyway I gave it try start

Even though the installation was not successful, anyway I gave it try % mysql.server start.

A error log file was created.

A error log file was created by starting mysql server.

the error log shows:

2020-05-30  8:47:10 0 [Warning] InnoDB: innodb_open_files 300 should not be greater than the open_files_limit 256
2020-05-30  8:47:10 0 [ERROR] /usr/local/Cellar/mariadb/10.4.13/bin/mysqld: unknown variable 'mysqlx-bind-address=127.0.0.1'
2020-05-30  8:47:10 0 [ERROR] Aborting

An unknown value in the mysqlx-bind-address seems to be causing the error.

How to fix unknown variable

I found
the same error question. This question discussed a my.conf file.

~/.my.conf did not exist on my mac

/etc/my.conf did not exist on my mac

this question teach me the my.conf location.

Finally I found my.conf in /usr/local/etc/my.cnf.Certainly the settings for mysqlx-bind-address were written in my.conf.

So rm /usr/local/etc/my.cnf, then brew reinstall SUCCESS!.

The permission was irrelevant at all.