问:
Get error when load tfrecord file in tensorflow 2.0
I'm trying to converting WAV files into TFRecord shards

In the code below, i use tf.audio.decode_wav to get an audio signal from wav file, label is an index list of sentence.

Then i save all wav file and label into train.tfrecord and split it

```<code>   def _write_tfrecord_file(self, shard_data):

        shard_path, indices = shard_data
        with tf.io.TFRecordWriter(shard_path, options='ZLIB') as out:
            for index in indices:
                file_path = self.data_dir + self.df['Filename'][index] + ".wav"
                label = str2index(self.df['Text'][index])

                raw_audio = tf.io.read_file(file_path)
                audio, sample_rate = tf.audio.decode_wav(
                    raw_audio,
                    desired_channels=1,  # mono
                    desired_samples=self.sample_rate * self.duration)

                example = tf.train.Example(features=tf.train.Features(feature={
                    'audio': _float_feature(audio.numpy().flatten().tolist()),
                    'label': _int64_feature(label)}))

                out.write(example.SerializeToString())
</code>```

Then, i write a function to load

```<code>def _parse_batch(record_batch, sample_rate, duration):

    n_sample = sample_rate * duration

    feature_description = {
        'audio': tf.io.FixedLenFeature([n_sample], tf.float32),
        'label': tf.io.FixedLenFeature([], tf.int64)
    }

    example = tf.io.parse_example(record_batch, feature_description)

    return example['audio'], example['label']

def get_dataset_from_tfrecords(tfrecords_dir='tfrecords', split='train', batch_size=16, sample_rate=44100, duration=5,
                               n_epochs=10):
    if split not in ('train', 'validate'):
        raise ValueError("Split must be either 'train' or 'validate'")

    pattern = os.path.join(tfrecords_dir, '{}*.tfrecord'.format(split))

    files_ds = tf.data.Dataset.list_files(pattern)

    ignore_order = tf.data.Options()
    ignore_order.experimental_deterministic = False
    files_ds = files_ds.with_options(ignore_order)

    ds = tf.data.TFRecordDataset(files_ds, compression_type='ZLIB')

    ds.batch(batch_size)

    ds = ds.map(lambda x: _parse_batch(x, sample_rate, duration))

    if split == 'train':
        ds.repeat(n_epochs)

    return ds.prefetch(buffer_size=AUTOTUNE)
</code>```

But i get an error

```<code>ValueError: in converted code:

    D:\Natural Language Processing\speech_to_text\utils\load_tfrecord.py:38 None  *
        ds = ds.map(lambda x: _parse_batch(x, sample_rate, duration))
    D:\Natural Language Processing\speech_to_text\utils\load_tfrecord.py:16 _parse_batch  *
        example = tf.io.parse_example(record_batch, feature_description)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\ops\parsing_ops.py:807 parse_example_v2
        dense_types, dense_defaults, dense_shapes, name)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\ops\parsing_ops.py:868 _parse_example_raw
        name=name)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\ops\gen_parsing_ops.py:626 parse_example
        name=name)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\op_def_library.py:793 _apply_op_helper
        op_def=op_def)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\func_graph.py:548 create_op
        compute_device)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\ops.py:3429 _create_op_internal
        op_def=op_def)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\ops.py:1773 __init__
        control_input_ops)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\ops.py:1613 _create_c_op
        raise ValueError(str(e))

    ValueError: Shape must be rank 1 but is rank 0 for 'ParseExample/ParseExample' (op: 'ParseExample') with input shapes: [], [0], [], [], [], [].
</code>```

How can i fix this?

答:
This error occurs when the shape passed to ParseExample doesn't match between serialized Example and features description.

I was able to reproduce your error using the below code where the shape between the serialized_tf_example and feature_configs don't match thus throws the error.

Code to reproduce the error -

```<code>import tensorflow as tf
sess = tf.InteractiveSession()
serialized_tf_example = tf.placeholder(tf.string, shape=[], name='serialized_tf_example')
feature_configs = {'x': tf.FixedLenFeature(shape=[1], dtype=tf.float32)}
tf_example = tf.parse_example(serialized_tf_example, feature_configs)

feature_dict = {'x': tf.train.Feature(float_list=tf.train.FloatList(value=[25]))}
example = tf.train.Example(features=tf.train.Features(feature=feature_dict))
f = example.SerializeToString()

sess.run(tf_example,feed_dict={serialized_tf_example:[f]})
</code>```

Output -

```<code>/tensorflow-1.15.2/python3.6/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).
  warnings.warn('An interactive session is already active. This can '
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1606   try:
-> 1607     c_op = c_api.TF_FinishOperation(op_desc)
   1608   except errors.InvalidArgumentError as e:

InvalidArgumentError: Shape must be rank 1 but is rank 0 for 'ParseExample_16/ParseExample' (op: 'ParseExample') with input shapes: [], [0], [], [0].
</code>```

Another example, the error also appears when the input type expected and the data passed are also different. For example if I modify tf_example = tf.parse_example([serialized_tf_example], feature_configs) then we get InvalidArgumentError: Shape must be rank 1 but is rank 2 for 'ParseExample_21/ParseExample' (op: 'ParseExample') error as expected.

The error was fixed when we passed proper shape to both serialized_tf_example and feature_configs.

Fixed Code -

```<code>import tensorflow as tf
sess = tf.InteractiveSession()
serialized_tf_example = tf.placeholder(tf.string, shape=[1], name='serialized_tf_example')
feature_configs = {'x': tf.FixedLenFeature(shape=[1], dtype=tf.float32)}
tf_example = tf.parse_example(serialized_tf_example, feature_configs)

feature_dict = {'x': tf.train.Feature(float_list=tf.train.FloatList(value=[25]))}
example = tf.train.Example(features=tf.train.Features(feature=feature_dict))
f = example.SerializeToString()

sess.run(tf_example,feed_dict={serialized_tf_example:[f]})
</code>```

Output -

```<code>{'x': array([[25.]], dtype=float32)}
</code>```

Hope this answers your question. Happy Learning.

Body:
I'm trying to converting WAV files into TFRecord shards

In the code below, i use tf.audio.decode_wav to get an audio signal from wav file, label is an index list of sentence.

Then i save all wav file and label into train.tfrecord and split it

   def _write_tfrecord_file(self, shard_data):

        shard_path, indices = shard_data
        with tf.io.TFRecordWriter(shard_path, options='ZLIB') as out:
            for index in indices:
                file_path = self.data_dir + self.df['Filename'][index] + ".wav"
                label = str2index(self.df['Text'][index])

                raw_audio = tf.io.read_file(file_path)
                audio, sample_rate = tf.audio.decode_wav(
                    raw_audio,
                    desired_channels=1,  # mono
                    desired_samples=self.sample_rate * self.duration)

                example = tf.train.Example(features=tf.train.Features(feature={
                    'audio': _float_feature(audio.numpy().flatten().tolist()),
                    'label': _int64_feature(label)}))

                out.write(example.SerializeToString())

Then, i write a function to load

def _parse_batch(record_batch, sample_rate, duration):

    n_sample = sample_rate * duration

    feature_description = {
        'audio': tf.io.FixedLenFeature([n_sample], tf.float32),
        'label': tf.io.FixedLenFeature([], tf.int64)
    }

    example = tf.io.parse_example(record_batch, feature_description)

    return example['audio'], example['label']

def get_dataset_from_tfrecords(tfrecords_dir='tfrecords', split='train', batch_size=16, sample_rate=44100, duration=5,
                               n_epochs=10):
    if split not in ('train', 'validate'):
        raise ValueError("Split must be either 'train' or 'validate'")

    pattern = os.path.join(tfrecords_dir, '{}*.tfrecord'.format(split))

    files_ds = tf.data.Dataset.list_files(pattern)

    ignore_order = tf.data.Options()
    ignore_order.experimental_deterministic = False
    files_ds = files_ds.with_options(ignore_order)

    ds = tf.data.TFRecordDataset(files_ds, compression_type='ZLIB')

    ds.batch(batch_size)

    ds = ds.map(lambda x: _parse_batch(x, sample_rate, duration))

    if split == 'train':
        ds.repeat(n_epochs)

    return ds.prefetch(buffer_size=AUTOTUNE)

But i get an error

ValueError: in converted code:

    D:\Natural Language Processing\speech_to_text\utils\load_tfrecord.py:38 None  *
        ds = ds.map(lambda x: _parse_batch(x, sample_rate, duration))
    D:\Natural Language Processing\speech_to_text\utils\load_tfrecord.py:16 _parse_batch  *
        example = tf.io.parse_example(record_batch, feature_description)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\ops\parsing_ops.py:807 parse_example_v2
        dense_types, dense_defaults, dense_shapes, name)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\ops\parsing_ops.py:868 _parse_example_raw
        name=name)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\ops\gen_parsing_ops.py:626 parse_example
        name=name)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\op_def_library.py:793 _apply_op_helper
        op_def=op_def)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\func_graph.py:548 create_op
        compute_device)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\ops.py:3429 _create_op_internal
        op_def=op_def)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\ops.py:1773 __init__
        control_input_ops)
    C:\Users\levan\Anaconda3\lib\site-packages\tensorflow_core\python\framework\ops.py:1613 _create_c_op
        raise ValueError(str(e))

    ValueError: Shape must be rank 1 but is rank 0 for 'ParseExample/ParseExample' (op: 'ParseExample') with input shapes: [], [0], [], [], [], [].

How can i fix this?

