问:
Invalid block tag on line 24: 'form.as_p', expected 'endblock'. Did you forget to register or load this tag?
I'm a new in Django and trying to do a app but now I'm having this error: "Invalid block tag on line 24: 'form.as_p', expected 'endblock'."

TEMPLATE

```<code>{% extends "base.html" %}

{% block title %}
    <title>Tarefas</title>
{% endblock title %}

{% block content %}
  <div class="content">
  {% if messages %}
    <div class="container">
      <br>
      {% for message in messages %}
      <div class="alert alert-info" role="alert">
        {{message}}
      </div>
      {% endfor %}
    </div>
  {% endif %}

      <div class="container tasks-box">
          <table class="table table-striped">
            <form method='POST'>
              {% csrf_token %}
              {% form.as_p %}
              <button type="submit" class="btn btn-secondary btn-sec">Adicionar</button>
            </form>
[...]
</code>```

forms.py

```<code>from django.forms import ModelForm
from todolist.models import Tasks

class TaskForm(ModelForm):
    class Meta:
        model = Tasks
        fields = ['task','responsible']
</code>```

views.py

```<code>from django.shortcuts import render, redirect
from django.http import HttpResponse
from todolist.models import Tasks
from todolist.forms import TaskForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required

@login_required
def todolist(request):
    if request.method == 'POST':
        form = TaskForm(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.manager = request.user
            instance.save()
        messages.success(request,("Tarefa adicionada"))
        return redirect('todolist')
    else:
        form = TaskForm
        all_tasks = Tasks.objects.filter(manager=request.user)
        all_users = Tasks.objects.all()
        return render(request,'todolist.html',{ 'form':form,
                                                'all_tasks':all_tasks,
                                                'all_users':all_users})
</code>```

models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
# Create your models here.

User = get_user_model()
class Tasks(models.Model):
    manager = models.ForeignKey(User, on_delete=models.CASCADE,default=None, related_name='tasks_manager')
    task = models.CharField(max_length=300)
    done = models.BooleanField(default=False)
    responsible = models.ForeignKey(User, on_delete=models.CASCADE, default=None, related_name='tasks_responsible', blank=True, null=True)

    def __str__(self):
        return self.task
</code>```

I tryed don't use {{ form }} tag in template and thats work.
I think the problem is in views, but i can't figure out why.
Someone can help me?

答:
From form rendering options as documented

All you need to do to get your form into a template is to place the form instance into the template context. So if your form is called form in the context, {{ form }} will render its  and  elements appropriately.

There are other output options though for the / pairs:

```<code>{{ form.as_table }} will render them as table cells wrapped in <tr> tags
{{ form.as_p }} will render them wrapped in <p> tags
{{ form.as_ul }} will render them wrapped in <li> tags
</code>```

So you have a typo error in {% form.as_p %} just replace this with {{ form.as_p }}

Body:
I'm a new in Django and trying to do a app but now I'm having this error: "Invalid block tag on line 24: 'form.as_p', expected 'endblock'."

TEMPLATE

{% extends "base.html" %}

{% block title %}
    <title>Tarefas</title>
{% endblock title %}

{% block content %}

  {% if messages %}

      {% for message in messages %}

        {{message}}

      {% endfor %}

  {% endif %}

            <form method='POST'>
              {% csrf_token %}
              {% form.as_p %}
              <button type="submit" class="btn btn-secondary btn-sec">Adicionar</button>
            </form>
[...]

forms.py

from django.forms import ModelForm
from todolist.models import Tasks

class TaskForm(ModelForm):
    class Meta:
        model = Tasks
        fields = ['task','responsible']

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from todolist.models import Tasks
from todolist.forms import TaskForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required

@login_required
def todolist(request):
    if request.method == 'POST':
        form = TaskForm(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.manager = request.user
            instance.save()
        messages.success(request,("Tarefa adicionada"))
        return redirect('todolist')
    else:
        form = TaskForm
        all_tasks = Tasks.objects.filter(manager=request.user)
        all_users = Tasks.objects.all()
        return render(request,'todolist.html',{ 'form':form,
                                                'all_tasks':all_tasks,
                                                'all_users':all_users})

models.py

from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
# Create your models here.

User = get_user_model()
class Tasks(models.Model):
    manager = models.ForeignKey(User, on_delete=models.CASCADE,default=None, related_name='tasks_manager')
    task = models.CharField(max_length=300)
    done = models.BooleanField(default=False)
    responsible = models.ForeignKey(User, on_delete=models.CASCADE, default=None, related_name='tasks_responsible', blank=True, null=True)

    def __str__(self):
        return self.task

I tryed don't use {{ form }} tag in template and thats work.
I think the problem is in views, but i can't figure out why.
Someone can help me?

Body:
From form rendering options as documented

All you need to do to get your form into a template is to place the form instance into the template context. So if your form is called form in the context, {{ form }} will render its  and  elements appropriately.

There are other output options though for the / pairs:

{{ form.as_table }} will render them as table cells wrapped in <tr> tags
{{ form.as_p }} will render them wrapped in <p> tags
{{ form.as_ul }} will render them wrapped in <li> tags

So you have a typo error in {% form.as_p %} just replace this with {{ form.as_p }}


来源: stackexchange

问:
When are javascripts loaders slower than the traditional approach?
I have an app that has a bunch of resources.  Having read about javascript loaders I decided to see what kind of boost I'd get from loading resources asynchronously.  To my surprise I found that using a loader was visibly slower (no stopwatch needed).  This has me wondering if others had similar results and what a dev ought consider regarding when to use or not use a javascript resource loader.

Here are some details about my tests:

Currently have 60 resources (primarily scripts)

Due to dependency hierarchies scripts had to be loaded in about 8 batches

Primarily used Firefox (but tried in Chrome as well)

Ran tests on both Ubunutu and Windows

Using a loader (YepNope in my case) does add a little overhead

I wrote a small bootloader class to simplify my interaction with YepNope.

Source code is on github (run tests.html and tests-loader.html)

When I say "slower" I'm not saying it's terribly slow.  It's just that I had to spend some time to set this up and that the results were worse than before I started.

Is 60 resources too few to use a loader?  Should resources generally be huge or can they be a bunch of small files?  What kinds of things would cause a loader to be slower than using traditional script tags?

答:
Resources are loaded asynchronously? First of all, is the device you are using multi-core? Async. loading is only useful if you have a multi-core computer, laptop, tablet, phone, or other device.

Second, is the loader you use a quality one? Try different loaders, as I see it, there are no standard "this is good" loaders right now, so one you have might be broken. Another one may work.

Are you sure browsers aren't already optimizing page resource loading? Using an alternate way may actually get in the way of new and faster browsers, slowing down page loading.

Personally I haven't used these loaders, these are just my educated guesses.

ContentLicense: CC BY-SA 3.0


问:
How to mock system call in C++ Unit Testing during runtime using GoogleMock?
I have a module written in C. In which I have API defined as follow.

```<code>int ReadData(void* data, int data_size, char* filename, int offset)
</code>```

When performing unit test in order to cover full coverage I need to hit at error condition for fseek and fread system call.
Can somebody explain me How can I override fseek/fread during particular test case so instead of system call it will call mock fseek/fread for that test case ?

```<code>ReadAPI.c
</code>```
```<code>#include<stdio.h>
#include<stdlib.h>

int readdata(void* data,int size, int offset, char* filename)
{
    if(data == NULL || size == 0 || filename == NULL)
    {
        return -1;
    }

    FILE* fp = fopen(filename,"rb");
    if(fp == NULL)
    {
        return -1;
    }

    if(fseek(fp,offset,SEEK_SET) != 0)
    {
        fclose(fp);
        return -1;
    }

    fread(data,size,1,fp);

    if(ferror(fp))
    {
        fclose(fp);
        return -1;
    }
    fclose(fp);
    return 1;
}

</code>```
```<code>readapi.h
</code>```
```<code>#include<stdio.h>
#include<stdlib.h>

int readdata(void* data,int size, int offset, char* filename)
</code>```
```<code>Test.cpp
</code>```
```<code>#include<gtest/gtest.h>
#include"readapi.h"

TEST(test, Test1fseek)
{
    // When fseek called in readdata API call mock fseek to hit fseek fail
    // fseek(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,"test.txt");
    EXPECT_EQ(status, -1);
}

TEST(test, Test2fread)
{
    //When fread called in readdata API call mock fread to hit read fail
    // fread(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,"test.txt");
    EXPECT_EQ(status, -1);
}

int main()
{
    return RUN_ALL_TEST();
}

</code>```

答:
You can refer to mocking-free-functions in Gmock's documentation.

Unfortunately, using the recommended method means you will have to change your code, which may not work if your code need to strictly be a C code.

However, if you are willing to accept this, based on the documentation, you will have to create a wrapper around all the system functions that you are using and then mock that wrapper.

Also, don't forget that you will have to add EXPECT_CALL or ON_CALL for all functions that are expected to be called and return a non-default (i.e. 0) value. For example, in your first test, you should also provide EXPECT_CALL or ON_CALL for fopen.

Here is an example implementation:

```<code>// System wrapper interface class.
class MySystemWrapperInterface {
 public:
  virtual FILE* fopen(const char* filename, const char* mode) = 0;
  virtual int fseek(FILE* stream, long int offset, int whence) = 0;
  virtual size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream) = 0;
  virtual int ferror(FILE* stream) = 0;
  virtual int fclose(FILE* stream) = 0;
};

// System wrapper actual class used in production code.
class MySystemWrapperClass : public MySystemWrapperInterface {
 public:
  FILE* fopen(const char* filename, const char* mode) {
    return ::fopen(filename, mode);
  }
  int fseek(FILE* stream, long int offset, int whence) {
    return ::fseek(stream, offset, whence);
  }
  size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream) {
    return ::fread(ptr, size, nmemb, stream);
  }
  int ferror(FILE* stream) { return ::ferror(stream); }
  int fclose(FILE* stream) { return ::fclose(stream); }
};

// Mocked System wrapper used for testint.
class MySystemWrapperMockClass : public MySystemWrapperInterface {
 public:
  MOCK_METHOD(FILE*, fopen, (const char*, const char*), (override));
  MOCK_METHOD(int, fseek, (FILE*, long int, int), (override));
  MOCK_METHOD(size_t, fread, (void*, size_t, size_t, FILE*), (override));
  MOCK_METHOD(int, ferror, (FILE*), (override));
  MOCK_METHOD(int, fclose, (FILE*), (override));
};

// Wrapper class for your own readdata function.
class MyClass {
  // The system wrapper passed by dependency injection through constructor.
  MySystemWrapperInterface* system_wrapper_;

 public:
  // Initialize the system wrapper in constructor.
  MyClass(MySystemWrapperInterface* system_wrapper)
      : system_wrapper_(system_wrapper) {}

  int readdata(void* data, int size, int offset, char* filename) {
    if (data == NULL || size == 0 || filename == NULL) {
      return -1;
    }

    FILE* fp = system_wrapper_->fopen(filename, "rb");
    if (fp == NULL) {
      return -1;
    }

    if (system_wrapper_->fseek(fp, offset, SEEK_SET) != 0) {
      system_wrapper_->fclose(fp);
      return -1;
    }

    system_wrapper_->fread(data, size, 1, fp);

    if (system_wrapper_->ferror(fp)) {
      system_wrapper_->fclose(fp);
      return -1;
    }
    system_wrapper_->fclose(fp);
    return 1;
  }
};

