问:
How to query a sub document that is less than a particular size in mongoose?
I have a game object that has a boolean isOpen and a sub document playersthat is an array of players. I'd like to find a game that is open for players to join that contains less than 5 players. How do I do this? Preferably without using $where

```<code>//made up sample for reference
const sampleDocument = {
    isOpen: true,
    isOver: false,
    players : [{
        socketID: 'sldfjskdfjsjdfsdfj',
        isBot: false,
        name: 'NickName',
    }],
    startTime: 32343234
</code>```

The relevant line of code

```<code>let game = await Game.findOne({isOpen: true, /*players : { $size: {$lt: 5} }*/})
</code>```

答:
You need $expr.

```<code>db.collection.find({
  $expr: {
    $and: [
      {
        $eq: [
          "$isOpen",
          true
        ],

      },
      {
        $lt: [
          {
            "$size": "$players"
          },
          5
        ]
      }
    ]
  }
})
</code>```

Body:
I have a game object that has a boolean isOpen and a sub document playersthat is an array of players. I'd like to find a game that is open for players to join that contains less than 5 players. How do I do this? Preferably without using $where

//made up sample for reference
const sampleDocument = {
    isOpen: true,
    isOver: false,
    players : [{
        socketID: 'sldfjskdfjsjdfsdfj',
        isBot: false,
        name: 'NickName',
    }],
    startTime: 32343234

The relevant line of code

let game = await Game.findOne({isOpen: true, /*players : { $size: {$lt: 5} }*/})

Body:
You need $expr.

db.collection.find({
  $expr: {
    $and: [
      {
        $eq: [
          "$isOpen",
          true
        ],

      },
      {
        $lt: [
          {
            "$size": "$players"
          },
          5
        ]
      }
    ]
  }
})


来源: stackexchange

问:
Updating a binary vector using numpy
Suppose I have a method that returns me a non-unique index list between 0 and (n-1) where n is a user-defined value. For the sake of simplicity, let us assume n is equal to five.

```<code>#arr = myMethod()
arr = np.array([4, 0, 4, 2])
</code>```

The way I interpret this array is that I have the following pairs. In other words, each number in arr matches with its corresponding index plus one.

```<code>(4,1)  - (0,2)  - (4,3) - (2,4)
</code>```

I have a numbering system for the pairs that should work as shown below. Note that since n=5, I should have 10 pairs.

```<code>(0,1) or (1,0) -> 0
(0,2) or (2,0) -> 1
(0,3) or (3,0) -> 2
(0,4) or (4,0) -> 3
(1,2) or (2,1) -> 4
(1,3) or (3,1) -> 5
(1,4) or (4,1) -> 6
(2,3) or (3,2) -> 7
(2,4) or (4,2) -> 8
(3,4) or (4,3) -> 9
</code>```

In the end, I would like to have a binary vector where each pair selected gets the value of one; zero otherwise. For the example I provided above, I should get a result as:

```<code>res = np.array([0, 1, 0, 0, 0, 0, 1, 0, 1, 1])
</code>```

I would like to perform this operation as efficiently as possible (without a for loop preferably) since I'll be working with large-scale data.  In essence, given array arr, I want to obtain array res.

答:
Here is a solution. It uses list comprehensions instead of loops. I guess the sum inside the first comprehension can be replaced by a simpler expression, but I think it is good enough. It is optimized for speed and not for space (see first edit for a solution that uses less space)

def positions(n, arr: np.ndarray) -> np.ndarray:
    """Return the positions where ones should be."""
    if any(arr >= n) or any(arr < 0):
        raise ValueError("Invalid values in input")
    # Please note that this check is not complete:  For example, a 2 could be
    # in the position 2, and other forbidden combinations are not tested
    n -= 1
    sums = [sum(((n-i) for i in range(x))) for x in range(n)]
    rv = [sums[min(x)] + abs(x[0]-x[1])-1 for x in enumerate(arr, start=1)]
    return np.array(rv)

def pairs(n, arr: np.ndarray) -> np.ndarray:
    pos = positions(n, test)
    rv = np.zeros((n * (n - 1) // 2, ), dtype=np.int_)
    rv[pos] = 1
    return rv

test = np.array([4, 0, 4, 2])
print(pairs(5, test))
```
<p>Output:</p>
```[0 1 0 0 0 0 1 0 1 1]
```

ContentLicense: CC BY-SA 4.0

Title: Updating a binary vector using numpy

Body:
Suppose I have a method that returns me a non-unique index list between 0 and (n-1) where n is a user-defined value. For the sake of simplicity, let us assume n is equal to five.

#arr = myMethod()
arr = np.array([4, 0, 4, 2])

The way I interpret this array is that I have the following pairs. In other words, each number in arr matches with its corresponding index plus one.

(4,1)  - (0,2)  - (4,3) - (2,4)

I have a numbering system for the pairs that should work as shown below. Note that since n=5, I should have 10 pairs.

(0,1) or (1,0) -> 0
(0,2) or (2,0) -> 1
(0,3) or (3,0) -> 2
(0,4) or (4,0) -> 3
(1,2) or (2,1) -> 4
(1,3) or (3,1) -> 5
(1,4) or (4,1) -> 6
(2,3) or (3,2) -> 7
(2,4) or (4,2) -> 8
(3,4) or (4,3) -> 9

In the end, I would like to have a binary vector where each pair selected gets the value of one; zero otherwise. For the example I provided above, I should get a result as:

res = np.array([0, 1, 0, 0, 0, 0, 1, 0, 1, 1])

I would like to perform this operation as efficiently as possible (without a for loop preferably) since I'll be working with large-scale data.  In essence, given array arr, I want to obtain array res.

Body:
Here is a solution. It uses list comprehensions instead of loops. I guess the sum inside the first comprehension can be replaced by a simpler expression, but I think it is good enough. It is optimized for speed and not for space (see first edit for a solution that uses less space)

def positions(n, arr: np.ndarray) -> np.ndarray:
    """Return the positions where ones should be."""
    if any(arr >= n) or any(arr < 0):
        raise ValueError("Invalid values in input")
    # Please note that this check is not complete:  For example, a 2 could be
    # in the position 2, and other forbidden combinations are not tested
    n -= 1
    sums = [sum(((n-i) for i in range(x))) for x in range(n)]
    rv = [sums[min(x)] + abs(x[0]-x[1])-1 for x in enumerate(arr, start=1)]
    return np.array(rv)

def pairs(n, arr: np.ndarray) -> np.ndarray:
    pos = positions(n, test)
    rv = np.zeros((n * (n - 1) // 2, ), dtype=np.int_)
    rv[pos] = 1
    return rv

test = np.array([4, 0, 4, 2])
print(pairs(5, test))

Output:

[0 1 0 0 0 0 1 0 1 1]


问:
Java: Rationale of the Object class not being declared abstract
Why wasn't the java.lang.Object class declared to be abstract ?

Surely for an Object to be useful it needs added state or behaviour, an Object class is an abstraction, and as such it should have been declared abstract ...  why did they choose not to ?

答:
You can instantiate Object for synchronization locks:

```<code>Object lock = new Object();

void someMethod() {
  //safe stuff
  synchronized(lock) {
     //some code avoiding race condition
  }
}

void someOtherMethod() {
  //safe code
  synchronized(lock) {
    //some other stuff avoiding race condition
  }
}
</code>```

OwnerDisplayName: Ande Turner

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ande

Body:
You can instantiate Object for synchronization locks:

Object lock = new Object();

void someMethod() {
  //safe stuff
  synchronized(lock) {
     //some code avoiding race condition
  }
}

void someOtherMethod() {
  //safe code
  synchronized(lock) {
    //some other stuff avoiding race condition
  }
}

OwnerDisplayName: Chochos

LastEditorDisplayName: mmyers


问:
ListView problem - how to put images from drawable into a listView
I'm using a web servis to get data for a places i need. In listView i need to show image, name of the Place, image for type of place and adress. I'm using Simple adapter. I know how to populate with the text, but dont know how to put images from folder drawable. First images will go in some order (like image A, second image B, third image C), and second image will depend of the type of a place (if the place is a bakery than image will be bread) and something like that. I forwarded to SimpleAdapter ArrayList of HashMaps... Can anybody give me some idea or some code???</p>

答:
I think this example would help you.

//Main Class

```<code>import android.app.Activity;
import android.os.Bundle;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Alertslistview extends Activity
{

private static class EfficientAdapter extends BaseAdapter
{
    private LayoutInflater mInflater;

    public EfficientAdapter(Context context)
    {
    mInflater = LayoutInflater.from(context);
    }

    public int getCount()
    {
    return alerts.length;
    }

    public Object getItem(int position)
    {
    return position;
    }

    public long getItemId(int position)
    {
    return position;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
    ViewHolder holder;
    if (convertView == null)
    {
        convertView = mInflater.inflate(R.layout.alertslist, null);
        holder = new ViewHolder();
        holder.img =(ImageView) convertView.findViewById(R.id.img);
        holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);

        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

        holder.img.setImageResource(imgid[position]);
        holder.text2.setText(alerts[position]);

        return convertView;
    }

    static class ViewHolder
    {
        ImageView img;
        TextView text2;
    }}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView l1 = (ListView) findViewById(R.id.ListView01);
    l1.setAdapter(new EfficientAdapter(this));      }

private static final String[] alerts= {"Service Request EBH123H has been reassigned to Mohammed","Appointment Request for May 29th declined","New Survey - Metro Rail Survey available on your device"};

static final Integer[] imgid = {R.drawable.alert,R.drawable.alert,R.drawable.alert};
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think this example would help you.

//Main Class

import android.app.Activity;
import android.os.Bundle;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Alertslistview extends Activity
{

private static class EfficientAdapter extends BaseAdapter
{
    private LayoutInflater mInflater;

    public EfficientAdapter(Context context)
    {
    mInflater = LayoutInflater.from(context);
    }

    public int getCount()
    {
    return alerts.length;
    }

    public Object getItem(int position)
    {
    return position;
    }

    public long getItemId(int position)
    {
    return position;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
    ViewHolder holder;
    if (convertView == null)
    {
        convertView = mInflater.inflate(R.layout.alertslist, null);
        holder = new ViewHolder();
        holder.img =(ImageView) convertView.findViewById(R.id.img);
        holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);

        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

        holder.img.setImageResource(imgid[position]);
        holder.text2.setText(alerts[position]);

        return convertView;
    }

    static class ViewHolder
    {
        ImageView img;
        TextView text2;
    }}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView l1 = (ListView) findViewById(R.id.ListView01);
    l1.setAdapter(new EfficientAdapter(this));      }

private static final String[] alerts= {"Service Request EBH123H has been reassigned to Mohammed","Appointment Request for May 29th declined","New Survey - Metro Rail Survey available on your device"};

static final Integer[] imgid = {R.drawable.alert,R.drawable.alert,R.drawable.alert};
}


问:
Replace values in one pandas dataframe using boolean values from another dataframe?
I have two pandas dataframes, one containing data and another consisting of True/False values

iris

Sepal.Length
Sepal.Width
Petal.Length
Petal.Width
Species

5.1
3.5
1.4
0.2
setosa

4.9
3.0
1.4
0.2
setosa

4.7
3.2
1.3
0.2
setosa

iris_bool

Sepal.Length
Sepal.Width
Petal.Length
Petal.Width
Species

True
False
True
False
False

False
True
False
False
False

False
False
False
False
True

I would like to replace values in table 1 with NA/NaNs based on the corresponding boolean in table 2. Is there an easy way to do this?

答:
Try mask:

```<code>iris = iris.mask(~iris_bool)
</code>```

Output:

```<code>>>> iris
   Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
0           5.1          NaN           1.4          NaN     NaN
1           NaN          3.0           NaN          NaN     NaN
2           NaN          NaN           NaN          NaN  setosa
</code>```

Body:
Try mask:

iris = iris.mask(~iris_bool)

Output:

>>> iris
   Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
0           5.1          NaN           1.4          NaN     NaN
1           NaN          3.0           NaN          NaN     NaN
2           NaN          NaN           NaN          NaN  setosa


问:
Custom iterator implementation that can skip on next() via tail recursion
I'm trying to implement a custom iterator that has some try/catch logic. Depending on some settings, a .next() call can skip the data it's processing if it encounters an exception.

What I have so far:

```<code>def doWork(data: InputStream): Iterator[CustomClass] = {
  val dataReader = // build reader from the input stream
  new Iterator[CustomClass] {
    override def hasNext: Boolean = dataReader.next() != null

    @tailrec
    override def next(): CustomClass = {
      try {
        getData(dataReader)
      } catch {
          case NonFatal(e) if settingEnabled => throw e
          case NonFatal(_) =>
            if (hasNext) {
              next() // recursive call
            } else {
              null // <--- this is what I'm not sure of
            }
          case badexception => badexception
      }
    }
  }
}
</code>```

I'm wondering about the case NonFatal(_) match, where I'm trying to skip the current piece of data if a NonFatal occurs (without the setting enabled). I think tail recursion would do the trick, but I'm confused about what happens if that pattern match occurs at the very end of the iterator. I don't see a way to exhaust the iterator and say "return nothing" at the end because that doesn't make sense.

I'm using Scala version 2.11.12.

答:
I would rather use some higher-level API like unfold:

Iterator.unfold(dataReader) { reader =>
  Option(reader.next()).map { _ =>
    Try(getData(reader)).toOption
  }
}.flatten
```

This will skip all non-fatalt exceptions, you may tune the code for your additional handling of that setting.

Body:
I'm trying to implement a custom iterator that has some try/catch logic. Depending on some settings, a .next() call can skip the data it's processing if it encounters an exception.

What I have so far:

def doWork(data: InputStream): Iterator[CustomClass] = {
  val dataReader = // build reader from the input stream
  new Iterator[CustomClass] {
    override def hasNext: Boolean = dataReader.next() != null

    @tailrec
    override def next(): CustomClass = {
      try {
        getData(dataReader)
      } catch {
          case NonFatal(e) if settingEnabled => throw e
          case NonFatal(_) =>
            if (hasNext) {
              next() // recursive call
            } else {
              null // <--- this is what I'm not sure of
            }
          case badexception => badexception
      }
    }
  }
}

I'm wondering about the case NonFatal(_) match, where I'm trying to skip the current piece of data if a NonFatal occurs (without the setting enabled). I think tail recursion would do the trick, but I'm confused about what happens if that pattern match occurs at the very end of the iterator. I don't see a way to exhaust the iterator and say "return nothing" at the end because that doesn't make sense.

I'm using Scala version 2.11.12.

Body:
I would rather use some higher-level API like unfold:

Iterator.unfold(dataReader) { reader =>
  Option(reader.next()).map { _ =>
    Try(getData(reader)).toOption
  }
}.flatten

This will skip all non-fatalt exceptions, you may tune the code for your additional handling of that setting.


问:
Get Locale Short Date Format using javascript
Is there anyway we can know using JavaScript the Short Date Format used in the Control Panel -> Regional and Language Settings?

I know the using the combination of following we can get the Locale Long Name format

```<code>toString()
toLocaleString()
toLocaleDateString()
toLocaleTimeString()
</code>```

But there is no direct function in JavaScript like toLocaleShortDateString().

Are there any scripts available to find out what the user setting is?

Thanks.

答:
This is a common problem in JavaScript implementations.

ECMA says Date#toLocaleDateString() is implementation-defined.
So JavaScript implementations are free to implement host-specific date-specific locales.

The problem is that most JavaScript implementations pass on the job of printing dates to the ICU library which itself does not normally support host-specific locale definitions, even though it is desired.

There is a "@compat=host" option for locales that ICU supports, but it's rarely, if ever, used and most JavaScript implementations seem to prevent setting such options on a selected locale.

Body:
Is there anyway we can know using JavaScript the Short Date Format used in the Control Panel -> Regional and Language Settings?

I know the using the combination of following we can get the Locale Long Name format

toString()
toLocaleString()
toLocaleDateString()
toLocaleTimeString()

But there is no direct function in JavaScript like toLocaleShortDateString().

Are there any scripts available to find out what the user setting is?

Thanks.


问:
Extract elements common in more than one column group
I have an R dataset as shown below

```<code>   Lake   Month.Day     Parameter
1   A     01-2003       chloride
2   A     01-2003       conductivity
3   B     02-2004       chloride
4   C     09-2007       conductivity
5   D     12-2008       chloride
6   D     12-2008       conductivity
7   D     02-2011       conductivity
</code>```

I want my new data set to only show the lakes that have both chloride and conductivity data for the same date. In this case, the new data frame would show:

```<code>   Lake   Month.Day     Parameter
1   A     01-2003       chloride
2   A     01-2003       conductivity
5   D     12-2008       chloride
6   D     12-2008       conductivity
</code>```

Is there a way to do this? Thanks in advance.

答:
Here is a simple solution for you:
We first group the data set by our desired variables, 'Lake' and 'Month.Day'. Then we make sure that both of the 'Parameter' values are present in the 'Parameter' variable in each group. So if both are present the all function returns TRUE and that group will be selected.

```<code>library(dplyr)

df %>%
  group_by(Lake, Month.Day) %>%
  filter(all(c("chloride", "conductivity") %in% Parameter))

# A tibble: 4 x 3
# Groups:   Lake, Month.Day [2]
  Lake  Month.Day Parameter
  <chr> <chr>     <chr>
1 A     01-2003   chloride
2 A     01-2003   conductivity
3 D     12-2008   chloride
4 D     12-2008   conductivity
</code>```

Body:
I have an R dataset as shown below

   Lake   Month.Day     Parameter
1   A     01-2003       chloride
2   A     01-2003       conductivity
3   B     02-2004       chloride
4   C     09-2007       conductivity
5   D     12-2008       chloride
6   D     12-2008       conductivity
7   D     02-2011       conductivity

I want my new data set to only show the lakes that have both chloride and conductivity data for the same date. In this case, the new data frame would show:

   Lake   Month.Day     Parameter
1   A     01-2003       chloride
2   A     01-2003       conductivity
5   D     12-2008       chloride
6   D     12-2008       conductivity

Is there a way to do this? Thanks in advance.

Body:
Here is a simple solution for you:
We first group the data set by our desired variables, 'Lake' and 'Month.Day'. Then we make sure that both of the 'Parameter' values are present in the 'Parameter' variable in each group. So if both are present the all function returns TRUE and that group will be selected.

library(dplyr)

df %>%
  group_by(Lake, Month.Day) %>%
  filter(all(c("chloride", "conductivity") %in% Parameter))

# A tibble: 4 x 3
# Groups:   Lake, Month.Day [2]
  Lake  Month.Day Parameter
  <chr> <chr>     <chr>
1 A     01-2003   chloride
2 A     01-2003   conductivity
3 D     12-2008   chloride
4 D     12-2008   conductivity


问:
How to serve video file / stream from ASP Net Core 6 Minimal API
I was trying to achieve this following different tutorials but did not succeed. How do I handle a http range request in minimal API to serve video stream ?

I have this bare minimal setup code for API with a single GET path "/video" mapped. I also made a folder "wwwroot" inside project folder. I placed in there a mp4 video file named "test.mp4". Would it be possible for someone knowledgeable to write a simple example of how to stream this file inside my mapped route ?

```<code>var builder = WebApplication.CreateBuilder(args);

 builder.Services.AddEndpointsApiExplorer();
 builder.Services.AddSwaggerGen();

 var app = builder.Build();

 if (app.Environment.IsDevelopment())
 {
     builder.Logging.AddJsonConsole();
     app.UseSwagger();
     app.UseSwaggerUI();
 }

 app.UseHttpsRedirection();

 app.MapGet("/video", () =>
 {

 });

</code>```

答:
You can use the Results.Stream() method to return a stream from a minimal api.

string wwwroot = builder.Environment.WebRootPath;
...
app.MapGet("/video", () =>
{
    string filePath = Path.Combine(wwwroot, "test.mp4");
    return Results.Stream(new FileStream(filePath, FileMode.Open));
});
```

The stream parameter is disposed after the response is sent.

Results.Stream takes a few other optional parameters such as fileDownloadName, and contentType (which defaults to "application/octet-stream") that might be useful to you.  Set enableRangeProcessing: true to enable range requests.

The above could easily be adapted to take a filename as a parameter, if you wish. You would need to consider validation (applies equally to the current code TBH). Tested and working for me.

Body:
I was trying to achieve this following different tutorials but did not succeed. How do I handle a http range request in minimal API to serve video stream ?

I have this bare minimal setup code for API with a single GET path "/video" mapped. I also made a folder "wwwroot" inside project folder. I placed in there a mp4 video file named "test.mp4". Would it be possible for someone knowledgeable to write a simple example of how to stream this file inside my mapped route ?

var builder = WebApplication.CreateBuilder(args);

 builder.Services.AddEndpointsApiExplorer();
 builder.Services.AddSwaggerGen();

 var app = builder.Build();

 if (app.Environment.IsDevelopment())
 {
     builder.Logging.AddJsonConsole();
     app.UseSwagger();
     app.UseSwaggerUI();
 }

 app.UseHttpsRedirection();

 app.MapGet("/video", () =>
 {

 });

Body:
You can use the Results.Stream() method to return a stream from a minimal api.

string wwwroot = builder.Environment.WebRootPath;
...
app.MapGet("/video", () =>
{
    string filePath = Path.Combine(wwwroot, "test.mp4");
    return Results.Stream(new FileStream(filePath, FileMode.Open));
});

The stream parameter is disposed after the response is sent.

Results.Stream takes a few other optional parameters such as fileDownloadName, and contentType (which defaults to "application/octet-stream") that might be useful to you.  Set enableRangeProcessing: true to enable range requests.

The above could easily be adapted to take a filename as a parameter, if you wish. You would need to consider validation (applies equally to the current code TBH). Tested and working for me.


问:
How to show data from two contexts in single view in ASP.NET Core
I'm sorry for my poor command of English.

To display a list of users for each consultant, I need to first display the first name, last name, phone number and field on a page in ASP.NET Core 5.

To do this, I need to be able to merge AspNetUsers and Students tables so that I can take information from them and save it in the view model so that I can show it on one page.

But the problem is that I can not merge these two tables. I even used the Join method in Linq, but I got an error.

Needless to say, these two tables are already relationshiped and the only problem is the simultaneous display of information from these two contexts - one IdentityDbContext and other is PlanContext.

Thank you!

View model Adminshowusers :

```<code>public class Adminshowusers
{
     public string FirstName { get; set; }
     public string LastName{ get; set; }
     public string PhoneNumber{ get; set; }
     public string Field { get; set; }
}
</code>```

And my action method that did not work

```<code>public async Task<IActionResult> ConsultantIndex(string Msg,string id)
{
    var data = await _userManager.GetAllUsersWithRolesAsync();

    var users = (from u in data
                 join a in _context.Students
                        on data.Select(x=>x.Id) equals a.ID
                 select new AdminAddUsers()
                            {
                                FirstName = u.FirstName,
                                LastName = u.LastName,
                                PhoneNumber = u.PhoneNumber,
                                Field = a.Field
                            });

    return View(users);
}
</code>```

Method GetAllUsersWithRolesAsync() is also pre-created and displays a list of all users along with their roles:

```<code>public async Task<List<UsersViewModel>> GetAllUsersWithRolesAsync()
{
    return await Users.Select(user => new UsersViewModel
        {
            Id = user.Id,
            Email = user.Email,
            UserName = user.UserName,
            PhoneNumber = user.PhoneNumber,
            FirstName = user.FirstName,
            LastName = user.LastName,
            BirthDate = user.BirthDate,
            IsActive = user.IsActive,
            LastVisitDateTime = user.LastVisitDateTime,
            Image = user.Image,
            RegisterDate = user.RegisterDate,
            Roles = user.Roles.Select(u => u.Role.Name),
        }).ToListAsync();
}
</code>```

答:
I would change code a little, you can't join code in server with code in database. At first bring all students from db and after this join with another list.</p>
```<code>    var data = await _userManager.GetAllUsersWithRolesAsync();
    var students = await _context.Students.Select(i=> new {ID=i.ID, Field=i.Field}).ToListAsync();
    var users = (from u in data
              join a in students on u.Id equals a.ID
              select new AdminAddUsers()
               {
                  FirstName=u.FirstName,
                  LastName=u.LastName,
                  PhoneNumber = u.PhoneNumber,
                  Field =a.Field
             }).ToList();

        return View(users);
</code>```

Body:
I'm sorry for my poor command of English.

To display a list of users for each consultant, I need to first display the first name, last name, phone number and field on a page in ASP.NET Core 5.

To do this, I need to be able to merge AspNetUsers and Students tables so that I can take information from them and save it in the view model so that I can show it on one page.

But the problem is that I can not merge these two tables. I even used the Join method in Linq, but I got an error.

Needless to say, these two tables are already relationshiped and the only problem is the simultaneous display of information from these two contexts - one IdentityDbContext and other is PlanContext.

Thank you!

View model Adminshowusers :

public class Adminshowusers
{
     public string FirstName { get; set; }
     public string LastName{ get; set; }
     public string PhoneNumber{ get; set; }
     public string Field { get; set; }
}

And my action method that did not work

public async Task<IActionResult> ConsultantIndex(string Msg,string id)
{
    var data = await _userManager.GetAllUsersWithRolesAsync();

    var users = (from u in data
                 join a in _context.Students
                        on data.Select(x=>x.Id) equals a.ID
                 select new AdminAddUsers()
                            {
                                FirstName = u.FirstName,
                                LastName = u.LastName,
                                PhoneNumber = u.PhoneNumber,
                                Field = a.Field
                            });

    return View(users);
}

Method GetAllUsersWithRolesAsync() is also pre-created and displays a list of all users along with their roles:

public async Task<List<UsersViewModel>> GetAllUsersWithRolesAsync()
{
    return await Users.Select(user => new UsersViewModel
        {
            Id = user.Id,
            Email = user.Email,
            UserName = user.UserName,
            PhoneNumber = user.PhoneNumber,
            FirstName = user.FirstName,
            LastName = user.LastName,
            BirthDate = user.BirthDate,
            IsActive = user.IsActive,
            LastVisitDateTime = user.LastVisitDateTime,
            Image = user.Image,
            RegisterDate = user.RegisterDate,
            Roles = user.Roles.Select(u => u.Role.Name),
        }).ToListAsync();
}

Body:
I would change code a little, you can't join code in server with code in database. At first bring all students from db and after this join with another list.

    var data = await _userManager.GetAllUsersWithRolesAsync();
    var students = await _context.Students.Select(i=> new {ID=i.ID, Field=i.Field}).ToListAsync();
    var users = (from u in data
              join a in students on u.Id equals a.ID
              select new AdminAddUsers()
               {
                  FirstName=u.FirstName,
                  LastName=u.LastName,
                  PhoneNumber = u.PhoneNumber,
                  Field =a.Field
             }).ToList();

        return View(users);


问:
How can I hide a modal element in Dittofi?
How do I use a "modal" element in #Dittofi. When I add the element it covers the entire page and I cannot access elements underneed.</p>

答:
When you add the modal box, you need to select the box marked "Modal" in the breadcrumb trial at the bottom of the page.

Then you can select the modal settings box to either show or hide the modal box.

Let me know if that works for you?


问:
How to use zlib in kernel extension projects for mac os x?
I want to develop a network kernel extension on mac os. I got some data with gzip format in function sf_data_in(). I included the header file named <libkern/zlib.h>, and my mac crashed when it was running the code below after I loading the kext with "kextload".

```<code>z_stream strm;
bzero(&strm, sizeof(z_stream));

if (Z_OK != inflateInit2(&strm))
{
    printf("inflateInit error.\n");

    inflateEnd(&strm);

    return 0;
}
</code>```

who can tell me how to use it in kernel programming. it's much better to give some samples.
Thanks very much.

答: I found some use of the zlib kernel library in the arch/powerpc/boot/gunzip_util.c file, maybe it will be a good starting point for your code.</p>

Body:
I want to develop a network kernel extension on mac os. I got some data with gzip format in function sf_data_in(). I included the header file named <libkern/zlib.h>, and my mac crashed when it was running the code below after I loading the kext with "kextload".

z_stream strm;
bzero(&strm, sizeof(z_stream));

if (Z_OK != inflateInit2(&strm))
{
    printf("inflateInit error.\n");

    inflateEnd(&strm);

    return 0;
}

who can tell me how to use it in kernel programming. it's much better to give some samples.
Thanks very much.


问:
AVD manager is not responding in Androd Studio BumbleBee 2021.1.1 for flutter
AVD manager icon is not responding. I opened a native app project and the icon is responding. But it doesn't respond if I click it from a flutter project. Tried restarting, reinstalling.</p>

答: Double press the SHIFT key on your keyboard and search for "virtual device manager" and it will open for you as usual.</p>


问:
how to use anko library in androidx
so I want to use Anko library on my apps by use Androidx, and I want to add Anko library inside of my apps on android studio, I use API version 30, android 10.0+ (R), but when I Add Anko library on my project I get the error :

```<code>Manifest merger failed : uses-sdk:minSdkVersion 14 cannot be smaller than version 15 declared in library [org.jetbrains.anko:anko-design:0.10.8] /Users/anjay/.gradle/caches/transforms-2/files-2.1/1d0aabee6b3e238a89acc21f650d01a8/jetified-anko-design-0.10.8/AndroidManifest.xml as the library might be using APIs not available in 14
    Suggestion: use a compatible library with a minSdk of at most 14,
        or increase this project's minSdk version to at least 15,
        or use tools:overrideLibrary="org.jetbrains.anko.generated.design" to force usage (may lead to runtime failures)
</code>```

This is my build.gradle (Module level):

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.apithemoviedb"
        minSdkVersion 14
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // implementasi atau library androidx design
    implementation 'com.google.android.material:material:1.0.0-alpha3'

    // implementasi atau library androidx anko
    implementation "org.jetbrains.anko:anko-design:$anko_version"
    implementation "org.jetbrains.anko:anko:$anko_version"

    // RecyclerView-v7
    implementation "org.jetbrains.anko:anko-recyclerview-v7:$anko_version"
    implementation "org.jetbrains.anko:anko-recyclerview-v7-coroutines:$anko_version"

    //implementasi atau library picasso
    implementation 'com.squareup.picasso:picasso:2.71828'

    //implementasi atau library Gson
    implementation 'com.google.code.gson:gson:2.8.6'
}
</code>```

This is my build.gradle (project level):

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.3.72"
    ext.anko_version='0.10.8'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

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

allprojects {
    repositories {
        google()
        jcenter()
    }
}

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

This is my AndroidManifest.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.apithemoviedb">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答: I don't understand... How about just increase minSdkVersion as the error log said and see what's gonna happen?</p>

Title: how to use anko library in androidx

Body:
so I want to use Anko library on my apps by use Androidx, and I want to add Anko library inside of my apps on android studio, I use API version 30, android 10.0+ (R), but when I Add Anko library on my project I get the error :

Manifest merger failed : uses-sdk:minSdkVersion 14 cannot be smaller than version 15 declared in library [org.jetbrains.anko:anko-design:0.10.8] /Users/anjay/.gradle/caches/transforms-2/files-2.1/1d0aabee6b3e238a89acc21f650d01a8/jetified-anko-design-0.10.8/AndroidManifest.xml as the library might be using APIs not available in 14
    Suggestion: use a compatible library with a minSdk of at most 14,
        or increase this project's minSdk version to at least 15,
        or use tools:overrideLibrary="org.jetbrains.anko.generated.design" to force usage (may lead to runtime failures)

This is my build.gradle (Module level):

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.apithemoviedb"
        minSdkVersion 14
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // implementasi atau library androidx design
    implementation 'com.google.android.material:material:1.0.0-alpha3'

    // implementasi atau library androidx anko
    implementation "org.jetbrains.anko:anko-design:$anko_version"
    implementation "org.jetbrains.anko:anko:$anko_version"

    // RecyclerView-v7
    implementation "org.jetbrains.anko:anko-recyclerview-v7:$anko_version"
    implementation "org.jetbrains.anko:anko-recyclerview-v7-coroutines:$anko_version"

    //implementasi atau library picasso
    implementation 'com.squareup.picasso:picasso:2.71828'

    //implementasi atau library Gson
    implementation 'com.google.code.gson:gson:2.8.6'
}

This is my build.gradle (project level):

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.3.72"
    ext.anko_version='0.10.8'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

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

allprojects {
    repositories {
        google()
        jcenter()
    }
}

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

This is my AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.apithemoviedb">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
typescript ignore window unknown property
I have a dapp that uses the MetaMask wallet extension, so I use window.ethereum a lot and get Property 'ethereum' does not exist on type 'Window & typeof globalThis'.ts(2339) a lot. How do I tell typescript to either ignore this or allow ther ethereum property  without use // @ts-ignore?

答:
The most obvious thing to do is to fix it with these type guards:

```<code>if (typeof window !== 'undefined' && typeof window.ethereum !== 'undefined') {
  // do something with window.ethereum
}
</code>```

If you're using this in a lot of places, it makes more sense to define a property on the Window interface:

```<code>import ethThing from 'your-meta-mask/thing';

interface Window {
  ethereum: typeof ethThing;
}

// no TS error
window.ethereum.something();
</code>```

The failing of the latter is a lack of runtime checking. You could of course use both in order to have typing and runtime checking.

2022-02-09 Edit:
What I was trying to get at with asking if you'd done a manual "TS check" is to figure out what conditions this is failing under. It may be that (A) static checking is failing in your IDE, (B) the build is failing, (C) you're somehow not getting that message until runtime. My assumption was (A).

Running the TypeScript compiler in a terminal will isolate it from anything that may be broken in the IDE. You can do so with a command similar to:

```<code>cd /path/to/your/project

# if you restore your tsconfig
./node_modules/typescript/bin/tsc --noEmit -p tsconfig.json

# using index.ts as an entry point
./node_modules/typescript/bin/tsc --noEmit src/index.ts

# if this is a react project, you'll need a jsx arg
./node_modules/typescript/bin/tsc --noEmit --jsx react-jsx -p tsconfig.json
</code>```

The "--noEmit" means that it won't output to a file. The "-p" is for running with a project defined by a tsconfig.json file.

Body:
The most obvious thing to do is to fix it with these type guards:

if (typeof window !== 'undefined' && typeof window.ethereum !== 'undefined') {
  // do something with window.ethereum
}

If you're using this in a lot of places, it makes more sense to define a property on the Window interface:

import ethThing from 'your-meta-mask/thing';

interface Window {
  ethereum: typeof ethThing;
}

// no TS error
window.ethereum.something();

The failing of the latter is a lack of runtime checking. You could of course use both in order to have typing and runtime checking.

2022-02-09 Edit:
What I was trying to get at with asking if you'd done a manual "TS check" is to figure out what conditions this is failing under. It may be that (A) static checking is failing in your IDE, (B) the build is failing, (C) you're somehow not getting that message until runtime. My assumption was (A).

Running the TypeScript compiler in a terminal will isolate it from anything that may be broken in the IDE. You can do so with a command similar to:

cd /path/to/your/project

# if you restore your tsconfig
./node_modules/typescript/bin/tsc --noEmit -p tsconfig.json

# using index.ts as an entry point
./node_modules/typescript/bin/tsc --noEmit src/index.ts

# if this is a react project, you'll need a jsx arg
./node_modules/typescript/bin/tsc --noEmit --jsx react-jsx -p tsconfig.json

The "--noEmit" means that it won't output to a file. The "-p" is for running with a project defined by a tsconfig.json file.


问:
How to use lodash or any other JavaScript package inside Dittofi?
How to use lodash (https://lodash.com/) or any other JavaScript package inside Dittofi?</p>

答:
Copy the lodash CDN from here

In the Dittofi front-end builder, go to the Home Page settings ("Edit Page Settings"). In there you will see an option to add "Custom code" (it's the last option).

Since lodash is JavaScript, you will need to add a script tag with the cdn as the src attribute in the "Before  tag" section and hit Save.

I.e., in the "Before  tag" section, put in  and save.

Body:
Copy the lodash CDN from here

In the Dittofi front-end builder, go to the Home Page settings ("Edit Page Settings"). In there you will see an option to add "Custom code" (it's the last option).

Since lodash is JavaScript, you will need to add a script tag with the cdn as the src attribute in the "Before  tag" section and hit Save.

I.e., in the "Before  tag" section, put in <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script> and save.


问:
PhoneGap Facebook plugin connect with Android
I have a problem using the Facebook Connect plugin with PhoneGap.

I have added this line to file plugins.xml:

```<code><plugin name="com.phonegap.facebook.Connect" value="com.phonegap.facebook.ConnectPlugin" />
</code>```

And this include on in file FbDialog.java:

```<code>import com.phonegap.helloworld.R;
</code>```

I have these files on src:

```<code>com
   /facebook/android/
                     AsyncFacebookRunner.java
                     DialogError.java
                     Facebook.java
                     FacebookError.java
                     FbDialog.java
                     Util.java
   /phonegap/
             facebook/ConnectPlugin.java
             helloworld/HelloPhoneGapActivity.java
</code>```

The ressources files close and the icon is copied. In HTML, I include some JavaScript code:

```<code>cordova-1.6.1.js
cdv-plugin-fb-connect.js
facebook_js_sdk.js
</code>```

I use the default HTML example with my appId.

When I run application on my Android phone, a dialog says:

Cordova Facebook connect plugin fail on init!

and

Cordova Facebook connect plugin fail on auth.status!

If I click the login bouton, the dialog says:

Cordova Facebook connect plugin fail on login!Class not found

And the Eclipse console log is:

I tried to install this with the officiel Git readme and the
tutorial Add Facebook login to PhoneGap/Cordova Android app Easiest way.

When I compile the application, I don't get the error.

How do I fix this problem?

答:
Verify that android studio isn't giving an error like:

A valid Facebook app id must be set in the AndroidManifest.xml or set by calling FacebookSdk.setApplicationId before initializing the sdk.

If so, then edit androidmanifest. See: A valid Facebook app id must be set in the AndroidManifest.xml

Body:
I have a problem using the Facebook Connect plugin with PhoneGap.

I have added this line to file plugins.xml:

<plugin name="com.phonegap.facebook.Connect" value="com.phonegap.facebook.ConnectPlugin" />

And this include on in file FbDialog.java:

import com.phonegap.helloworld.R;

I have these files on src:

com
   /facebook/android/
                     AsyncFacebookRunner.java
                     DialogError.java
                     Facebook.java
                     FacebookError.java
                     FbDialog.java
                     Util.java
   /phonegap/
             facebook/ConnectPlugin.java
             helloworld/HelloPhoneGapActivity.java

The ressources files close and the icon is copied. In HTML, I include some JavaScript code:

cordova-1.6.1.js
cdv-plugin-fb-connect.js
facebook_js_sdk.js

I use the default HTML example with my appId.

When I run application on my Android phone, a dialog says:

Cordova Facebook connect plugin fail on init!

and

Cordova Facebook connect plugin fail on auth.status!

If I click the login bouton, the dialog says:

Cordova Facebook connect plugin fail on login!Class not found

And the Eclipse console log is:

I tried to install this with the officiel Git readme and the
tutorial Add Facebook login to PhoneGap/Cordova Android app Easiest way.

When I compile the application, I don't get the error.

How do I fix this problem?


问:
How to make REST calls to Azure Pipelines from c#
From c# code, I want to call Azure Devops Pipeline Url and get the job/build ids for that url. And then get the result if the job/build succeds/fail.
How to make REST call from c# code my Azure pipelines (I have the pipeline url)?</p>

答:
There are 2 ways to do authentication for Azure DevOps API.

Private PAT

Environment Variable: System.AccessToken

For PAT you can review Shamrai Aleksander's code, if you want to call Azure DevOps API in your pipeline, you can conside use System.AccessToken.

Here is Powershell Script for your reference, the field of Authorization is different.

```<code>function Http-Request {
    param (
        [Parameter(Mandatory=$true)]
        [string] $Url,
        [Parameter(Mandatory=$false)]
        [string] $SystemToken
    )
    if([string]::IsNullOrEmpty($SystemToken)) {
        $pat = 'YOUR_PAT'
        $username = 'YOUR_USERNAME'
        $auth = '{0}:{1}' -f $username, $pat
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($auth)
        $encoded = [Convert]::ToBase64String($bytes)
        $auth = 'Basic ' + $encoded
    } else {
        $auth = 'Bearer ' + $SystemToken
    }
    $headers = @{
      'Content-Type' = 'application/json'
      'Authorization' = $auth
    }

    Write-Host -ForegroundColor Green 'Http Request:'$Url
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
    $response = Invoke-RestMethod -Uri $Url -Method Get -Headers $headers
    Write-Host ($reponse | Format-List | Out-String)
    return $response
}
</code>```

Body:
There are 2 ways to do authentication for Azure DevOps API.

Private PAT

Environment Variable: System.AccessToken

For PAT you can review Shamrai Aleksander's code, if you want to call Azure DevOps API in your pipeline, you can conside use System.AccessToken.

Here is Powershell Script for your reference, the field of Authorization is different.

function Http-Request {
    param (
        [Parameter(Mandatory=$true)]
        [string] $Url,
        [Parameter(Mandatory=$false)]
        [string] $SystemToken
    )
    if([string]::IsNullOrEmpty($SystemToken)) {
        $pat = 'YOUR_PAT'
        $username = 'YOUR_USERNAME'
        $auth = '{0}:{1}' -f $username, $pat
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($auth)
        $encoded = [Convert]::ToBase64String($bytes)
        $auth = 'Basic ' + $encoded
    } else {
        $auth = 'Bearer ' + $SystemToken
    }
    $headers = @{
      'Content-Type' = 'application/json'
      'Authorization' = $auth
    }

    Write-Host -ForegroundColor Green 'Http Request:'$Url
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
    $response = Invoke-RestMethod -Uri $Url -Method Get -Headers $headers
    Write-Host ($reponse | Format-List | Out-String)
    return $response
}


问:
What is the best practice for adding a token to an HTTP header in MSAL?
When I sign in, get a token silently:

```<code>            var accounts = await this.PublicClientApplication.GetAccountsAsync().ConfigureAwait(false);
            foreach (IAccount account in accounts)
            {
                var authenticationResult = await this.PublicClientApplication.AcquireTokenSilent(this.Scopes, account)
                    .ExecuteAsync(cancellationToken)
                    .ConfigureAwait(false);
                this.Account = authenticationResult.Account;
                return true;
            }
</code>```

Now that I have a token and I can add it to my HTTP headers. But I have a program that's running continuously, hours or days, many tasks.

So What's the best practice for managing the lifetime of the token?

Should I wait until I take an exception with the existing token and then try this function again? Or should I just trust the credential cache to manage the token lifetime for me by doing something like this before each invocation of an HttpClient call:

```<code>                // Get the cached credentials for the currently selected account.
                AuthenticationResult authenticationResult = await this.host.PublicClientApplication
                    .AcquireTokenSilent(this.host.Scopes, this.host.Account)
                    .ExecuteAsync(cancellationToken)
                    .ConfigureAwait(false);

                // Update the request header with the security token acquired from the authentication service.
                lock (this.headerLock)
                {
                    this.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
                }

                request.Content = stringContent;
                using (HttpResponseMessage response = await this.httpClient.SendAsync(request).ConfigureAwait(true))
                 {
                     // Report any errors.
                     if (!response.IsSuccessStatusCode)
                     {
                         this.logger.LogError($"{(int)response.StatusCode}: {response.ReasonPhrase}");
                      }
                  }
</code>```

答: This page from Microsoft seems to confirm the best pattern is the second one: grab a token before each HttpClient call.</p>

Body:
When I sign in, get a token silently:

            var accounts = await this.PublicClientApplication.GetAccountsAsync().ConfigureAwait(false);
            foreach (IAccount account in accounts)
            {
                var authenticationResult = await this.PublicClientApplication.AcquireTokenSilent(this.Scopes, account)
                    .ExecuteAsync(cancellationToken)
                    .ConfigureAwait(false);
                this.Account = authenticationResult.Account;
                return true;
            }

Now that I have a token and I can add it to my HTTP headers. But I have a program that's running continuously, hours or days, many tasks.

So What's the best practice for managing the lifetime of the token?

Should I wait until I take an exception with the existing token and then try this function again? Or should I just trust the credential cache to manage the token lifetime for me by doing something like this before each invocation of an HttpClient call:

                // Get the cached credentials for the currently selected account.
                AuthenticationResult authenticationResult = await this.host.PublicClientApplication
                    .AcquireTokenSilent(this.host.Scopes, this.host.Account)
                    .ExecuteAsync(cancellationToken)
                    .ConfigureAwait(false);

                // Update the request header with the security token acquired from the authentication service.
                lock (this.headerLock)
                {
                    this.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
                }

                request.Content = stringContent;
                using (HttpResponseMessage response = await this.httpClient.SendAsync(request).ConfigureAwait(true))
                 {
                     // Report any errors.
                     if (!response.IsSuccessStatusCode)
                     {
                         this.logger.LogError($"{(int)response.StatusCode}: {response.ReasonPhrase}");
                      }
                  }


问:
Fetch request must have an entity using @FetchRequest in SwiftUI
I am trying to use @FetchRequest to fetch all records from the SQLite database through CoreData. I have setup CoreData stack as shown below:

```<code>class CoreDataManager {

    private let persistentContainer: NSPersistentContainer
    static let shared = CoreDataManager()

    var context: NSManagedObjectContext {
        return persistentContainer.viewContext
    }

    private init() {
        persistentContainer = NSPersistentContainer(name: "FooModel")
        persistentContainer.loadPersistentStores { description, error in
            if let error = error {
                print("Unable to initialize Core Data \(error)")
            }
        }
    }

}

@main
struct FooAppApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView().environment(\.managedObjectContext, CoreDataManager.shared.context)
        }
    }
}
</code>```

When I try to access it is my ContentView as shown below:

```<code>struct ContentView: View {

    @FetchRequest(entity: MyList.entity(), sortDescriptors: []) var myLists: FetchedResults<MyList>

    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

I get the following error:

```<code>A fetch request must have an entity.'
terminating with uncaught exception of type NSException
</code>```

Am I missing something?

UPDATE: I removed the MyList.entity() part from the FetchRequest and now it works.

答:
Remove

```<code>entity: MyList.entity(),
</code>```

From the FetchRequest

Body:
I am trying to use @FetchRequest to fetch all records from the SQLite database through CoreData. I have setup CoreData stack as shown below:

class CoreDataManager {

    private let persistentContainer: NSPersistentContainer
    static let shared = CoreDataManager()

    var context: NSManagedObjectContext {
        return persistentContainer.viewContext
    }

    private init() {
        persistentContainer = NSPersistentContainer(name: "FooModel")
        persistentContainer.loadPersistentStores { description, error in
            if let error = error {
                print("Unable to initialize Core Data \(error)")
            }
        }
    }

}

@main
struct FooAppApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView().environment(\.managedObjectContext, CoreDataManager.shared.context)
        }
    }
}