Body:
This error occurs when the shape passed to ParseExample doesn't match between serialized Example and features description.

I was able to reproduce your error using the below code where the shape between the serialized_tf_example and feature_configs don't match thus throws the error.

Code to reproduce the error -

import tensorflow as tf
sess = tf.InteractiveSession()
serialized_tf_example = tf.placeholder(tf.string, shape=[], name='serialized_tf_example')
feature_configs = {'x': tf.FixedLenFeature(shape=[1], dtype=tf.float32)}
tf_example = tf.parse_example(serialized_tf_example, feature_configs)

feature_dict = {'x': tf.train.Feature(float_list=tf.train.FloatList(value=[25]))}
example = tf.train.Example(features=tf.train.Features(feature=feature_dict))
f = example.SerializeToString()

sess.run(tf_example,feed_dict={serialized_tf_example:[f]})

Output -

/tensorflow-1.15.2/python3.6/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).
  warnings.warn('An interactive session is already active. This can '
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1606   try:
-> 1607     c_op = c_api.TF_FinishOperation(op_desc)
   1608   except errors.InvalidArgumentError as e:

InvalidArgumentError: Shape must be rank 1 but is rank 0 for 'ParseExample_16/ParseExample' (op: 'ParseExample') with input shapes: [], [0], [], [0].

Another example, the error also appears when the input type expected and the data passed are also different. For example if I modify tf_example = tf.parse_example([serialized_tf_example], feature_configs) then we get InvalidArgumentError: Shape must be rank 1 but is rank 2 for 'ParseExample_21/ParseExample' (op: 'ParseExample') error as expected.

The error was fixed when we passed proper shape to both serialized_tf_example and feature_configs.

Fixed Code -

import tensorflow as tf
sess = tf.InteractiveSession()
serialized_tf_example = tf.placeholder(tf.string, shape=[1], name='serialized_tf_example')
feature_configs = {'x': tf.FixedLenFeature(shape=[1], dtype=tf.float32)}
tf_example = tf.parse_example(serialized_tf_example, feature_configs)

feature_dict = {'x': tf.train.Feature(float_list=tf.train.FloatList(value=[25]))}
example = tf.train.Example(features=tf.train.Features(feature=feature_dict))
f = example.SerializeToString()

sess.run(tf_example,feed_dict={serialized_tf_example:[f]})

Output -

{'x': array([[25.]], dtype=float32)}

Hope this answers your question. Happy Learning.


来源: stackexchange

问:
How to auto-create row space / spacial definition between rows with different column values?
I want to create a row, or some kind of definition, between Google Sheets rows whenever one of the value in my columns contain a new / different value.

Here's an example of the kind of spreadsheets I'm putting together, which shows how  Agencies are listed in Column A, and Sub-Agencies are listed in Column B.

I'd like to create some kind of row space / spacial definition between every new / different Sub-Agency, which are values that I enter in Column B of my spreadsheet -- but no space between rows with the same Sub-Agency value.  Here's an example of the kind of row space / spacial definition that I'm seeking.

Any ideas / suggestion on how do this?

Many thanks for your help!

答:
You can insert a row after X condition.

Using insertRowAfter(afterPosition) inserts a row after the row you want:

```<code>var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// This inserts a row after the first row position
sheet.insertRowAfter(1);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can insert a row after X condition.

Using insertRowAfter(afterPosition) inserts a row after the row you want:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// This inserts a row after the first row position
sheet.insertRowAfter(1);


问:
Auth::attempt always return false even with proper input
Here are the facades I used

```<code>namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
</code>```

I've successfully created user signup page with hashed password using bcrypt.

```<code>    //Get singnup view
    public function getSignup()
    {
        return view('user.signup');
    }
    //Process signup
    public function postSignup(Request $request)
    {
        $this->validate($request, [
            'email' => 'email|required|unique:users',
            'password' => 'required|min:4'
        ]);
        $user = new User([
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
        ]);
        $user->save();
        return redirect()->route('product.index');
    }
</code>```

And now I'm stuck at the signin page. The Auth::attempt always return false. I even tried to store a plain password in my database and signin without bcrypt but it still returned false. I have no idea where I'm wrong right now.

```<code>//Get signin view
    public function getSignin()
    {
        return view('user.signin');
    }
    //Process signin
    public function postSignin(Request $request)
    {
        $this->validate($request, [
                'email' => 'email|required',
                'password' => 'required|min:4'
                ]);
        $credentials = array(
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password'))
                );
        if(Auth::attempt($credentials))
        {
            return redirect()->route('user.profile');
        }
        return redirect()->route('product.index');
    }
</code>```

答: You don't need bcrypt() in Auth::attempt(). Remove it and try again.

Body:
Here are the facades I used

namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

I've successfully created user signup page with hashed password using bcrypt.

    //Get singnup view
    public function getSignup()
    {
        return view('user.signup');
    }
    //Process signup
    public function postSignup(Request $request)
    {
        $this->validate($request, [
            'email' => 'email|required|unique:users',
            'password' => 'required|min:4'
        ]);
        $user = new User([
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
        ]);
        $user->save();
        return redirect()->route('product.index');
    }

And now I'm stuck at the signin page. The Auth::attempt always return false. I even tried to store a plain password in my database and signin without bcrypt but it still returned false. I have no idea where I'm wrong right now.

//Get signin view
    public function getSignin()
    {
        return view('user.signin');
    }
    //Process signin
    public function postSignin(Request $request)
    {
        $this->validate($request, [
                'email' => 'email|required',
                'password' => 'required|min:4'
                ]);
        $credentials = array(
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password'))
                );
        if(Auth::attempt($credentials))
        {
            return redirect()->route('user.profile');
        }
        return redirect()->route('product.index');
    }


问:
Access to XMLHttpRequest at '...' from origin 'localhost:3000' has been blocked by CORS policy

Edit

A little late, but I remember that I ended up solving this issue by setting credentials: true in my cors config on my backend.

By complete accident, I noticed that if I set credentials: false in my axios client on the frontend, everything worked fine. However, switching it to true kept throwing the error. I then put two and two together and set credentials: true on my backend and everything worked as expected.

My app used cookies, so it had to be done this way.

This may be a duplicate, but I havent found a thread relating specifically to my issue.

I am making the following API call:

```<code>const config = {
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS"
  }
};

const {
  data: { ip }
} = await axios.get("https://api.ipify.org?format=json", config);
</code>```

And this throws an error:

Access to XMLHttpRequest at 'https://api.ipify.org/?format=json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When I deploy my app to Heroku, the API call works as expected. However it does not work when developing on my local machine. Not sure what I'm missing here.

答:
This may be due to the POST request from react app in development mode. You can bypass the CORS policy in development mode by the adding following line of code in your ' file.

```<code>{
    ...
    "proxy": "http://localhost:3000",
    ...
}
</code>```

Body:
Edit

A little late, but I remember that I ended up solving this issue by setting credentials: true in my cors config on my backend.

By complete accident, I noticed that if I set credentials: false in my axios client on the frontend, everything worked fine. However, switching it to true kept throwing the error. I then put two and two together and set credentials: true on my backend and everything worked as expected.

My app used cookies, so it had to be done this way.

This may be a duplicate, but I havent found a thread relating specifically to my issue.

I am making the following API call:

const config = {
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS"
  }
};

const {
  data: { ip }
} = await axios.get("https://api.ipify.org?format=json", config);

And this throws an error:

Access to XMLHttpRequest at 'https://api.ipify.org/?format=json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When I deploy my app to Heroku, the API call works as expected. However it does not work when developing on my local machine. Not sure what I'm missing here.

Body:
This may be due to the POST request from react app in development mode. You can bypass the CORS policy in development mode by the adding following line of code in your ' file.

{
    ...
    "proxy": "http://localhost:3000",
    ...
}


问:
How to check with LocalDateTime that a given time is within 24 hours of now using Scala
I want to create a method which takes one parameter and returns true if the the date provided is within 24 hours of the current time. </p>

```<code>def compareDates(date: LocalDateTime): Boolean = {
  val now = LocalDateTime.now
  date.compareTo(now)
}
</code>```

答:
You can use isBefore and isAfter (closed range):

```<code>!(date.isAfter(now.plusDays(1)) || date.isBefore(now.minusDays(1)))
</code>```

For open range:

```<code>date.isBefore(now.plusDays(1)) && date.isAfter(now.minusDays(1))
</code>```

Body:
I want to create a method which takes one parameter and returns true if the the date provided is within 24 hours of the current time.

def compareDates(date: LocalDateTime): Boolean = {
  val now = LocalDateTime.now
  date.compareTo(now)
}

Body:
You can use isBefore and isAfter (closed range):

!(date.isAfter(now.plusDays(1)) || date.isBefore(now.minusDays(1)))

For open range:

date.isBefore(now.plusDays(1)) && date.isAfter(now.minusDays(1))


问:
Polly Retry is not working and logs are not added for the retry
Currently, I have the code in which the while loop get's stuck when connection.IsConnected = true

```<code>private  bool TryConnect()
    {
        if (!connection.IsConnected)
        {
            Monitor.Enter(_syncRoot);
            try
            {
                while (!connection.IsConnected)
                {
                    Thread.Sleep(100);
                }
            }
            finally
            {
                Monitor.Exit(_syncRoot);
            }
        }
        return true;
    }
