问:
Receiving message from Service Bus queue is working on console apps but not in windows form apps?
I have the following c# functions that allow me to receive messages from a given queue from Azure, it works fine on console apps :

```<code>public  async Task MainReceiver()
        {
            queueClient = new QueueClient(connectionString, queueName);

            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 5,
                AutoComplete = false,

            };

            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);

            Console.ReadLine();

            await queueClient.CloseAsync();
        }

        public  async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            var jsonString = Encoding.UTF8.GetString(message.Body);
            Console.WriteLine($"Person Received: { jsonString }");
            List<string> data = new List<string>();

            if (messageLists.ContainsKey(queueName))
            {
                data = messageLists[queueName];
                messageLists.Remove(queueName);
                data.Add(jsonString);
            }
            else
            {
                data.Add(jsonString);
            }
            messageLists.Add(queueName, data);

            await queueClient.CompleteAsync(message.SystemProperties.LockToken);
        }
</code>```

My goal now is to list the messages using a listbox control.
But if i try to call the same main methode in a button click, nothing happends, in debug mode i noticed that my breakpoint in ProcessMessagesAsync is never reached by my win form app.

```<code>public async void button2_Click(object sender, EventArgs e)
        {
            await receiveMessage();
        }
public async Task receiveMessage()
        {
            await messages.MainReceiver();
            List<string> data = new List<string>();
            data = messages.messageLists["eventsqueue"];
            for (int i = 0; i < messages.messageLists.Count; i++)
                listBox1.Items.Add(data[i]);
        }
</code>```

I tried to use to queue my task in the thread pool using the following code , but it didn't help :

```<code>ThreadPool.QueueUserWorkItem(async (w) => await messages.MainReceiver());
</code>```

答:
Please follow the below workaround to achieve Service Bus queue messages into Windows Forms

Three major steps to show your data into LISTBOX

Create a list box using the ListBox() constructor is provided by the ListBox class.

```<code> ListBox listBox1 = new ListBox();
</code>```

Set/Add the Items property of the ListBox provided by the ListBox class.

```<code> listBox1.Items.Add("your data to add in listbox");
</code>```

Add this ListBox control to the form using Add() method.

```<code> this.Controls.Add(listBox1);
</code>```

Here I am following the above steps.

Program.cs

    using System.Collections.Generic;
    using System.Windows.Forms;

    namespace servicebuswinform
    {
        using Microsoft.Azure.ServiceBus;
        using System;
        using System.Text;
        using System.Threading;
        using System.Threading.Tasks;
        public class Program
        {
            const string ServiceBusConnectionString = <ServiceBus Connection string>;
            const string QueueName = "<Queue name>";
            static IQueueClient queueClient;
            public static List<string> data = new List<string>();

            [STAThread]

            public static void Main()
            {
                Application.SetHighDpiMode(HighDpiMode.SystemAware);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }

            public static async Task MainAsync()
            {
                const int numberOfMessages = 10;
                queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
                RegisterOnMessageHandlerAndReceiveMessages();
                // Send Messages
                await SendMessagesAsync(numberOfMessages);
                await queueClient.CloseAsync();
            }

            public static void RegisterOnMessageHandlerAndReceiveMessages()
            {
                var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
                {
                    MaxConcurrentCalls = 1,
                    AutoComplete = false
                };
                // Register the function that will process messages
                queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
            }

            public static async Task ProcessMessagesAsync(Message message, CancellationToken token)
            {
                //Adding message into list
                data.Add("Received message: SequenceNumber:"+ message.SystemProperties.SequenceNumber.ToString()+" Body:" + Encoding.UTF8.GetString(message.Body));
                await queueClient.CompleteAsync(message.SystemProperties.LockToken);
            }

        // Use this Handler to look at the exceptions received on the MessagePump

            public static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
            {
                Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
                var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
                Console.WriteLine("Exception context for troubleshooting:");
                Console.WriteLine($"- Endpoint: {context.Endpoint}");
                Console.WriteLine($"- Entity Path: {context.EntityPath}");
                Console.WriteLine($"- Executing Action: {context.Action}");
                return Task.CompletedTask;
            }

            public static async Task SendMessagesAsync(int numberOfMessagesToSend)
            {
                try
                {
                for (var i = 0; i < numberOfMessagesToSend; i++)
                    {
                        // Create a new message to send to the queue
                        string messageBody = $"Message {i}";
                        var message = new Message(Encoding.UTF8.GetBytes(messageBody));
                        // Write the body of the message to the console
                        Console.WriteLine($"Sending message: {messageBody}");
                        // Send the message to the queue
                        await queueClient.SendAsync(message);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
                }
            }
        }
    }
```
<p><strong>Form.cs</strong></p>
<p><strong>Here I am adding one button if we hit the button it will get the service bus queue messages and it will be added in Listbox.</strong></p>
<pre class="lang-cs prettyprint-override"><code>    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    namespace servicebuswinform
    {
        public partial class Form1 : Form
        {
            public static List<string> data1 = new List<string>();
            public Form1()
            {
                InitializeComponent();
            }

            public async void button1_Click(object sender, EventArgs e)
            {
                await receiveMessage();
                ListBox listBox1 = new ListBox();
                this.listBox1.Visible = true;
                for (int i = 0; i < data1.Count; i++)
                {
                    listBox1.FormattingEnabled = true;
                    listBox1.Enabled = true;
                    listBox1.Size = new System.Drawing.Size(692, 214);
                    listBox1.Location = new System.Drawing.Point(1, 131);
                    listBox1.MultiColumn = true;
                    listBox1.SelectionMode = SelectionMode.MultiExtended;
                    listBox1.BeginUpdate();
                    listBox1.Items.Add("item" + data1[i].ToString());
                }
                this.Controls.Add(listBox1);
            }

            public static async Task receiveMessage()
            {
                await Program.MainAsync();
                data1 = Program.data;
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                this.listBox1.Visible = false;
            }
        }
    }
</code>```

You can follow the above steps which I have mentioned. Using this I can see the list of service bus queue messages in windows forms

Body:
I have the following c# functions that allow me to receive messages from a given queue from Azure, it works fine on console apps :

public  async Task MainReceiver()
        {
            queueClient = new QueueClient(connectionString, queueName);

            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 5,
                AutoComplete = false,

            };

            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);

            Console.ReadLine();

            await queueClient.CloseAsync();
        }

        public  async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            var jsonString = Encoding.UTF8.GetString(message.Body);
            Console.WriteLine($"Person Received: { jsonString }");
            List<string> data = new List<string>();

            if (messageLists.ContainsKey(queueName))
            {
                data = messageLists[queueName];
                messageLists.Remove(queueName);
                data.Add(jsonString);
            }
            else
            {
                data.Add(jsonString);
            }
            messageLists.Add(queueName, data);

            await queueClient.CompleteAsync(message.SystemProperties.LockToken);
        }

My goal now is to list the messages using a listbox control.
But if i try to call the same main methode in a button click, nothing happends, in debug mode i noticed that my breakpoint in ProcessMessagesAsync is never reached by my win form app.

public async void button2_Click(object sender, EventArgs e)
        {
            await receiveMessage();
        }
public async Task receiveMessage()
        {
            await messages.MainReceiver();
            List<string> data = new List<string>();
            data = messages.messageLists["eventsqueue"];
            for (int i = 0; i < messages.messageLists.Count; i++)
                listBox1.Items.Add(data[i]);
        }

I tried to use to queue my task in the thread pool using the following code , but it didn't help :

ThreadPool.QueueUserWorkItem(async (w) => await messages.MainReceiver());

Body:
Please follow the below workaround to achieve Service Bus queue messages into Windows Forms

Three major steps to show your data into LISTBOX

Create a list box using the ListBox() constructor is provided by the ListBox class.

 ListBox listBox1 = new ListBox();

Set/Add the Items property of the ListBox provided by the ListBox class.

 listBox1.Items.Add("your data to add in listbox");

Add this ListBox control to the form using Add() method.

 this.Controls.Add(listBox1);

Here I am following the above steps.