TEST(test, Test1fseek) {
  // Create the mock object and inject it into your class.
  MySystemWrapperMockClass mock_system_wrapper;
  MyClass my_object(&mock_system_wrapper);

  // When fseek called in readdata API call mock fseek to hit fseek fail
  // fseek(){return -1;}

  // IMPORTANT: Don't forget to add EXPECT_CALL or ON_CALL for all functions
  // that are expected to be called.
  EXPECT_CALL(mock_system_wrapper, fopen)
      .Times(1)
      .WillOnce(Return(reinterpret_cast<FILE*>(0x1)));

  EXPECT_CALL(mock_system_wrapper, fseek).Times(1).WillOnce(Return(1));
  EXPECT_CALL(mock_system_wrapper, fclose).Times(1).WillOnce(Return(1));

  char data[10] = {0};
  int status = my_object.readdata(data, sizeof(data), 0, "test.txt");
  EXPECT_EQ(status, -1);
}

TEST(test, Test2fread) {
  // Create the mock object and inject it into your class.
  MySystemWrapperMockClass mock_system_wrapper;
  MyClass my_object(&mock_system_wrapper);

  // When fread called in readdata API call mock fread to hit read fail
  // fread(){return -1;}
  // IMPORTANT: Don't forget to add EXPECT_CALL or ON_CALL for all functions
  // that are expected to be called.
  EXPECT_CALL(mock_system_wrapper, fopen)
      .Times(1)
      .WillOnce(Return(reinterpret_cast<FILE*>(0x1)));
  EXPECT_CALL(mock_system_wrapper, fseek).Times(1).WillOnce(Return(0));
  EXPECT_CALL(mock_system_wrapper, fread).Times(1).WillOnce(Return(-1));
  EXPECT_CALL(mock_system_wrapper, ferror).Times(1).WillOnce(Return(-1));
  EXPECT_CALL(mock_system_wrapper, fclose).Times(1).WillOnce(Return(1));

  char data[10] = {0};
  int status = my_object.readdata(data, sizeof(data), 0, "test.txt");
  EXPECT_EQ(status, -1);
}
</code>```

Live example: https://godbolt.org/z/qxf74fWGh

ContentLicense: CC BY-SA 4.0

Body:
I have a module written in C. In which I have API defined as follow.

int ReadData(void* data, int data_size, char* filename, int offset)

When performing unit test in order to cover full coverage I need to hit at error condition for fseek and fread system call.
Can somebody explain me How can I override fseek/fread during particular test case so instead of system call it will call mock fseek/fread for that test case ?

ReadAPI.c

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

int readdata(void* data,int size, int offset, char* filename)
{
    if(data == NULL || size == 0 || filename == NULL)
    {
        return -1;
    }

    FILE* fp = fopen(filename,"rb");
    if(fp == NULL)
    {
        return -1;
    }

    if(fseek(fp,offset,SEEK_SET) != 0)
    {
        fclose(fp);
        return -1;
    }

    fread(data,size,1,fp);

    if(ferror(fp))
    {
        fclose(fp);
        return -1;
    }
    fclose(fp);
    return 1;
}

readapi.h

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

int readdata(void* data,int size, int offset, char* filename)

Test.cpp

#include<gtest/gtest.h>
#include"readapi.h"

TEST(test, Test1fseek)
{
    // When fseek called in readdata API call mock fseek to hit fseek fail
    // fseek(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,"test.txt");
    EXPECT_EQ(status, -1);
}

TEST(test, Test2fread)
{
    //When fread called in readdata API call mock fread to hit read fail
    // fread(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,"test.txt");
    EXPECT_EQ(status, -1);
}

int main()
{
    return RUN_ALL_TEST();
}

Body:
You can refer to mocking-free-functions in Gmock's documentation.

Unfortunately, using the recommended method means you will have to change your code, which may not work if your code need to strictly be a C code.

However, if you are willing to accept this, based on the documentation, you will have to create a wrapper around all the system functions that you are using and then mock that wrapper.

Also, don't forget that you will have to add EXPECT_CALL or ON_CALL for all functions that are expected to be called and return a non-default (i.e. 0) value. For example, in your first test, you should also provide EXPECT_CALL or ON_CALL for fopen.

Here is an example implementation:

// System wrapper interface class.
class MySystemWrapperInterface {
 public:
  virtual FILE* fopen(const char* filename, const char* mode) = 0;
  virtual int fseek(FILE* stream, long int offset, int whence) = 0;
  virtual size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream) = 0;
  virtual int ferror(FILE* stream) = 0;
  virtual int fclose(FILE* stream) = 0;
};

// System wrapper actual class used in production code.
class MySystemWrapperClass : public MySystemWrapperInterface {
 public:
  FILE* fopen(const char* filename, const char* mode) {
    return ::fopen(filename, mode);
  }
  int fseek(FILE* stream, long int offset, int whence) {
    return ::fseek(stream, offset, whence);
  }
  size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream) {
    return ::fread(ptr, size, nmemb, stream);
  }
  int ferror(FILE* stream) { return ::ferror(stream); }
  int fclose(FILE* stream) { return ::fclose(stream); }
};

// Mocked System wrapper used for testint.
class MySystemWrapperMockClass : public MySystemWrapperInterface {
 public:
  MOCK_METHOD(FILE*, fopen, (const char*, const char*), (override));
  MOCK_METHOD(int, fseek, (FILE*, long int, int), (override));
  MOCK_METHOD(size_t, fread, (void*, size_t, size_t, FILE*), (override));
  MOCK_METHOD(int, ferror, (FILE*), (override));
  MOCK_METHOD(int, fclose, (FILE*), (override));
};

// Wrapper class for your own readdata function.
class MyClass {
  // The system wrapper passed by dependency injection through constructor.
  MySystemWrapperInterface* system_wrapper_;

 public:
  // Initialize the system wrapper in constructor.
  MyClass(MySystemWrapperInterface* system_wrapper)
      : system_wrapper_(system_wrapper) {}

  int readdata(void* data, int size, int offset, char* filename) {
    if (data == NULL || size == 0 || filename == NULL) {
      return -1;
    }

    FILE* fp = system_wrapper_->fopen(filename, "rb");
    if (fp == NULL) {
      return -1;
    }

    if (system_wrapper_->fseek(fp, offset, SEEK_SET) != 0) {
      system_wrapper_->fclose(fp);
      return -1;
    }

    system_wrapper_->fread(data, size, 1, fp);

    if (system_wrapper_->ferror(fp)) {
      system_wrapper_->fclose(fp);
      return -1;
    }
    system_wrapper_->fclose(fp);
    return 1;
  }
};

TEST(test, Test1fseek) {
  // Create the mock object and inject it into your class.
  MySystemWrapperMockClass mock_system_wrapper;
  MyClass my_object(&mock_system_wrapper);

  // When fseek called in readdata API call mock fseek to hit fseek fail
  // fseek(){return -1;}

  // IMPORTANT: Don't forget to add EXPECT_CALL or ON_CALL for all functions
  // that are expected to be called.
  EXPECT_CALL(mock_system_wrapper, fopen)
      .Times(1)
      .WillOnce(Return(reinterpret_cast<FILE*>(0x1)));

  EXPECT_CALL(mock_system_wrapper, fseek).Times(1).WillOnce(Return(1));
  EXPECT_CALL(mock_system_wrapper, fclose).Times(1).WillOnce(Return(1));

  char data[10] = {0};
  int status = my_object.readdata(data, sizeof(data), 0, "test.txt");
  EXPECT_EQ(status, -1);
}

TEST(test, Test2fread) {
  // Create the mock object and inject it into your class.
  MySystemWrapperMockClass mock_system_wrapper;
  MyClass my_object(&mock_system_wrapper);

  // When fread called in readdata API call mock fread to hit read fail
  // fread(){return -1;}
  // IMPORTANT: Don't forget to add EXPECT_CALL or ON_CALL for all functions
  // that are expected to be called.
  EXPECT_CALL(mock_system_wrapper, fopen)
      .Times(1)
      .WillOnce(Return(reinterpret_cast<FILE*>(0x1)));
  EXPECT_CALL(mock_system_wrapper, fseek).Times(1).WillOnce(Return(0));
  EXPECT_CALL(mock_system_wrapper, fread).Times(1).WillOnce(Return(-1));
  EXPECT_CALL(mock_system_wrapper, ferror).Times(1).WillOnce(Return(-1));
  EXPECT_CALL(mock_system_wrapper, fclose).Times(1).WillOnce(Return(1));

  char data[10] = {0};
  int status = my_object.readdata(data, sizeof(data), 0, "test.txt");
  EXPECT_EQ(status, -1);
}

Live example: https://godbolt.org/z/qxf74fWGh


问:
Is there an Octave function to remove outlier percentiles of data from a distribution?
I am trying to sort a large dataset to contain only the top 99% of the data (within a normal distribution) . Is there a function that already exists in Octave to do this ?</p>

答:
You can achieve this by using the following example code:</p>
```<code>n = 1000;
a = randn(1,n);
q1 = sort(a)(n*0.01:n);
</code>```

Body:
You can achieve this by using the following example code:

n = 1000;
a = randn(1,n);
q1 = sort(a)(n*0.01:n);


问:
How to check if user was available in a particular interval? I have to check users busy time and available online in a particular interval?
This is my sample dataframe: Here U1 was online from 9:45 to 15:00 PM and then from 22:00 PM to 23:45, and same is with U2.

user
Status
Flag
Timestamp

U1
0
Offline
09:30

U1
1
Online
09:45

U1
0
Offline
15:00

U1
0
Offline
16:00

U1
0
Offline
00:00

U1
1
Online
22:00

U1
0
Offline
23:45

U2
0
Offline
09:30

U2
1
Online
09:45

U2
0
Offline
15:00

U2
0
Offline
16:00

U2
0
Offline
00:00

U2
1
Online
22:00

U2
0
Offline
23:45

Expected output for each user:

User
TimeInterval
Online/Offline

U1
00:00-00:30
offline

U1
00:31-01:00
offline

U1
01:00-01:30
offline

U1
01:31-02:00
offline

U1
02:00-02:30
offline

U1
02:31-03:00
offline

U1
03:00-03:30
offline

U1
03:31-04:00
offline

U1
04:00-04:30
offline

U1
04:31-05:00
offline

U1
05:00-05:30
offline

U1
05:31-06:00
offline

U1
06:00-06:30
offline

U1
06:31-07:00
offline

U1
07:00-07:30
offline

U1
07:31-08:00
offline

U1
08:00-08:30
offline

U1
08:31-09:00
offline

U1
09:00-09:30
offline

U1
09:31-10:00
Online

U1
10:00-10:30
Online

U1
10:31-11:00
Online

U1
11:00-11:30
Online

U1
11:31-12:00
online

U1
12:00-12:30
Online

U1
12:31-13:00
Online

U1
13:00-13:30
Online

U1
13:31-14:00
Online

U1
14:00-14:30
Online

U1
14:31-15:00
Online

U1
15:00-15:30
Offline

U1
15:31-16:00
offline

U1
16:00-16:30
offline

U1
16:31-17:00
offline

U1
17:00-17:30
offline

U1
17:31-18:00
offline

U1
18:00-18:30
offline

U1
18:31-19:00
offline

U1
19:00-19:30
offline

U1
19:31-20:00
offline

U1
20:00-20:30
offline

U1
20:31-21:00
offline

U1
21:00-21:30
offline

U1
21:31-22:00
offline

U1
22:00-22:30
Online

U1
22:31-23:00
Online

U1
23:00-23:30
Online

U1
23:31-00:00
Online

答:
Here I first create online periods and then check if a half-hour intersects one of those:

dataframe = [
    ['U1',     'Offline',   '09:30'],
    ['U1',     'Online',    '09:45'],
    ['U1',     'Offline',   '15:00'],
    ['U1',     'Offline',   '16:00'],
    ['U1',     'Offline',   '00:00'],
    ['U1',     'Online',    '22:00'],
    ['U1',     'Offline',   '23:45'],
    ['U2',     'Offline',   '09:30'],
    ['U2',     'Online',    '09:45'],
    ['U2',     'Offline',   '15:00'],
    ['U2',     'Offline',   '16:00'],
    ['U2',     'Offline',   '00:00'],
    ['U2',     'Online',    '22:00'],
    ['U2',     'Offline',   '23:45'],
]

def get_online_periods(dataframe):
    online_periods = {}
    for row in dataframe:
        user, status, time = row
        user_info = online_periods.setdefault(
            user, {
                'status': 'Offline',
                'online_time': None,
                'periods': []
            }
        )
        if status != user_info['status']:
            user_info['status'] = status
            if status == 'Online':
                user_info['online_time'] = time
            else:
                user_info['periods'].append((user_info['online_time'], time))
    return {
        user: info['periods']
            for user, info in online_periods.items()
    }

def overlap(period1, period2):
    """Checks if two intervals overlap"""
    start1, stop1 = period1
    start2, stop2 = period2
    return start1 < stop2 and start2 < stop1

def print_halfhour_status(user, online_periods):
    for i in range(48):
        hour = i//2
        start_minute = 30*(i%2)
        stop_minute  = start_minute + 29
        half_hour = ("{:02d}:{:02d}".format(hour, start_minute), "{:02d}:{:02d}".format(hour, stop_minute))
        print(
            user,
            f"{half_hour[0]} -- {half_hour[1]}",
            'Online' if any(map(lambda p: overlap(p, half_hour), online_periods)) else 'Offline'
        )

def main():
    for user, online_periods in get_online_periods(dataframe).items():
        print_halfhour_status(user, online_periods)

if __name__ == '__main__':
    main()
```