</code>```

So for this, I have tried replacing this with Polly retry but using Polly it does not wait and the log is not added

```<code>private  bool TryConnect()
    {
        if (!connection.IsConnected)
        {
            Monitor.Enter(_syncRoot);
            try
            {
                var policy = Policy.HandleResult<bool>(r => r == false)
                    .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                        (ex, time) =>
                        {
                            Log.LogInformation(
                                "retry {TimeOut}s");
                        }
                    );
                policy.Execute(() => connection.IsConnected);
            }
            finally
            {
                Monitor.Exit(_syncRoot);
            }
        }
        return true;
    }
</code>```

If someone can let me know, what I am doing wrong with the code. It will be really helpful

答:
From the code that you have posted it is hard to guess which C# driver are you using to connect to RabbitMq. So, I will not able to help you with driver specific code.

But as I can see the connection object's IsConnected is a property. Which means it is a public surface, which can be used to examine the underlying object's state. In order words it should not cause state change just because you are retrieving the internal state several times.

Your retry logic should focus on the action itself which is responsible to connect to your RabbitMq instance.

```<code>retryPolicy.Execute(() => connection.Open());
</code>```

By the way your code never returns with false. It's either succeed or fail with some timeout related exception.

Body:
Currently, I have the code in which the while loop get's stuck when connection.IsConnected = true

private  bool TryConnect()
    {
        if (!connection.IsConnected)
        {
            Monitor.Enter(_syncRoot);
            try
            {
                while (!connection.IsConnected)
                {
                    Thread.Sleep(100);
                }
            }
            finally
            {
                Monitor.Exit(_syncRoot);
            }
        }
        return true;
    }

So for this, I have tried replacing this with Polly retry but using Polly it does not wait and the log is not added

private  bool TryConnect()
    {
        if (!connection.IsConnected)
        {
            Monitor.Enter(_syncRoot);
            try
            {
                var policy = Policy.HandleResult<bool>(r => r == false)
                    .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                        (ex, time) =>
                        {
                            Log.LogInformation(
                                "retry {TimeOut}s");
                        }
                    );
                policy.Execute(() => connection.IsConnected);
            }
            finally
            {
                Monitor.Exit(_syncRoot);
            }
        }
        return true;
    }

If someone can let me know, what I am doing wrong with the code. It will be really helpful

Body:
From the code that you have posted it is hard to guess which C# driver are you using to connect to RabbitMq. So, I will not able to help you with driver specific code.

But as I can see the connection object's IsConnected is a property. Which means it is a public surface, which can be used to examine the underlying object's state. In order words it should not cause state change just because you are retrieving the internal state several times.

Your retry logic should focus on the action itself which is responsible to connect to your RabbitMq instance.

retryPolicy.Execute(() => connection.Open());

By the way your code never returns with false. It's either succeed or fail with some timeout related exception.


问:
Vue.js route params
I saw a line of code in a project that I just started working on. So, I am kind of new to Vue.js. The code is as below:

```<code> routes: [{
    path: '/coursePage/:contentId/:title?',
    name: 'coursePage',
    component: coursePage,
    meta: {requireAuth: false}
  },
</code>```

The route param - contentId works fine but I can't figure out the purpose of ? in param - title?
Can anyone help me understand this? Thanks.

答:
The last ? means this parameter is optional.

The vue-router will not complain if you do not pass this parameter while building the dynamic route.

You can do

```<code>this.$router.push({
    name: coursePage,
    params: { contentId: 1 }
})
</code>```

or

```<code>this.$router.push({
    name: coursePage,
    params: { contentId: 1, title: 2 }
})
</code>```

Title: Vue.js route params

Body:
I saw a line of code in a project that I just started working on. So, I am kind of new to Vue.js. The code is as below:

 routes: [{
    path: '/coursePage/:contentId/:title?',
    name: 'coursePage',
    component: coursePage,
    meta: {requireAuth: false}
  },

The route param - contentId works fine but I can't figure out the purpose of ? in param - title?
Can anyone help me understand this? Thanks.

Body:
The last ? means this parameter is optional.

The vue-router will not complain if you do not pass this parameter while building the dynamic route.

You can do

this.$router.push({
    name: coursePage,
    params: { contentId: 1 }
})

or

this.$router.push({
    name: coursePage,
    params: { contentId: 1, title: 2 }
})


问:
Add SQL Server configuration in .NET Core app project with Docker
I follow this tutorial to set up docket with VueJS (Quasar), docker and SQL Server:

https://dev.to/quasar-pt-br/qpanc-parte-2-postgresql-51pb

I want to use SQL Server instead of PostgresSQL.

How can we set up a SQL Server database (localDB) with docker in Visual Studio?

答:
Short answer: ASP.NET Core on a different platform than windows does not support LocalDB.

You can start SQL Server in a container according to this documentation. You can then connect from your asp.net core container. This is the way I'm developing on a mac.


问:
Could not find an option named "DartDefines"
When I open up an IOS simulator to launch my flutter apps, it fails. Before it used to work fine. I get the following error:

```<code>Xcode build done.                                           122.2s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **
Xcode's output:
↳
    Could not find an option named "DartDefines".
    Run 'flutter -h' (or 'flutter <command> -h') for available flutter commands and options.
    Command PhaseScriptExecution failed with a nonzero exit code
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
Could not build the application for the simulator.
Error launching application on iPhone 11.
Exited (sigterm)
</code>```

I tried the following

Getting error when launching flutter apps in simulators.

答:
I have the same issue, and I've fixed it by running two command.
Please try, hope it help.

flutter channel dev

flutter upgrade

Good luck!

Body:
When I open up an IOS simulator to launch my flutter apps, it fails. Before it used to work fine. I get the following error:

Xcode build done.                                           122.2s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **
Xcode's output:
↳
    Could not find an option named "DartDefines".
    Run 'flutter -h' (or 'flutter <command> -h') for available flutter commands and options.
    Command PhaseScriptExecution failed with a nonzero exit code
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
Could not build the application for the simulator.
Error launching application on iPhone 11.
Exited (sigterm)

I tried the following

Getting error when launching flutter apps in simulators.


问:
Split a Dataframe per time interval
I have a dataframe in the following format:

```<code>timestamp,name,age
2020-03-01 00:00:01,nick
2020-03-01 00:00:01,john
2020-03-01 00:00:02,nick
2020-03-01 00:00:02,john
2020-03-01 00:00:04,peter
2020-03-01 00:00:05,john
2020-03-01 00:00:10,nick
2020-03-01 00:00:12,john
2020-03-01 00:00:54,hank
2020-03-01 00:01:03,peter
</code>```

I am trying to split this dataframe into many dataframes based on a time interval (for example 1 minute) and append the results into a dictionary.

I am trying:

```<code>df = pd.read_csv('/home/antonis/repos/newtest.csv')
minutesplit = {n: g.reset_index()
             for n, g in df.set_index('timestamp').groupby(pd.Grouper(key='timestamp',freq='1Min'))}
</code>```

but an error occurs like:

KeyError: 'The grouper name timestamp is not found'

Does anyone know what am I doing wrong?

答:
First convert column timestamp to datetimes by parameter parse_dates:

```<code>df = pd.read_csv('/home/antonis/repos/newtest.csv', parse_dates=['timestamp'])
</code>```

And then convert to index by set_index with convert index to column by reset_index is not necessary, Grouper is use parameter key for looking for column timestamp:

Here are keys in dictionary of DataFrames created by datetimes, so for seelcting is used pd.Timestamp:

```<code>minutesplit = {n: g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='1Min'))}

print (minutesplit[pd.Timestamp('2020-03-01 00:01')])
            timestamp   name  age
9 2020-03-01 00:01:03  peter  NaN
</code>```

If keys convert to strings YYYY-MM-DD HH:MM is used strftime:

```<code>minutesplit = {n.strftime('%Y-%m-%d %H:%M'): g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='1Min'))}

print (minutesplit['2020-03-01 00:01'])
            timestamp   name  age
9 2020-03-01 00:01:03  peter  NaN
</code>```

If need list of DataFrames:

```<code>minutesplit = [g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='1Min'))]

print (minutesplit[1])
            timestamp   name  age