Program.cs

    using System.Collections.Generic;
    using System.Windows.Forms;

    namespace servicebuswinform
    {
        using Microsoft.Azure.ServiceBus;
        using System;
        using System.Text;
        using System.Threading;
        using System.Threading.Tasks;
        public class Program
        {
            const string ServiceBusConnectionString = <ServiceBus Connection string>;
            const string QueueName = "<Queue name>";
            static IQueueClient queueClient;
            public static List<string> data = new List<string>();

            [STAThread]

            public static void Main()
            {
                Application.SetHighDpiMode(HighDpiMode.SystemAware);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }

            public static async Task MainAsync()
            {
                const int numberOfMessages = 10;
                queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
                RegisterOnMessageHandlerAndReceiveMessages();
                // Send Messages
                await SendMessagesAsync(numberOfMessages);
                await queueClient.CloseAsync();
            }

            public static void RegisterOnMessageHandlerAndReceiveMessages()
            {
                var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
                {
                    MaxConcurrentCalls = 1,
                    AutoComplete = false
                };
                // Register the function that will process messages
                queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
            }

            public static async Task ProcessMessagesAsync(Message message, CancellationToken token)
            {
                //Adding message into list
                data.Add("Received message: SequenceNumber:"+ message.SystemProperties.SequenceNumber.ToString()+" Body:" + Encoding.UTF8.GetString(message.Body));
                await queueClient.CompleteAsync(message.SystemProperties.LockToken);
            }

        // Use this Handler to look at the exceptions received on the MessagePump

            public static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
            {
                Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
                var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
                Console.WriteLine("Exception context for troubleshooting:");
                Console.WriteLine($"- Endpoint: {context.Endpoint}");
                Console.WriteLine($"- Entity Path: {context.EntityPath}");
                Console.WriteLine($"- Executing Action: {context.Action}");
                return Task.CompletedTask;
            }

            public static async Task SendMessagesAsync(int numberOfMessagesToSend)
            {
                try
                {
                for (var i = 0; i < numberOfMessagesToSend; i++)
                    {
                        // Create a new message to send to the queue
                        string messageBody = $"Message {i}";
                        var message = new Message(Encoding.UTF8.GetBytes(messageBody));
                        // Write the body of the message to the console
                        Console.WriteLine($"Sending message: {messageBody}");
                        // Send the message to the queue
                        await queueClient.SendAsync(message);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
                }
            }
        }
    }

Form.cs

Here I am adding one button if we hit the button it will get the service bus queue messages and it will be added in Listbox.

    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    namespace servicebuswinform
    {
        public partial class Form1 : Form
        {
            public static List<string> data1 = new List<string>();
            public Form1()
            {
                InitializeComponent();
            }

            public async void button1_Click(object sender, EventArgs e)
            {
                await receiveMessage();
                ListBox listBox1 = new ListBox();
                this.listBox1.Visible = true;
                for (int i = 0; i < data1.Count; i++)
                {
                    listBox1.FormattingEnabled = true;
                    listBox1.Enabled = true;
                    listBox1.Size = new System.Drawing.Size(692, 214);
                    listBox1.Location = new System.Drawing.Point(1, 131);
                    listBox1.MultiColumn = true;
                    listBox1.SelectionMode = SelectionMode.MultiExtended;
                    listBox1.BeginUpdate();
                    listBox1.Items.Add("item" + data1[i].ToString());
                }
                this.Controls.Add(listBox1);
            }

            public static async Task receiveMessage()
            {
                await Program.MainAsync();
                data1 = Program.data;
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                this.listBox1.Visible = false;
            }
        }
    }

You can follow the above steps which I have mentioned. Using this I can see the list of service bus queue messages in windows forms


来源: stackexchange

问:
How do you return the last element in an array in C?
How do I return the last element in an array? I thought this function would work, as it worked for a similar function that returned the first element.</p>
```<code>int END(int arr[]) {
    int last;
    size_t s = sizeof(arr) / sizeof(arr[0]);
    if (s != 0) {
        last = arr[s - 1];
        return last;
    } else {
        return -1 ; //END(arr);
    }
}
</code>```

答:
int END(int arr[]) is adjusted to int END(int* arr), since you can't pass arrays as arguments in C. This means that sizeof(arr) is sizeof(int*), and your calculation for s is wrong.

You can use a macro for this, as the macro argument won't be turned into a pointer implicitly:

#define END(ARR) (ARR)[(sizeof(ARR) / sizeof((ARR)[0])) - 1u]
```

(Note that there are no arrays of size 0, so your -1 case is redundant)

ContentLicense: CC BY-SA 4.0

Body:
How do I return the last element in an array? I thought this function would work, as it worked for a similar function that returned the first element.

int END(int arr[]) {
    int last;
    size_t s = sizeof(arr) / sizeof(arr[0]);
    if (s != 0) {
        last = arr[s - 1];
        return last;
    } else {
        return -1 ; //END(arr);
    }
}

Body:
int END(int arr[]) is adjusted to int END(int* arr), since you can't pass arrays as arguments in C. This means that sizeof(arr) is sizeof(int*), and your calculation for s is wrong.

You can use a macro for this, as the macro argument won't be turned into a pointer implicitly:

#define END(ARR) (ARR)[(sizeof(ARR) / sizeof((ARR)[0])) - 1u]

(Note that there are no arrays of size 0, so your -1 case is redundant)


问:
Returning index of an Array when it stops increasing and begins decreasing
having a problem when running two tests using this code, test 1 returns the whole array, test2 returns the appropriate index. (the point in the array in which it stops decreasing or increasing and starts the reverse) if there is only one sequence it should return -1

the test cases are
Input: [-4, -2, 9, 10]
Output: -1
Input: [5, 4, 3, 2, 10, 11]
Output: 3

```<code>for (i = 0; i < arr.length; i++) {
    while (arr[i] < arr[i + 1]) {
      i++;
      if (arr[i] < arr[i - 1]) {
        return -1
      }
      else if (arr[i] > arr[i + 1]) {
        return i
      }
    } while (arr[i] > arr[i + 1]) {
      i++;
      if (arr[i] > arr[i - 1]) {
        return -1
      } else if (arr[i] < arr[i + 1]) {
        return i
      }
    }
  }
  return arr;

}
</code>```

答:
Maybe this approach would be useful:

Find the index of the maximum and minimum element.
Check if this index is the beginning or the end of the array and retern -1 if it is.
And last return the maximal index out of the found ones.

  const first = [-4, -2, 9, 10];
  const second = [5, 4, 3, 2, 10, 11];

  const getMyIndex = (arr) => {
    const maxIndex = arr.indexOf(Math.max(...arr));
    const minIndex = arr.indexOf(Math.min(...arr));
    const getResult = (index) =>
      (index === 0) || (index === arr.length - 1) ? -1 : index;

    return Math.max(getResult(maxIndex), getResult(minIndex));
  };

  console.log('arr:', first, 'result:', getMyIndex(first));
  console.log('arr:', second, 'result:', getMyIndex(second));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height: 100%!important; top: 0}</code>```

Body:
having a problem when running two tests using this code, test 1 returns the whole array, test2 returns the appropriate index. (the point in the array in which it stops decreasing or increasing and starts the reverse) if there is only one sequence it should return -1

the test cases are
Input: [-4, -2, 9, 10]
Output: -1
Input: [5, 4, 3, 2, 10, 11]
Output: 3

for (i = 0; i < arr.length; i++) {
    while (arr[i] < arr[i + 1]) {
      i++;
      if (arr[i] < arr[i - 1]) {
        return -1
      }
      else if (arr[i] > arr[i + 1]) {
        return i
      }
    } while (arr[i] > arr[i + 1]) {
      i++;
      if (arr[i] > arr[i - 1]) {
        return -1
      } else if (arr[i] < arr[i + 1]) {
        return i
      }
    }
  }
  return arr;

}

Body:
Maybe this approach would be useful:

Find the index of the maximum and minimum element.
Check if this index is the beginning or the end of the array and retern -1 if it is.
And last return the maximal index out of the found ones.

  const first = [-4, -2, 9, 10];
  const second = [5, 4, 3, 2, 10, 11];

  const getMyIndex = (arr) => {
    const maxIndex = arr.indexOf(Math.max(...arr));
    const minIndex = arr.indexOf(Math.min(...arr));
    const getResult = (index) =>
      (index === 0) || (index === arr.length - 1) ? -1 : index;

    return Math.max(getResult(maxIndex), getResult(minIndex));
  };

  console.log('arr:', first, 'result:', getMyIndex(first));
  console.log('arr:', second, 'result:', getMyIndex(second));

.as-console-wrapper{min-height: 100%!important; top: 0}


问:
Strip blanks at the beginning & trailing blanks in AWK
I am asking for your assistance to strip blanks/spaces before & at the end each field. ie Remove the trailing space from the $1, the same apply to the beginning & trailing spaces in $2, and the leading spaces from $3 using AWK on AIX 7.2 platform. Below is some data in the file Employee.txt

```<code>001 |  George John Aden Brown   | gbrown
002 |   Barry Street White      | bwhite
003 |    Kelly Jones            | kjones
004 |   Jolene Davidson Smith   | jsmith
</code>```

My objective is to achieve the following set of data (without the leading/trailing spaces)

```<code>001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
</code>```

I have tried the following without satisfaction.

```<code>awk -F"|" '{ print $1 "|" gsub(" ", "", $2) "|" $3 }' Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[ \t]/,"",$2) "|" $3 }'  Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[[:blank:]]/, "", $2) "|" $3 }' Employee.txt

001 |8| gbrown
002 |11| bwhite
003 |17| kjones
004 |8| jsmith
</code>```

答:
With your shown samples, please try following awk code. Written and tested in GNU awk, should work in any awk. Simple explanation would be, setting field separator as [[:space:]]+\\|[[:space:]]+(spaces followed by pipe followed by spaces) for all the lines of Input_file then setting OFS as | for all the lines. In main program then resetting $1 to itself to actually apply new value of OFS to whole line, once its done, simple printing that line by mentioning 1.

```<code>awk -v FS='[[:space:]]+\\|[[:space:]]+' -v OFS='|' '{$1=$1} 1'  Input_file
</code>```

Body:
I am asking for your assistance to strip blanks/spaces before & at the end each field. ie Remove the trailing space from the $1, the same apply to the beginning & trailing spaces in $2, and the leading spaces from $3 using AWK on AIX 7.2 platform. Below is some data in the file Employee.txt

001 |  George John Aden Brown   | gbrown
002 |   Barry Street White      | bwhite
003 |    Kelly Jones            | kjones
004 |   Jolene Davidson Smith   | jsmith

My objective is to achieve the following set of data (without the leading/trailing spaces)

001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith

I have tried the following without satisfaction.

awk -F"|" '{ print $1 "|" gsub(" ", "", $2) "|" $3 }' Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[ \t]/,"",$2) "|" $3 }'  Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[[:blank:]]/, "", $2) "|" $3 }' Employee.txt

001 |8| gbrown
002 |11| bwhite
003 |17| kjones
004 |8| jsmith

Body:
With your shown samples, please try following awk code. Written and tested in GNU awk, should work in any awk. Simple explanation would be, setting field separator as [[:space:]]+\\|[[:space:]]+(spaces followed by pipe followed by spaces) for all the lines of Input_file then setting OFS as | for all the lines. In main program then resetting $1 to itself to actually apply new value of OFS to whole line, once its done, simple printing that line by mentioning 1.

awk -v FS='[[:space:]]+\\|[[:space:]]+' -v OFS='|' '{$1=$1} 1'  Input_file


问:
Python: eval() combined with list comprehension does not work in AWS Lambda
I executed the following code in my MacBook Pro, with Python 3.9.8, and the code yielded what I expected.

```<code>lista = [{'hello': 'foo'}, {'hello': 'bar'}]
listb = ["a['hello']"]
for a in lista:
    print([eval(x) for x in listb])

# result
['foo']
['bar']
</code>```