问:
Name Error- name "xxxxx" is not defined with the objects - Python
Am very new to Python programming.Which am getting the naming error in my function with the object but without the object it works fine.

Hope to get a help from the community.

```<code>--Code works
def determine_grade(TestScore):
     print("test")
def Mainfunction():
     test1 = float(input('Enter the score for test 1: '))
     print("Your Grade for Test 1 is : ",determine_grade(test1))
Mainfunction()

--Code doesnot works

class clsCalcScore_Ex6(object):

def determine_grade(TestScore):
     print("test")
def Mainfunction():
     test1 = float(input('Enter the score for test 1: '))
     print("Your Grade for Test 1 is : ",determine_grade(test1))
Mainfunction(object)

</code>```

答:
The minimal problem with your code is that your definition of the class clsCalcScore_Ex6 is incomplete.  If you add a single line to fully define the class, like this, your code will work:

```<code>class clsCalcScore_Ex6(object):
    pass
</code>```

If what you want to do is move your functions into the class as methods, then you have more work to do. Here's what doing that correctly might look like:

```<code>class clsCalcScore_Ex6(object):

    def determine_grade(self, TestScore):
         print("test")

    def Mainfunction(self):
         test1 = float(input('Enter the score for test 1: '))
         print("Your Grade for Test 1 is : ", self.determine_grade(test1))

clsCalcScore_Ex6().Mainfunction()
</code>```

Here's another way that uses static methods and avoids you having to instantiate an instance of the class (note the removal of the first set of parens in the last line):

```<code>class clsCalcScore_Ex6(object):

    @staticmethod
    def determine_grade(TestScore):
         print("test")

    @staticmethod
    def Mainfunction():
         test1 = float(input('Enter the score for test 1: '))
         print("Your Grade for Test 1 is : ", clsCalcScore_Ex6.determine_grade(test1))

clsCalcScore_Ex6.Mainfunction()
</code>```

The second way is functionally identical to your original code.  It just adds a namespace, placing most of your code under the name clsCalcScore_Ex6.

Body:
Am very new to Python programming.Which am getting the naming error in my function with the object but without the object it works fine.

Hope to get a help from the community.

--Code works
def determine_grade(TestScore):
     print("test")
def Mainfunction():
     test1 = float(input('Enter the score for test 1: '))
     print("Your Grade for Test 1 is : ",determine_grade(test1))
Mainfunction()

--Code doesnot works

class clsCalcScore_Ex6(object):

def determine_grade(TestScore):
     print("test")
def Mainfunction():
     test1 = float(input('Enter the score for test 1: '))
     print("Your Grade for Test 1 is : ",determine_grade(test1))
Mainfunction(object)

Body:
The minimal problem with your code is that your definition of the class clsCalcScore_Ex6 is incomplete.  If you add a single line to fully define the class, like this, your code will work:

class clsCalcScore_Ex6(object):
    pass

If what you want to do is move your functions into the class as methods, then you have more work to do. Here's what doing that correctly might look like:

class clsCalcScore_Ex6(object):

    def determine_grade(self, TestScore):
         print("test")

    def Mainfunction(self):
         test1 = float(input('Enter the score for test 1: '))
         print("Your Grade for Test 1 is : ", self.determine_grade(test1))

clsCalcScore_Ex6().Mainfunction()

Here's another way that uses static methods and avoids you having to instantiate an instance of the class (note the removal of the first set of parens in the last line):

class clsCalcScore_Ex6(object):

    @staticmethod
    def determine_grade(TestScore):
         print("test")

    @staticmethod
    def Mainfunction():
         test1 = float(input('Enter the score for test 1: '))
         print("Your Grade for Test 1 is : ", clsCalcScore_Ex6.determine_grade(test1))

clsCalcScore_Ex6.Mainfunction()

The second way is functionally identical to your original code.  It just adds a namespace, placing most of your code under the name clsCalcScore_Ex6.


问:
How to make Php rest server send reponse back to client
I am making a simple PHP rest service, I am calling this service with CURL here is the code for this

```<code>//client code example

 $ch = curl_init($URL);
 //curl_setopt($ch, CURLOPT_MUTE, 1);

 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

 curl_setopt($ch, CURLOPT_POST, 1);

 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));

 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

 $output = curl_exec($ch);
</code>```

Now on Rest Service I am receiving the request and doing the task. Then I have to send the response back.

```<code>  //server code example

  $xml_post = file_get_contents('php://input');

  $xmlparser = new XMLParser;

  $parsedata = $xmlparser->parse($xml_post);

  $resultobj = new ResultGenerate;

  $result = $resultobj->generate($parsedata);
</code>```

I have no idea how to send the reponse ($result) back.So that $output has the xml string in the end. Please Help

答:
```<code>echo $result
</code>```

is all you need. think about it like this. when using PHP to serve web pages, all you are doing is serving a response to the web browser. You use echo there just like you are using echo here.

Body:
I am making a simple PHP rest service, I am calling this service with CURL here is the code for this

//client code example

 $ch = curl_init($URL);
 //curl_setopt($ch, CURLOPT_MUTE, 1);

 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

 curl_setopt($ch, CURLOPT_POST, 1);

 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));

 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

 $output = curl_exec($ch);

Now on Rest Service I am receiving the request and doing the task. Then I have to send the response back.

  //server code example

  $xml_post = file_get_contents('php://input');

  $xmlparser = new XMLParser;

  $parsedata = $xmlparser->parse($xml_post);

  $resultobj = new ResultGenerate;

  $result = $resultobj->generate($parsedata);

I have no idea how to send the reponse ($result) back.So that $output has the xml string in the end. Please Help

Body:
echo $result

is all you need. think about it like this. when using PHP to serve web pages, all you are doing is serving a response to the web browser. You use echo there just like you are using echo here.


问:
I want to access the products with total amount
I have 2 tables. One is product(id, name). another is In(id, amount, products_id).
I am trying to get product name with total amount.
Example:
Aerobat-34
God of war-3
Rs537-15

I Joined the tables. Now output is

```<code>[{"name":"Aerobat","amount":"10"},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":"2"},{"name":"Aerobat","amount":"56"},{"name":"Aerobat","amount":"56"},{"name":"god of war","amount":"7"},{"name":"god of war","amount":"23"},{"name":"Rs537","amount":null},{"name":"Rs537","amount":null},{"name":"Rs537","amount":null}]
</code>```
```<code>public function index()
    {
        $product = DB::table('Products')
            ->join('ins', 'products.id', '=', 'ins.products_id')
            ->select('Products.name', 'ins.amount')
            ->get();
        echo $product;
    }
</code>```

How to find the expected result?

答:
Try this</p>
```<code>public function index()
{
    $product = DB::table('products')
        ->join('ins', 'products.id', '=', 'ins.products_id')
        ->select('products.name', DB::raw('sum(ins.amount) as total_amount'))
        ->groupBy('ins.products_id')
        ->get();

    echo $product;
}
</code>```

Body:
I have 2 tables. One is product(id, name). another is In(id, amount, products_id).
I am trying to get product name with total amount.
Example:
Aerobat-34
God of war-3
Rs537-15

I Joined the tables. Now output is

[{"name":"Aerobat","amount":"10"},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":"2"},{"name":"Aerobat","amount":"56"},{"name":"Aerobat","amount":"56"},{"name":"god of war","amount":"7"},{"name":"god of war","amount":"23"},{"name":"Rs537","amount":null},{"name":"Rs537","amount":null},{"name":"Rs537","amount":null}]

public function index()
    {
        $product = DB::table('Products')
            ->join('ins', 'products.id', '=', 'ins.products_id')
            ->select('Products.name', 'ins.amount')
            ->get();
        echo $product;
    }

How to find the expected result?

Body:
Try this

public function index()
{
    $product = DB::table('products')
        ->join('ins', 'products.id', '=', 'ins.products_id')
        ->select('products.name', DB::raw('sum(ins.amount) as total_amount'))
        ->groupBy('ins.products_id')
        ->get();

    echo $product;
}


问:
from_stream not a member of std::chrono
I am currently working on a small home project for some data processing in C++. My input data contains timestamps, e.g. "2022-02-11T16:05:05+01:00". As I need to do some arithmetic on it (e.g. subtracting and adding minutes), I would like to convert this to a date/time format.

I came across this answer on Stack Overflow. I copy-pasted the exact same code into my code editor (Visual Studio 17.0.6), which produces buckets of errors, two of these being:

```<code>C2039   'sys_time': is not a member of 'std::chrono'
C2039   'from_stream': is not a member of 'std::chrono'
</code>```

I then tried Wandbox with the latest GCC and Clang compilers, again with many errors (although the sys_time error has disappeared).

I haven't used C++ that much in the last couple of years, so I am not entirely familiar with
all the additions to the recent versions. However, I see that the chrono library has been implemented in all of these compilers as part of the C++20 additions. Why do I keep getting these errors?

答:
This part of the chrono library is new with C++20, and has only been implemented by Visual Studio 19.x to date.

I was about to recommend my free open-source preview, but I see Orkhan has already done that for me. :-)