9 2020-03-01 00:01:03  peter  NaN
</code>```

Title: Split a Dataframe per time interval

Body:
I have a dataframe in the following format:

timestamp,name,age
2020-03-01 00:00:01,nick
2020-03-01 00:00:01,john
2020-03-01 00:00:02,nick
2020-03-01 00:00:02,john
2020-03-01 00:00:04,peter
2020-03-01 00:00:05,john
2020-03-01 00:00:10,nick
2020-03-01 00:00:12,john
2020-03-01 00:00:54,hank
2020-03-01 00:01:03,peter

I am trying to split this dataframe into many dataframes based on a time interval (for example 1 minute) and append the results into a dictionary.

I am trying:

df = pd.read_csv('/home/antonis/repos/newtest.csv')
minutesplit = {n: g.reset_index()
             for n, g in df.set_index('timestamp').groupby(pd.Grouper(key='timestamp',freq='1Min'))}

but an error occurs like:

KeyError: 'The grouper name timestamp is not found'

Does anyone know what am I doing wrong?

Body:
First convert column timestamp to datetimes by parameter parse_dates:

df = pd.read_csv('/home/antonis/repos/newtest.csv', parse_dates=['timestamp'])

And then convert to index by set_index with convert index to column by reset_index is not necessary, Grouper is use parameter key for looking for column timestamp:

Here are keys in dictionary of DataFrames created by datetimes, so for seelcting is used pd.Timestamp:

minutesplit = {n: g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='1Min'))}

print (minutesplit[pd.Timestamp('2020-03-01 00:01')])
            timestamp   name  age
9 2020-03-01 00:01:03  peter  NaN

If keys convert to strings YYYY-MM-DD HH:MM is used strftime:

minutesplit = {n.strftime('%Y-%m-%d %H:%M'): g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='1Min'))}

print (minutesplit['2020-03-01 00:01'])
            timestamp   name  age
9 2020-03-01 00:01:03  peter  NaN

If need list of DataFrames:

minutesplit = [g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='1Min'))]

print (minutesplit[1])
            timestamp   name  age
9 2020-03-01 00:01:03  peter  NaN


问:
Log4j2 log4j-core
I have added spring-boot-starter-log4j2 dependency in pom.xml which is of version 2.2.5. I am trying to change the version of org.apache.logging.log4j.log4j-core from 2.12.1 to 2.13.3
However, in doing so I am getting runtime exception. I went through other solutions which suggest that maybe log4j jar is included twice. I am unable to solve the error by excluding that also. This runtime exception occurs only when org.apache.logging.log4j.log4j-core version is changed. Changing version of other api included under spring-boot-starter-log4j2 does not cause any exception.
What am I missing?
Pom.xml
...

```<code>  <!-- Add Log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.3</version>
</dependency>
</code>```

...
Dependency Tree
Dependency Tree
Runtime Exception
...

```<code>Exception in thread "main" java.lang.NoSuchMethodError: org.apache.logging.log4j.util.PropertiesUtil.getStringProperty([Ljava/lang/String;Ljava/lang/String;Lorg/apache/logging/log4j/util/Supplier;)Ljava/lang/String;
at org.apache.logging.log4j.core.util.BasicAuthorizationProvider.<init>(BasicAuthorizationProvider.java:45)
at org.apache.logging.log4j.core.config.ConfigurationFactory.authorizationProvider(ConfigurationFactory.java:216)
at org.apache.logging.log4j.core.config.ConfigurationFactory.getInstance(ConfigurationFactory.java:189)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:687)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:708)
at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:263)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:243)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:45)
at org.apache.logging.log4j.LogManager.getContext(LogManager.java:174)
at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:648)
at com.vzw.jitrjis.StartUp.<clinit>(StartUp.java:22)
</code>```

...

答: If you want to control the version of Log4j2 do not add the dependency on spring-boot-starter-logging-Log4j2. Just add Log4J-bom with import scope to the dependencyManagement to control the version and then add the various Log4J dependencies you want. Spring will have no problem using a newer version of Log4j2.</p>

Title: Log4j2 log4j-core

Body:
I have added spring-boot-starter-log4j2 dependency in pom.xml which is of version 2.2.5. I am trying to change the version of org.apache.logging.log4j.log4j-core from 2.12.1 to 2.13.3
However, in doing so I am getting runtime exception. I went through other solutions which suggest that maybe log4j jar is included twice. I am unable to solve the error by excluding that also. This runtime exception occurs only when org.apache.logging.log4j.log4j-core version is changed. Changing version of other api included under spring-boot-starter-log4j2 does not cause any exception.
What am I missing?
Pom.xml
...

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.3</version>
</dependency>

...
Dependency Tree
Dependency Tree
Runtime Exception
...

Exception in thread "main" java.lang.NoSuchMethodError: org.apache.logging.log4j.util.PropertiesUtil.getStringProperty([Ljava/lang/String;Ljava/lang/String;Lorg/apache/logging/log4j/util/Supplier;)Ljava/lang/String;
at org.apache.logging.log4j.core.util.BasicAuthorizationProvider.<init>(BasicAuthorizationProvider.java:45)
at org.apache.logging.log4j.core.config.ConfigurationFactory.authorizationProvider(ConfigurationFactory.java:216)
at org.apache.logging.log4j.core.config.ConfigurationFactory.getInstance(ConfigurationFactory.java:189)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:687)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:708)
at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:263)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:243)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:45)
at org.apache.logging.log4j.LogManager.getContext(LogManager.java:174)
at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:648)
at com.vzw.jitrjis.StartUp.<clinit>(StartUp.java:22)

...


问:
Quarkus project Graal Native using Maven
I am trying can create a native executable using: ./mvnw package -Pnative
The command is running from the last 2 hours but it's still not complete.

I have attempted it multiple times, I have restarted the system too but nothing helped till now.

Complete Log:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< org.acme:code-with-quarkus >---------------------
[INFO] Building code-with-quarkus 1.0.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ code-with-quarkus ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ code-with-quarkus ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ code-with-quarkus ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/testuser/Desktop/quarkus-rest/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ code-with-quarkus ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ code-with-quarkus ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running org.acme.ExampleResourceTest
2020-06-01 06:38:37,777 INFO  [io.quarkus] (main) Quarkus 1.4.2.Final started in 4.412s. Listening on: http://0.0.0.0:8081
2020-06-01 06:38:37,852 INFO  [io.quarkus] (main) Profile test activated.
2020-06-01 06:38:37,855 INFO  [io.quarkus] (main) Installed features: [cdi, resteasy]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 9.505 s - in org.acme.ExampleResourceTest
2020-06-01 06:38:41,842 INFO  [io.quarkus] (main) Quarkus stopped in 0.068s
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ code-with-quarkus ---
[INFO]
[INFO] --- quarkus-maven-plugin:1.4.2.Final:build (default) @ code-with-quarkus ---
[INFO] [org.jboss.threads] JBoss Threads version 3.1.1.Final
[INFO] [io.quarkus.deployment.pkg.steps.JarResultBuildStep] Building native image source jar: /home/testuser/Desktop/quarkus-rest/target/code-with-quarkus-1.0.0-SNAPSHOT-native-image-source-jar/code-with-quarkus-1.0.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Building native image from /home/testuser/Desktop/quarkus-rest/target/code-with-quarkus-1.0.0-SNAPSHOT-native-image-source-jar/code-with-quarkus-1.0.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Running Quarkus native-image plugin on GraalVM Version 20.1.0 (Java Version 11.0.7)
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] /usr/lib/jvm/graalvm-ce-java11-20.1.0/bin/native-image -J-Djava.util.logging.manager=org.jboss.logmanager.LogManager -J-Dsun.nio.ch.maxUpdateArraySize=100 -J-Dvertx.logger-delegate-factory-class-name=io.quarkus.vertx.core.runtime.VertxLogDelegateFactory -J-Dvertx.disableDnsResolver=true -J-Dio.netty.leakDetection.level=DISABLED -J-Dio.netty.allocator.maxOrder=1 -J-Duser.language=en -J-Dfile.encoding=UTF-8 --initialize-at-build-time= -H:InitialCollectionPolicy=com.oracle.svm.core.genscavenge.CollectionPolicy$BySpaceAndTime -H:+JNI -jar code-with-quarkus-1.0.0-SNAPSHOT-runner.jar -H:FallbackThreshold=0 -H:+ReportExceptionStackTraces -H:-AddAllCharsets -H:-IncludeAllTimeZones -H:EnableURLProtocols=http -H:NativeLinkerOption=-no-pie --no-server -H:-UseServiceLoaderFeature -H:+StackTrace code-with-quarkus-1.0.0-SNAPSHOT-runner
-H:IncludeAllTimeZones and -H:IncludeTimeZones are now deprecated. Native-image includes all timezonesby default.
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]    classlist:  18,228.62 ms,  0.74 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]        (cap):   3,989.95 ms,  0.74 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]        setup:  12,572.12 ms,  0.74 GB
06:41:15,775 INFO  [org.jbo.threads] JBoss Threads version 3.1.1.Final
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]     (clinit):  10,836.94 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]   (typeflow): 198,049.68 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]    (objects): 499,552.27 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]   (features):  13,579.92 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]     analysis: 756,771.78 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]     universe:  66,599.46 ms,  0.74 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]      (parse): 221,467.49 ms,  0.65 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]     (inline): 2,025,552.89 ms,  0.67 GB
</code>```

Versions of different technologies:

OS: Ubuntu 20.04-VB-64bit

GraalVM runtime: OpenJDK Runtime

Environment GraalVM CE 20.1.0  Native-Image: GraalVM Version 20.1.0
(Java Version 11.0.7)

答:
Currently (on 1.4 and the upcoming 1.5), Quarkus is only compatible with GraaVM 19.3.1 (LTS) and 20.0.0, you can see that in the Getting Started page: https://quarkus.io/get-started/

Both Java 8 and Java 11 versions are supported.

20.1 should be supported in 1.6.

Can you try with 20.0.0?

In addition to version, I see that the memory available for native-image is really low, 0.67 GB. You didn't specify any memory limit (Xmx) for a native-image command so I assume you run it on a low memory device (or inside a low memory container). The native image needs a lot of memory (4GB or more), I think it's why it never ends

Body:
I am trying can create a native executable using: ./mvnw package -Pnative
The command is running from the last 2 hours but it's still not complete.

I have attempted it multiple times, I have restarted the system too but nothing helped till now.

Complete Log:

[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< org.acme:code-with-quarkus >---------------------
[INFO] Building code-with-quarkus 1.0.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ code-with-quarkus ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ code-with-quarkus ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ code-with-quarkus ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/testuser/Desktop/quarkus-rest/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ code-with-quarkus ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ code-with-quarkus ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running org.acme.ExampleResourceTest
2020-06-01 06:38:37,777 INFO  [io.quarkus] (main) Quarkus 1.4.2.Final started in 4.412s. Listening on: http://0.0.0.0:8081
2020-06-01 06:38:37,852 INFO  [io.quarkus] (main) Profile test activated.
2020-06-01 06:38:37,855 INFO  [io.quarkus] (main) Installed features: [cdi, resteasy]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 9.505 s - in org.acme.ExampleResourceTest
2020-06-01 06:38:41,842 INFO  [io.quarkus] (main) Quarkus stopped in 0.068s
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ code-with-quarkus ---
[INFO]
[INFO] --- quarkus-maven-plugin:1.4.2.Final:build (default) @ code-with-quarkus ---
[INFO] [org.jboss.threads] JBoss Threads version 3.1.1.Final
[INFO] [io.quarkus.deployment.pkg.steps.JarResultBuildStep] Building native image source jar: /home/testuser/Desktop/quarkus-rest/target/code-with-quarkus-1.0.0-SNAPSHOT-native-image-source-jar/code-with-quarkus-1.0.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Building native image from /home/testuser/Desktop/quarkus-rest/target/code-with-quarkus-1.0.0-SNAPSHOT-native-image-source-jar/code-with-quarkus-1.0.0-SNAPSHOT-runner.jar
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] Running Quarkus native-image plugin on GraalVM Version 20.1.0 (Java Version 11.0.7)
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] /usr/lib/jvm/graalvm-ce-java11-20.1.0/bin/native-image -J-Djava.util.logging.manager=org.jboss.logmanager.LogManager -J-Dsun.nio.ch.maxUpdateArraySize=100 -J-Dvertx.logger-delegate-factory-class-name=io.quarkus.vertx.core.runtime.VertxLogDelegateFactory -J-Dvertx.disableDnsResolver=true -J-Dio.netty.leakDetection.level=DISABLED -J-Dio.netty.allocator.maxOrder=1 -J-Duser.language=en -J-Dfile.encoding=UTF-8 --initialize-at-build-time= -H:InitialCollectionPolicy=com.oracle.svm.core.genscavenge.CollectionPolicy$BySpaceAndTime -H:+JNI -jar code-with-quarkus-1.0.0-SNAPSHOT-runner.jar -H:FallbackThreshold=0 -H:+ReportExceptionStackTraces -H:-AddAllCharsets -H:-IncludeAllTimeZones -H:EnableURLProtocols=http -H:NativeLinkerOption=-no-pie --no-server -H:-UseServiceLoaderFeature -H:+StackTrace code-with-quarkus-1.0.0-SNAPSHOT-runner
-H:IncludeAllTimeZones and -H:IncludeTimeZones are now deprecated. Native-image includes all timezonesby default.
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]    classlist:  18,228.62 ms,  0.74 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]        (cap):   3,989.95 ms,  0.74 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]        setup:  12,572.12 ms,  0.74 GB
06:41:15,775 INFO  [org.jbo.threads] JBoss Threads version 3.1.1.Final
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]     (clinit):  10,836.94 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]   (typeflow): 198,049.68 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]    (objects): 499,552.27 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]   (features):  13,579.92 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]     analysis: 756,771.78 ms,  0.75 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]     universe:  66,599.46 ms,  0.74 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]      (parse): 221,467.49 ms,  0.65 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:41959]     (inline): 2,025,552.89 ms,  0.67 GB

Versions of different technologies:

OS: Ubuntu 20.04-VB-64bit

GraalVM runtime: OpenJDK Runtime

Environment GraalVM CE 20.1.0  Native-Image: GraalVM Version 20.1.0
(Java Version 11.0.7)


问:
How do I do a "natural sort" in PyICU?
Using PyICU, how can I use a Collator to sort a list of strings by "natural order", i.e., putting 10 after 2 instead of before?

In the ICU docs http://userguide.icu-project.org/collation/customization#TOC-Default-Options, I can see that there is a "numericOrdering" option (a.k.a. UCOL_NUMERIC_COLLATION) that can be set on or off, but I can't figure out how to set that attribute from Python code.

答:
You can use the .setAttribute method on the Collator instance.

The attribute name and value come from an enum that's attached to the main icu module:

```<code>import icu

collator = icu.Collator.createInstance(icu.Locale('en_US'))
collator.setAttribute(icu.UCollAttribute.NUMERIC_COLLATION, icu.UCollAttributeValue.ON)

sorted(['3 three', '1 one', '10 ten', '2 two'])
# ['1 one', '10 ten', '2 two', '3 three']

sorted(['3 three', '1 one', '10 ten', '2 two'], key=collator.getSortKey)
# ['1 one', '2 two', '3 three', '10 ten']
</code>```

Title: How do I do a "natural sort" in PyICU?

Body:
You can use the .setAttribute method on the Collator instance.

The attribute name and value come from an enum that's attached to the main icu module:

import icu

collator = icu.Collator.createInstance(icu.Locale('en_US'))
collator.setAttribute(icu.UCollAttribute.NUMERIC_COLLATION, icu.UCollAttributeValue.ON)

sorted(['3 three', '1 one', '10 ten', '2 two'])
# ['1 one', '10 ten', '2 two', '3 three']

sorted(['3 three', '1 one', '10 ten', '2 two'], key=collator.getSortKey)
# ['1 one', '2 two', '3 three', '10 ten']


问:
How to change caption position right under image on mobile resolution - Fancybox 3
By default fancybox 3 caption is right under the image on pc/tablet device BUT on mobile (350x800) caption is not under the image its on the bottom of tha page .

How can i make caption right under the image on mobile device ?

After looking an hour i did not found the way to do it

Here is the example of the image just turn on mobile (350x800) Fancybox 3 Image

I was trying beforeShow function to get width/height of fancybox-content and then set posittion of caption but beforeShow working only when you swipe next/prev image not on first open

```<code>        $('[data-fancybox]').fancybox({

          beforeShow: function() {
            console.log($('.fancybox-content').width());
          },

        });
</code>```

Log

```<code>null
</code>```

答:
this done for me </p>

```<code>            afterLoad: function(instance, current) {
              var width = $('#fancybox-content').context.activeElement.clientWidth;
              var height = $(window).height();
              var calHeight = (height - width ) / 3

              if (img < 600) {
                $('.fancybox-caption.fancybox-caption--separate').css('bottom', ''+calHeight+'px');
              }
            },
</code>```

Body:
By default fancybox 3 caption is right under the image on pc/tablet device BUT on mobile (350x800) caption is not under the image its on the bottom of tha page .

How can i make caption right under the image on mobile device ?

After looking an hour i did not found the way to do it

Here is the example of the image just turn on mobile (350x800) Fancybox 3 Image

I was trying beforeShow function to get width/height of fancybox-content and then set posittion of caption but beforeShow working only when you swipe next/prev image not on first open

        $('[data-fancybox]').fancybox({

          beforeShow: function() {
            console.log($('.fancybox-content').width());
          },

        });

Log

null

Body:
this done for me

            afterLoad: function(instance, current) {
              var width = $('#fancybox-content').context.activeElement.clientWidth;
              var height = $(window).height();
              var calHeight = (height - width ) / 3

              if (img < 600) {
                $('.fancybox-caption.fancybox-caption--separate').css('bottom', ''+calHeight+'px');
              }
            },


问:
What do these Spring debug messages mean?
I use Spring IoC in my stand-alone Java application. When the application starts it creates a log with start-up info. Some messages I don't understand, please help me to understand them and explain how to fix them if they must be fixed? Also I am curious: Is there any danger for my application stability because of these messages?

Messages that scare me off starts with word "Unable". At the moment the application works quite well.

```<code>INFO - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@52cc95d: startup date     [Thu Jun 02 16:02:12 MSD 2011]; root of context hierarchy
INFO - Loading XML bean definitions from class path resource [application-config.xml]
DEBUG - Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
DEBUG - Loading schema mappings from [META-INF/spring.schemas]
DEBUG - Loaded schema mappings: {http://www.springframework.org/schema/tx/spring-tx-2.5.xsd=org/springframework/transaction/config/spring-tx-2.5.xsd, http://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd, http://www.springframework.org/schema/tx/spring-tx-3.0.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd}
DEBUG - Loading bean definitions
DEBUG - Loaded 3 bean definitions from location pattern [application-config.xml]
DEBUG - Bean factory for org.springframework.context.support.ClassPathXmlApplicationContext@52cc95d: org.springframework.beans.factory.support.DefaultListableBeanFactory@33aae94f: defining beans [propertyPlaceholderConfigurer,dbWorker,connectionPool]; root of factory hierarchy
DEBUG - Creating shared instance of singleton bean 'propertyPlaceholderConfigurer'
DEBUG - Creating instance of bean 'propertyPlaceholderConfigurer'
DEBUG - Eagerly caching bean 'propertyPlaceholderConfigurer' to allow for resolving potential circular references
DEBUG - Finished creating instance of bean 'propertyPlaceholderConfigurer'
INFO - Loading properties file from class path resource [config.properties]
DEBUG - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@49bdc9d8]
DEBUG - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@255d17d7]
INFO - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@33aae94f: defining beans [propertyPlaceholderConfigurer,dbWorker,connectionPool]; root of factory hierarchy
DEBUG - Returning cached instance of singleton bean 'propertyPlaceholderConfigurer'
DEBUG - Creating shared instance of singleton bean 'dbWorker'
DEBUG - Creating instance of bean 'dbWorker'
DEBUG - Eagerly caching bean 'dbWorker' to allow for resolving potential circular references
DEBUG - Creating shared instance of singleton bean 'connectionPool'
DEBUG - Creating instance of bean 'connectionPool'
DEBUG - Eagerly caching bean 'connectionPool' to allow for resolving potential circular references
DEBUG - Finished creating instance of bean 'connectionPool'
DEBUG - Finished creating instance of bean 'dbWorker'
DEBUG - Returning cached instance of singleton bean 'connectionPool'
DEBUG - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@4b1c2b67]
DEBUG - Returning cached instance of singleton bean 'lifecycleProcessor'
</code>```