However, if I execute the exactly same code on AWS Lambda, an error occurrs:

```<code>[ERROR] NameError: name 'a' is not defined
</code>```

The same error occurs if I replace the list comprehension with map() and a lambda function.
If I use a for loop instead, it works well.

```<code>lista = [{'hello': 'foo'}, {'hello': 'bar'}]
listb = ["a['hello']"]
for a in lista:
    listc = []
    for x in listb:
        listc.append(eval(x))
    print(listc)

# result
['foo']
['bar']
</code>```

What would be the reason for this?

答:
This is partially based on a guess, so it may be wrong, but here goes:

Guess: The code in AWS Lambda gets wrapped in a function. This is at least plausible, because I get the same error if I wrap it in a function and run it locally.

Now, the documentation for eval says

Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

So, when you run the code at the module level, a is a global variable, and the eval:ed expression can see it. However, when the code is wrapped in a function, a is function local. Since the list comprehension introduces an even more local scope, the eval:ed expression does not see the function scope! Similarly, a lambda creates an intermediate scope that hides the function scope.

Using for loops, however, does not create an intermediate scope, so then eval can see the function scope.

Body:
I executed the following code in my MacBook Pro, with Python 3.9.8, and the code yielded what I expected.

lista = [{'hello': 'foo'}, {'hello': 'bar'}]
listb = ["a['hello']"]
for a in lista:
    print([eval(x) for x in listb])

# result
['foo']
['bar']

However, if I execute the exactly same code on AWS Lambda, an error occurrs:

[ERROR] NameError: name 'a' is not defined

The same error occurs if I replace the list comprehension with map() and a lambda function.
If I use a for loop instead, it works well.

lista = [{'hello': 'foo'}, {'hello': 'bar'}]
listb = ["a['hello']"]
for a in lista:
    listc = []
    for x in listb:
        listc.append(eval(x))
    print(listc)

# result
['foo']
['bar']

What would be the reason for this?


Title: How would I center a multiline ascii art

Body:
I'm new to C++ I have a ASCII art that looks like this

    string title =
        "  _____ ____  _   _  _____ _      ______  _____ _____ _ \n"
        " / ____/ __ \\| \\ | |/ ____| |    |  ____|/ ____/ ____| |\n"
        "| |   | |  | |  \\| | (___ | |    | |__  | (___| (___ | |\n"
        "| |   | |  | | . ` |\\___ \\| |    |  __|  \\___ \\\\___ \\| |\n"
        "| |___| |__| | |\\  |____) | |____| |____ ____) |___) |_|\n"
        " \\_____\\____/|_| \\_|_____/|______|______|_____/_____/(_)\n";

I want to paste this ASCII art in the console but I don't want it to be on the left side I want it to be centered how would I go about centering this ASCII art in the console.

Body:
Here's an example if you're using fmt with center alignment.

#include <string>
#include <fmt/core.h>

void print(std::string s){
    int width = 100;
    fmt::print("{:*^{}}\n", s, width); // '*' fills the blank space so it's easier to see the center alignment effect.
}

int main(){
    print("  _____ ____  _   _  _____ _      ______  _____ _____ _ ");
    print(" / ____/ __ \\| \\ | |/ ____| |    |  ____|/ ____/ ____| |");
    print("| |   | |  | |  \\| | (___ | |    | |__  | (___| (___ | |");
    print("| |   | |  | | . ` |\\___ \\| |    |  __|  \\___ \\\\___ \\| |");
    print("| |___| |__| | |\\  |____) | |____| |____ ____) |___) |_|");
    print(" \\_____\\____/|_| \\_|_____/|______|______|_____/_____/(_)");

    return 0;
}

Synax for fmt

Live Demo

Output

**********************  _____ ____  _   _  _____ _      ______  _____ _____ _ **********************
********************** / ____/ __ \| \ | |/ ____| |    |  ____|/ ____/ ____| |**********************
**********************| |   | |  | |  \| | (___ | |    | |__  | (___| (___ | |**********************
**********************| |   | |  | | . ` |\___ \| |    |  __|  \___ \\___ \| |**********************
**********************| |___| |__| | |\  |____) | |____| |____ ____) |___) |_|**********************
********************** \_____\____/|_| \_|_____/|______|______|_____/_____/(_)**********************


问:
How to hide a Recyclerview Item
I have a recyclerview like this:

The distance between all items is 15dp. Except for the first item, I want to check the left and right distances on other items and hide that item if it is less than 15 dp. How can I do that?

Thank you!

Item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:id="@+id/intervalCard"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/white"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.textview.MaterialTextView
            android:id="@+id/itemTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10dp"
            tools:text="99" />

        <View
            android:id="@+id/dateIndicator"
            android:layout_width="0.5dp"
            android:layout_height="5dp"
            android:background="@color/ripple_gray" />

    </LinearLayout>

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

Adapter.kt

```<code>class TimeIntervalAdapter(
    private val data: List<String>
) : RecyclerView.Adapter<TimeIntervalAdapter.ItemHolder>() {

    private val items: MutableList<TimeIntervalItem>

    init {
        this.items = ArrayList()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.time_interval_item, parent, false)
        return ItemHolder(view)
    }

    override fun onBindViewHolder(holder: ItemHolder, position: Int) {
        holder.itemTitle.text = data[position]
    }

    override fun getItemCount(): Int = data.size

    inner class ItemHolder
    internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val itemTitle: MaterialTextView = itemView.findViewById(R.id.itemTitle)
    }
}
</code>```

LayoutManager.kt - for set dynamic distance to items -

```<code>class SpanningLinearLayoutManager : LinearLayoutManager {
    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, orientation: Int, reverseLayout: Boolean) : super(
        context,
        orientation,
        reverseLayout
    ) {
    }

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
    }

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return spanLayoutSize(super.generateDefaultLayoutParams())
    }

    override fun generateLayoutParams(c: Context, attrs: AttributeSet): RecyclerView.LayoutParams {
        return spanLayoutSize(super.generateLayoutParams(c, attrs))
    }

    override fun generateLayoutParams(lp: ViewGroup.LayoutParams): RecyclerView.LayoutParams {
        return spanLayoutSize(super.generateLayoutParams(lp))
    }

    override fun checkLayoutParams(lp: RecyclerView.LayoutParams): Boolean {
        return super.checkLayoutParams(lp)
    }

    private fun spanLayoutSize(layoutParams: RecyclerView.LayoutParams): RecyclerView.LayoutParams {
        if (orientation == HORIZONTAL) {
            layoutParams.width = horizontalSpace.roundToInt()
        }
        return layoutParams
    }

    override fun canScrollVertically(): Boolean {
        return false
    }

    override fun canScrollHorizontally(): Boolean {
        return false
    }

    var horizontalSpace: Double = 0.0
        get() {
            return if (field > 1440) (timelineWidth * 60.0 * 24.0) / (field)
            else (timelineWidth * 60.0) / (field)
        }
    var timelineWidth: Int = 0
}
</code>```

答:
You can hide view for start position in onBindViewHolder method of Adapter

Example code:

```<code>   if(position == 0){
       holder.viewBefore.setVisibility(View.GONE);
   }else{
       holder.viewBefore.setVisibility(View.VISIBLE);
   }
</code>```

viewBefore is your view name that you want to hide or visible.

Title: How to hide a Recyclerview Item

Body:
I have a recyclerview like this:

The distance between all items is 15dp. Except for the first item, I want to check the left and right distances on other items and hide that item if it is less than 15 dp. How can I do that?

Thank you!

Item.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:id="@+id/intervalCard"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/white"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.textview.MaterialTextView
            android:id="@+id/itemTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10dp"
            tools:text="99" />

        <View
            android:id="@+id/dateIndicator"
            android:layout_width="0.5dp"
            android:layout_height="5dp"
            android:background="@color/ripple_gray" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Adapter.kt

class TimeIntervalAdapter(
    private val data: List<String>
) : RecyclerView.Adapter<TimeIntervalAdapter.ItemHolder>() {

    private val items: MutableList<TimeIntervalItem>

    init {
        this.items = ArrayList()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.time_interval_item, parent, false)
        return ItemHolder(view)
    }

    override fun onBindViewHolder(holder: ItemHolder, position: Int) {
        holder.itemTitle.text = data[position]
    }

    override fun getItemCount(): Int = data.size

    inner class ItemHolder
    internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val itemTitle: MaterialTextView = itemView.findViewById(R.id.itemTitle)
    }
}

LayoutManager.kt - for set dynamic distance to items -

class SpanningLinearLayoutManager : LinearLayoutManager {
    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, orientation: Int, reverseLayout: Boolean) : super(
        context,
        orientation,
        reverseLayout
    ) {
    }

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
    }

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return spanLayoutSize(super.generateDefaultLayoutParams())
    }

    override fun generateLayoutParams(c: Context, attrs: AttributeSet): RecyclerView.LayoutParams {
        return spanLayoutSize(super.generateLayoutParams(c, attrs))
    }

    override fun generateLayoutParams(lp: ViewGroup.LayoutParams): RecyclerView.LayoutParams {
        return spanLayoutSize(super.generateLayoutParams(lp))
    }

    override fun checkLayoutParams(lp: RecyclerView.LayoutParams): Boolean {
        return super.checkLayoutParams(lp)
    }

    private fun spanLayoutSize(layoutParams: RecyclerView.LayoutParams): RecyclerView.LayoutParams {
        if (orientation == HORIZONTAL) {
            layoutParams.width = horizontalSpace.roundToInt()
        }
        return layoutParams
    }

    override fun canScrollVertically(): Boolean {
        return false
    }

    override fun canScrollHorizontally(): Boolean {
        return false
    }

    var horizontalSpace: Double = 0.0
        get() {
            return if (field > 1440) (timelineWidth * 60.0 * 24.0) / (field)
            else (timelineWidth * 60.0) / (field)
        }
    var timelineWidth: Int = 0
}

Body:
You can hide view for start position in onBindViewHolder method of Adapter

Example code:

   if(position == 0){
       holder.viewBefore.setVisibility(View.GONE);
   }else{
       holder.viewBefore.setVisibility(View.VISIBLE);
   }

viewBefore is your view name that you want to hide or visible.


问:
Call getBounds() on MapView.Circle
I want to call the getBounds(points) function from Geolib, on Map View.Circle component. I am not pretty sure, how do I fetch the list of coordinates inside my circle region. So that I can pass it as a parameter to the getBounds function.
I see posts where getBounds() from google maps API is being called on react google maps and so on. But not sure in this case.
Below is my code for map display and Circle. Please share your knowledge and suggestions.</p>
```<code><MapView style={styles.mapContainer}
        region = {{latitude: region.latitude,
              longitude: region.longitude,
              latitudeDelta: region.latitudeDelta,
              longitudeDelta: region.longitudeDelta}}
        >
        <MapView.Marker
            coordinate={{
            latitude: region.latitude,
            longitude:region.longitude}}
            title={"Me"}
         />
         <MapView.Circle
                key = { (region.latitude + region.longitude).toString() }
                center = {pickedLocation}
                radius = { 100 }
                strokeWidth = { 2 }
                strokeColor = { '#1a66ff' }
                fillColor = { 'rgba(230,238,255,0.5)' }
        />
        </MapView>