Title: from_stream not a member of std::chrono

Body:
I am currently working on a small home project for some data processing in C++. My input data contains timestamps, e.g. "2022-02-11T16:05:05+01:00". As I need to do some arithmetic on it (e.g. subtracting and adding minutes), I would like to convert this to a date/time format.

I came across this answer on Stack Overflow. I copy-pasted the exact same code into my code editor (Visual Studio 17.0.6), which produces buckets of errors, two of these being:

C2039   'sys_time': is not a member of 'std::chrono'
C2039   'from_stream': is not a member of 'std::chrono'

I then tried Wandbox with the latest GCC and Clang compilers, again with many errors (although the sys_time error has disappeared).

I haven't used C++ that much in the last couple of years, so I am not entirely familiar with
all the additions to the recent versions. However, I see that the chrono library has been implemented in all of these compilers as part of the C++20 additions. Why do I keep getting these errors?


问:
insert csv file into snowflake as variant not working
I am trying to copy csv data into snowflake table with only one column(variant). When I run copy into statement, my variant column is only displaying data from first column. I'm not sure what the problem is. Please help.

Create or replace table name(
RAW variant )

COPY INTO db_name.table_name
FROM (SELECT s.$1::VARIANT FROM @stage_name.csv s);

答:
Assuming your .csv file consists of multiple, valid JSON, try using a file format of type JSON instead of .csv. See https://docs.snowflake.com/en/sql-reference/sql/create-file-format.html.
Alternatively, use PARSE_JSON in your SELECT.</p>


问:
Fade a color to white (increasing brightness)
I want to make a text box in .NET "glow" yellow, and then "fade" to white (basically, by incrementally increasing the brightness). I think Stackoverflow does this after you've posted an answer. I know that increasing brightness is not all that simple (it's not just uniformly increasing/decreasing RGB), but I'm not sure how to do this.

Perfect color accuracy is not important for this. I am using C#, although VB examples would be just fine, too.

Edit: This is for Winforms.

答:
Just interpolate between the colors based on the time.

If your orange color is (r1,g1,b1) and you wish to fade to a different color (r2,g2,b2), the formula for linear interpolation is (r1 + (r2-r1) * t, g1 + (g2-g1) * t, b1 + (b2-b1) * t), where t is in the range of [0.0 1.0].

In your example, your first color is probably something like (255,200,0) and your second color would be (255,255,255).

If you wish for smoother transitions, look up different ways of interpolation.

OwnerDisplayName: Jon B

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jon B

OwnerDisplayName: Andrei Krotkov


问:
Using Traits to configure an application
I've been trying to figure out a good idiomatic configuration pattern in Rust. I read a few articles and the impression I'm getting is that Traits are a way to go for my use-case. However the examples were either too simplistic or too complex. But I went ahead an refactored my application but encountered some stuff I've never seen/understood. I marked the two locations in the code.

(a) - It took a minute to get this running as I kept dealing with compiler errors but finally tried &* assuming I was de-referencing the Box and then passing a reference to it. I'm not entirely sure this is correct and would like some insight into why it works and if it'll bite me later.

(b) - None of the articles/examples I read explained how to pass the configuration to other internal methods. Again I just kept adding symbols until the compiler was happy so I'm not too confident this is the right way.

On the pattern:

My example code's structure is very similar the actual application. I take the user's input then pass it to the App which delegates the creation of the data to Words::add() who delegates the creation of a Word to Word::new() and so on. In the actual application there's an additional layer or so where metadata is generated but in the end a each of these need access to the configuration. I started with a global static config which led to testing headaches, then moved to a concrete Config type which resulted in a massive struct dealing with all the different contexts.

My goal is to have an immutable configuration that can change based on context e.g. dev, testing, production etc. I'm assuming this is a big topic that might not have a simple answer but curious if there any insights into this. I was unable to find one that fits my use-case so I'm not 100% confident I'm going in the right direction.

Link to the playground.

Edit: Updated example to better represent actual application.

// Trait

pub trait Configuration: std::fmt::Debug {
    fn change_case(&self, s: &str) -> String;
    fn add_suffix(&self, s: &str) -> String;
}

// App

#[derive(Debug)]
pub struct App {
    config: Box<dyn Configuration>,
    data: Words,
}

impl App {
    pub fn new(config: Box<dyn Configuration>) -> Self {
        Self {
            config,
            data: Words::default(),
        }
    }

    pub fn add(&mut self, word: &str) {
        self.data.insert(&*self.config, word);
        // (a) This -----^^
    }
}

#[derive(Debug, Default)]
struct AppConfig;

impl Configuration for AppConfig {
    fn change_case(&self, s: &str) -> String {
        s.to_lowercase()
    }

    fn add_suffix(&self, s: &str) -> String {
        format!("{s}able")
    }
}

// Words

#[derive(Debug, Default)]
struct Words(Vec<Word>);

impl Words {
    fn insert(&mut self, config: &dyn Configuration, word: &str) {
        // (b) This -------------^^^^

        let word = Word::new(config, word);

        println!("Adding {:?}", word);

        self.0.push(word);
    }
}

#[derive(Debug, PartialEq)]
struct Word(String);

impl Word {
    pub fn new(config: &dyn Configuration, word: &str) -> Self {
        let word = config.add_suffix(word);
        let word = config.change_case(&word);
        Self(word)
    }
}

fn main() {
    let config = AppConfig::default();
    let mut app = App::new(Box::new(config));
    app.add("use");
    app.add("mark");
    app.add("seal");
}

#[cfg(test)]
mod tests {

    use super::*;

    #[derive(Debug, Default)]
    struct TestConfig;

    impl Configuration for TestConfig {
        fn change_case(&self, s: &str) -> String {
            s.to_uppercase()
        }

        fn add_suffix(&self, s: &str) -> String {
            format!("{s}ing")
        }
    }