答: If you have explicitly defined any of those beans then you might have a problem as Spring would be injecting the wrong type, since it is not finding your custom bean. However, if you have not defined these beans, then these messages are benign. Spring is just letting you know that the default bean is being used - as @Phill has already answered. </p>

ContentLicense: CC BY-SA 3.0

Body:
I use Spring IoC in my stand-alone Java application. When the application starts it creates a log with start-up info. Some messages I don't understand, please help me to understand them and explain how to fix them if they must be fixed? Also I am curious: Is there any danger for my application stability because of these messages?

Messages that scare me off starts with word "Unable". At the moment the application works quite well.

INFO - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@52cc95d: startup date     [Thu Jun 02 16:02:12 MSD 2011]; root of context hierarchy
INFO - Loading XML bean definitions from class path resource [application-config.xml]
DEBUG - Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
DEBUG - Loading schema mappings from [META-INF/spring.schemas]
DEBUG - Loaded schema mappings: {http://www.springframework.org/schema/tx/spring-tx-2.5.xsd=org/springframework/transaction/config/spring-tx-2.5.xsd, http://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd, http://www.springframework.org/schema/tx/spring-tx-3.0.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd}
DEBUG - Loading bean definitions
DEBUG - Loaded 3 bean definitions from location pattern [application-config.xml]
DEBUG - Bean factory for org.springframework.context.support.ClassPathXmlApplicationContext@52cc95d: org.springframework.beans.factory.support.DefaultListableBeanFactory@33aae94f: defining beans [propertyPlaceholderConfigurer,dbWorker,connectionPool]; root of factory hierarchy
DEBUG - Creating shared instance of singleton bean 'propertyPlaceholderConfigurer'
DEBUG - Creating instance of bean 'propertyPlaceholderConfigurer'
DEBUG - Eagerly caching bean 'propertyPlaceholderConfigurer' to allow for resolving potential circular references
DEBUG - Finished creating instance of bean 'propertyPlaceholderConfigurer'
INFO - Loading properties file from class path resource [config.properties]
DEBUG - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@49bdc9d8]
DEBUG - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@255d17d7]
INFO - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@33aae94f: defining beans [propertyPlaceholderConfigurer,dbWorker,connectionPool]; root of factory hierarchy
DEBUG - Returning cached instance of singleton bean 'propertyPlaceholderConfigurer'
DEBUG - Creating shared instance of singleton bean 'dbWorker'
DEBUG - Creating instance of bean 'dbWorker'
DEBUG - Eagerly caching bean 'dbWorker' to allow for resolving potential circular references
DEBUG - Creating shared instance of singleton bean 'connectionPool'
DEBUG - Creating instance of bean 'connectionPool'
DEBUG - Eagerly caching bean 'connectionPool' to allow for resolving potential circular references
DEBUG - Finished creating instance of bean 'connectionPool'
DEBUG - Finished creating instance of bean 'dbWorker'
DEBUG - Returning cached instance of singleton bean 'connectionPool'
DEBUG - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@4b1c2b67]
DEBUG - Returning cached instance of singleton bean 'lifecycleProcessor'


问:
Allure serve command to update realtime and make use of the advanced features(trends, history, etc)
The way I am creating the Allure report is by creating the XMLs with the allure plugin for pytest, like so

```<code>pytest LoginTest.py --alluredir C:\Users\xxx\Desktop\Allure\xml
</code>```

Here will generate a hand-full of XMLs and txt files. As expected.

Next I serve the Allure with these XMLs, like so.

```<code>allure serve C:\Users\xxx\Desktop\Allure\xml --port 9000
</code>```

This then kicks off the Allure server and displays me the test results in the correct fashion and everything is great.

However, if I were to run the same test again and make it fail, for example - the server doesnt update automatically, I have to kill it and re-run the 2nd command. Surely there is a way for it to automatically notice new XMLs and update accordingly? Or am I missing something?

I also do not understand how to make use of the other features of Allure, (trends, history, etc). I have looked at Github, documentation, etc - and cant seem to find an answer to help me.

答:
You can use the docker container to see your reports automatically updated.

https://github.com/fescobar/allure-docker-service/tree/master/allure-docker-python-pytest-example

https://github.com/fescobar/allure-docker-service

Body:
The way I am creating the Allure report is by creating the XMLs with the allure plugin for pytest, like so

pytest LoginTest.py --alluredir C:\Users\xxx\Desktop\Allure\xml

Here will generate a hand-full of XMLs and txt files. As expected.

Next I serve the Allure with these XMLs, like so.

allure serve C:\Users\xxx\Desktop\Allure\xml --port 9000

This then kicks off the Allure server and displays me the test results in the correct fashion and everything is great.

However, if I were to run the same test again and make it fail, for example - the server doesnt update automatically, I have to kill it and re-run the 2nd command. Surely there is a way for it to automatically notice new XMLs and update accordingly? Or am I missing something?

I also do not understand how to make use of the other features of Allure, (trends, history, etc). I have looked at Github, documentation, etc - and cant seem to find an answer to help me.


问:
How to create virtual env with python3
I am using python 2.7 + virtualenv version 1.10.1 for running myproject projects. Due to some other projects requirement I have to work with other version of python(Python 3.5) and Django 1.9. For this I have installed python in my user directory. Also I have dowloaded and installed virtualenv( version - 15.1.0) into my user directory.
But whenever I am trying to create virtual env I am getting the below error

```<code>python virtualenv/virtualenv.py myproject
</code>```

```<code>Using base prefix '/home/myuser/python3'
New python executable in /home/mount/myuser/project_python3/myproject/bin/python
ERROR: The executable /home/mount/myuser/project_python3/myproject/bin/python is not functioning
ERROR: It thinks sys.prefix is '/home/myuser/python3' (should be '/home/mount/myuser/project_python3/myproject')
ERROR: virtualenv is not compatible with this system or executable
</code>```

Can anybody tell what I am doing wrong with this

答:
Since the launch of Python version 3.3, there has been no need to download the virtualenv package separately as it comes built-in in Python.

Refer to the documentation to gain complete insights on it.

Test the installation of virtualenv:

```<code>$ virtualenv --version
</code>```

Usage:

1.Creating a virtual environment:

  $ virtualenv --system-site-packages -p python3 ./virtual_env_name

2.For enabling it, use the following command:

  $ source ./virtual_env_name/bin/activate

3.For disabling the virtual environment and get back to working with the local environment:

  $ deactivate

For listing down the packages in the virtual environment, use the
  following command:

  $ pip3 list

Title: How to create virtual env with python3

Body:
I am using python 2.7 + virtualenv version 1.10.1 for running myproject projects. Due to some other projects requirement I have to work with other version of python(Python 3.5) and Django 1.9. For this I have installed python in my user directory. Also I have dowloaded and installed virtualenv( version - 15.1.0) into my user directory.
But whenever I am trying to create virtual env I am getting the below error

python virtualenv/virtualenv.py myproject

Using base prefix '/home/myuser/python3'
New python executable in /home/mount/myuser/project_python3/myproject/bin/python
ERROR: The executable /home/mount/myuser/project_python3/myproject/bin/python is not functioning
ERROR: It thinks sys.prefix is '/home/myuser/python3' (should be '/home/mount/myuser/project_python3/myproject')
ERROR: virtualenv is not compatible with this system or executable

Can anybody tell what I am doing wrong with this

Body:
Since the launch of Python version 3.3, there has been no need to download the virtualenv package separately as it comes built-in in Python.

Refer to the documentation to gain complete insights on it.

Test the installation of virtualenv:

$ virtualenv --version

Usage:

1.Creating a virtual environment:

  $ virtualenv --system-site-packages -p python3 ./virtual_env_name

2.For enabling it, use the following command:

  $ source ./virtual_env_name/bin/activate

3.For disabling the virtual environment and get back to working with the local environment:

  $ deactivate

For listing down the packages in the virtual environment, use the
  following command:

  $ pip3 list


问:
How to make CSS Sticky work with Flex issue
I have an HTML structure where I can't seem to get the CSS position sticky working.

I think it because it's within the aside container. If I make aside stick it works.

I want the .product-info div to be sticky and when it hits the div .content-other it unsticks.

Unless with flex I could move out .personal-info and .product-info from within the aside and have them sit to the right on top of each other? Like

content | Personal info
         | Product info

Then not bother having the wrapping aside? Not sure how to stack these like this though with flex.

body {
  padding: 20px;
}

.container {
  margin-left: auto;
  margin-right: auto;
  position: relative;
  padding-bottom: 16px;
  padding-top: 16px;
  width: 100%;
  display: flex;
}

.content {
  position: relative;
  max-width: 100%;
  flex-basis: 74%;
  border: 1px solid black;
  width: 300px;
  margin-right: 20px;
  height: 540px;
}

.right-side {
  align-self: flex-start;
  background-color: #ffffff;
  border: 2px solid #e8e8e3;
  border-radius: 0 4px 4px 4px;
  flex: 1 1;
  flex-basis: 40%;
  min-width: 338px;
  padding: 16px 16px 0;
  display: block;
  width: 400px;
}

.personal-info {
  height: 250px;
}

.product-info {
  position: sticky;
  position: -webkit-sticky;
  top: 24px;
  border: 1px solid red;
}