</code>```

答:
Probably use geolib and do this</p>
```<code>import { getBoundsOfDistance } from 'geolib';
const cordinates = getBoundsOfDistance({latitude: number, longitude: number}, radius);
mapRef.current?.fitToCoordinates(cordinates, {
                edgePadding: {
                    top: 20,
                    right: 20,
                    bottom: 20,
                    left: 20,
                },
            });
</code>```

Title: Call getBounds() on MapView.Circle

Body:
I want to call the getBounds(points) function from Geolib, on Map View.Circle component. I am not pretty sure, how do I fetch the list of coordinates inside my circle region. So that I can pass it as a parameter to the getBounds function.
I see posts where getBounds() from google maps API is being called on react google maps and so on. But not sure in this case.
Below is my code for map display and Circle. Please share your knowledge and suggestions.

<MapView style={styles.mapContainer}
        region = {{latitude: region.latitude,
              longitude: region.longitude,
              latitudeDelta: region.latitudeDelta,
              longitudeDelta: region.longitudeDelta}}
        >
        <MapView.Marker
            coordinate={{
            latitude: region.latitude,
            longitude:region.longitude}}
            title={"Me"}
         />
         <MapView.Circle
                key = { (region.latitude + region.longitude).toString() }
                center = {pickedLocation}
                radius = { 100 }
                strokeWidth = { 2 }
                strokeColor = { '#1a66ff' }
                fillColor = { 'rgba(230,238,255,0.5)' }
        />
        </MapView>

Body:
Probably use geolib and do this

import { getBoundsOfDistance } from 'geolib';
const cordinates = getBoundsOfDistance({latitude: number, longitude: number}, radius);
mapRef.current?.fitToCoordinates(cordinates, {
                edgePadding: {
                    top: 20,
                    right: 20,
                    bottom: 20,
                    left: 20,
                },
            });


问:
Difference of Camunda and BPEL
What's the difference between Camunda and BPEL (Business Process Expression Language) and Where do we use Camunda and where do we use BPEL and which one is better?

I found this question, but BPMN != Camunda. So where is the difference between Camunda and BPEL?

答:
Please see Jan's comment. The thread you already found is already good. You need to compare the two modelling standards, not an engine product and a standard.

BPEL was popular in SOA times, for service orchestration in full automated processes. BPEL can be excuted by a BPEL engine. There are different products offering this capability.

Early plans to be able to map BPMN 1.0 (Notation only, no model) mostly failed. This was one motivation for BPMN 2.0, which also standardases the model, not only the notation. Due to its block orientation and lack of support for human tasks BPEL did not cover all BPM/Workflow requirements. I would say BPEL is dying if not already dead. I would not spend time on it today. Of course that is a personal, biased opinion.

BPMN 2.0 on the other hand is a mature OMG standard, stable since 2014, works for a variety of process management and automation needs and has a wide and growing adoption.

Camunda offers process engine products, which interpret and execute process models based on the BPMN 2.0 standard. There are other product, which also use this modelling standard. engine specific attributes for process automation beyond the standard may differ between vendors. It depends on how closely the vendors are implementing the standard. See for instance https://www.omgwiki.org/bpmn-miwg/doku.php

Title: Difference of Camunda and BPEL


问:
Algorithm for slicing a dynamic graph
I am currently working on a project based on graph and I am searching for an algorithm for slicing an dynamic graph. I have already done some research but most algorithms that I have found works only for a static graph. In my environment, the graph is dynamic, it means that users add/delete elements, create/delete dependences at runtime.
(In reality I am working with UML models but UML models can be also represented by typed graphs, wich are composed of typed Vertices and edges)
I also search for the terms graph fragmentation but I did not find anything. And I would like to know if exist such algorithm for slicing a dynamic graph?

[UPDATE]

Sorry for not being clear and I am updating my question.Let me first expose the context.

In MDE (Model Driven Engineering), large-scale industrial systems involve nowadays hundreds of developpers working on hundreds of models representing pars of the whole system specification. In a such context, the approach commonly adopted is to use a central repository. The solution I provide for my project (I am currently working on a research lab), is a solution which is peer-to-peer oriented, that means that every developper has his own replication of the system specification.

My main problem is how to replicate this data, the models.
For instance, imagine Alice and Bob working on this UML diagram and Alice has the whole diagram in his repository. Bob wants to have the elements {FeedOrEntry, Entry}, how can I slice this diagram UML?
I search for the terms of "model Slicing".I have found one paper which gives an approach for slicing UML Class Diagrams but the problem with this algorithm is it only works for a static graph. In our context, developpers add/update/remove elements constantly and the shared elements should be consistent with the other replicas.

Since UML Models can also be seen as a graph, I also search for the terms for "graph slicing" or "graph fragment" but I have found nothing useful.
And I would like to know if exist such algorithm for slicing a dynamic graph

答:
If you make slicing atomic, I see no problem with using algorithm shown in paper you linked.

However, for your consistency constraints, I believe that your p2p approach is incompatible. Alternative is merge operation, but I have no idea how would that operation work. It probably, at least partially, would have to be done manually.

ContentLicense: CC BY-SA 3.0

Title: Algorithm for slicing a dynamic graph


问:
mutable borrows in a loop

My code:

struct Foo<'a> {
    bytes: &'a mut [u8],
}

impl<'a> Foo<'a> {
    fn bar<'b>(&'b mut self) {
        self.bytes = &mut self.bytes[1..];
    }
}

fn baz<'a, 'b>(foo: &'b mut Foo<'a>) {
    println!("baz!");

    for _ in 0..3 {
        foo.bar();
    }
}
```
<p>Also here in a Rust Playground.</p>
<p>This results in the following error traceback:</p>
```   Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/main.rs:12:27
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                           ^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'b` as defined here...
  --> src/main.rs:11:12
   |
11 |     fn bar<'b>(&'b mut self) {
   |            ^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:27
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                           ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
  --> src/main.rs:10:6
   |
10 | impl<'a> Foo<'a> {
   |      ^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:22
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                      ^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground` due to previous error
```

Goal

I'm looking to change the function signatures of bar / baz to get this to compile. My understanding was that I needed to specify lifetime bounds on 'a & 'b and it would work, but I get different errors for both 'b: 'a and 'a: 'b in either/both functions.

I've also looked through ~10 other "mutable borrow in loop" questions, but I don't understand the answers well enough to apply them to my problem, so even if this is a duplicate I'd appreciate an answer relevant to this toy example specifically.

Any help is appreciated!

答:
The problem here is the borrow happens through 'b. ('b and 'a are disjoint). The compiler wants you to guarantee the reference 'b needs to be atleast as long as 'a. So we should look for a way where 'b isn't involved when (re)borrowing the slice, as 'b is considered to be valid only for the function call duration. There is no return or an "outgoing" lifetime from the call.

You can use the std::mem::* functions to achieve this

Title: mutable borrows in a loop

Body:
My code:

struct Foo<'a> {
    bytes: &'a mut [u8],
}

impl<'a> Foo<'a> {
    fn bar<'b>(&'b mut self) {
        self.bytes = &mut self.bytes[1..];
    }
}

fn baz<'a, 'b>(foo: &'b mut Foo<'a>) {
    println!("baz!");

    for _ in 0..3 {
        foo.bar();
    }
}

Also <a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=%23!%5Ballow(unused)%5D%0Afn%20main()%20%7B%0Ause%20std%3A%3Aany%3A%3AAny%3B%0Ause%20std%3A%3Aio%3A%3ARead%3B%0A%0Astruct%20Foo%3C%27a%3E%20%7B%0A%20%20%20%20bytes%3A%20%26%27a%20mut%20%5Bu8%5D%2C%0A%7D%0A%0Aimpl%3C%27a%3E%20Foo%3C%27a%3E%20%7B%0A%20%20%20%20fn%20bar%3C%27b%3E(%26%27b%20mut%20self)%20%7B%0A%20%20%20%20%20%20%20%20self.bytes%20%3D%20%26mut%20self.bytes%5B1..%5D%3B%0A%20%20%20%20%7D%0A%7D%0A%0Afn%20baz%3C%27a%2C%20%27b%3E(foo%3A%20%26%27b%20mut%20Foo%3C%27a%3E)%20%7B%0A%20%20%20%20println!(%22baz!%22)%3B%0A%20%20%20%20%0A%20%20%20%20for%20_%20in%200..3%20%7B%0A%20%20%20%20%20%20%20%20foo.bar()%3B%0A%20%20%20%20%7D%0A%7D%0A%0A%7D" rel="nofollow noreferrer">here in a Rust Playground.

This results in the following error traceback:

   Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/main.rs:12:27
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                           ^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'b` as defined here...
  --> src/main.rs:11:12
   |