    #[test]
    fn test() {
        let config = TestConfig::default();
        let mut app = App::new(Box::new(config));
        app.add("test");

        assert_eq!(app.data.0[0], Word("TESTING".to_string()));
    }
}
```

答:
The point of traits is to enable polymorphism. If your configuration is just plain old data, then you probably don't need polymorphism: structs and enums would be enough.

If parts of your configuration involves changing behavior, then you might consider defining a trait for each behavior, defining each behavior using a function/closure, or in some cases an enum might be simpler to deal with. Aggregate these with the plain old data elements in a struct.

My goal is to have an immutable configuration

When you pass a shared reference around, the object is basically frozen (unless the object itself uses interior mutability through e.g. RefCell or Mutex). In other words, shared references provide scoped immutability for free. You could even expose public fields on your struct and the callee wouldn't be able to mutate them.


问:
Can a TestNG cross-browser test be executed with Cucumber runner?
I am working with Selenium Webdriver with Cucumber. My tests work as expected with that combination. In order to achieve cross-browser testing, I added TestNG framework. To verify that my cross-browser test was working good, I ran it with TestNG alone, without Cucumber. It ran perfectly in both Chrome and Firefox browsers.

```<code>public class WebTest {

  WebDriver driver = null;
  BasePageWeb basePage;
  public String browser;

  @Parameters({ "Browser" })
  public WebTest(String browser) {
    this.browser = browser;
  }

  @BeforeClass
  public void navigateToUrl() {
    switch (browser) {

      case "CHROME":
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        break;

      case "FF":
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        break;

      default:
        driver = null;
        break;
    }
    driver.get("https://demosite.executeautomation.com/Login.html");

  }

  @Test
  public void loginToWebApp() {

    basePage = new BasePageWeb(driver);
    basePage.enterUsername("admin")
            .enterPassword("admin")
            .clickLoginButton();

    driver.quit();
  }
</code>```

}

The testng.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="tests" thread-count="5">

    <test name="Chrome Test">
        <parameter name="Browser" value="CHROME"/>
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>
    <test name="Firefox Test">
        <parameter name="Browser" value="FF"/>
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>
</suite>
</code>```

I needed to integrate the TestNG test with my Cucumber set-up so that I can run the whole test with Cucumber. To do this, I added cucumber-testng dependency to POM and created a Cucumber runner extending the AbstractCucumberTestNG class. I specified the location of my feature file and step definition. The step definition is mapped to the TestNG test.

Cucumber runner:

```<code>@CucumberOptions(
                plugin = {"pretty", "html:target/surefire-reports/cucumber",
                        "json:target/surefire-reports/cucumberOriginal.json"},
                glue = {"stepdefinitions"},
                tags = "@web-1",
                features = {"src/test/resources/features/web.feature"})

 public class RunCucumberNGTest extends AbstractTestNGCucumberTests {
    }
</code>```

Step definition:

```<code>public class WebAppStepDefinitions {
      private final WebTest webTest = new WebTest("CHROME"); //create an object of the class holding the testng test. If I change the argument to FF, the test will run only on Firefox
      static boolean prevScenarioFailed = false;

      @Before
      public void setUp() {
        if (prevScenarioFailed) {
          throw new IllegalStateException("Previous scenario failed!");
        }

      }

      @After()
      public void stopExecutionAfterFailure(Scenario scenario) throws Exception {
        prevScenarioFailed = scenario.isFailed();
      }

      @Given("^I have navigated to the web url \"([^\"]*)\"$")
      public void navigateToUrl(String url) {  test
        webTest.navigateToUrl(url); //calling the first method holding the testng
      }

      @When("^I log into my web account with valid credentials as specicified in (.*) and (.*)$")
      public void logintoWebApp(String username, String password) {
        webTest.loginToWebApp(username, password); //calling the second method holding the testng
      }
    }
</code>```

On running the class, the test got executed only in one browser (Chrome). Somehow, Firefox got lost in the build-up. I suspect that I am calling the parameterised TestNG method wrongly from another class. How do I do the call successfully?

答:
For running TestNG tests with Cucumber you have to define Test Runner classes in testng.xml.

your Test Runner class is RunCucumberNGTest.

So the xml should look like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="tests" thread-count="5">

    <test name="Chrome Test">
        <parameter name="Browser" value="CHROME"/>
        <classes>
            <class name="some.package.name.RunCucumberNGTest"/>
        </classes>
    </test>
    <test name="Firefox Test">
        <parameter name="Browser" value="FF"/>
        <classes>
            <class name="some.package.name.RunCucumberNGTest"/>
        </classes>
    </test>
</suite>
</code>```

From this xml I see the next requirements:

Run the same set of tests but with different parameter value.

This should work in parallel, so this should be thread-safe.

1 Introduce TestNG Parameter for Test Runner class

@CucumberOptions(
                plugin = {"pretty", "html:target/surefire-reports/cucumber",
                        "json:target/surefire-reports/cucumberOriginal.json"},
                glue = {"stepdefinitions"},
                tags = "@web-1",
                features = {"src/test/resources/features/web.feature"})
public class RunCucumberNGTest extends AbstractTestNGCucumberTests {

    // static thread-safe container to keep the browser value
    public final static ThreadLocal<String> BROWSER = new ThreadLocal<>();

    @BeforeTest
    @Parameters({"Browser"})
    public void defineBrowser(String browser) {
        //put browser value to thread-safe container
        RunCucumberNGTest.BROWSER.set(browser);
        System.out.println(browser);
    }

}
```
<p><strong>2 Use the value in Step Definition class</strong></p>
```public class WebAppStepDefinitions {
      private WebTest webTest;
      static boolean prevScenarioFailed = false;

      @Before
      public void setUp() {
        if (prevScenarioFailed) {
          throw new IllegalStateException("Previous scenario failed!");
        }
        //get the browser value for current thread
        String browser = RunCucumberNGTest.BROWSER.get();
        System.out.println("WebAppStepDefinitions: " + browser);
        //create an object of the class holding the testng test. If I change the argument to FF, the test will run only on Firefox
        webTest = new WebTest(browser);
      }

      @After
      public void stopExecutionAfterFailure(Scenario scenario) throws Exception {
        prevScenarioFailed = scenario.isFailed();
      }

      @Given("^I have navigated to the web url \"([^\"]*)\"$")
      public void navigateToUrl(String url) {
        webTest.navigateToUrl(url); //calling the first method holding the testng
      }

      @When("^I log into my web account with valid credentials as specicified in (.*) and (.*)$")
      public void logintoWebApp(String username, String password) {
        webTest.loginToWebApp(username, password); //calling the second method holding the testng
      }

}
```
<hr />
<p><strong>NOTE:</strong> All TestNG annotations should be removed from <code>WebTest</code> class, they won't work and not required. <code>WebTest</code> used explicitly by <code>WebAppStepDefinitions</code> class, all the methods invoked explicitly and not by TestNG.</p>
<p>So, based on your initial requirements:</p>
```public class WebTest {

  WebDriver driver = null;
  BasePageWeb basePage;
  public String browser;

  public WebTest(String browser) {
    this.browser = browser;
  }

  public void navigateToUrl(String url) {
    switch (browser) {

      case "CHROME":
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        break;

      case "FF":
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        break;

      default:
        driver = null;
        break;
    }
    driver.get(url);

  }

  public void loginToWebApp(String username, String password) {

    basePage = new BasePageWeb(driver);
    basePage.enterUsername(username)
            .enterPassword(password)
            .clickLoginButton();

    driver.quit();
  }
```

Body:
I am working with Selenium Webdriver with Cucumber. My tests work as expected with that combination. In order to achieve cross-browser testing, I added TestNG framework. To verify that my cross-browser test was working good, I ran it with TestNG alone, without Cucumber. It ran perfectly in both Chrome and Firefox browsers.

public class WebTest {

  WebDriver driver = null;
  BasePageWeb basePage;
  public String browser;

  @Parameters({ "Browser" })
  public WebTest(String browser) {
    this.browser = browser;
  }

  @BeforeClass
  public void navigateToUrl() {
    switch (browser) {

      case "CHROME":
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        break;

      case "FF":
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        break;

      default:
        driver = null;
        break;
    }
    driver.get("https://demosite.executeautomation.com/Login.html");

  }

  @Test
  public void loginToWebApp() {

    basePage = new BasePageWeb(driver);
    basePage.enterUsername("admin")
            .enterPassword("admin")
            .clickLoginButton();

    driver.quit();
  }

}

The testng.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="tests" thread-count="5">

    <test name="Chrome Test">
        <parameter name="Browser" value="CHROME"/>
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>
    <test name="Firefox Test">
        <parameter name="Browser" value="FF"/>
        <classes>
            <class name="tests.web.WebTest"/>
        </classes>
    </test>
</suite>

I needed to integrate the TestNG test with my Cucumber set-up so that I can run the whole test with Cucumber. To do this, I added cucumber-testng dependency to POM and created a Cucumber runner extending the AbstractCucumberTestNG class. I specified the location of my feature file and step definition. The step definition is mapped to the TestNG test.

Cucumber runner:

@CucumberOptions(
                plugin = {"pretty", "html:target/surefire-reports/cucumber",
                        "json:target/surefire-reports/cucumberOriginal.json"},
                glue = {"stepdefinitions"},
                tags = "@web-1",
                features = {"src/test/resources/features/web.feature"})

 public class RunCucumberNGTest extends AbstractTestNGCucumberTests {
    }

Step definition:

public class WebAppStepDefinitions {
      private final WebTest webTest = new WebTest("CHROME"); //create an object of the class holding the testng test. If I change the argument to FF, the test will run only on Firefox
      static boolean prevScenarioFailed = false;

      @Before
      public void setUp() {
        if (prevScenarioFailed) {
          throw new IllegalStateException("Previous scenario failed!");
        }

      }

      @After()
      public void stopExecutionAfterFailure(Scenario scenario) throws Exception {
        prevScenarioFailed = scenario.isFailed();
      }

      @Given("^I have navigated to the web url \"([^\"]*)\"$")
      public void navigateToUrl(String url) {  test
        webTest.navigateToUrl(url); //calling the first method holding the testng
      }

      @When("^I log into my web account with valid credentials as specicified in (.*) and (.*)$")
      public void logintoWebApp(String username, String password) {
        webTest.loginToWebApp(username, password); //calling the second method holding the testng
      }
    }

On running the class, the test got executed only in one browser (Chrome). Somehow, Firefox got lost in the build-up. I suspect that I am calling the parameterised TestNG method wrongly from another class. How do I do the call successfully?

Body:
For running TestNG tests with Cucumber you have to define Test Runner classes in testng.xml.

your Test Runner class is RunCucumberNGTest.

So the xml should look like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="tests" thread-count="5">

    <test name="Chrome Test">
        <parameter name="Browser" value="CHROME"/>
        <classes>
            <class name="some.package.name.RunCucumberNGTest"/>
        </classes>
    </test>
    <test name="Firefox Test">
        <parameter name="Browser" value="FF"/>
        <classes>
            <class name="some.package.name.RunCucumberNGTest"/>
        </classes>
    </test>
</suite>

From this xml I see the next requirements:

Run the same set of tests but with different parameter value.

This should work in parallel, so this should be thread-safe.

1 Introduce TestNG Parameter for Test Runner class

@CucumberOptions(
                plugin = {"pretty", "html:target/surefire-reports/cucumber",
                        "json:target/surefire-reports/cucumberOriginal.json"},
                glue = {"stepdefinitions"},
                tags = "@web-1",
                features = {"src/test/resources/features/web.feature"})
public class RunCucumberNGTest extends AbstractTestNGCucumberTests {

    // static thread-safe container to keep the browser value
    public final static ThreadLocal<String> BROWSER = new ThreadLocal<>();

    @BeforeTest
    @Parameters({"Browser"})
    public void defineBrowser(String browser) {
        //put browser value to thread-safe container
        RunCucumberNGTest.BROWSER.set(browser);
        System.out.println(browser);
    }

}

2 Use the value in Step Definition class

public class WebAppStepDefinitions {
      private WebTest webTest;
      static boolean prevScenarioFailed = false;

      @Before
      public void setUp() {
        if (prevScenarioFailed) {
          throw new IllegalStateException("Previous scenario failed!");
        }
        //get the browser value for current thread
        String browser = RunCucumberNGTest.BROWSER.get();
        System.out.println("WebAppStepDefinitions: " + browser);
        //create an object of the class holding the testng test. If I change the argument to FF, the test will run only on Firefox
        webTest = new WebTest(browser);
      }

      @After
      public void stopExecutionAfterFailure(Scenario scenario) throws Exception {
        prevScenarioFailed = scenario.isFailed();
      }

      @Given("^I have navigated to the web url \"([^\"]*)\"$")
      public void navigateToUrl(String url) {
        webTest.navigateToUrl(url); //calling the first method holding the testng
      }

      @When("^I log into my web account with valid credentials as specicified in (.*) and (.*)$")
      public void logintoWebApp(String username, String password) {
        webTest.loginToWebApp(username, password); //calling the second method holding the testng
      }

}

NOTE: All TestNG annotations should be removed from WebTest class, they won't work and not required. WebTest used explicitly by WebAppStepDefinitions class, all the methods invoked explicitly and not by TestNG.

So, based on your initial requirements:

public class WebTest {

  WebDriver driver = null;
  BasePageWeb basePage;
  public String browser;

  public WebTest(String browser) {
    this.browser = browser;
  }

  public void navigateToUrl(String url) {
    switch (browser) {

      case "CHROME":
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        break;

      case "FF":
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        break;

      default:
        driver = null;
        break;
    }
    driver.get(url);

  }

  public void loginToWebApp(String username, String password) {

    basePage = new BasePageWeb(driver);
    basePage.enterUsername(username)
            .enterPassword(password)
            .clickLoginButton();

    driver.quit();
  }


问:
variable masking in tidyverse programming in R
it is hard to reuse code in functions. I subset .data with [[ however received splicing error. i provide an example and the a solution using an "if" statement within a tidy function below. Is it possible use variable masking in tidyverse programming?

data frame

```<code>set.seed(123)
(df=data.frame(
  Yrs_Before=sample(1:8, 3),
  Yrs_After=sample(1:8, 3),
  Before.Yr_1=sample(1:8, 3),
  Before.Yr_2=sample(1:8, 3),
  Before.Yr_3=sample(1:8, 3),
  Before.Yr_4=sample(1:8, 3),
  Before.Yr_5=sample(1:8, 3),
  Before.Yr_6=sample(1:8, 3),
  Before.Yr_7=sample(1:8, 3),
  Before.Yr_8=sample(1:8, 3),
  After.Yr_1=sample(1:8, 3),
  After.Yr_2=sample(1:8, 3),
  After.Yr_3=sample(1:8, 3),
  After.Yr_4=sample(1:8, 3),
  After.Yr_5=sample(1:8, 3),
  After.Yr_6=sample(1:8, 3),
  After.Yr_7=sample(1:8, 3),
  After.Yr_8=sample(1:8, 3)

))
</code>```

is it possible to use variable masking for the following function?

```<code>sums=function(data,crashes,yrs){
  data %>%
    dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(.data[[crashes]])))[.data[[yrs]]])
}
</code>```

however an  error was recieved.

```<code>
sums(df,"After.Yr")
Error in splice(dot_call(capture_dots, frame_env = frame_env, named = named,  :
                           argument "yrs" is missing, with no default
                         Called from: splice(dot_call(capture_dots, frame_env = frame_env, named = named,
                                                      ignore_empty = ignore_empty, unquote_names = unquote_names,
                                                      homonyms = homonyms, check_assign = check_assign))
</code>```

similarly with for counts occuring during the respective "before year" periods (eg. "Before.Yr.").

```<code>sums(df,"Before.Yr")
Error in splice(dot_call(capture_dots, frame_env = frame_env, named = named,  :
  argument "yrs" is missing, with no default
Called from: splice(dot_call(capture_dots, frame_env = frame_env, named = named,
    ignore_empty = ignore_empty, unquote_names = unquote_names,
    homonyms = homonyms, check_assign = check_assign))

</code>```

the following was accomplished using an "if" statement, which provides the desired results. The desired results are provided below for the "before" (Before.Yr) and "after"(After.Yr) periods

```<code>
sums = function(data,counts){
  data %>%
    dplyr::rowwise() %>%
    dplyr::transmute(sums = if(counts=="Before.Yr") {cumsum(c_across(matches('Before.Yr')))[Yrs_Before]} else{cumsum(c_across(matches('After.Yr')))[Yrs_After]})}

</code>```

using crashes in the after period.

```<code>sums(df,"After.Yr")
# A tibble: 3 × 1
# Rowwise:
sums
<int>
  1    21
2    20
3     6

</code>```

using crashes in the before period.

```<code>> sums(df,"Before.Yr")
# A tibble: 3 × 1
# Rowwise:
sums
<int>
  1    23
2    33
3    11
</code>```

答:
Instead of using matches(.data[[crashes]]) simply do matches(crashes) and of course do you have to pass a column name for yrs:

library(dplyr)

sums <- function(data, crashes, yrs) {
  data %>%
    dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(crashes)))[.data[[yrs]]])
}

sums(df, "After.Yr", "Yrs_After")
#> # A tibble: 3 × 1
#> # Rowwise:
#>     sum
#>   <int>
#> 1    21
#> 2    20
#> 3     6

sums(df, "Before.Yr", "Yrs_Before")
#> # A tibble: 3 × 1
#> # Rowwise:
#>     sum
#>   <int>
#> 1    23
#> 2    33
#> 3    11
```

Body:
it is hard to reuse code in functions. I subset .data with [[ however received splicing error. i provide an example and the a solution using an "if" statement within a tidy function below. Is it possible use variable masking in tidyverse programming?

data frame

set.seed(123)
(df=data.frame(
  Yrs_Before=sample(1:8, 3),
  Yrs_After=sample(1:8, 3),
  Before.Yr_1=sample(1:8, 3),
  Before.Yr_2=sample(1:8, 3),
  Before.Yr_3=sample(1:8, 3),
  Before.Yr_4=sample(1:8, 3),
  Before.Yr_5=sample(1:8, 3),
  Before.Yr_6=sample(1:8, 3),
  Before.Yr_7=sample(1:8, 3),
  Before.Yr_8=sample(1:8, 3),
  After.Yr_1=sample(1:8, 3),
  After.Yr_2=sample(1:8, 3),
  After.Yr_3=sample(1:8, 3),
  After.Yr_4=sample(1:8, 3),
  After.Yr_5=sample(1:8, 3),
  After.Yr_6=sample(1:8, 3),
  After.Yr_7=sample(1:8, 3),
  After.Yr_8=sample(1:8, 3)

))

is it possible to use variable masking for the following function?

sums=function(data,crashes,yrs){
  data %>%
    dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(.data[[crashes]])))[.data[[yrs]]])
}

however an  error was recieved.

sums(df,"After.Yr")
Error in splice(dot_call(capture_dots, frame_env = frame_env, named = named,  :
                           argument "yrs" is missing, with no default
                         Called from: splice(dot_call(capture_dots, frame_env = frame_env, named = named,
                                                      ignore_empty = ignore_empty, unquote_names = unquote_names,
                                                      homonyms = homonyms, check_assign = check_assign))

similarly with for counts occuring during the respective "before year" periods (eg. "Before.Yr.").

sums(df,"Before.Yr")
Error in splice(dot_call(capture_dots, frame_env = frame_env, named = named,  :
  argument "yrs" is missing, with no default
Called from: splice(dot_call(capture_dots, frame_env = frame_env, named = named,
    ignore_empty = ignore_empty, unquote_names = unquote_names,
    homonyms = homonyms, check_assign = check_assign))

the following was accomplished using an "if" statement, which provides the desired results. The desired results are provided below for the "before" (Before.Yr) and "after"(After.Yr) periods

sums = function(data,counts){
  data %>%
    dplyr::rowwise() %>%
    dplyr::transmute(sums = if(counts=="Before.Yr") {cumsum(c_across(matches('Before.Yr')))[Yrs_Before]} else{cumsum(c_across(matches('After.Yr')))[Yrs_After]})}

using crashes in the after period.

sums(df,"After.Yr")
# A tibble: 3 × 1
# Rowwise:
sums
<int>
  1    21
2    20
3     6

using crashes in the before period.

> sums(df,"Before.Yr")
# A tibble: 3 × 1
# Rowwise:
sums
<int>
  1    23
2    33
3    11


问:
Getting "undefined is not an object" on a validated array
I'm trying to access an array inside of an object that comes in a response:

```<code>getMatches().then((matches) =>{
let possibleDraws = []
console.log(matches)
console.log(typeof matches)
matches.forEach(match => {
    if(isPossibleDraw(match)){
        possibleDraws.push(match)
    }
    console.log(match.homeForm)
})
console.log(possibleDraws)}).catch((err) =>{
console.log(err)})
</code>```

console.log(matches) returns correctly an array with just one value for testing purposes:

```<code>0:
awayForm: (4) ['L', 'D', 'W', 'D']
awayTeamID: 15994
awayTeamName: "Maritzburg United U23"
homeForm: (4) ['L', 'D', 'W', 'D']
homeTeamID: 15990
homeTeamName: "Chippa United U23"
leagueID: 734
matchID: 793855
season: 2021
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)
</code>```

However, when accessing match.homeForm, it returns "Undefined is not an object", even when match.homeForm does exist (based on the last console.log) . I even mocked the response of getMatches() to the same array (original function calls an API and get the response as a promise) and it works perfectly fine, so I really have no idea what could be happening here.

答:
if you try match[homeForm] or match['homeForm'] does it work?

also if it is an array then you need to select first item matches[0]

Body:
I'm trying to access an array inside of an object that comes in a response:

getMatches().then((matches) =>{
let possibleDraws = []
console.log(matches)
console.log(typeof matches)
matches.forEach(match => {
    if(isPossibleDraw(match)){
        possibleDraws.push(match)
    }
    console.log(match.homeForm)
})
console.log(possibleDraws)}).catch((err) =>{
console.log(err)})

console.log(matches) returns correctly an array with just one value for testing purposes:

0:
awayForm: (4) ['L', 'D', 'W', 'D']
awayTeamID: 15994
awayTeamName: "Maritzburg United U23"
homeForm: (4) ['L', 'D', 'W', 'D']
homeTeamID: 15990
homeTeamName: "Chippa United U23"
leagueID: 734
matchID: 793855
season: 2021
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)

However, when accessing match.homeForm, it returns "Undefined is not an object", even when match.homeForm does exist (based on the last console.log) . I even mocked the response of getMatches() to the same array (original function calls an API and get the response as a promise) and it works perfectly fine, so I really have no idea what could be happening here.


问:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
I need to check a JavaScript array to see if there are any duplicate values. What's the easiest way to do this? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated.

I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way.

Similar question:

Get all unique values in a JavaScript array (remove duplicates)

答:
The shortest way to remove duplicates is by using Set and Spread syntax

const remove = (array) => [...new Set(array)];
console.log(remove([1,1,2,2,3]); //1,2,3
```