.content-other {
  width: 100%;
  background: #f5f5f5;
  height: 400px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="content">content area here</div>
  <aside class="right-side">
    <div class="personal-info">some info</div>
    <div class="product-info">sticky info</div>
  </aside>
</div>

<div class="content-other">.product-info unsticks when it hits here</div></code>```

Cheers

答:
Simply remove align-self: flex-start;

body {
  padding: 20px;
}

.container {
  margin-left: auto;
  margin-right: auto;
  position: relative;
  padding-bottom: 16px;
  padding-top: 16px;
  width: 100%;
  display: flex;
}

.content {
  position: relative;
  max-width: 100%;
  flex-basis: 74%;
  border: 1px solid black;
  width: 300px;
  margin-right: 20px;
  height: 540px;
}

.right-side {
  /*align-self: flex-start;*/
  background-color: #ffffff;
  border: 2px solid #e8e8e3;
  border-radius: 0 4px 4px 4px;
  flex: 1 1;
  flex-basis: 40%;
  min-width: 338px;
  padding: 16px 16px 0;
  display: block;
  width: 400px;
}

.personal-info {
  height: 250px;
}

.product-info {
  position: sticky;
  position: -webkit-sticky;
  top: 24px;
  border: 1px solid red;
}

.content-other {
  width: 100%;
  background: #f5f5f5;
  height: 400px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="content">content area here</div>
  <aside class="right-side">
    <div class="personal-info">some info</div>
    <div class="product-info">sticky info</div>
  </aside>
</div>

<div class="content-other">.product-info unsticks when it hits here</div></code>```

Body:
I have an HTML structure where I can't seem to get the CSS position sticky working.

I think it because it's within the aside container. If I make aside stick it works.

I want the .product-info div to be sticky and when it hits the div .content-other it unsticks.

Unless with flex I could move out .personal-info and .product-info from within the aside and have them sit to the right on top of each other? Like

content | Personal info
         | Product info

Then not bother having the wrapping aside? Not sure how to stack these like this though with flex.

body {
  padding: 20px;
}

.container {
  margin-left: auto;
  margin-right: auto;
  position: relative;
  padding-bottom: 16px;
  padding-top: 16px;
  width: 100%;
  display: flex;
}

.content {
  position: relative;
  max-width: 100%;
  flex-basis: 74%;
  border: 1px solid black;
  width: 300px;
  margin-right: 20px;
  height: 540px;
}

.right-side {
  align-self: flex-start;
  background-color: #ffffff;
  border: 2px solid #e8e8e3;
  border-radius: 0 4px 4px 4px;
  flex: 1 1;
  flex-basis: 40%;
  min-width: 338px;
  padding: 16px 16px 0;
  display: block;
  width: 400px;
}

.personal-info {
  height: 250px;
}

.product-info {
  position: sticky;
  position: -webkit-sticky;
  top: 24px;
  border: 1px solid red;
}

.content-other {
  width: 100%;
  background: #f5f5f5;
  height: 400px;
}

content area here

some info

sticky info

.product-info unsticks when it hits here

Cheers

Body:
Simply remove align-self: flex-start;

body {
  padding: 20px;
}

.container {
  margin-left: auto;
  margin-right: auto;
  position: relative;
  padding-bottom: 16px;
  padding-top: 16px;
  width: 100%;
  display: flex;
}

.content {
  position: relative;
  max-width: 100%;
  flex-basis: 74%;
  border: 1px solid black;
  width: 300px;
  margin-right: 20px;
  height: 540px;
}

.right-side {
  /*align-self: flex-start;*/
  background-color: #ffffff;
  border: 2px solid #e8e8e3;
  border-radius: 0 4px 4px 4px;
  flex: 1 1;
  flex-basis: 40%;
  min-width: 338px;
  padding: 16px 16px 0;
  display: block;
  width: 400px;
}

.personal-info {
  height: 250px;
}

.product-info {
  position: sticky;
  position: -webkit-sticky;
  top: 24px;
  border: 1px solid red;
}

.content-other {
  width: 100%;
  background: #f5f5f5;
  height: 400px;
}

<div class="container">
  <div class="content">content area here</div>
  <aside class="right-side">
    <div class="personal-info">some info</div>
    <div class="product-info">sticky info</div>
  </aside>
</div>

<div class="content-other">.product-info unsticks when it hits here</div>


问:
Check if an object is present in a nested array reactjs
I have the following set of data:

person:

```<code>person: { id:1
          groups:[
                  {id:1 , name: john, permissions : [{id:1 , codename="can_edit"},{id:2,codename="can_write"},{id:3,codename="can_delete"}]} ,

                  ]
            }
</code>```

What i wish to do is conduct some conditional rendering based on whether this user has a permission.

```<code>             { this.passtest()?
            <Button type="primary" shape="circle" icon={<EditOutlined />}/>
              :
              null
              }
</code>```

This will then call the this.passtest() method which will contain the logic for checking if the user has the permission i require :

```<code>   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      // Not sure what logic I can put here to return true as long as the permission 'codename' field tallies
     });

    return passing
  }
</code>```

Would appreciate your help! Thanks!

答:
```<code>   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      group.permissions.forEach((permission) => {
        // do a check in here for each permission
        if (permission.codename === 'can_edit') {
            return true
        }
      })
      return false
     });

    return passing
  }
</code>```

Body:
I have the following set of data:

person:

person: { id:1
          groups:[
                  {id:1 , name: john, permissions : [{id:1 , codename="can_edit"},{id:2,codename="can_write"},{id:3,codename="can_delete"}]} ,

                  ]
            }

What i wish to do is conduct some conditional rendering based on whether this user has a permission.

             { this.passtest()?
            <Button type="primary" shape="circle" icon={<EditOutlined />}/>
              :
              null
              }

This will then call the this.passtest() method which will contain the logic for checking if the user has the permission i require :

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      // Not sure what logic I can put here to return true as long as the permission 'codename' field tallies
     });

    return passing
  }

Would appreciate your help! Thanks!


问:
Rails help model design problem
I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a ZeroDivisionerror.

What is the best solution to solve this kind of problem?

My model:

```<code>before_update :do_foobar
def do_foobar
  self.rating = (rating_score/ratings)
end
</code>```

答:
You have to initialize this value before use, for example like this:</p>

```<code>def do_foobar
  self.rating |= 1
  self.rating = (rating_score/rating)
end
</code>```

Title: Rails help model design problem

Body:
I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a ZeroDivisionerror.

What is the best solution to solve this kind of problem?

My model:

before_update :do_foobar
def do_foobar
  self.rating = (rating_score/ratings)
end

Body:
You have to initialize this value before use, for example like this:

def do_foobar
  self.rating |= 1
  self.rating = (rating_score/rating)
end


问:
How to store Object in SortedList
I have a sorted list that contains a name and a integer value. I am new to c sharp, so I am not sure what am I doing wrong.

My code:

//first class

```<code>class Tool {
 public Tool(string name, int quantity)
        {
            this.name = name;
            this.quantity = quantity;
        }
}
</code>```

//main class

This is a different class (2nd class)

```<code> SortedList<Tool> gardeningTools = new SortedList<Tool>(); //error

        gardeningTools.Add(new Tool("nameA", 1)); //error
</code>```

Here I am trying to add some kinds of tools inside the gardening tools. The above two lines has error says "new" is not a valid keyword and both of the lines are red. I assume it's completely a wrong way to write like that. Could anyone tell me how to write it the right way?

答:
SortedList requires two generic type arguments, the type of the key and the type of the item you're storing. In your case this might be:

```<code>SortedList<string, Tool> gardeningTools = new SortedList<string, Tool>();
</code>```

Assuming that Tool is defined something like this:

```<code>class Tool
{
  public Tool(string name, int quantity)
  {
    this.Name = name;
    this.Quantity = quantity;
  }

  public string Name{get;}
  public int Quantity{get;}
}
</code>```

Also, the Add method takes two parameters, the key, and the value, so you want something like this:

```<code>Tool tool = new Tool("nameA", 1);
gardeningTools.Add(tool.Name, tool);
</code>```

Now you can acccess them in order. For example:

```<code>foreach(var tool in gardeningTools.Values)
{
  Console.WriteLine("Name = {0}, Qty = {1}", tool.Name, tool.Quantity);
}
</code>```

Title: How to store Object in SortedList

Body:
I have a sorted list that contains a name and a integer value. I am new to c sharp, so I am not sure what am I doing wrong.

My code:

//first class

class Tool {
 public Tool(string name, int quantity)
        {
            this.name = name;
            this.quantity = quantity;
        }
}

//main class

This is a different class (2nd class)

 SortedList<Tool> gardeningTools = new SortedList<Tool>(); //error

        gardeningTools.Add(new Tool("nameA", 1)); //error

Here I am trying to add some kinds of tools inside the gardening tools. The above two lines has error says "new" is not a valid keyword and both of the lines are red. I assume it's completely a wrong way to write like that. Could anyone tell me how to write it the right way?

Body:
SortedList requires two generic type arguments, the type of the key and the type of the item you're storing. In your case this might be:

SortedList<string, Tool> gardeningTools = new SortedList<string, Tool>();

Assuming that Tool is defined something like this:

class Tool
{
  public Tool(string name, int quantity)
  {
    this.Name = name;
    this.Quantity = quantity;
  }

  public string Name{get;}
  public int Quantity{get;}
}

Also, the Add method takes two parameters, the key, and the value, so you want something like this:

Tool tool = new Tool("nameA", 1);
gardeningTools.Add(tool.Name, tool);

Now you can acccess them in order. For example:

foreach(var tool in gardeningTools.Values)
{
  Console.WriteLine("Name = {0}, Qty = {1}", tool.Name, tool.Quantity);
}


问:
recyclerview not rendering to screen
I have the following XML file -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E0E0E0 "
    android:orientation="vertical"
    tools:context=".fragments.CountriesListFragment">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/white"
        app:title="Countries" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/fragment_countries_list_countries_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:listitem="@layout/country_viewholder" />

</LinearLayout>
```

<p>and the following fragment - </p>

<pre class="lang-kotlin prettyprint-override"><code>class CountriesListFragment : Fragment(R.layout.fragment_countries_list) {

    private lateinit var countriesViewModel: CountriesListViewModel
    private lateinit var countriesAdapter: CountriesListAdapter
    private var countriesList = mutableListOf<CountryEntity>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setHasOptionsMenu(true)
        initViewModel()
        init()
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.country_list_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    private fun initViewModel(){
        countriesViewModel = ViewModelProvider(this).get(CountriesListViewModel::class.java)
        countriesViewModel.fetchAllCountries(object : CountriesRepository.CountryFetchCallback {
            override fun onFetchError(reason: String) {
                Toast.makeText(context, reason, Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun init() {
        countriesAdapter = CountriesListAdapter(countriesList)
        countriesRecyclerview.adapter = countriesAdapter
        countriesRecyclerview.setHasFixedSize(true)
        countriesRecyclerview.layoutManager = LinearLayoutManager(context)
        countriesViewModel.getAllCountries().observe(requireActivity(), Observer { countryList ->
            countriesList.addAll(countryList)
            countriesAdapter.notifyDataSetChanged()
        })
    }
}
</code>```

edit -

my adapter -

class CountriesListAdapter(private val countriesList: List<CountryEntity>) : RecyclerView.Adapter<CountryViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CountryViewHolder {
        val view = LayoutInflater.from(App.context!!).inflate(R.layout.country_viewholder, parent, false)
        return CountryViewHolder(view)
    }

    override fun getItemCount(): Int  = countriesList.size

    override fun onBindViewHolder(holder: CountryViewHolder, position: Int) {
        holder.bind(countriesList[position])
    }

}
```

<p>my viewholder xml - </p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tool="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@color/white"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/country_viewholder_native_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="16sp"
                tools:text="Country native name" />

            <TextView
                android:id="@+id/country_viewholder_country_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="16sp"
                tools:text="Country name" />

            <TextView
                android:id="@+id/country_viewholder_area"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="16sp"
                tools:text="Area" />

        </LinearLayout>

        <Space
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <ImageView
            android:id="@+id/country_viewholder_country_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:src="@mipmap/ic_launcher" />

    </LinearLayout>

</LinearLayout>
</code>```

the activity holding the fragment -

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CountriesListActivity">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/app_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

<p>thw navigation graph - </p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/app_navigation"
    app:startDestination="@id/countriesListFragment">

    <fragment
        android:id="@+id/countriesListFragment"
        android:name="com.countriesborders.fragments.CountriesListFragment"
        android:label="fragment_countries_list"
        tools:layout="@layout/fragment_countries_list">
        <action
            android:id="@+id/action_countriesListFragment_to_countryBordersFragment"
            app:destination="@id/countryBordersFragment" />
    </fragment>
    <fragment
        android:id="@+id/countryBordersFragment"
        android:name="com.countriesborders.fragments.CountryBordersFragment"
        android:label="fragment_country_borders"
        tools:layout="@layout/fragment_country_borders" />
</navigation>
</code>```

For some reason, the data is not being rendered into the screen. I really have no idea what is causing it, but I am stuck clueless what is happening.

I have tried adding manually hardcoded values into the list but it did not help at all.

Any idea?

答:
You have two conflicting dimensions in your layout.

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">
</code>```

As you can see, the most inner one is instructing the system to draw the items matching the parent height, but the parent layout is saying to wrap its content (and they result in a 0 height in the end). If you change the inner one to match_parent, it will work and the items will be displayed.

Title: recyclerview not rendering to screen

Body:
I have the following XML file -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E0E0E0 "
    android:orientation="vertical"
    tools:context=".fragments.CountriesListFragment">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/white"
        app:title="Countries" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/fragment_countries_list_countries_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:listitem="@layout/country_viewholder" />

</LinearLayout>

and the following fragment -

class CountriesListFragment : Fragment(R.layout.fragment_countries_list) {

    private lateinit var countriesViewModel: CountriesListViewModel
    private lateinit var countriesAdapter: CountriesListAdapter
    private var countriesList = mutableListOf<CountryEntity>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setHasOptionsMenu(true)
        initViewModel()
        init()
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.country_list_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    private fun initViewModel(){
        countriesViewModel = ViewModelProvider(this).get(CountriesListViewModel::class.java)
        countriesViewModel.fetchAllCountries(object : CountriesRepository.CountryFetchCallback {
            override fun onFetchError(reason: String) {
                Toast.makeText(context, reason, Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun init() {
        countriesAdapter = CountriesListAdapter(countriesList)
        countriesRecyclerview.adapter = countriesAdapter
        countriesRecyclerview.setHasFixedSize(true)
        countriesRecyclerview.layoutManager = LinearLayoutManager(context)
        countriesViewModel.getAllCountries().observe(requireActivity(), Observer { countryList ->
            countriesList.addAll(countryList)
            countriesAdapter.notifyDataSetChanged()
        })
    }
}

edit -

my adapter -

class CountriesListAdapter(private val countriesList: List<CountryEntity>) : RecyclerView.Adapter<CountryViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CountryViewHolder {
        val view = LayoutInflater.from(App.context!!).inflate(R.layout.country_viewholder, parent, false)
        return CountryViewHolder(view)
    }

    override fun getItemCount(): Int  = countriesList.size

    override fun onBindViewHolder(holder: CountryViewHolder, position: Int) {
        holder.bind(countriesList[position])
    }

}

my viewholder xml -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tool="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@color/white"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/country_viewholder_native_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="16sp"
                tools:text="Country native name" />

            <TextView
                android:id="@+id/country_viewholder_country_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="16sp"
                tools:text="Country name" />

            <TextView
                android:id="@+id/country_viewholder_area"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="16sp"
                tools:text="Area" />

        </LinearLayout>

        <Space
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <ImageView
            android:id="@+id/country_viewholder_country_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:src="@mipmap/ic_launcher" />

    </LinearLayout>

</LinearLayout>

the activity holding the fragment -

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CountriesListActivity">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/app_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

thw navigation graph -

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/app_navigation"
    app:startDestination="@id/countriesListFragment">

    <fragment
        android:id="@+id/countriesListFragment"
        android:name="com.countriesborders.fragments.CountriesListFragment"
        android:label="fragment_countries_list"
        tools:layout="@layout/fragment_countries_list">
        <action
            android:id="@+id/action_countriesListFragment_to_countryBordersFragment"
            app:destination="@id/countryBordersFragment" />
    </fragment>
    <fragment
        android:id="@+id/countryBordersFragment"
        android:name="com.countriesborders.fragments.CountryBordersFragment"
        android:label="fragment_country_borders"
        tools:layout="@layout/fragment_country_borders" />
</navigation>

For some reason, the data is not being rendered into the screen. I really have no idea what is causing it, but I am stuck clueless what is happening.

I have tried adding manually hardcoded values into the list but it did not help at all.

Any idea?

Body:
You have two conflicting dimensions in your layout.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

As you can see, the most inner one is instructing the system to draw the items matching the parent height, but the parent layout is saying to wrap its content (and they result in a 0 height in the end). If you change the inner one to match_parent, it will work and the items will be displayed.


问:
Checkbox Alert Controller - Show image
I make one application with IONIC-2 Beta version. i 'm use Checkbox Alert Controller, and want to add image like,

my code is

```<code>showCheckbox() {
let alert = this.alertCtrl.create();
alert.setTitle('Which planets have you visited?');

alert.addInput({
  type: 'checkbox',
  label: 'Alderaan',
  value: 'value1',
  checked: true
});

alert.addInput({
  type: 'checkbox',
  label: 'Bespin',
  value: 'value2'
});

alert.addButton('Cancel');
alert.addButton({
  text: 'Okay',
  handler: data => {
    console.log('Checkbox data:', data);
    this.testCheckboxOpen = false;
    this.testCheckboxResult = data;
  }
});
alert.present();
</code>```

}

is it possible to add image like this??

If anyone knows the solution, please help me.

Thanks.

答: Actually you can add the image as html tags in message.  Here's the answer that helped me do this.</p>

Title: Checkbox Alert Controller - Show image

Body:
I make one application with IONIC-2 Beta version. i 'm use Checkbox Alert Controller, and want to add image like,

my code is

showCheckbox() {
let alert = this.alertCtrl.create();
alert.setTitle('Which planets have you visited?');

alert.addInput({
  type: 'checkbox',
  label: 'Alderaan',
  value: 'value1',
  checked: true
});

alert.addInput({
  type: 'checkbox',
  label: 'Bespin',
  value: 'value2'
});

alert.addButton('Cancel');
alert.addButton({
  text: 'Okay',
  handler: data => {
    console.log('Checkbox data:', data);
    this.testCheckboxOpen = false;
    this.testCheckboxResult = data;
  }
});
alert.present();

}

is it possible to add image like this??

If anyone knows the solution, please help me.

Thanks.