11 |     fn bar<'b>(&'b mut self) {
   |            ^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:27
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                           ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
  --> src/main.rs:10:6
   |
10 | impl<'a> Foo<'a> {
   |      ^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:22
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                      ^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground` due to previous error

Goal

I'm looking to change the function signatures of bar / baz to get this to compile. My understanding was that I needed to specify lifetime bounds on 'a & 'b and it would work, but I get different errors for both 'b: 'a and 'a: 'b in either/both functions.

I've also looked through ~10 other "mutable borrow in loop" questions, but I don't understand the answers well enough to apply them to my problem, so even if this is a duplicate I'd appreciate an answer relevant to this toy example specifically.

Any help is appreciated!


问:
Where can I find high-quality artwork for my app?
I am looking especially for tab bar icons, buttons and backgrounds. Are there any websites intended for this purpose?</p>

答: I'm not sure how high is the quality you're expecting, but you will certainly find GUI images on Open Game Art that you can legally use.


问:
how could I use 2 foreach in Laravel using 1 view

الكورس الاول

    @foreach ($data as $item)

{{$item->name}}

            show lectures

    @endforeach

الكورس الثاني

    @foreach ($data2 as $item)

{{$item->name}}

            show lectures

    @endforeach

```

答:
```<code>@foreach ($data as $item)
     {{ $item->name }}

     @foreach ($data2 as $item2)
          {{ $item2->name }}
     @endforeach

@endforeach
</code>```


问:
How can we add Admob and Firebase crashlytics to Android studio bumble bee Build.Gradle file
How can we add Admob and Firebase crashlytics  to Android studio bumble bee

earlier the build.gradle: was some thing like this

```<code>buildscript {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"
        // Add the following line:
        classpath 'com.google.gms:google-services:4.3.10'  // Google Services plugin
        // Add the Crashlytics Gradle plugin
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

However now the changes look like these

```<code>plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

I tried adding these lines

```<code>// Add the following line:
        id 'com.google.gms:google-services' version '4.3.10' apply false
        // Google Services plugin
        // Add the Crashlytics Gradle plugin
        id 'com.google.firebase:firebase-crashlytics-gradle' version '2.8.1' apply false
</code>```

But it  error is

```<code>Caused by: org.gradle.plugin.internal.InvalidPluginIdException: plugin id 'com.google.gms:google-services' is invalid: Plugin id contains invalid char ':' (only ASCII alphanumeric characters, '.', '_' and '-' characters are valid)
    at org.gradle.plugin.use.internal.DefaultPluginId.validate(DefaultPluginId.java:65)
    at org.gradle.plugin.use.internal.DefaultPluginId.of(DefaultPluginId.java:48)
    at org.gradle.plugin.use.internal.PluginRequestCollector$PluginDependencySpecImpl.<init>(PluginRequestCollector.java:139)
    at org.gradle.plugin.use.internal.PluginRequestCollector$PluginDependencySpecImpl.<init>(PluginRequestCollector.java:129)
    at org.gradle.plugin.use.internal.PluginRequestCollector$PluginDependenciesSpecImpl.id(PluginRequestCollector.java:116)
</code>```

答:
Add buildscript  above plugins

```<code>buildscript {
  dependencies {
    // Add our classpath
     classpath 'com.google.gms:google-services:4.3.10'
     classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
 }
}
 plugins {
      id 'com.android.application' version '7.1.0' apply false
      id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
   delete rootProject.buildDir
}
</code>```

Body:
How can we add Admob and Firebase crashlytics  to Android studio bumble bee

earlier the build.gradle: was some thing like this

buildscript {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"
        // Add the following line:
        classpath 'com.google.gms:google-services:4.3.10'  // Google Services plugin
        // Add the Crashlytics Gradle plugin
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

However now the changes look like these

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I tried adding these lines

// Add the following line:
        id 'com.google.gms:google-services' version '4.3.10' apply false
        // Google Services plugin
        // Add the Crashlytics Gradle plugin
        id 'com.google.firebase:firebase-crashlytics-gradle' version '2.8.1' apply false

But it  error is

Caused by: org.gradle.plugin.internal.InvalidPluginIdException: plugin id 'com.google.gms:google-services' is invalid: Plugin id contains invalid char ':' (only ASCII alphanumeric characters, '.', '_' and '-' characters are valid)
    at org.gradle.plugin.use.internal.DefaultPluginId.validate(DefaultPluginId.java:65)
    at org.gradle.plugin.use.internal.DefaultPluginId.of(DefaultPluginId.java:48)
    at org.gradle.plugin.use.internal.PluginRequestCollector$PluginDependencySpecImpl.<init>(PluginRequestCollector.java:139)
    at org.gradle.plugin.use.internal.PluginRequestCollector$PluginDependencySpecImpl.<init>(PluginRequestCollector.java:129)
    at org.gradle.plugin.use.internal.PluginRequestCollector$PluginDependenciesSpecImpl.id(PluginRequestCollector.java:116)

Body:
Add buildscript  above plugins

buildscript {
  dependencies {
    // Add our classpath
     classpath 'com.google.gms:google-services:4.3.10'
     classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
 }
}
 plugins {
      id 'com.android.application' version '7.1.0' apply false
      id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
   delete rootProject.buildDir
}


问:
When and how can we start forgetting about non-retina display iPhones and iPod Touches?
Now more than one year passed since a retina display device appeared. Does anyone know some numbers how many users still suffer under the low-resolution devices? How long do they use their iPhones or iPods until they realize that a retina display is so much better?

I'm sick of having to create every graphic two times, trashing the binary with all these low-resolution files. I wonder if anyone has stopped supporting low resolution hardware without a big loss.

And: If I wanted to stop supporting low resolution devices, what kind of settings in the info.plist must I make? And what would happen if a low-res device still installs my retina-only app?

答:
Maybe its not possible right now as it isnt yet supported here.

But releasing your app with a iOS deployment target of iOS 4.2 may reduce the number of non-retina display users to a great extent.

And the main reason for users not switching to new devices is explained perfectly in the previous answer. :)


答:
I usually - and a LOT:

```<code>$ awk '
BEGIN {
    FS=OFS="|"                 # set both separators to pipe
}
{
    for(i=1;i<=NF;i++)         # loop all fields
        gsub(/^ +| +$/,"",$i)  # strip leading and trailing space
}1' file                       # output
</code>```

Output:

```<code>001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
</code>```

If you got other junk there, feel free to tune the regex:

```<code>gsub(/^"?[ \t]*(N\/A)?|[ \t]*"?$/),"",$i)  # etc
</code>```

Title: Strip blanks at the beginning & trailing blanks in AWK

Body:
I usually - and a LOT:

$ awk '
BEGIN {
    FS=OFS="|"                 # set both separators to pipe
}
{
    for(i=1;i<=NF;i++)         # loop all fields
        gsub(/^ +| +$/,"",$i)  # strip leading and trailing space
}1' file                       # output

Output:

001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith

If you got other junk there, feel free to tune the regex:

gsub(/^"?[ \t]*(N\/A)?|[ \t]*"?$/),"",$i)  # etc


问:
How to inject componant dependancies inside a service?
I would like to fix some issues and automate some stuff when I create a modal in Ionic V4. The solution I've found is to create a service to create my modals for me.

```<code>@Injectable({
    providedIn: 'root'
})
export class ModalSingleton {

   public lock = false;
   public modal: HTMLIonModalElement;

   constructor(
       public toastHelper: ToastHelper,
       public modalController: ModalController,
   ) {
   }

    /**
     * This helper adds a Double click Guard to the modal and implement the progress bar when opening
     * @param $config The modal
     */
   async presentModal( $config: ModalOptions ) {
       if ( this.lock ) {
           console.log('Double click detected');
           return;
       } // Double click guard
       this.lock = true;

       this.toastHelper.presentProgressBar();
       this.modal = await this.modalController.create( $config );

       await new Promise(r => setTimeout(r, 2));
       await this.modal.present();
       this.modal.onDidDismiss().then( onDismiss => {
            this.dismissModal();
       });
       this.toastHelper.dismissProgressBar();
   }

   async dismissModal() {
       this.modal = null;
       this.lock  = false;
   }
</code>```

Then in my component, I call it.

this.modalSingleton.presentModal( {
component: PaymentMethodModal,
});

It works but I MUST add "PaymentMethodModal" and EVERY other modal.module in app.module.ts, therefore, losing the lazy loading feature.

How can my service resolve and use modals dynamically?

Thank you for your time

答:
You can try to add PaymentMethodModal to the  entryComponents array inside the containing module:

```<code>@NgModule({
    declarations: [AppComponent],
    entryComponents: [PaymentMethodModal],
    imports: [
        BrowserModule,
        HttpClientModule,
        AppRoutingModule,

        LayoutSharedModule,
        MatSnackBarModule,

        IonicModule.forRoot()
    ],
    providers: [
        AppAuthGuard,
        { provide: HTTP_INTERCEPTORS,   useClass: AuthInterceptor, multi: true },
    ],
    exports: [],
    bootstrap: [AppComponent]
})

export class AppModule {}
</code>```

Note: entryComponents is deprecated since Angular 9, but it can still be used in the case of a library that is consumed by a View Engine application (I don't know how Ionic v4 is implemented). I didn't test this.

Body:
I would like to fix some issues and automate some stuff when I create a modal in Ionic V4. The solution I've found is to create a service to create my modals for me.

@Injectable({
    providedIn: 'root'
})
export class ModalSingleton {

   public lock = false;
   public modal: HTMLIonModalElement;

   constructor(
       public toastHelper: ToastHelper,
       public modalController: ModalController,
   ) {
   }

    /**
     * This helper adds a Double click Guard to the modal and implement the progress bar when opening
     * @param $config The modal
     */
   async presentModal( $config: ModalOptions ) {
       if ( this.lock ) {
           console.log('Double click detected');
           return;
       } // Double click guard
       this.lock = true;

       this.toastHelper.presentProgressBar();
       this.modal = await this.modalController.create( $config );

       await new Promise(r => setTimeout(r, 2));
       await this.modal.present();
       this.modal.onDidDismiss().then( onDismiss => {
            this.dismissModal();
       });
       this.toastHelper.dismissProgressBar();
   }

   async dismissModal() {
       this.modal = null;
       this.lock  = false;
   }

Then in my component, I call it.

this.modalSingleton.presentModal( {
component: PaymentMethodModal,
});

It works but I MUST add "PaymentMethodModal" and EVERY other modal.module in app.module.ts, therefore, losing the lazy loading feature.

How can my service resolve and use modals dynamically?

Thank you for your time

Body:
You can try to add PaymentMethodModal to the  entryComponents array inside the containing module:

@NgModule({
    declarations: [AppComponent],
    entryComponents: [PaymentMethodModal],
    imports: [
        BrowserModule,
        HttpClientModule,
        AppRoutingModule,

        LayoutSharedModule,
        MatSnackBarModule,

        IonicModule.forRoot()
    ],
    providers: [
        AppAuthGuard,
        { provide: HTTP_INTERCEPTORS,   useClass: AuthInterceptor, multi: true },
    ],
    exports: [],
    bootstrap: [AppComponent]
})

export class AppModule {}

Note: entryComponents is deprecated since Angular 9, but it can still be used in the case of a library that is consumed by a View Engine application (I don't know how Ionic v4 is implemented). I didn't test this.


问:
How to find min/max aggregations with diffrerent filters in MongoDB?
Considering collection clothing of documents with this strucure

```<code>{
  "brand": <string>,
  "color": <string>,
  "size": <number>
}
</code>```

In a single aggregation grouing by brand I would like to find two values:

min size for all documents in a group where color="blue"

max size for all documents in a group where color="red"

In SQL it would be something like this:

```<code>SELECT MIN(CASE color WHEN "blue" THEN size ELSE NULL END),
       MAX(CASE color WHEN "red" THEN size ELSE NULL END),
       brand
  FROM clothing
 GROUP BY brand
</code>```

How to express this in MongoDB query?

答:
```<code>db.collection.aggregate([
  {
    "$match": {
      "color": { "$in": [ "red", "blue" ] }
    }
  },
  {
    "$group": {
      "_id": "$color",
      "max": { "$max": "$size" },
      "min": { "$min": "$size" }
    }
  }
])
</code>```

mongoplayground

Body:
Considering collection clothing of documents with this strucure

{
  "brand": <string>,
  "color": <string>,
  "size": <number>
}

In a single aggregation grouing by brand I would like to find two values:

min size for all documents in a group where color="blue"

max size for all documents in a group where color="red"

In SQL it would be something like this:

SELECT MIN(CASE color WHEN "blue" THEN size ELSE NULL END),
       MAX(CASE color WHEN "red" THEN size ELSE NULL END),
       brand
  FROM clothing
 GROUP BY brand

How to express this in MongoDB query?

Body:
db.collection.aggregate([
  {
    "$match": {
      "color": { "$in": [ "red", "blue" ] }
    }
  },
  {
    "$group": {
      "_id": "$color",
      "max": { "$max": "$size" },
      "min": { "$min": "$size" }
    }
  }
])

mongoplayground


问:
Update happens only on the last row, instead of first
```<code>function createTextFields(obj) {
    for (var i = 0; i < obj.length; i++) {
        var dataDump = {};
        for (var key in obj[i]) {
            var textField = Ti.UI.createTextField(pm.combine($$.labelBrown, {
            left: 200,
            height:35,
            value:obj[i][key],
            width:550,
            keyboardType:Ti.UI.KEYBOARD_NUMBER_PAD,
            layout:'horizontal',
            backgroundColor:'transparent',
            id:i
         }));

            dataDump[key] = textField.value;
            var callback = function (vbKey) {
                    return function (e) {
                        dataDump[vbKey] = e.source.value;
                    };
                }(key);
        }
        globalData.push(dataDump);
    }

}
</code>```

I am using the simlar code for Adding the data and it works fine. I posted the problem yesterday and it got resolved...

Last Object is always getting updated?

Now when i go to edit page, it shows me four text fields or number of text fields added... now when i edit something and click on save... the value get's updated on the fourth or the last TextFields Object...

答:
JavaScript does not have block level scope, so your variables dataDump and callback, though "declared" inside for-loops actually belong to the function.  As in, you're saving a value to dataDump, then you're overwriting it, each time you go through the loop.  Which is why finally only the code that operated on the last value remains.

Take a look at What is the scope of variables in JavaScript? too.

Body:
function createTextFields(obj) {
    for (var i = 0; i < obj.length; i++) {
        var dataDump = {};
        for (var key in obj[i]) {
            var textField = Ti.UI.createTextField(pm.combine($$.labelBrown, {
            left: 200,
            height:35,
            value:obj[i][key],
            width:550,
            keyboardType:Ti.UI.KEYBOARD_NUMBER_PAD,
            layout:'horizontal',
            backgroundColor:'transparent',
            id:i
         }));

            dataDump[key] = textField.value;
            var callback = function (vbKey) {
                    return function (e) {
                        dataDump[vbKey] = e.source.value;
                    };
                }(key);
        }
        globalData.push(dataDump);
    }

}

I am using the simlar code for Adding the data and it works fine. I posted the problem yesterday and it got resolved...

Last Object is always getting updated?

Now when i go to edit page, it shows me four text fields or number of text fields added... now when i edit something and click on save... the value get's updated on the fourth or the last TextFields Object...


问:
Counting values based on certain conditions in R?
I have a dataset and I'm trying to count the number of codes each patient has, as well as the number of codes of interest that each patient has.

Let's say that I have this table below and my code of interest is 26.

```<code>patient code
1       25
1       26
1       39
1       26
1       86
2       26
2       24
2       89
3       56
3       45
3       26
3       89
4       56
4       25
4       66
4       56
</code>```

Patient 1 total code: 5 total codes, 2 codes of interest

Patient 2 total code: 3 total codes, 1 code of interest

Patient 3 total code: 4 total codes, 1 code of interest

Patient 4 total code: 4 total codes, 0 codes of interest

How can I do this in R? Thank you!

答:
Here's a data.table approach:

```<code>library(data.table)

setDT(dt)[ , list(cases = .N, interest = sum(code == 26)), by=patient]
</code>```

Output

```<code>   patient cases interest
1:       1     5        2
2:       2     3        1
3:       3     4        1
4:       4     4        0
</code>```

Data

```<code>dt <- structure(list(patient = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L), code = c(25L, 26L, 39L, 26L, 86L,
26L, 24L, 89L, 56L, 45L, 26L, 89L, 56L, 25L, 66L, 56L)), class = "data.frame", row.names = c(NA,
-16L))
</code>```

Body:
I have a dataset and I'm trying to count the number of codes each patient has, as well as the number of codes of interest that each patient has.

Let's say that I have this table below and my code of interest is 26.

patient code
1       25
1       26
1       39
1       26
1       86
2       26
2       24
2       89
3       56
3       45
3       26
3       89
4       56
4       25
4       66
4       56

Patient 1 total code: 5 total codes, 2 codes of interest

Patient 2 total code: 3 total codes, 1 code of interest

Patient 3 total code: 4 total codes, 1 code of interest

Patient 4 total code: 4 total codes, 0 codes of interest

How can I do this in R? Thank you!

Body:
Here's a data.table approach:

library(data.table)

setDT(dt)[ , list(cases = .N, interest = sum(code == 26)), by=patient]

Output

   patient cases interest
1:       1     5        2
2:       2     3        1
3:       3     4        1
4:       4     4        0

Data

dt <- structure(list(patient = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L), code = c(25L, 26L, 39L, 26L, 86L,
26L, 24L, 89L, 56L, 45L, 26L, 89L, 56L, 25L, 66L, 56L)), class = "data.frame", row.names = c(NA,
-16L))


问:
How not to dismiss a PopUpMenuButton after selecting an item?
I am using flutter PopUpMenuButton. All i want is when i select any item on the menu, the popup should not be dismissed, rather let me select multiple values from the popup.The documentation says that you can override the handleTap property, but it is unclear for me how to do that?
This is  documented </p>

```<code> ///The [handleTap] method can be overridden to adjust exactly what happens when
/// the item is tapped. By default, it uses [Navigator.pop] to return the
/// [PopupMenuItem.value] from the menu route.

    void handleTap() {
    Navigator.pop<T>(context, widget.value);
  }
</code>```

答:
You have to modifythe package popupmenubutton. Whenever something is selected in the menu, the menu popped out. So you have to just comment out the Navigator.pop() in the main file of this widget.
comment out the
Navigator.pop<T>(context, widget.value); in the the main file.

```<code>/// The handler for when the user selects the menu item.
///
/// Used by the [InkWell] inserted by the [build] method.
///
/// By default, uses [Navigator.pop] to return the [PopupMenuItem.value] from
/// the menu route.
@protected
void handleTap() {
widget.onTap?.call();

// Navigator.pop<T>(context, widget.value);
}
</code>```

Body:
I am using flutter PopUpMenuButton. All i want is when i select any item on the menu, the popup should not be dismissed, rather let me select multiple values from the popup.The documentation says that you can override the handleTap property, but it is unclear for me how to do that?
This is  documented

 ///The [handleTap] method can be overridden to adjust exactly what happens when
/// the item is tapped. By default, it uses [Navigator.pop] to return the
/// [PopupMenuItem.value] from the menu route.

    void handleTap() {
    Navigator.pop<T>(context, widget.value);
  }

Body:
You have to modifythe package popupmenubutton. Whenever something is selected in the menu, the menu popped out. So you have to just comment out the Navigator.pop() in the main file of this widget.
comment out the
Navigator.pop<T>(context, widget.value); in the the main file.

/// The handler for when the user selects the menu item.
///
/// Used by the [InkWell] inserted by the [build] method.
///
/// By default, uses [Navigator.pop] to return the [PopupMenuItem.value] from
/// the menu route.
@protected
void handleTap() {
widget.onTap?.call();

// Navigator.pop<T>(context, widget.value);
}


问:
Error handling external file: 'Inserting value to batch for column type DATE failed. Invalid argument provided.'
I am reading parquet file and I found the two columns that cause this problem:

```<code>SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) AS [result]
</code>```

These columns contain values that are undefined and I have tried the following to get rid of the error, yet it persists.

```<code>SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) AS [result]
WHERE cast(POST_SEARCH_DEPARTURE_DATE as varchar(100))!= 'undefined'
and cast (SEARCH_DEPARTURE_DATE as varchar(100)) != 'undefined'
</code>```

The code from above will throw the same:

Error handling external file: 'Inserting value to batch for column type DATE failed. Invalid argument provided.'.

I also tried the following for one column:

```<code>SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) with (POST_SEARCH_DATEVARCHAR(60)) AS [result]
</code>```

But this throws the following:

Error handling external file: 'Converting value to batch for column POST_SEARCH_DEPARTURE_DATE failed. Invalid argument provided.'

As instructed, no rows cannot be removed from this raw file and I am unsure how to solve this problem. Any suggestion is welcome.

答:
The solution is to use the with clause and define the data type that you expect to receive when you perform the open row set ( see below ):</p>
```<code>SELECT
  TOP 100
  POST_SEARCH_DATE,
  SEARCH_DATE

FROM
   OPENROWSET(
      BULK 'https://test/refined-parquet/data/v1.0/loaddt=2021-01-01/**',
      FORMAT = 'PARQUET'
     WITH (
        [SEARCH_DEPARTURE_DATE] VARCHAR(100) COLLATE Latin1_General_BIN2 3,
        [POST_SEARCH_DEPARTURE_DATE] VARCHAR(100) COLLATE Latin1_General_BIN2 2
) AS [result]
</code>```

Body:
I am reading parquet file and I found the two columns that cause this problem:

SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) AS [result]

These columns contain values that are undefined and I have tried the following to get rid of the error, yet it persists.

SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) AS [result]
WHERE cast(POST_SEARCH_DEPARTURE_DATE as varchar(100))!= 'undefined'
and cast (SEARCH_DEPARTURE_DATE as varchar(100)) != 'undefined'

The code from above will throw the same:

Error handling external file: 'Inserting value to batch for column type DATE failed. Invalid argument provided.'.

I also tried the following for one column:

SELECT
TOP 100
POST_SEARCH_DATE,
SEARCH_DATE

FROM
OPENROWSET(
    BULK 'https://test/refined-parquet/data/v1.0/loaddt=2022-01-01/**',
    FORMAT = 'PARQUET'

) with (POST_SEARCH_DATEVARCHAR(60)) AS [result]

But this throws the following:

Error handling external file: 'Converting value to batch for column POST_SEARCH_DEPARTURE_DATE failed. Invalid argument provided.'

As instructed, no rows cannot be removed from this raw file and I am unsure how to solve this problem. Any suggestion is welcome.

Body:
The solution is to use the with clause and define the data type that you expect to receive when you perform the open row set ( see below ):

SELECT
  TOP 100
  POST_SEARCH_DATE,
  SEARCH_DATE

FROM
   OPENROWSET(
      BULK 'https://test/refined-parquet/data/v1.0/loaddt=2021-01-01/**',
      FORMAT = 'PARQUET'
     WITH (
        [SEARCH_DEPARTURE_DATE] VARCHAR(100) COLLATE Latin1_General_BIN2 3,
        [POST_SEARCH_DEPARTURE_DATE] VARCHAR(100) COLLATE Latin1_General_BIN2 2
) AS [result]


问:
where to add related dependencies .jar files used in MyCustomHandler.java (WSO2 APIM 3.2.0)
I have extended the Abstract  handler class and written my own custom handler class in wso2 apim.
I am able to get the logs for this custom handler as well. For token validation I am using some okta dependencies in my project (okta-jwt-verifier and okta-jwt-verifier-impl). I have added the myCustomHandler.jar and other 2 jars of the above mentioned dependencies in /repository/components/lib folder. After starting the server I am not getting any error but when I hit the API request I am getting following runtime error,

```<code>java.lang.IllegalStateException: No `interface com.okta.jwt.AccessTokenVerifier$Builder` implementation found on the classpath. Have you remembered to include the okta-jwt-verifier-impl.jar in your runtime classpath?
    at com.okta.jwt.JwtVerifiers.lambda$loadService$1(JwtVerifiers.java:60) ~[okta-jwt-verifier-0.5.0.jar:0.5.0]
    at java.util.Optional.orElseThrow(Optional.java:408) ~[?:?]
    at com.okta.jwt.JwtVerifiers.loadService(JwtVerifiers.java:60) ~[okta-jwt-verifier-0.5.0.jar:0.5.0]
    at com.okta.jwt.JwtVerifiers.accessTokenVerifierBuilder(JwtVerifiers.java:51) ~[okta-jwt-verifier-0.5.0.jar:0.5.0]
    at org.wso2.carbon.test.CustomAPIAuthenticationHandler.authenticate(CustomAPIAuthenticationHandler.java:44) ~[MCM_Custom_handler.jar:?]
    at org.wso2.carbon.test.CustomAPIAuthenticationHandler.handleRequest(CustomAPIAuthenticationHandler.java:24) ~[MCM_Custom_handler.jar:?]
    at org.apache.synapse.rest.API.process(API.java:373)
</code>```

My code part where I am getting error,

```<code>        AccessTokenVerifier jwtVerifier = JwtVerifiers.accessTokenVerifierBuilder()
            .setIssuer("https://{{myDomain}}/oauth2/default").setAudience("api://default")
            .setConnectionTimeout(Duration.ofSeconds(1)) // defaults to 1s
            .setRetryMaxAttempts(2) // defaults to 2
            .setRetryMaxElapsed(Duration.ofSeconds(10)) // defaults to 10s
            .build();
</code>```

I think somehow the wso2apim is not able to find the jar that I have provided and /lib folder and it is searching for it in some other directory as it is runtime dependencie...
OR this could be some OKTA issue that I don't know :(
Can you please help me with this issue ?, I have been stuck since 1 week but did not got any breakthrough thanks in advance

My pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.test</groupId>
<artifactId>org.wso2.carbon.test</artifactId>
<packaging>bundle</packaging>
<version>1.0-SNAPSHOT</version>

<name>org.wso2.carbon.test.authenticator</name>
<url>http://maven.apache.org</url>

<repositories>
    <repository>
        <id>wso2-nexus</id>
        <name>WSO2 internal Repository</name>
        <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
            <checksumPolicy>ignore</checksumPolicy>
        </releases>
    </repository>

    <repository>
        <id>wso2.releases</id>
        <name>WSO2 internal Repository</name>
        <url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
            <checksumPolicy>ignore</checksumPolicy>
        </releases>
    </repository>

    <repository>
        <id>wso2.snapshots</id>
        <name>Apache Snapshot Repository</name>
        <url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </snapshots>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>wso2.releases</id>
        <name>WSO2 internal Repository</name>
        <url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
            <checksumPolicy>ignore</checksumPolicy>
        </releases>
    </pluginRepository>

    <pluginRepository>
        <id>wso2.snapshots</id>
        <name>WSO2 Snapshot Repository</name>
        <url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </snapshots>
        <releases>
            <enabled>false</enabled>
        </releases>
    </pluginRepository>
    <pluginRepository>
        <id>wso2-nexus</id>
        <name>WSO2 internal Repository</name>
        <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
            <checksumPolicy>ignore</checksumPolicy>
        </releases>
    </pluginRepository>
</pluginRepositories>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.0</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>1.4.0</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>org.wso2.carbon.test</Bundle-SymbolicName>
                    <Bundle-Name>org.wso2.carbon.test</Bundle-Name>
                    <Import-Package>
                        com.okta.jwt,
                        *; resolution:=optional
                    </Import-Package>
                    <Export-Package>
                        org.wso2.carbon.test.*,
                    </Export-Package>
                </instructions>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.apache.synapse</groupId>
        <artifactId>synapse-core</artifactId>
        <version>2.1.7-wso2v183</version>
        <scope>provided</scope>

    </dependency>
    <dependency>
        <groupId>org.apache.synapse</groupId>
        <artifactId>synapse-commons</artifactId>
        <version>2.1.7-wso2v183</version>
        <scope>provided</scope>

    </dependency>
    <dependency>
        <groupId>org.wso2.carbon.apimgt</groupId>
        <artifactId>org.wso2.carbon.apimgt.gateway</artifactId>
        <version>6.7.206</version>
        <scope>provided</scope>

    </dependency>
    <dependency>
        <groupId>com.okta.jwt</groupId>
        <artifactId>okta-jwt-verifier</artifactId>
        <version>0.5.0</version>
    </dependency>

    <dependency>
        <groupId>com.okta.jwt</groupId>
        <artifactId>okta-jwt-verifier-impl</artifactId>
        <version>0.5.0</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>
</code>```

References that I followed

For writing Custom handler

OKTA validation

答:
My problem got solved, when I created an OSGI bundle with eclipse plugin with all the external jars that were needed for token validation.
Steps to follow.

Create an osgi project in eclipse select option add external jar and add the jars that are needed.

Export the bundle in say mybundle.jar

Copy this bundle to /component/dropins/ directory

Copy your project myCustomHandler.jar  to /component/lib directory

Restart/Start the server

If you get any conflicts error just remove those jars from bundle and if you get any class not found error add those jar to bundle and export it.

Body:
I have extended the Abstract  handler class and written my own custom handler class in wso2 apim.
I am able to get the logs for this custom handler as well. For token validation I am using some okta dependencies in my project (okta-jwt-verifier and okta-jwt-verifier-impl). I have added the myCustomHandler.jar and other 2 jars of the above mentioned dependencies in /repository/components/lib folder. After starting the server I am not getting any error but when I hit the API request I am getting following runtime error,

java.lang.IllegalStateException: No `interface com.okta.jwt.AccessTokenVerifier$Builder` implementation found on the classpath. Have you remembered to include the okta-jwt-verifier-impl.jar in your runtime classpath?
    at com.okta.jwt.JwtVerifiers.lambda$loadService$1(JwtVerifiers.java:60) ~[okta-jwt-verifier-0.5.0.jar:0.5.0]
    at java.util.Optional.orElseThrow(Optional.java:408) ~[?:?]
    at com.okta.jwt.JwtVerifiers.loadService(JwtVerifiers.java:60) ~[okta-jwt-verifier-0.5.0.jar:0.5.0]
    at com.okta.jwt.JwtVerifiers.accessTokenVerifierBuilder(JwtVerifiers.java:51) ~[okta-jwt-verifier-0.5.0.jar:0.5.0]
    at org.wso2.carbon.test.CustomAPIAuthenticationHandler.authenticate(CustomAPIAuthenticationHandler.java:44) ~[MCM_Custom_handler.jar:?]
    at org.wso2.carbon.test.CustomAPIAuthenticationHandler.handleRequest(CustomAPIAuthenticationHandler.java:24) ~[MCM_Custom_handler.jar:?]
    at org.apache.synapse.rest.API.process(API.java:373)

My code part where I am getting error,

        AccessTokenVerifier jwtVerifier = JwtVerifiers.accessTokenVerifierBuilder()
            .setIssuer("https://{{myDomain}}/oauth2/default").setAudience("api://default")
            .setConnectionTimeout(Duration.ofSeconds(1)) // defaults to 1s
            .setRetryMaxAttempts(2) // defaults to 2
            .setRetryMaxElapsed(Duration.ofSeconds(10)) // defaults to 10s
            .build();

I think somehow the wso2apim is not able to find the jar that I have provided and /lib folder and it is searching for it in some other directory as it is runtime dependencie...
OR this could be some OKTA issue that I don't know :(
Can you please help me with this issue ?, I have been stuck since 1 week but did not got any breakthrough thanks in advance

My pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.test</groupId>
<artifactId>org.wso2.carbon.test</artifactId>
<packaging>bundle</packaging>
<version>1.0-SNAPSHOT</version>

<name>org.wso2.carbon.test.authenticator</name>
<url>http://maven.apache.org</url>

<repositories>
    <repository>
        <id>wso2-nexus</id>
        <name>WSO2 internal Repository</name>
        <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
            <checksumPolicy>ignore</checksumPolicy>
        </releases>
    </repository>

    <repository>
        <id>wso2.releases</id>
        <name>WSO2 internal Repository</name>
        <url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
            <checksumPolicy>ignore</checksumPolicy>
        </releases>
    </repository>

    <repository>
        <id>wso2.snapshots</id>
        <name>Apache Snapshot Repository</name>
        <url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </snapshots>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>wso2.releases</id>
        <name>WSO2 internal Repository</name>
        <url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
            <checksumPolicy>ignore</checksumPolicy>
        </releases>
    </pluginRepository>

    <pluginRepository>
        <id>wso2.snapshots</id>
        <name>WSO2 Snapshot Repository</name>
        <url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </snapshots>
        <releases>
            <enabled>false</enabled>
        </releases>
    </pluginRepository>
    <pluginRepository>
        <id>wso2-nexus</id>
        <name>WSO2 internal Repository</name>
        <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
            <checksumPolicy>ignore</checksumPolicy>
        </releases>
    </pluginRepository>
</pluginRepositories>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.0</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>1.4.0</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>org.wso2.carbon.test</Bundle-SymbolicName>
                    <Bundle-Name>org.wso2.carbon.test</Bundle-Name>
                    <Import-Package>
                        com.okta.jwt,
                        *; resolution:=optional
                    </Import-Package>
                    <Export-Package>
                        org.wso2.carbon.test.*,
                    </Export-Package>
                </instructions>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.apache.synapse</groupId>
        <artifactId>synapse-core</artifactId>
        <version>2.1.7-wso2v183</version>
        <scope>provided</scope>

    </dependency>
    <dependency>
        <groupId>org.apache.synapse</groupId>
        <artifactId>synapse-commons</artifactId>
        <version>2.1.7-wso2v183</version>
        <scope>provided</scope>

    </dependency>
    <dependency>
        <groupId>org.wso2.carbon.apimgt</groupId>
        <artifactId>org.wso2.carbon.apimgt.gateway</artifactId>
        <version>6.7.206</version>
        <scope>provided</scope>

    </dependency>
    <dependency>
        <groupId>com.okta.jwt</groupId>
        <artifactId>okta-jwt-verifier</artifactId>
        <version>0.5.0</version>
    </dependency>

    <dependency>
        <groupId>com.okta.jwt</groupId>
        <artifactId>okta-jwt-verifier-impl</artifactId>
        <version>0.5.0</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

References that I followed

For writing Custom handler

OKTA validation


问:
i dont understand how can I put an amount in these letters?
```<code>totalBought = float(input("how much you bought in total:"))
discountAmt = input("what is your status:")
if discountAmt == "S":
    S == 10
elif discountAmt == "O":
    O == 5
elif discountAmt == "M":
    M == 15
elif discountAmt == "E":
    E == 20

totalPrice = totalBought - discountAmt

print(totalPrice)
</code>```

These letters are discounts ,students,old people,pwds,and vips

答:
You can try something with Using Dictionary:

Using Dictionary code is more more readable and less if else condition

```<code>totalBought = float(input("how much you bought in total:"))
discountDict ={
     'S':10,
     'O': 5,
     'M':15,
     'E':20

}
discountAmt = input("what is your status:")

totalPrice = totalBought - discountDict[discountAmt]

print(totalPrice)
</code>```

Body:
totalBought = float(input("how much you bought in total:"))
discountAmt = input("what is your status:")
if discountAmt == "S":
    S == 10
elif discountAmt == "O":
    O == 5
elif discountAmt == "M":
    M == 15
elif discountAmt == "E":
    E == 20

totalPrice = totalBought - discountAmt

print(totalPrice)

These letters are discounts ,students,old people,pwds,and vips

Body:
You can try something with Using Dictionary:

Using Dictionary code is more more readable and less if else condition

totalBought = float(input("how much you bought in total:"))
discountDict ={
     'S':10,
     'O': 5,
     'M':15,
     'E':20

}
discountAmt = input("what is your status:")

totalPrice = totalBought - discountDict[discountAmt]

print(totalPrice)


问:
How do I run a high pass or low pass filter on data points in R?
I am a beginner in R and I have tried to find information about the following without finding anything.

The green graph in the picture is composed by the red and yellow graphs. But let's say that I only have the data points of something like the green graph. How do I extract the low/high frequencies (i.e. approximately the red/yellow graphs) using a low pass/high pass filter?

Update: The graph was generated with

```<code>number_of_cycles = 2
max_y = 40

x = 1:500
a = number_of_cycles * 2*pi/length(x)

y = max_y * sin(x*a)
noise1 = max_y * 1/10 * sin(x*a*10)

plot(x, y, type="l", col="red", ylim=range(-1.5*max_y,1.5*max_y,5))
points(x, y + noise1, col="green", pch=20)
points(x, noise1, col="yellow", pch=20)
</code>```

Update 2: Using the Butterworth filter in the signal package suggested I get the following:

```<code>library(signal)

bf <- butter(2, 1/50, type="low")
b <- filter(bf, y+noise1)
points(x, b, col="black", pch=20)

bf <- butter(2, 1/25, type="high")
b <- filter(bf, y+noise1)
points(x, b, col="black", pch=20)
</code>```

The calculations was a bit work, signal.pdf gave next to no hints about what values W should have, but the original octave documentation at least mentioned radians which got me going. The values in my original graph was not chosen with any specific frequency in mind, so I ended up with the following not so simple frequencies: f_low = 1/500 * 2 = 1/250, f_high = 1/500 * 2*10 = 1/25 and the sampling frequency f_s = 500/500 = 1. Then I chose a f_c somewhere inbetween the low and high frequencies for the low/high pass filters (1/100 and 1/50 respectively).

答:
Check out this link where there's R code for filtering (medical signals). It's by Matt Shotwell and the site is full of interesting R/stats info with a medical bent:

biostattmat.com

The package fftfilt contains lots of filtering algorithms that should help too.

Body:
I am a beginner in R and I have tried to find information about the following without finding anything.

The green graph in the picture is composed by the red and yellow graphs. But let's say that I only have the data points of something like the green graph. How do I extract the low/high frequencies (i.e. approximately the red/yellow graphs) using a low pass/high pass filter?

Update: The graph was generated with

number_of_cycles = 2
max_y = 40

x = 1:500
a = number_of_cycles * 2*pi/length(x)

y = max_y * sin(x*a)
noise1 = max_y * 1/10 * sin(x*a*10)

plot(x, y, type="l", col="red", ylim=range(-1.5*max_y,1.5*max_y,5))
points(x, y + noise1, col="green", pch=20)
points(x, noise1, col="yellow", pch=20)

Update 2: Using the Butterworth filter in the signal package suggested I get the following:

library(signal)

bf <- butter(2, 1/50, type="low")
b <- filter(bf, y+noise1)
points(x, b, col="black", pch=20)

bf <- butter(2, 1/25, type="high")
b <- filter(bf, y+noise1)
points(x, b, col="black", pch=20)

The calculations was a bit work, signal.pdf gave next to no hints about what values W should have, but the original octave documentation at least mentioned radians which got me going. The values in my original graph was not chosen with any specific frequency in mind, so I ended up with the following not so simple frequencies: f_low = 1/500 * 2 = 1/250, f_high = 1/500 * 2*10 = 1/25 and the sampling frequency f_s = 500/500 = 1. Then I chose a f_c somewhere inbetween the low and high frequencies for the low/high pass filters (1/100 and 1/50 respectively).