问:
cmake, build with /MD and find_package(Boost)
I have a library that is a Python extension (pyd) and to be able to debug it I need to compile with Multi-threaded DLL (/MD) Runtime Libraries.
This works great until I injected a Boost dependency.
But first time I call a Boost function the code crashes with a read access violation exception.

After some investigation it turns out cmake find_package(Boost) pulls in the boost libraries build with a different run-time library i.e.boost_filesystem-vc140-mt-gd.lib

I have put this in an easy test case.

Build boost using vcpkg:

    git clone https://github.com/Microsoft/vcpkg.git

    .\bootstrap-vcpkg.bat

    vcpkg install boost

This only generates the -mt and -md-gd boost libraries.

CMakeLists.txt

```<code>cmake_minimum_required (VERSION 3.6.3)
project (FindMDBoost CXX)
set (CMAKE_CXX_STANDARD 14)

set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MD")
file (GLOB_RECURSE SOURCES "source.cpp")

set(Boost_DEBUG ON)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTI_THREADED OFF)
find_package(Boost COMPONENTS filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})

add_executable(testcode ${SOURCES})
target_link_libraries(testcode ${Boost_LIBRARIES})
</code>```

source.cpp

```<code>#include <boost/filesystem/path.hpp>
int main()
{
    auto path = boost::filesystem::path("c:\\"); // Call  Boost to see if it crashes
}
</code>```

Run cmake:

```<code>mkdir build; cd build
cmake .. "-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake"
</code>```

As you can see in the output cmake still tried to find the wrong run time and ignores my Boost_USE_STATIC_LIBS and Boost_USE_MULTI_THREADED flags!