When I try to access it is my ContentView as shown below:

struct ContentView: View {

    @FetchRequest(entity: MyList.entity(), sortDescriptors: []) var myLists: FetchedResults<MyList>

    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I get the following error:

A fetch request must have an entity.'
terminating with uncaught exception of type NSException

Am I missing something?

UPDATE: I removed the MyList.entity() part from the FetchRequest and now it works.

Body:
Remove

entity: MyList.entity(),

From the FetchRequest


问:
Hiding empty inputs by parent row in jquery
I have the following HTML:

```<code><table>
   <tr class="row">
        <td class="field">
            <input type="text" />
        </td>
        <td class="field">
            <input type="text" />
        </td>
        <td class="field">
            <input type="text" />
        </td>
   </tr>
   <tr>
   ...
   ...
   </tr>
</table>
</code>```

I want to be able to hide the
 with the class="row" but only when the input within the  with the class="field" is empty when the page loads.

I've tried this, but it doesn't work:

$('td.field:text[value=""]').parents('tr.row').hide();

However, for some reason, this DOES work:

$('td.field).parents('tr.row').hide();

(ie: it hides all of the rows with class="row")

Also, the following DOES work:

$('td.field:text[value=""]').val('test');

(ie: all empty inputs are populated with 'test' on page load)

I'm new to JQuery so I'm suspecting that I may have just misunderstood the way chaining works. can anyone give me any pointers? It semms like the two parts of what I am trying to do are correct when attempted separately, but don't work together as one.

答:
and why dont you go the oposite way - select the INPUT with empty value, and than go to its

parents().parents().hide()

first parents to get TD, the second one to get TR

Body:
I have the following HTML:

            <input type="text" />

            <input type="text" />

            <input type="text" />

   ...
   ...

I want to be able to hide the
 with the class="row" but only when the input within the  with the class="field" is empty when the page loads.

I've tried this, but it doesn't work:

$('td.field:text[value=""]').parents('tr.row').hide();

However, for some reason, this DOES work:

$('td.field).parents('tr.row').hide();

(ie: it hides all of the rows with class="row")

Also, the following DOES work:

$('td.field:text[value=""]').val('test');

(ie: all empty inputs are populated with 'test' on page load)

I'm new to JQuery so I'm suspecting that I may have just misunderstood the way chaining works. can anyone give me any pointers? It semms like the two parts of what I am trying to do are correct when attempted separately, but don't work together as one.


问:
Is there a way to do automation testing for a Flutter desktop application without image processing?
The current dilemma is clicking through a Flutter desktop application. We are able to click through the desktop application using image processing with PyAutoGui but this comes with a scalability limitation.

The ideal solution would be some sort of software that can click on elements by element ID rather than image recognition. Similar to how Selinum works on web applications.

Thanks, any guidance would be greatly appreciated :)
Jeff

答:
Did you consider flutter driver?

https://docs.flutter.dev/testing/integration-tests

https://docs.flutter.dev/cookbook/testing/integration/introduction

It will be like automation click and something else


问:
py.test import error "- 'config' not found."
While trying to add py.test functionality to a Flask API I ran into the following error message when calling py.test on my source directory

```<code>E               ImportStringError: import_string() failed for 'config'. Possible reasons are:
E
E               - missing __init__.py in a package;
E               - package or module path not included in sys.path;
E               - duplicated package or module name taking precedence in sys.path;
E               - missing module, class, function or variable;
E
E               Debugged import:
E
E               - 'config' not found.
E
E               Original exception:
E
E               ImportError: No module named config
</code>```

The issue seems to stem after I have instantiated my Flask app and try to import the config from config.py (line 5).

```<code>from flask import Flask

# Setup app
app = Flask(__name__)
app.config.from_object('config')

# Import views
from views import *

if __name__ == '__main__':
    app.run()
</code>```

Everything seems to work accordingly if I manually set the config variables instead of importing them. Has anyone encountered anything like this? I wasn't able to find anything helpful in the documentation.

答:
Just in case it help someone else, removing the empty __init__.py next to app.py and config.py has resolved my issue.

I was able to continue the usage of: app.config.from_object('config')

Body:
While trying to add py.test functionality to a Flask API I ran into the following error message when calling py.test on my source directory

E               ImportStringError: import_string() failed for 'config'. Possible reasons are:
E
E               - missing __init__.py in a package;
E               - package or module path not included in sys.path;
E               - duplicated package or module name taking precedence in sys.path;
E               - missing module, class, function or variable;
E
E               Debugged import:
E
E               - 'config' not found.
E
E               Original exception:
E
E               ImportError: No module named config

The issue seems to stem after I have instantiated my Flask app and try to import the config from config.py (line 5).

from flask import Flask

# Setup app
app = Flask(__name__)
app.config.from_object('config')

# Import views
from views import *

if __name__ == '__main__':
    app.run()

Everything seems to work accordingly if I manually set the config variables instead of importing them. Has anyone encountered anything like this? I wasn't able to find anything helpful in the documentation.


问:
Image not found using angular material
I get this error when trying to display an image:

http://localhost:4200/daily-process/src/WebUI/Angular/src/images/DailyProcessBlack.png 404 (Not Found)

I put the image in a mat-card and I can see the image when I navigate to the folder path but it doesn't show on the site:

```<code><mat-card class="example-card">
 <mat-card-header>
<div mat-card-avatar class="example-header-image"></div>
 </mat-card-header>
<img mat-card-image src="/daily-process/src/WebUI/Angular/src/images/DailyProcessBlack.png"
alt="Image">
</mat-card>
</code>```

angular.json

```<code> {
 "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
 "version": 1,
 "newProjectRoot": "projects",
 "projects": {
  "daily-process": {
  "projectType": "application",
  "schematics": {},
  "root": "",
  "sourceRoot": "src",
  "prefix": "app",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "outputPath": "dist/daily-process",
        "index": "src/index.html",
        "main": "src/main.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "tsconfig.app.json",
        "assets": [
          "src/favicon.ico",
          "src/assets"
        ],
        // "styles": [
        //   "src/styles.css"
        // ],
        "scripts": []
      },
      "configurations": {
        "production": {
          "budgets": [
            {
              "type": "initial",
              "maximumWarning": "2mb",
              "maximumError": "5mb"
            },
            {
              "type": "anyComponentStyle",
              "maximumWarning": "6kb",
              "maximumError": "10kb"
            }
          ],
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "outputHashing": "all"
        },
        "development": {
          "buildOptimizer": false,
          "optimization": false,
          "vendorChunk": true,
          "extractLicenses": false,
          "sourceMap": true,
          "namedChunks": true
        }
      },
      "defaultConfiguration": "production"
    },
    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "configurations": {
        "production": {
          "browserTarget": "daily-process:build:production"
        },
        "development": {
          "browserTarget": "daily-process:build:development"
        }
      },
      "defaultConfiguration": "development"
    },
    "extract-i18n": {
      "builder": "@angular-devkit/build-angular:extract-i18n",
      "options": {
        "browserTarget": "daily-process:build"
      }
    },
    "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "tsconfig.spec.json",
        "karmaConfig": "karma.conf.js",
        "assets": [
          "src/favicon.ico",
          "src/assets"
        ],
        // "styles": [
        //   "src/styles.css"
        // ],
         "scripts": []
        }
      }
    }
  }
 },
 "defaultProject": "daily-process"
}
</code>```

Image of folder structure

Can someone please provide a reason why and a solution to what I need to do to get this to work properly.

答:
In angular.json there is an array called assets

These are the default values

"assets": ["src/favicon.ico", "src/assets"],
```

This is where angular will host files / images. You can put your assets in src/assets, or you can add your own paths.

There are two copies of the assets array - one for the build command and one for the test command, so make sure to keep them synchronized.

Title: Image not found using angular material

Body:
I get this error when trying to display an image:

http://localhost:4200/daily-process/src/WebUI/Angular/src/images/DailyProcessBlack.png 404 (Not Found)

I put the image in a mat-card and I can see the image when I navigate to the folder path but it doesn't show on the site:

<mat-card class="example-card">
 <mat-card-header>

 </mat-card-header>

</mat-card>

angular.json

 {
 "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
 "version": 1,
 "newProjectRoot": "projects",
 "projects": {
  "daily-process": {
  "projectType": "application",
  "schematics": {},
  "root": "",
  "sourceRoot": "src",
  "prefix": "app",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "outputPath": "dist/daily-process",
        "index": "src/index.html",
        "main": "src/main.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "tsconfig.app.json",
        "assets": [
          "src/favicon.ico",
          "src/assets"
        ],
        // "styles": [
        //   "src/styles.css"
        // ],
        "scripts": []
      },
      "configurations": {
        "production": {
          "budgets": [
            {
              "type": "initial",
              "maximumWarning": "2mb",
              "maximumError": "5mb"
            },
            {
              "type": "anyComponentStyle",
              "maximumWarning": "6kb",
              "maximumError": "10kb"
            }
          ],
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "outputHashing": "all"
        },
        "development": {
          "buildOptimizer": false,
          "optimization": false,
          "vendorChunk": true,
          "extractLicenses": false,
          "sourceMap": true,
          "namedChunks": true
        }
      },
      "defaultConfiguration": "production"
    },
    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "configurations": {
        "production": {
          "browserTarget": "daily-process:build:production"
        },
        "development": {
          "browserTarget": "daily-process:build:development"
        }
      },
      "defaultConfiguration": "development"
    },
    "extract-i18n": {
      "builder": "@angular-devkit/build-angular:extract-i18n",
      "options": {
        "browserTarget": "daily-process:build"
      }
    },
    "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "tsconfig.spec.json",
        "karmaConfig": "karma.conf.js",
        "assets": [
          "src/favicon.ico",
          "src/assets"
        ],
        // "styles": [
        //   "src/styles.css"
        // ],
         "scripts": []
        }
      }
    }
  }
 },
 "defaultProject": "daily-process"
}

Image of folder structure

Can someone please provide a reason why and a solution to what I need to do to get this to work properly.

Body:
In angular.json there is an array called assets

These are the default values

"assets": ["src/favicon.ico", "src/assets"],

This is where angular will host files / images. You can put your assets in src/assets, or you can add your own paths.

There are two copies of the assets array - one for the build command and one for the test command, so make sure to keep them synchronized.


问:
ImportError: No module named MySQLdb
I am referring the following tutorial to make a login page for my web application.
http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out--net-29982

I am having issue with the database.
I am getting an

```<code>ImportError: No module named MySQLdb
</code>```

when I execute

```<code>http://127.0.0.1:5000/testdb
</code>```

I have tried all possible ways to install python mysql, the one mentioned in the tutorial, easy_install, sudo apt-get install.

I have installed mysql in my virtual env. My directory structure is just the same as whats explained in the tutorial. The module is sucessfully installed in my system and still I am getting this error.

Please help. What could be causing this.

答:
for Ubuntu 20.04 with python3

```<code> sudo apt-get install python3-mysqldb
</code>```

by default, this work for me

Create a sqlite engine instance

engine = create_engine('mysql://username:password@your_host/your_dbname')

OR

```<code>pip install pymysql
</code>```

Create a sqlite engine instance

create_engine('mysql://...

Title: ImportError: No module named MySQLdb

Body:
I am referring the following tutorial to make a login page for my web application.
http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out--net-29982

I am having issue with the database.
I am getting an

ImportError: No module named MySQLdb

when I execute

http://127.0.0.1:5000/testdb

I have tried all possible ways to install python mysql, the one mentioned in the tutorial, easy_install, sudo apt-get install.

I have installed mysql in my virtual env. My directory structure is just the same as whats explained in the tutorial. The module is sucessfully installed in my system and still I am getting this error.

Please help. What could be causing this.

Body:
for Ubuntu 20.04 with python3

 sudo apt-get install python3-mysqldb

by default, this work for me

Create a sqlite engine instance

engine = create_engine('mysql://username:password@your_host/your_dbname')

OR

pip install pymysql

Create a sqlite engine instance

create_engine('mysql://...


问:
Swift Command Line Tool -> Select with arrow keys and spacebar
I'm building command line tools with swift and I'd like to make them more interactive to provide a better user experience.

I was wondering if it's possible to build a select menu for a command line tool similar to the one used in the firebase cli or the angular cli in swift.
I'm using the swift argument parser at the moment and it would be very nice if the user could select from different options in a menu via the arrow keys and selecting with the space bar.

Firebase CLI option selection with firebase init

答:
As far as I know, this is not possible with swift-argument-parser at this monent. This was actually in the Summer of Code idea list for potential projects.

Swift ArgumentParser: Interactive mode

ArgumentParser provides a straightforward way to declare command-line interfaces in Swift, with the dual goals of making it (1) fast and easy to create (2) high-quality, user-friendly CLI tools. For this project, we would design and implement an interactive mode for tools built using ArgumentParser that prompts for any required arguments not given in the initial command. This work would need to allow partial initialization of types, and could include features like validation and auto-completion for user input.

https://www.swift.org/gsoc2021/

So I believe it might be implemented in the future.


问:
Jetpack Compose Textfield Alignment
I'm new to jetpack compose. I want to start typing from TextField's centervertically-start
position but I can't put "Example" to center
vertically-start position.

```<code>Row(
    modifier = Modifier
        .fillMaxWidth()
        .height(50.dp)
        .shadow(5.dp)
        .background(Color.Yellow),

) {

    BasicTextField(
        value = text,
        onValueChange = {onvalueChange(it)},
        modifier = Modifier.weight(10f).background(Color.Blue).fillMaxSize(),
        singleLine = true,
        textStyle = LocalTextStyle.current.copy(
            textAlign = TextAlign.Center
        )

    )
    Image(painter = painterResource(id = R.drawable.ic_baseline_search_24),
        contentDescription = "Search",
        modifier = Modifier.weight(2f).fillMaxSize()

    )
</code>```

This is my code

And this is what I want to do.

答:
Use background box to control, please try:</p>
```<code>Row(
    modifier = Modifier
    .fillMaxWidth()
    .height(50.dp)
    .shadow(5.dp)
    .background(Color.Yellow),
    ) {
        Box(Modifier.weight(10f).background(Color.Blue).fillMaxSize(),contentAlignment = CenterStart){
            BasicTextField(
                value = text,
                onValueChange = { onvalueChange(it) },
                modifier = Modifier.wrapContentHeight(
                    Alignment.CenterVertically),
                singleLine = true,
                textStyle = LocalTextStyle.current.copy(
                    textAlign = TextAlign.Start
                )
            )
        }
        Image(
            Icons.Filled.Search,
            contentDescription = "Search",
            modifier = Modifier.weight(2f).fillMaxSize()

        )
    }
</code>```

Title: Jetpack Compose Textfield Alignment

Body:
I'm new to jetpack compose. I want to start typing from TextField's centervertically-start
position but I can't put "Example" to center
vertically-start position.

Row(
    modifier = Modifier
        .fillMaxWidth()
        .height(50.dp)
        .shadow(5.dp)
        .background(Color.Yellow),

) {

    BasicTextField(
        value = text,
        onValueChange = {onvalueChange(it)},
        modifier = Modifier.weight(10f).background(Color.Blue).fillMaxSize(),
        singleLine = true,
        textStyle = LocalTextStyle.current.copy(
            textAlign = TextAlign.Center
        )

    )
    Image(painter = painterResource(id = R.drawable.ic_baseline_search_24),
        contentDescription = "Search",
        modifier = Modifier.weight(2f).fillMaxSize()

    )

This is my code

And this is what I want to do.

Body:
Use background box to control, please try:

Row(
    modifier = Modifier
    .fillMaxWidth()
    .height(50.dp)
    .shadow(5.dp)
    .background(Color.Yellow),
    ) {
        Box(Modifier.weight(10f).background(Color.Blue).fillMaxSize(),contentAlignment = CenterStart){
            BasicTextField(
                value = text,
                onValueChange = { onvalueChange(it) },
                modifier = Modifier.wrapContentHeight(
                    Alignment.CenterVertically),
                singleLine = true,
                textStyle = LocalTextStyle.current.copy(
                    textAlign = TextAlign.Start
                )
            )
        }
        Image(
            Icons.Filled.Search,
            contentDescription = "Search",
            modifier = Modifier.weight(2f).fillMaxSize()

        )
    }


问:
Convert columns of R dataframe to JSON
I have this dataframe:

```<code>df <- data.frame(
  option_label_1 = c("thickness", "strength", "color"),
  option_value_1 = c("0.5 in", "2 lb" , "red"),
  option_label_2 = c("size", "color", "thickness"),
  option_value_2 = c("0.5 Inches x 7200 Feet", "blue" , "1 in"),
  option_label_3 = c("stretch", NA, NA),
  option_value_3 = c("wide", NA , NA)
  )
</code>```
```<code>  option_label_1 option_value_1 option_label_2         option_value_2 option_label_3 option_value_3
1      thickness         0.5 in           size 0.5 Inches x 7200 Feet        stretch           wide
2       strength           2 lb          color                   blue           <NA>           <NA>
3          color            red      thickness                   1 in           <NA>           <NA>
</code>```

I want this data frame:

```<code>  option_label_1 option_value_1 option_label_2         option_value_2 option_label_3 option_value_3
1      thickness         0.5 in           size 0.5 Inches x 7200 Feet        stretch           wide
2       strength           2 lb          color                   blue           <NA>           <NA>
3          color            red      thickness                   1 in           <NA>           <NA>
                                                                       json
1 {"thickness":"0.5 in","size":"0.5 Inches x 7200 Feet","stretch":"wide"}
2                                       {"strength":"2 lb","color":"blue"}
3                                        {"color":"red","thickness":"1 in"}
</code>```

Essentially I want a JSON column added to the original df built off of the original columns using the option labels and option values. Please note I do not want a solution that converts the whole dataframe to JSON using toJSON. I have a much larger dataframe with other fields I do not want in JSON. I just want the option_labels and their respective option_values to be in JSON.

I have tried using list and paste functions nested in toJSON, but the "option_labels" are static and don't change accordingly in the resulting JSON column.

Thanks for your help!

答:
Here's an option using dplyr and tidyr -

```<code>library(dplyr)
library(tidyr)

#Add a row number column to keep track of each row
#Useful for joining afterwards.
df1 <- df %>% mutate(rownum = row_number())

df1 <- df1 %>%
  #Get the data in long format so that we have
  #option_label and option_value as 2 separate columns
  #Drop NA values.
  pivot_longer(cols = -rownum,
               names_to = '.value',
               names_pattern = '(option_\\w+)_',
               values_drop_na = TRUE) %>%
  #Create a string with the pattern "column_name" : "column_value"
  mutate(json = sprintf('"%s" : "%s"', option_label, option_value)) %>%
  #for each row
  group_by(rownum) %>%
  #Combine the json value in a comma separated string.
  #Also add "{..}" surrounding them.
  summarise(json = sprintf('{%s}', toString(json))) %>%
  #Join to get original dataframe back with a new column
  inner_join(df1, by = 'rownum')

#View the output
cat(df1$json, sep = "\n")

#{"thickness" : "0.5 in", "size" : "0.5 Inches x 7200 Feet", "stretch" : "wide"}
#{"strength" : "2 lb", "color" : "blue"}
#{"color" : "red", "thickness" : "1 in"}
</code>```

Title: Convert columns of R dataframe to JSON

Body:
I have this dataframe:

df <- data.frame(
  option_label_1 = c("thickness", "strength", "color"),
  option_value_1 = c("0.5 in", "2 lb" , "red"),
  option_label_2 = c("size", "color", "thickness"),
  option_value_2 = c("0.5 Inches x 7200 Feet", "blue" , "1 in"),
  option_label_3 = c("stretch", NA, NA),
  option_value_3 = c("wide", NA , NA)
  )

  option_label_1 option_value_1 option_label_2         option_value_2 option_label_3 option_value_3
1      thickness         0.5 in           size 0.5 Inches x 7200 Feet        stretch           wide
2       strength           2 lb          color                   blue           <NA>           <NA>
3          color            red      thickness                   1 in           <NA>           <NA>

I want this data frame:

  option_label_1 option_value_1 option_label_2         option_value_2 option_label_3 option_value_3
1      thickness         0.5 in           size 0.5 Inches x 7200 Feet        stretch           wide
2       strength           2 lb          color                   blue           <NA>           <NA>
3          color            red      thickness                   1 in           <NA>           <NA>
                                                                       json
1 {"thickness":"0.5 in","size":"0.5 Inches x 7200 Feet","stretch":"wide"}
2                                       {"strength":"2 lb","color":"blue"}
3                                        {"color":"red","thickness":"1 in"}

Essentially I want a JSON column added to the original df built off of the original columns using the option labels and option values. Please note I do not want a solution that converts the whole dataframe to JSON using toJSON. I have a much larger dataframe with other fields I do not want in JSON. I just want the option_labels and their respective option_values to be in JSON.

I have tried using list and paste functions nested in toJSON, but the "option_labels" are static and don't change accordingly in the resulting JSON column.

Thanks for your help!

Body:
Here's an option using dplyr and tidyr -

library(dplyr)
library(tidyr)

#Add a row number column to keep track of each row
#Useful for joining afterwards.
df1 <- df %>% mutate(rownum = row_number())

df1 <- df1 %>%
  #Get the data in long format so that we have
  #option_label and option_value as 2 separate columns
  #Drop NA values.
  pivot_longer(cols = -rownum,
               names_to = '.value',
               names_pattern = '(option_\\w+)_',
               values_drop_na = TRUE) %>%
  #Create a string with the pattern "column_name" : "column_value"
  mutate(json = sprintf('"%s" : "%s"', option_label, option_value)) %>%
  #for each row
  group_by(rownum) %>%
  #Combine the json value in a comma separated string.
  #Also add "{..}" surrounding them.
  summarise(json = sprintf('{%s}', toString(json))) %>%
  #Join to get original dataframe back with a new column
  inner_join(df1, by = 'rownum')

#View the output
cat(df1$json, sep = "\n")

#{"thickness" : "0.5 in", "size" : "0.5 Inches x 7200 Feet", "stretch" : "wide"}
#{"strength" : "2 lb", "color" : "blue"}
#{"color" : "red", "thickness" : "1 in"}


问:
Upgrading from PHP7.4 => PHP8, is it possible to ignore certain errors
We have a huge codebase where we ignored the notice from php7 when accessing undefined variables or array-keys.
For example

```<code>$somethingThatMayNotExist = $_REQUEST['somethingThatMayNotExist']
</code>```

PHP8 now throws an Error. I know that we should always check if the key exists, or if the variable is defined. But the codebase is so big and we have poor unit-test coverage that I would rather switch to php8 and have these errors handled as notices (And setting the value to null).
Is this with somekind of custom error-handler possible? If so, how to do that?

答:
I used this regex find and replace:

$_REQUEST[(.+)]

($_REQUEST[$1] ?? "")

Without the outer parenthesis in the replace, the html got messed up in places.

I used Regexxer from the Linux Mint Software Manager to replace in the multiple files. The regex find and replace in Notepadqq doesn't work properly.

Body:
We have a huge codebase where we ignored the notice from php7 when accessing undefined variables or array-keys.
For example

$somethingThatMayNotExist = $_REQUEST['somethingThatMayNotExist']

PHP8 now throws an Error. I know that we should always check if the key exists, or if the variable is defined. But the codebase is so big and we have poor unit-test coverage that I would rather switch to php8 and have these errors handled as notices (And setting the value to null).
Is this with somekind of custom error-handler possible? If so, how to do that?


问:
Regex for specific numbers and special characters
I want to extract the values 9.6%,2021,4th from the below input string and tried with different solutions but not displaying output as expected.
input string: Gross Domestic Product decreased by 5.9% in volume in the fourth quarter 2021 and by 9.6% in 2021 - 4th Quarter 2021

```<code>var pattren = "^-?\\d*(\\.\\d+)?$";
var result  = Regex.Match(s, pattren);
</code>```

答:
A solution I came up, might not be optimal though, as it takes extra step I think.

Get the wanted part by (\d+\.*\d*%)\s*in\s*(\d{4})\s*-\s*(1st|2nd|3rd|4th)

Since there's a nuance in your question, there're 2 possibilities as the next step:

Replace() in and - to , to get string "9.6%,2021,4th"

Group 1,2,3 of the Match will be "9.6%", "2021" and "4th".

Problem is, dealing with text always has surprises waiting for you. Test for more cases and adjust the method to deal with exceptional inputs.

For reference:

String.Replace()

String.Split()

Match.Groups

Body:
I want to extract the values 9.6%,2021,4th from the below input string and tried with different solutions but not displaying output as expected.
input string: Gross Domestic Product decreased by 5.9% in volume in the fourth quarter 2021 and by 9.6% in 2021 - 4th Quarter 2021

var pattren = "^-?\\d*(\\.\\d+)?$";
var result  = Regex.Match(s, pattren);


问:
Why is item not adding to dictionary in Python
This code

```<code>def process_hero_box_annotations(post_to_boxes):
  for box in post_to_boxes:
    k = box
    a = post_to_boxes.get(box)
    new = ()
    post_to_processed_box = {}
    if len(a) != 0:
      x0 = a[0][0]
      y0 = a[0][1]
      x1 = a[0][2]
      y1 = a[0][3]
      if len(a) == 2:
        if a[0][0] < a[1][0]:
          x0 = a[0][0]
        else:
          x0 = a[1][0]
        if a[0][1] < a[1][1]:
          y0 = a[0][1]
        else:
          y0 = a[1][1]
        if a[0][2] > a[1][2]:
          x1 = a[0][2]
        else:
          x1 = a[1][2]
        if a[0][3] > a[1][3]:
          y1 = a[0][3]
        else:
          y1 = a[1][3]
      new = (x0, y0, x1, y1)
      print(new)
      post_to_processed_box[k] = new
  return post_to_processed_box
</code>```

gives me

```<code>{
    384121: (10, 20, 100, 300)
}
</code>```

when I want

```<code>{
    149321: (14, 10, 503, 545),
    384121: (10, 20, 100, 300)
}
</code>```

Why is one item not adding?

答:
Move the following statement @ line 6 outside of the loop

post_to_processed_box = {}

So it would look more similar to the following

```<code>def process_hero_box_annotations(post_to_boxes):
  post_to_processed_box = {}
  for box in post_to_boxes:
    k = box
    a = post_to_boxes.get(box)
    new = ()
    if len(a) != 0:
      x0 = a[0][0]
      y0 = a[0][1]
      x1 = a[0][2]
      y1 = a[0][3]
      if len(a) == 2:
        if a[0][0] < a[1][0]:
          x0 = a[0][0]
        else:
          x0 = a[1][0]
        if a[0][1] < a[1][1]:
          y0 = a[0][1]
        else:
          y0 = a[1][1]
        if a[0][2] > a[1][2]:
          x1 = a[0][2]
        else:
          x1 = a[1][2]
        if a[0][3] > a[1][3]:
          y1 = a[0][3]
        else:
          y1 = a[1][3]
      new = (x0, y0, x1, y1)
      print(new)
      post_to_processed_box[k] = new
  return post_to_processed_box
</code>```

with your current code you are setting post_to_processed_box to an empty dictionary each iteration of the loop.

Body:
This code

def process_hero_box_annotations(post_to_boxes):
  for box in post_to_boxes:
    k = box
    a = post_to_boxes.get(box)
    new = ()
    post_to_processed_box = {}
    if len(a) != 0:
      x0 = a[0][0]
      y0 = a[0][1]
      x1 = a[0][2]
      y1 = a[0][3]
      if len(a) == 2:
        if a[0][0] < a[1][0]:
          x0 = a[0][0]
        else:
          x0 = a[1][0]
        if a[0][1]  a[1][2]:
          x1 = a[0][2]
        else:
          x1 = a[1][2]
        if a[0][3] > a[1][3]:
          y1 = a[0][3]
        else:
          y1 = a[1][3]
      new = (x0, y0, x1, y1)
      print(new)
      post_to_processed_box[k] = new
  return post_to_processed_box

gives me

{
    384121: (10, 20, 100, 300)
}

when I want

{
    149321: (14, 10, 503, 545),
    384121: (10, 20, 100, 300)
}

Why is one item not adding?

Body:
Move the following statement @ line 6 outside of the loop

post_to_processed_box = {}

So it would look more similar to the following

def process_hero_box_annotations(post_to_boxes):
  post_to_processed_box = {}
  for box in post_to_boxes:
    k = box
    a = post_to_boxes.get(box)
    new = ()
    if len(a) != 0:
      x0 = a[0][0]
      y0 = a[0][1]
      x1 = a[0][2]
      y1 = a[0][3]
      if len(a) == 2:
        if a[0][0] < a[1][0]:
          x0 = a[0][0]
        else:
          x0 = a[1][0]
        if a[0][1] < a[1][1]:
          y0 = a[0][1]
        else:
          y0 = a[1][1]
        if a[0][2] > a[1][2]:
          x1 = a[0][2]
        else:
          x1 = a[1][2]
        if a[0][3] > a[1][3]:
          y1 = a[0][3]
        else:
          y1 = a[1][3]
      new = (x0, y0, x1, y1)
      print(new)
      post_to_processed_box[k] = new
  return post_to_processed_box

with your current code you are setting post_to_processed_box to an empty dictionary each iteration of the loop.


问:
Different SubGrids depend on Main Grid's Column Value in jqGrid
I faced a critical problem with jqGrid today. Let's explain my problem first.

I have a main grid which contains the following columns:

```<code>Scholarship Name .................................. Student Type
-----------------------------------------------------------------
Full Free Studentship ............................. Poor
Sir Alfred Nobel Scholarship ...................... Meritorious
Taj Uddin Memorial Scholarship .................... Individual
</code>```

Now I need a sub-grid of this main grid. Student Type is a select type column. When user choose Poor for the Student Type column and click on sub-grid icon then the following sub-grid will be shown:

```<code>Guardian Income Range Start Value ....................... Range End Value
--------------------------------------------------------------------------
0 ....................................................... 5000
5001 .................................................... 10000
</code>```

When user choose Meritorious then a different sub-grid will be shown which is as follows:

```<code>Merit Start .................. Merit End
----------------------------------------
1 ............................ 7
</code>```

And Individual shows the following:

```<code>Student ID
----------
115588
225577
336699
</code>```

My Question:

Is it possible in jqGrid or any other simple way to implement this.

Thanks in advance.

答:
As far I know, it is not possible in jqGrid. You have to use same sub-grid for a single Grid. Thanks for the nice question.

Oh... If it is possible, then let us inform the process.

Body:
I faced a critical problem with jqGrid today. Let's explain my problem first.

I have a main grid which contains the following columns:

Scholarship Name .................................. Student Type
-----------------------------------------------------------------
Full Free Studentship ............................. Poor
Sir Alfred Nobel Scholarship ...................... Meritorious
Taj Uddin Memorial Scholarship .................... Individual

Now I need a sub-grid of this main grid. Student Type is a select type column. When user choose Poor for the Student Type column and click on sub-grid icon then the following sub-grid will be shown:

Guardian Income Range Start Value ....................... Range End Value
--------------------------------------------------------------------------
0 ....................................................... 5000
5001 .................................................... 10000

When user choose Meritorious then a different sub-grid will be shown which is as follows:

Merit Start .................. Merit End
----------------------------------------
1 ............................ 7

And Individual shows the following:

Student ID
----------
115588
225577
336699

My Question:

Is it possible in jqGrid or any other simple way to implement this.

Thanks in advance.


问:
When creating stored procedure in Snowflake is there a way to return same output as a query, executed within it?
I created a stored procedure that sets the certain variable value and executes merge using this variable. Currently, it just returns a hardcoded message "Successfully executed.".
Is it possible to return the same result as the original merge query returns, like

number of rows inserted

number of rows updated

?

```<code>    CREATE OR REPLACE PROCEDURE ALERTS_MERGE_PROCEDURE ()
RETURNS STRING NOT NULL
LANGUAGE JAVASCRIPT
AS
    $$
    var sql_command = '
    MERGE INTO tablename
..
WHEN MATCHED THEN
UPDATE SET ...
WHEN NOT MATCHED THEN
INSERT ...
);
    '
    snowflake.execute(
        {
        sqlText: sql_command
        });
    return "Successfully executed.";
    $$;
</code>```

答:
You can iterate over the columns of the first row of the returned object from the execution:

create or replace temp table tablename as
select 1::int  id, 'a'::string tx;

create or replace temp table tablesource as
select 1::int  id, 'b'::string tx
union select 2, 'c';

CREATE OR REPLACE PROCEDURE ALERTS_MERGE_PROCEDURE ()
RETURNS STRING NOT NULL
LANGUAGE JAVASCRIPT
AS
$$
    var sql_command = `
    merge into tablename a
    using tablesource b
    on a.id = b.id
    when matched then update set tx=b.tx
    when not matched then insert (id, tx) values (b.id, b.tx);
    `;
    var x = snowflake.execute({sqlText: sql_command});
    x.next();
    var result = '';
    for (i=1; i<=x.getColumnCount(); i++) {
        result += x.getColumnName(i) + ': ' + x.getColumnValue(i) + '\n';
    }
    return result;
$$;

call alerts_merge_procedure();
```
<p>Returns:</p>
```number of rows inserted: 1
number of rows updated: 1
```

Body:
I created a stored procedure that sets the certain variable value and executes merge using this variable. Currently, it just returns a hardcoded message "Successfully executed.".
Is it possible to return the same result as the original merge query returns, like

number of rows inserted

number of rows updated

?

    CREATE OR REPLACE PROCEDURE ALERTS_MERGE_PROCEDURE ()
RETURNS STRING NOT NULL
LANGUAGE JAVASCRIPT
AS
    $$
    var sql_command = '
    MERGE INTO tablename
..
WHEN MATCHED THEN
UPDATE SET ...
WHEN NOT MATCHED THEN
INSERT ...
);
    '
    snowflake.execute(
        {
        sqlText: sql_command
        });
    return "Successfully executed.";
    $$;

Body:
You can iterate over the columns of the first row of the returned object from the execution:

create or replace temp table tablename as
select 1::int  id, 'a'::string tx;

create or replace temp table tablesource as
select 1::int  id, 'b'::string tx
union select 2, 'c';

CREATE OR REPLACE PROCEDURE ALERTS_MERGE_PROCEDURE ()
RETURNS STRING NOT NULL
LANGUAGE JAVASCRIPT
AS
$$
    var sql_command = `
    merge into tablename a
    using tablesource b
    on a.id = b.id
    when matched then update set tx=b.tx
    when not matched then insert (id, tx) values (b.id, b.tx);
    `;
    var x = snowflake.execute({sqlText: sql_command});
    x.next();
    var result = '';
    for (i=1; i<=x.getColumnCount(); i++) {
        result += x.getColumnName(i) + ': ' + x.getColumnValue(i) + '\n';
    }
    return result;
$$;

call alerts_merge_procedure();

Returns:

number of rows inserted: 1
number of rows updated: 1