```<code>-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1078 ] _boost_TEST_VERSIONS = 1.65.1;1.65.0;1.65;1.64.0;1.64;1.63.0;1.63;1.62.0;1.62;1.61.0;1.61;1.60.0;1.60;1.59.0;1.59;1.58.0;1.58;1.57.0;1.57;1.56.0;1.56;1.55.0;1.55;1.54.0;1.54;1.53.0;1.53;1.52.0;1.52;1.51.0;1.51;1.50.0;1.50;1.49.0;1.49;1.48.0;1.48;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.0;1.45;1.44.0;1.44;1.43.0;1.43;1.42.0;1.42;1.41.0;1.41;1.40.0;1.40;1.39.0;1.39;1.38.0;1.38;1.37.0;1.37;1.36.1;1.36.0;1.36;1.35.1;1.35.0;1.35;1.34.1;1.34.0;1.34;1.33.1;1.33.0;1.33
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1080 ] Boost_USE_MULTITHREADED = TRUE
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1082 ] Boost_USE_STATIC_LIBS =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1084 ] Boost_USE_STATIC_RUNTIME =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1086 ] Boost_ADDITIONAL_VERSIONS =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1088 ] Boost_NO_SYSTEM_PATHS =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1156 ] Declared as CMake or Environmental Variables:
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1158 ]   BOOST_ROOT =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1160 ]   BOOST_INCLUDEDIR =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1162 ]   BOOST_LIBRARYDIR =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1164 ] _boost_TEST_VERSIONS = 1.65.1;1.65.0;1.65;1.64.0;1.64;1.63.0;1.63;1.62.0;1.62;1.61.0;1.61;1.60.0;1.60;1.59.0;1.59;1.58.0;1.58;1.57.0;1.57;1.56.0;1.56;1.55.0;1.55;1.54.0;1.54;1.53.0;1.53;1.52.0;1.52;1.51.0;1.51;1.50.0;1.50;1.49.0;1.49;1.48.0;1.48;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.0;1.45;1.44.0;1.44;1.43.0;1.43;1.42.0;1.42;1.41.0;1.41;1.40.0;1.40;1.39.0;1.39;1.38.0;1.38;1.37.0;1.37;1.36.1;1.36.0;1.36;1.35.1;1.35.0;1.35;1.34.1;1.34.0;1.34;1.33.1;1.33.0;1.33
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1263 ] location of version.hpp: C:/dev/vcpkg/installed/x86-windows/include/boost/version.hpp
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1287 ] version.hpp reveals boost 1.66.0
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1363 ] using user-specified Boost_COMPILER = -vc140
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1383 ] _boost_MULTITHREADED = -mt
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1427 ] _boost_RELEASE_ABI_TAG = -
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1429 ] _boost_DEBUG_ABI_TAG = -gd
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1491 ] _boost_LIBRARY_SEARCH_DIRS_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH_boost_LIBRARY_SEARCH_DIRS_DEBUG   = C:/dev/vcpkg/installed/x86-windows/debug/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1641 ] Searching for FILESYSTEM_LIBRARY_RELEASE: boost_filesystem-vc140-mt-1_66;boost_filesystem-vc140-mt;boost_filesystem-mt-1_66;boost_filesystem-mt;boost_filesystem
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:380 ]  Boost_LIBRARY_DIR_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib _boost_LIBRARY_SEARCH_DIRS_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1692 ] Searching for FILESYSTEM_LIBRARY_DEBUG: boost_filesystem-vc140-mt-gd-1_66;boost_filesystem-vc140-mt-gd;boost_filesystem-mt-gd-1_66;boost_filesystem-mt-gd;boost_filesystem-mt;boost_filesystem
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:380 ]  Boost_LIBRARY_DIR_DEBUG = C:/dev/vcpkg/installed/x86-windows/debug/lib _boost_LIBRARY_SEARCH_DIRS_DEBUG = C:/dev/vcpkg/installed/x86-windows/debug/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1641 ] Searching for SYSTEM_LIBRARY_RELEASE: boost_system-vc140-mt-1_66;boost_system-vc140-mt;boost_system-mt-1_66;boost_system-mt;boost_system
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:380 ]  Boost_LIBRARY_DIR_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib _boost_LIBRARY_SEARCH_DIRS_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1692 ] Searching for SYSTEM_LIBRARY_DEBUG: boost_system-vc140-mt-gd-1_66;boost_system-vc140-mt-gd;boost_system-mt-gd-1_66;boost_system-mt-gd;boost_system-mt;boost_system
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:380 ]  Boost_LIBRARY_DIR_DEBUG = C:/dev/vcpkg/installed/x86-windows/debug/lib _boost_LIBRARY_SEARCH_DIRS_DEBUG = C:/dev/vcpkg/installed/x86-windows/debug/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1767 ] Boost_FOUND = 1
-- Boost version: 1.66.0
-- Found the following Boost libraries:
--   filesystem
--   system
-- Configuring done
-- Generating done
-- Build files have been written to: C:/dev/cpptests/FindMDBoost/build
</code>```

Here is the output from the linking phase.

Update: I build the boost libraries from scratch and the code stopped crashing. So this seems to be a vcpkg issue that is does not build the version of boost I need.

b2 runtime-link=shared -j16

My new CmakeList.txt file

```<code>cmake_minimum_required (VERSION 3.6.3)
project (FindMDBoost CXX)
set (CMAKE_CXX_STANDARD 14)

set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MD")
file (GLOB_RECURSE SOURCES "source.cpp")

include_directories(C:/dev/boost/boost_1_66_0)

link_directories("C:/dev/boost/boost_1_66_0/stage/lib")
add_executable(testcode ${SOURCES})
target_link_libraries(testcode libboost_filesystem-vc141-mt-x32-1_66.lib)
</code>```

答: The version of the library with an -mt is the correct one for linking to /MD ; confusingly the static library would have an s but does not seem what you want from the remarks at the beginning.  You were loading the mt-gd versions which are just the debug versions of these libraries; I suppose they expect the calling python to be the debug version as well.</p>

Body:
I have a library that is a Python extension (pyd) and to be able to debug it I need to compile with Multi-threaded DLL (/MD) Runtime Libraries.
This works great until I injected a Boost dependency.
But first time I call a Boost function the code crashes with a read access violation exception.

After some investigation it turns out cmake find_package(Boost) pulls in the boost libraries build with a different run-time library i.e.boost_filesystem-vc140-mt-gd.lib

I have put this in an easy test case.

Build boost using vcpkg:

    git clone https://github.com/Microsoft/vcpkg.git

    .\bootstrap-vcpkg.bat

    vcpkg install boost

This only generates the -mt and -md-gd boost libraries.

CMakeLists.txt

cmake_minimum_required (VERSION 3.6.3)
project (FindMDBoost CXX)
set (CMAKE_CXX_STANDARD 14)

set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MD")
file (GLOB_RECURSE SOURCES "source.cpp")

set(Boost_DEBUG ON)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTI_THREADED OFF)
find_package(Boost COMPONENTS filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})

add_executable(testcode ${SOURCES})
target_link_libraries(testcode ${Boost_LIBRARIES})

source.cpp

#include <boost/filesystem/path.hpp>
int main()
{
    auto path = boost::filesystem::path("c:\\"); // Call  Boost to see if it crashes
}

Run cmake:

mkdir build; cd build
cmake .. "-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake"

As you can see in the output cmake still tried to find the wrong run time and ignores my Boost_USE_STATIC_LIBS and Boost_USE_MULTI_THREADED flags!

-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1078 ] _boost_TEST_VERSIONS = 1.65.1;1.65.0;1.65;1.64.0;1.64;1.63.0;1.63;1.62.0;1.62;1.61.0;1.61;1.60.0;1.60;1.59.0;1.59;1.58.0;1.58;1.57.0;1.57;1.56.0;1.56;1.55.0;1.55;1.54.0;1.54;1.53.0;1.53;1.52.0;1.52;1.51.0;1.51;1.50.0;1.50;1.49.0;1.49;1.48.0;1.48;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.0;1.45;1.44.0;1.44;1.43.0;1.43;1.42.0;1.42;1.41.0;1.41;1.40.0;1.40;1.39.0;1.39;1.38.0;1.38;1.37.0;1.37;1.36.1;1.36.0;1.36;1.35.1;1.35.0;1.35;1.34.1;1.34.0;1.34;1.33.1;1.33.0;1.33
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1080 ] Boost_USE_MULTITHREADED = TRUE
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1082 ] Boost_USE_STATIC_LIBS =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1084 ] Boost_USE_STATIC_RUNTIME =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1086 ] Boost_ADDITIONAL_VERSIONS =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1088 ] Boost_NO_SYSTEM_PATHS =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1156 ] Declared as CMake or Environmental Variables:
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1158 ]   BOOST_ROOT =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1160 ]   BOOST_INCLUDEDIR =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1162 ]   BOOST_LIBRARYDIR =
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1164 ] _boost_TEST_VERSIONS = 1.65.1;1.65.0;1.65;1.64.0;1.64;1.63.0;1.63;1.62.0;1.62;1.61.0;1.61;1.60.0;1.60;1.59.0;1.59;1.58.0;1.58;1.57.0;1.57;1.56.0;1.56;1.55.0;1.55;1.54.0;1.54;1.53.0;1.53;1.52.0;1.52;1.51.0;1.51;1.50.0;1.50;1.49.0;1.49;1.48.0;1.48;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.0;1.45;1.44.0;1.44;1.43.0;1.43;1.42.0;1.42;1.41.0;1.41;1.40.0;1.40;1.39.0;1.39;1.38.0;1.38;1.37.0;1.37;1.36.1;1.36.0;1.36;1.35.1;1.35.0;1.35;1.34.1;1.34.0;1.34;1.33.1;1.33.0;1.33
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1263 ] location of version.hpp: C:/dev/vcpkg/installed/x86-windows/include/boost/version.hpp
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1287 ] version.hpp reveals boost 1.66.0
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1363 ] using user-specified Boost_COMPILER = -vc140
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1383 ] _boost_MULTITHREADED = -mt
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1427 ] _boost_RELEASE_ABI_TAG = -
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1429 ] _boost_DEBUG_ABI_TAG = -gd
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1491 ] _boost_LIBRARY_SEARCH_DIRS_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH_boost_LIBRARY_SEARCH_DIRS_DEBUG   = C:/dev/vcpkg/installed/x86-windows/debug/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1641 ] Searching for FILESYSTEM_LIBRARY_RELEASE: boost_filesystem-vc140-mt-1_66;boost_filesystem-vc140-mt;boost_filesystem-mt-1_66;boost_filesystem-mt;boost_filesystem
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:380 ]  Boost_LIBRARY_DIR_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib _boost_LIBRARY_SEARCH_DIRS_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1692 ] Searching for FILESYSTEM_LIBRARY_DEBUG: boost_filesystem-vc140-mt-gd-1_66;boost_filesystem-vc140-mt-gd;boost_filesystem-mt-gd-1_66;boost_filesystem-mt-gd;boost_filesystem-mt;boost_filesystem
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:380 ]  Boost_LIBRARY_DIR_DEBUG = C:/dev/vcpkg/installed/x86-windows/debug/lib _boost_LIBRARY_SEARCH_DIRS_DEBUG = C:/dev/vcpkg/installed/x86-windows/debug/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1641 ] Searching for SYSTEM_LIBRARY_RELEASE: boost_system-vc140-mt-1_66;boost_system-vc140-mt;boost_system-mt-1_66;boost_system-mt;boost_system
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:380 ]  Boost_LIBRARY_DIR_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib _boost_LIBRARY_SEARCH_DIRS_RELEASE = C:/dev/vcpkg/installed/x86-windows/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1692 ] Searching for SYSTEM_LIBRARY_DEBUG: boost_system-vc140-mt-gd-1_66;boost_system-vc140-mt-gd;boost_system-mt-gd-1_66;boost_system-mt-gd;boost_system-mt;boost_system
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:380 ]  Boost_LIBRARY_DIR_DEBUG = C:/dev/vcpkg/installed/x86-windows/debug/lib _boost_LIBRARY_SEARCH_DIRS_DEBUG = C:/dev/vcpkg/installed/x86-windows/debug/lib;NO_DEFAULT_PATH;NO_CMAKE_FIND_ROOT_PATH
-- [ C:/install/cmake-3.10.2-win64-x64/share/cmake-3.10/Modules/FindBoost.cmake:1767 ] Boost_FOUND = 1
-- Boost version: 1.66.0
-- Found the following Boost libraries:
--   filesystem
--   system
-- Configuring done
-- Generating done
-- Build files have been written to: C:/dev/cpptests/FindMDBoost/build

Here is the output from the linking phase.

Update: I build the boost libraries from scratch and the code stopped crashing. So this seems to be a vcpkg issue that is does not build the version of boost I need.

b2 runtime-link=shared -j16

My new CmakeList.txt file

cmake_minimum_required (VERSION 3.6.3)
project (FindMDBoost CXX)
set (CMAKE_CXX_STANDARD 14)

set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MD")
file (GLOB_RECURSE SOURCES "source.cpp")

include_directories(C:/dev/boost/boost_1_66_0)

link_directories("C:/dev/boost/boost_1_66_0/stage/lib")
add_executable(testcode ${SOURCES})
target_link_libraries(testcode libboost_filesystem-vc141-mt-x32-1_66.lib)


问:
VSCode - open ALL files returned by file search (CTRL+SHIFT+N)
If I search filenames (not file contents) for files containing a string, e.g. Mutation.js and VSCode returns 30 results, how can I open ALL those files in one shot without clicking one and repeating it 30 times?

答:
you can use this extension on your vsCode : OpenMatchingFiles

You can find how to use it in the link provided.


问:
How to collect a specific value from a text that is always a few lines below another text value?
To retrieve the values from the JSON file, I use this code:

```<code>import json

json_file = json.load(open('Bla_Bla_Bla.json'))

master_data = json_file['messages']

for unique_message in master_data:
    print(unique_message['text'])
</code>```

This is the JSON template:

```<code>{
 "name": "Bla Bla Bla",
 "type": "public_channel",
 "id": 123456789,
 "messages": [
  {
   "id": 12460,
   "type": "message",
   "date": "2022-02-07T04:14:51",
   "from": "Bla Bla Bla",
   "from_id": "channel1127646148",
   "text": "Yesterday's Tips\n   \n   First Half\n   Tips: 2\n   Win/Loss: 0/2\n   Void: 0\n   Win Ratio: 0%\n   Invested: 2u\n   Net Profit: -2u\n   ROI: -100%\n   \n   Second Half\n   Tips: 10\n   Win/Loss: 4/4\n   Void: 2\n   Win Ratio: 40%\n   Invested: 8u\n   Net Profit: 1.145u\n   ROI: 14.3%\n   \n   Total\n   Tips: 12\n   Win/Loss: 4/6\n   Void: 2\n   Win Ratio: 33.3%\n   Invested: 10u\n   Net Profit: -0.855u\n   ROI: -8.6%\n   \n   Highest Odds won: 2.500"
  }
 ]
}
</code>```

This is the output text:

```<code>Yesterday's Tips

   First Half
   Tips: 2
   Win/Loss: 0/2
   Void: 0
   Win Ratio: 0%
   Invested: 2u
   Net Profit: -2u
   ROI: -100%

   Second Half
   Tips: 10
   Win/Loss: 4/4
   Void: 2
   Win Ratio: 40%
   Invested: 8u
   Net Profit: 1.145u
   ROI: 14.3%

   Total
   Tips: 12
   Win/Loss: 4/6
   Void: 2
   Win Ratio: 33.3%
   Invested: 10u
   Net Profit: -0.855u
   ROI: -8.6%

   Highest Odds won: 2.500
</code>```

I'm trying to collect the value to Net Profit: that is inserted inside Total, the texts can change and the positions too, but whenever there is a Total, there will be a Net Profit:.

The value I want to collect in this case is:

```<code>-0.855u
</code>```

How can I go about getting that specific part of the text value?

答:
For more complex cases, you may want to look into Regular Expressions (Regex), but for this simple case:

string = unique_message["text"]  # the json data

string = string[string.find("Total"):]  # cut all the part before "Total"
string = string[string.find("Net Profit") + 12:]   # cut all the part before "Net Profit" (the + 12 removes the Net Profit bit too)
string = string[:string.find("\n")]  # take the part of the string till the next line
print(string)
```

Here, we use the str.find() function which returns the index of a certain part of a string together with string slicing string[start:end] to find only the part of the string needed. The \n is a special character which denotes the end of a line.

Body:
To retrieve the values from the JSON file, I use this code:

import json

json_file = json.load(open('Bla_Bla_Bla.json'))

master_data = json_file['messages']

for unique_message in master_data:
    print(unique_message['text'])

This is the JSON template:

{
 "name": "Bla Bla Bla",
 "type": "public_channel",
 "id": 123456789,
 "messages": [
  {
   "id": 12460,
   "type": "message",
   "date": "2022-02-07T04:14:51",
   "from": "Bla Bla Bla",
   "from_id": "channel1127646148",
   "text": "Yesterday's Tips\n   \n   First Half\n   Tips: 2\n   Win/Loss: 0/2\n   Void: 0\n   Win Ratio: 0%\n   Invested: 2u\n   Net Profit: -2u\n   ROI: -100%\n   \n   Second Half\n   Tips: 10\n   Win/Loss: 4/4\n   Void: 2\n   Win Ratio: 40%\n   Invested: 8u\n   Net Profit: 1.145u\n   ROI: 14.3%\n   \n   Total\n   Tips: 12\n   Win/Loss: 4/6\n   Void: 2\n   Win Ratio: 33.3%\n   Invested: 10u\n   Net Profit: -0.855u\n   ROI: -8.6%\n   \n   Highest Odds won: 2.500"
  }
 ]
}

This is the output text:

Yesterday's Tips

   First Half
   Tips: 2
   Win/Loss: 0/2
   Void: 0
   Win Ratio: 0%
   Invested: 2u
   Net Profit: -2u
   ROI: -100%

   Second Half
   Tips: 10
   Win/Loss: 4/4
   Void: 2
   Win Ratio: 40%
   Invested: 8u
   Net Profit: 1.145u
   ROI: 14.3%

   Total
   Tips: 12
   Win/Loss: 4/6
   Void: 2
   Win Ratio: 33.3%
   Invested: 10u
   Net Profit: -0.855u
   ROI: -8.6%

   Highest Odds won: 2.500

I'm trying to collect the value to Net Profit: that is inserted inside Total, the texts can change and the positions too, but whenever there is a Total, there will be a Net Profit:.

The value I want to collect in this case is:

-0.855u

How can I go about getting that specific part of the text value?

Body:
For more complex cases, you may want to look into Regular Expressions (Regex), but for this simple case:

string = unique_message["text"]  # the json data

string = string[string.find("Total"):]  # cut all the part before "Total"
string = string[string.find("Net Profit") + 12:]   # cut all the part before "Net Profit" (the + 12 removes the Net Profit bit too)
string = string[:string.find("\n")]  # take the part of the string till the next line
print(string)

Here, we use the str.find() function which returns the index of a certain part of a string together with string slicing string[start:end] to find only the part of the string needed. The \n is a special character which denotes the end of a line.


问:
Is it possible to keep cursor in the text area after a click even?
I'm a front-end learner. I created a primitive app that I saw in Duolingo or Memrise. It consists of a text-area and buttons situated below with extra Spanish letters which can be used in necessary. I'm a Spanish learner and need to use the letters to type outside the language apps.

The problem is that when I type in the text and click on the button with a specific extra letter the cursor in the text area disappears. I need to click again in the text area. It's a bit annoying. In Duolingo it stays in the area and the use of mouse is reduced. Does anyone know how to fix it?

```<code>     <div class="container">
      <div class="input-container">
        <div class="upper-box">
          <textarea name="" id="textarea" rows="3"></textarea>
        </div>
        <div class="input-keyboard">
          <button id="a">á</button>
          <button id="e">é</button>
          <button id="i">í</button>
          <button id="o">ó</button>
          <button id="u">ú</button>
          <button id="n">ñ</button>
          <button id="exclamation">¡</button>
          <button id="question">¿</button>
          <button id="clear">Clear</button>
          <!-- input-keyboard ends below -->
        </div>
      </div>
    </div>

</code>```
```<code>     const textarea = document.querySelector("#textarea");

// buttons

const clearBtn = document.querySelector("#clear");
const aBtn = document.querySelector("#a");
const eBtn = document.querySelector("#e");
const iBtn = document.querySelector("#i");
const oBtn = document.querySelector("#o");
const uBtn = document.querySelector("#u");
const nBtn = document.querySelector("#n");
const exlBtn = document.querySelector("#exclamation");
const queBtn = document.querySelector("#question");

aBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "á");
});

eBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "é");
});

iBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "í");
});

oBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "ó");
});

uBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "ú");
});

nBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "ñ");
});

exlBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "¡");
});

queBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "¿");
});

clearBtn.addEventListener("click", function () {
  let inputText = (textarea.value = "");
});

</code>```

答:
In each button click event, you can set focus the textarea after inserting the respective letter. Check below example (With jQuery):

```<code>$(document).on("click", "#a", function () {
    var text = $("#textarea").val();
    $("#textarea").val(text + 'á');
    $("#textarea").focus();
}
</code>```

Even with Javascript you can have a similar approach.

```<code>document.getElementById("textarea").focus();
</code>```

Body:
I'm a front-end learner. I created a primitive app that I saw in Duolingo or Memrise. It consists of a text-area and buttons situated below with extra Spanish letters which can be used in necessary. I'm a Spanish learner and need to use the letters to type outside the language apps.

The problem is that when I type in the text and click on the button with a specific extra letter the cursor in the text area disappears. I need to click again in the text area. It's a bit annoying. In Duolingo it stays in the area and the use of mouse is reduced. Does anyone know how to fix it?

          <textarea name="" id="textarea" rows="3"></textarea>

          <button id="a">á</button>
          <button id="e">é</button>
          <button id="i">í</button>
          <button id="o">ó</button>
          <button id="u">ú</button>
          <button id="n">ñ</button>
          <button id="exclamation">¡</button>
          <button id="question">¿</button>
          <button id="clear">Clear</button>

     const textarea = document.querySelector("#textarea");

// buttons

const clearBtn = document.querySelector("#clear");
const aBtn = document.querySelector("#a");
const eBtn = document.querySelector("#e");
const iBtn = document.querySelector("#i");
const oBtn = document.querySelector("#o");
const uBtn = document.querySelector("#u");
const nBtn = document.querySelector("#n");
const exlBtn = document.querySelector("#exclamation");
const queBtn = document.querySelector("#question");

aBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "á");
});

eBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "é");
});

iBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "í");
});

oBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "ó");
});

uBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "ú");
});

nBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "ñ");
});

exlBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "¡");
});

queBtn.addEventListener("click", function () {
  let inputText = (textarea.value += "¿");
});

clearBtn.addEventListener("click", function () {
  let inputText = (textarea.value = "");
});

Body:
In each button click event, you can set focus the textarea after inserting the respective letter. Check below example (With jQuery):

$(document).on("click", "#a", function () {
    var text = $("#textarea").val();
    $("#textarea").val(text + 'á');
    $("#textarea").focus();
}

Even with Javascript you can have a similar approach.

document.getElementById("textarea").focus();


答:
If the Net Profit: -0.855u is always after the Total, you can first find the index of Total and then use that to further narrow down your search scope and look for Net Profit.

# Your other logics
text = unique_message['text']
try:
    i = text.index("Total")
    profit_beginning = text[i:].index("Net Profit:")
except ValueError:
    # Don't look for profit
    pass
```

You can further enhance the lookup by using a RegEx and catch the number only.

Title: How to collect a specific value from a text that is always a few lines below another text value?

Body:
If the Net Profit: -0.855u is always after the Total, you can first find the index of Total and then use that to further narrow down your search scope and look for Net Profit.

# Your other logics
text = unique_message['text']
try:
    i = text.index("Total")
    profit_beginning = text[i:].index("Net Profit:")
except ValueError:
    # Don't look for profit
    pass

You can further enhance the lookup by using a RegEx and catch the number only.