问:
User exists but not able to authenticate using simpleJWT and Django Admin
When trying to authenticate a user created through a view in DRF Browsable API, I get

No active account found with the given credentials

The view:

```<code>class MyUserCreate(APIView):

    def post(self, request, format='json'):
        serializer = MyUserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

The serializer:

```<code>class MyUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
            required=True,
            validators=[UniqueValidator(queryset=MyUser.objects.all())],
            min_length=5,
            max_length=20
            ),
    password = serializers.CharField(
            required=True,
            max_length=256
            )

    class Meta:
        model = MyUser
        fields = ('username', 'password')

    def create(self, validated_data):
        password = make_password(validated_data['password'])
        user = MyUser.objects.create_user(validated_data['username'], password)
        return user
</code>```

The password is being hashed. At this stage, went on to the admin page and tested to login there too with the created account and got

Made sure the custom user model had is_active, is_superuser and is_staff and checked if that would fix the issue but it didn't.

```<code>class MyUserManager(BaseUserManager):
    def create_user(self, username, password, **extra_fields):
        user = self.model(
            username=username
        )
        user.is_staff=True
        user.is_active=True
        user.is_superuser=True
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(username, password, **extra_fields)

class MyUser(AbstractBaseUser):
    objects = MyUserManager()
    class Meta:
        # managed = False
        db_table = 'user_entity'

    user_id = models.AutoField(primary_key=True, db_column='userId')
    username = models.CharField(db_column='username', unique=True, max_length=20)
    password = models.CharField(db_column='userPassword', max_length=256)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=True)

    USERNAME_FIELD = 'username'

    def __str__(self):
        return str(self.user_id) + " (%s)" % str(self.username)

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True
</code>```

Then, tried to create the user using python manage.py createsuperuser... doing so then I'm able to both login in the admin pannel and authenticate that user with the Token Obtain Pair view shown initially.

答:
First of all. Thank you for providing all the details. It is always easier to debug. Coming to the issue, the problem is that you are using make_password explicitly.

If you would look through the Django's set_password documentation, you'd find that it takes care of hashing.

What you are doing is, first you are hashing your password, and providing it as a raw value to set_password method via create_user. The set_password would assume that as a raw value and would hash it again. Hence, your original password is not used at all.

You can just remove the use of make_password and instead change your serializer's create method to

```<code>class MyUserSerializer(serializers.ModelSerializer):

    ...

    def create(self, validated_data):
        user = MyUser.objects.create_user(validated_data['username'], validated_data["password"])
        return user

</code>```

This should resolve your query. I hope it helps! :)

Body:
When trying to authenticate a user created through a view in DRF Browsable API, I get

No active account found with the given credentials

The view:

class MyUserCreate(APIView):

    def post(self, request, format='json'):
        serializer = MyUserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The serializer:

class MyUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
            required=True,
            validators=[UniqueValidator(queryset=MyUser.objects.all())],
            min_length=5,
            max_length=20
            ),
    password = serializers.CharField(
            required=True,
            max_length=256
            )

    class Meta:
        model = MyUser
        fields = ('username', 'password')

    def create(self, validated_data):
        password = make_password(validated_data['password'])
        user = MyUser.objects.create_user(validated_data['username'], password)
        return user

The password is being hashed. At this stage, went on to the admin page and tested to login there too with the created account and got

Made sure the custom user model had is_active, is_superuser and is_staff and checked if that would fix the issue but it didn't.

class MyUserManager(BaseUserManager):
    def create_user(self, username, password, **extra_fields):
        user = self.model(
            username=username
        )
        user.is_staff=True
        user.is_active=True
        user.is_superuser=True
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(username, password, **extra_fields)

class MyUser(AbstractBaseUser):
    objects = MyUserManager()
    class Meta:
        # managed = False
        db_table = 'user_entity'

    user_id = models.AutoField(primary_key=True, db_column='userId')
    username = models.CharField(db_column='username', unique=True, max_length=20)
    password = models.CharField(db_column='userPassword', max_length=256)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=True)

    USERNAME_FIELD = 'username'

    def __str__(self):
        return str(self.user_id) + " (%s)" % str(self.username)

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

Then, tried to create the user using python manage.py createsuperuser... doing so then I'm able to both login in the admin pannel and authenticate that user with the Token Obtain Pair view shown initially.

Body:
First of all. Thank you for providing all the details. It is always easier to debug. Coming to the issue, the problem is that you are using make_password explicitly.

If you would look through the Django's set_password documentation, you'd find that it takes care of hashing.

What you are doing is, first you are hashing your password, and providing it as a raw value to set_password method via create_user. The set_password would assume that as a raw value and would hash it again. Hence, your original password is not used at all.

You can just remove the use of make_password and instead change your serializer's create method to

class MyUserSerializer(serializers.ModelSerializer):

    ...

    def create(self, validated_data):
        user = MyUser.objects.create_user(validated_data['username'], validated_data["password"])
        return user

This should resolve your query. I hope it helps! :)


来源: stackexchange

问:
Variable is not assigned C# Unity
i have a problem with a variable:

```<code>private ScriptCorredor objetivo = null;
public List<ScriptCorredor> corredores2;
</code>```

I'm adding a series of ScriptCorridor to the list

I edit and add the full Enter method

```<code>public void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.tag == "enemigo")
    {
        corredores2.Add(collision.GetComponent<ScriptCorredor>());
        if (objetivo=null)
        {
            objetivo = corredores2.ElementAt(0);
        }
    }
}
</code>```

then i try asign the first objeto in the objetivo variable with:

```<code>objetivo = corredores2.ElementAt(0);
</code>```

but cannot be assigned, when I read the objetivo variable, it is always empty.

any idea what I'm failing at?

答:
You need to check (and maybe provide to this question post) your OnCollisionEnter() code and check that the object you collide with has the ScriptCorredor component attached. Also I think you should not access the component in the collision object directly, but through the collision.gameObject.
For example:

```<code>if (collision.gameObject.name == "MyGameObjectName")
{
    //If the GameObject's name matches the one you suggest, output this
    message in the console
    Debug.Log("Do something here");
}
</code>```

So I would suggest to try:

```<code>collision.gameObject.GetComponent<ScriptCorredor>()
</code>```

You can check:

https://docs.unity3d.com/ScriptReference/Collision-gameObject.html

Ánimo Ivan ;). Hope that helps

Edit: Full method with my suggestion:

```<code>public void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "enemigo")
    {
        corredores2.Add(collision.gameObject.GetComponent<ScriptCorredor>());
        if (objetivo == null)
        {
            objetivo = corredores2[0];
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Variable is not assigned C# Unity

Body:
i have a problem with a variable:

private ScriptCorredor objetivo = null;
public List

Body:
You need to check (and maybe provide to this question post) your OnCollisionEnter() code and check that the object you collide with has the ScriptCorredor component attached. Also I think you should not access the component in the collision object directly, but through the collision.gameObject.
For example:

if (collision.gameObject.name == "MyGameObjectName")
{
    //If the GameObject's name matches the one you suggest, output this
    message in the console
    Debug.Log("Do something here");
}

So I would suggest to try:

collision.gameObject.GetComponent<ScriptCorredor>()

You can check:

https://docs.unity3d.com/ScriptReference/Collision-gameObject.html

Ánimo Ivan ;). Hope that helps

Edit: Full method with my suggestion:

public void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "enemigo")
    {
        corredores2.Add(collision.gameObject.GetComponent<ScriptCorredor>());
        if (objetivo == null)
        {
            objetivo = corredores2[0];
        }
    }
}


问:
When a different radio button is checked on submission, it doesn't remember that checkbox when returning to the view
```<code>@Html.RadioButtonFor(model => model.EditSearchVM.SearchBy, "Id") <text> ID  &nbsp &nbsp</text>
@Html.RadioButtonFor(model => model.EditSearchVM.SearchBy, "CreationDate", new { @checked = "checked" }) <text> Creation Date  &nbsp &nbsp</text><br />
</code>```

I have one selected by default but when I check the other one it should have that one still checked when returning from the controller.

答:
As you also mentioned in the question first you need to create your viewModel. for example:

```<code>public class EditSearchVM
{
    public string SearchBy { get; set; }
    //Some other properties ....
}
</code>```

To keep the example simple, I will use Home controller and Index. In your View you need to Create an HTML Form and pass the data to your view.

```<code>@model EditSearchVM
<form method="post" action="/Home/Index">
    @Html.RadioButtonFor(r => r.SearchBy, "Id") ID
    @Html.RadioButtonFor(r => r.SearchBy, "CreationDate") CreationDate
    <input id="submitBtn" type="submit" value="Submit the form" />
</form>
</code>```

Inside of Home controller, in the Index (Get) action you need to set the default selected. There are many ways that you can do it. This one is one example.

```<code>public IActionResult Index()
{
     //Set the default selected
     var model =  new EditSearchVM (){ SearchBy = "CreationDate" };
     return View(model);
}
</code>```

Then you need the Post action. If you want to keep the current selected when you return the page you need to pass the model as well. So your Post action will be this like:

```<code>[HttpPost]
public IActionResult Index(EditSearchVM model)
{
    if (ModelState.IsValid)
    {
        //Do something and redirect to proper controller and action
    }
    return View(model);
}
</code>```

Body:
@Html.RadioButtonFor(model => model.EditSearchVM.SearchBy, "Id") <text> ID  &nbsp &nbsp</text>
@Html.RadioButtonFor(model => model.EditSearchVM.SearchBy, "CreationDate", new { @checked = "checked" }) <text> Creation Date  &nbsp &nbsp</text>

I have one selected by default but when I check the other one it should have that one still checked when returning from the controller.

Body:
As you also mentioned in the question first you need to create your viewModel. for example:

public class EditSearchVM
{
    public string SearchBy { get; set; }
    //Some other properties ....
}

To keep the example simple, I will use Home controller and Index. In your View you need to Create an HTML Form and pass the data to your view.

@model EditSearchVM
<form method="post" action="/Home/Index">
    @Html.RadioButtonFor(r => r.SearchBy, "Id") ID
    @Html.RadioButtonFor(r => r.SearchBy, "CreationDate") CreationDate
    <input id="submitBtn" type="submit" value="Submit the form" />
</form>

Inside of Home controller, in the Index (Get) action you need to set the default selected. There are many ways that you can do it. This one is one example.

public IActionResult Index()
{
     //Set the default selected
     var model =  new EditSearchVM (){ SearchBy = "CreationDate" };
     return View(model);
}

Then you need the Post action. If you want to keep the current selected when you return the page you need to pass the model as well. So your Post action will be this like:

[HttpPost]
public IActionResult Index(EditSearchVM model)
{
    if (ModelState.IsValid)
    {
        //Do something and redirect to proper controller and action
    }
    return View(model);
}


问:
Is the pointer passed to placement new a non-UB pointer to its object representation?

struct foo {
   int a;
   int b;
};

std::array<char, sizeof(foo)> buffer;
foo a {1, 2};
foo* b {new (buffer.data()) foo};
std::memcpy(buffer.data(), &a, sizeof(foo));
a == *b; // the important part
```

I know that the placement new leaves the values of b's fields indeterminate, but does the subsequent memcpy, through the pointer to the buffer passed to new, then turn b into a copy of a? Or is there UB, since I'm not memcpy-ing through the pointer returned by new?

cppreference ended being a bit too obtuse for me, in this case, to figure out if this is defined or not.

Edit: assume buffer is properly aligned to make the placement new make sense

答:
Placement new

If placement_params are provided, they are passed to the allocation
  function as additional arguments. Such allocation functions are known
  as "placement new", after the standard allocation function void*
  operator new(std::size_t, void*), which simply returns its second
  argument unchanged. This is used to construct objects in allocated
  storage:

The above is from cppreference, so you are correct after memcpy the memory contents of 'b' is the same as 'a'

Source : https://en.cppreference.com/w/cpp/language/new

Body:
struct foo {
   int a;
   int b;
};

std::array<char, sizeof(foo)> buffer;
foo a {1, 2};
foo* b {new (buffer.data()) foo};
std::memcpy(buffer.data(), &a, sizeof(foo));
a == *b; // the important part

I know that the placement new leaves the values of b's fields indeterminate, but does the subsequent memcpy, through the pointer to the buffer passed to new, then turn b into a copy of a? Or is there UB, since I'm not memcpy-ing through the pointer returned by new?

cppreference ended being a bit too obtuse for me, in this case, to figure out if this is defined or not.

Edit: assume buffer is properly aligned to make the placement new make sense


问:
How can I make my pc hibernate if pc battery level drops 18%?
I get my battery level via -

```<code>WMIC PATH Win32_Battery Get EstimatedChargeRemaining
</code>```

and the output is =>
EstimatedChargeRemaining
100

Also, I can hibernate my pc with command like,

```<code>shutdown /h
</code>```

So, how come I write a script such that when the battery level drops below 20%, it just hibernate my pc,
 how do I make it happen? Also, when I power on it again it won't just hibernate again, I mean to only function it once, and activate the function again when the battery level goes above 21%, so that its a feasible service. Any help would be really worth... Thanks in advance!!

答:
I know about these things in windows as suggested, but I wanted to create something that would hibernate automatically even if the laptop is tried to start by someone else so, the opened processes or other running tasks won't run out/ or crash abruptly. So finally I made this program in node, and made a bat file, with

```<code>node Autohibernate.js
</code>```

and hence the node program will be executed by this. And finally to make it run in hidden mode, and even if the pc is restarted, I made a vbscript program that does this. And it is like this-

```<code>Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\autohibernate.bat" & Chr(34), 0
Set WshShell = Nothing
</code>```

So, finally there is the node program, i.e., autohibernate.js shown below-

```<code>const { exec, spawn } = require("child_process");
let current;
let critical = 18; // Battery level at which hibernates.
let repeatAfterActionFired = 1; //In minutes.
let generalCheckTimer = 3; // Check after every this time(in second).

async function somelife() {
  exec("WMIC PATH Win32_Battery Get EstimatedChargeRemaining", (err, stdout, stderr) => {
    current = stdout.slice(29);
    console.log("battery-", current);
    if (current > critical) {
      checkAndHibernate();
    } else {
      console.log(
        `Hibernation Fired, Next checkAndHibernate after ${repeatAfterActionFired} minutes.`
      );
      setTimeout(() => {
        checkAndHibernate();
      }, repeatAfterActionFired * 60 * 1_000);

      exec("shutdown /h");
      // exec()
    }
  });
}
const checkAndHibernate = () =>
  setTimeout(() => {
    somelife();
  }, generalCheckTimer * 1_000);
checkAndHibernate();
</code>```

Thanks, Stackoverflow.

Body:
I get my battery level via -

WMIC PATH Win32_Battery Get EstimatedChargeRemaining

and the output is =>
EstimatedChargeRemaining
100

Also, I can hibernate my pc with command like,

shutdown /h

So, how come I write a script such that when the battery level drops below 20%, it just hibernate my pc,
 how do I make it happen? Also, when I power on it again it won't just hibernate again, I mean to only function it once, and activate the function again when the battery level goes above 21%, so that its a feasible service. Any help would be really worth... Thanks in advance!!

Body:
I know about these things in windows as suggested, but I wanted to create something that would hibernate automatically even if the laptop is tried to start by someone else so, the opened processes or other running tasks won't run out/ or crash abruptly. So finally I made this program in node, and made a bat file, with

node Autohibernate.js

and hence the node program will be executed by this. And finally to make it run in hidden mode, and even if the pc is restarted, I made a vbscript program that does this. And it is like this-

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\autohibernate.bat" & Chr(34), 0
Set WshShell = Nothing

So, finally there is the node program, i.e., autohibernate.js shown below-

const { exec, spawn } = require("child_process");
let current;
let critical = 18; // Battery level at which hibernates.
let repeatAfterActionFired = 1; //In minutes.
let generalCheckTimer = 3; // Check after every this time(in second).

async function somelife() {
  exec("WMIC PATH Win32_Battery Get EstimatedChargeRemaining", (err, stdout, stderr) => {
    current = stdout.slice(29);
    console.log("battery-", current);
    if (current > critical) {
      checkAndHibernate();
    } else {
      console.log(
        `Hibernation Fired, Next checkAndHibernate after ${repeatAfterActionFired} minutes.`
      );
      setTimeout(() => {
        checkAndHibernate();
      }, repeatAfterActionFired * 60 * 1_000);

      exec("shutdown /h");
      // exec()
    }
  });
}
const checkAndHibernate = () =>
  setTimeout(() => {
    somelife();
  }, generalCheckTimer * 1_000);
checkAndHibernate();

Thanks, Stackoverflow.


问:
Temperature and salinity data from Argo but Error appeared $ operator is invalid for atomic vectors
I am trying to extract temperature and salinity data from Argovis website "https://argovis.colorado.edu/selection/profiles/"
to run modeling analysis with fish catch. I used the code from "https://www.itsonlyamodel.us/argovis-r-api.html" assigned especially for extracting temperature and salinity for the different oceans depth profiles.

```<code>    library(httr)
options(warn=-1)

get.profile <- function(profileName){
  baseURL <- "https://argovis.colorado.edu/catalog/profiles/"
  url <- paste(baseURL, profileName, sep="")
  resp <- GET(url)
  if(resp$status_code==200) {
    profile = content(resp, "parsed")
  }
  else {
    profile = profile = content(resp, "raw")
  }
  return(profile)
}

parse.into.df <- function(profile) {
  paramNames <- names(profile)
  meas <- profile$measurements
  names = unique(names(unlist(meas)))
  df <- data.frame(matrix(unlist(meas), nrow=length(meas), byrow=T))
  colnames(df) <- names
  df$profile_id <- profile$`_id`
  df$date <- profile$date
  df$cycle_number <- profile$cycle_number
  df$lat <- profile$lat
  df$lon <- profile$lon
  return (df)
}
profileName = "3900737_279"
profile = get.profile(profileName)
df = parse.into.df(profile)
head(df)

get.platform <- function(platformNumber){
  baseURL <- "https://argovis.colorado.edu/catalog/platforms/"
  url <- paste(baseURL, platformNumber, sep="")
  resp <- GET(url)
  if(resp$status_code==200) {
    profiles <- content(resp, "parsed")
  }
  else {
    profiles = content(resp, "raw")
  }
  return(profiles)
}
platformNumber <- '3900737'
platformProfiles <- get.platform(platformNumber)

platformDf <- data.frame()
for (profile in platformProfiles)
{
  df <- parse.into.df(profile)
  platformDf <- rbind(platformDf, df)
}
tail(platformDf)

get.selection <- function(startDate, endDate, shape, presRange){
  baseURL <- "https://argovis.colorado.edu/selection/profiles/"
  startDateQuery <- paste('?startDate=', startDate, sep="")
  endDateQuery <- paste('&endDate;=', endDate, sep="")
  shapeQuery <- paste('&shape;=', shape, sep="")

  if(missing(presRange)) {
    url <- paste(baseURL, startDateQuery, endDateQuery, shapeQuery, sep="")
  }
  else {
    presRangeQuery = paste('&presRange;=', presRange, sep="")
    url <- paste(baseURL, startDateQuery, endDateQuery, presRangeQuery, shapeQuery, sep="")
  }
  resp <- GET(url)
  if(resp$status_code==200) {
    profiles <- content(resp, "parsed")
  }
  else {
    profiles <- content(resp, "raw")
  }
  return(profiles)
}
startDate='2017-9-15'
endDate='2017-10-31'
shape = '[[[-18.6,31.7],[-18.6,37.7],[-5.9,37.7],[-5.9,31.7],[-18.6,31.7]]]'
presRange='[0,30]'

selectionProfiles = get.selection(startDate, endDate, shape, presRange)
selectionDf <- data.frame()
for (profile in selectionProfiles)
{
  df <- parse.into.df(profile)
  selectionDf <- rbind(selectionDf, df)
}
</code>```

but that what I get when I reach the last step:

Error: $ operator is invalid for atomic vectors

Could you please help me

答:
Your problem comes from line 22:

```<code>df$profile_id <- profile$`_id`
</code>```

should probably be:

```<code>df$profile_id <- profile$_id
</code>```

Perhaps this fix won't work because I dont really know what the profiles object contains.

But your issue stemmed from trying to use $ to call an atomic vector ( vector with length = 1) which was the "_id" reference.

Body:
I am trying to extract temperature and salinity data from Argovis website "https://argovis.colorado.edu/selection/profiles/"
to run modeling analysis with fish catch. I used the code from "https://www.itsonlyamodel.us/argovis-r-api.html" assigned especially for extracting temperature and salinity for the different oceans depth profiles.

    library(httr)
options(warn=-1)

get.profile <- function(profileName){
  baseURL <- "https://argovis.colorado.edu/catalog/profiles/"
  url <- paste(baseURL, profileName, sep="")
  resp <- GET(url)
  if(resp$status_code==200) {
    profile = content(resp, "parsed")
  }
  else {
    profile = profile = content(resp, "raw")
  }
  return(profile)
}

parse.into.df <- function(profile) {
  paramNames <- names(profile)
  meas <- profile$measurements
  names = unique(names(unlist(meas)))
  df <- data.frame(matrix(unlist(meas), nrow=length(meas), byrow=T))
  colnames(df) <- names
  df$profile_id <- profile$`_id`
  df$date <- profile$date
  df$cycle_number <- profile$cycle_number
  df$lat <- profile$lat
  df$lon <- profile$lon
  return (df)
}
profileName = "3900737_279"
profile = get.profile(profileName)
df = parse.into.df(profile)
head(df)

get.platform <- function(platformNumber){
  baseURL <- "https://argovis.colorado.edu/catalog/platforms/"
  url <- paste(baseURL, platformNumber, sep="")
  resp <- GET(url)
  if(resp$status_code==200) {
    profiles <- content(resp, "parsed")
  }
  else {
    profiles = content(resp, "raw")
  }
  return(profiles)
}
platformNumber <- '3900737'
platformProfiles <- get.platform(platformNumber)

platformDf <- data.frame()
for (profile in platformProfiles)
{
  df <- parse.into.df(profile)
  platformDf <- rbind(platformDf, df)
}
tail(platformDf)

get.selection <- function(startDate, endDate, shape, presRange){
  baseURL <- "https://argovis.colorado.edu/selection/profiles/"
  startDateQuery <- paste('?startDate=', startDate, sep="")
  endDateQuery <- paste('&endDate;=', endDate, sep="")
  shapeQuery <- paste('&shape;=', shape, sep="")

  if(missing(presRange)) {
    url <- paste(baseURL, startDateQuery, endDateQuery, shapeQuery, sep="")
  }
  else {
    presRangeQuery = paste('&presRange;=', presRange, sep="")
    url <- paste(baseURL, startDateQuery, endDateQuery, presRangeQuery, shapeQuery, sep="")
  }
  resp <- GET(url)
  if(resp$status_code==200) {
    profiles <- content(resp, "parsed")
  }
  else {
    profiles <- content(resp, "raw")
  }
  return(profiles)
}
startDate='2017-9-15'
endDate='2017-10-31'
shape = '[[[-18.6,31.7],[-18.6,37.7],[-5.9,37.7],[-5.9,31.7],[-18.6,31.7]]]'
presRange='[0,30]'

selectionProfiles = get.selection(startDate, endDate, shape, presRange)
selectionDf <- data.frame()
for (profile in selectionProfiles)
{
  df <- parse.into.df(profile)
  selectionDf <- rbind(selectionDf, df)
}

but that what I get when I reach the last step:

Error: $ operator is invalid for atomic vectors

Could you please help me

Body:
Your problem comes from line 22:

df$profile_id <- profile$`_id`

should probably be:

df$profile_id <- profile$_id

Perhaps this fix won't work because I dont really know what the profiles object contains.

But your issue stemmed from trying to use $ to call an atomic vector ( vector with length = 1) which was the "_id" reference.


问:
Jenkins MSBuild fails, error NETSDK1064: Package Microsoft.CodeAnalysis.Analyzers, version 2.9.3 was not found
I am trying to deploy a sample aspnet core project but Jenkins build fails.

```<code>C:\Program Files\dotnet\sdk\3.0.100\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,
5): error NETSDK1064: Package Microsoft.CodeAnalysis.Analyzers, version 2.9.3 was not found. It might have
 been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which
might have been due to maximum path length restrictions. [C:\Program Files
(x86)\Jenkins\workspace\test\ProductCoreApi\ProductCoreApi.csproj]
</code>```

I'm using VS2019. I removed and reinstalled the package and tried all possible measures. Still unable to get an idea of what went wrong. The project is in github. Any idea on what went wrong?

答:
I encountered a similar problem when trying to build a solution through an MSBuild script.
There's a problematic section in one of the .csproj files:

```<code><Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    ....
    <Error Condition="!Exists('..\packages\Microsoft.CodeAnalysis.Analyzers.2.9.4"...>
    </Error>
    ...
</Target>
</code>```

When it was removed, I could continue running the build.
The packages it complains about are all there.

Body:
I am trying to deploy a sample aspnet core project but Jenkins build fails.

C:\Program Files\dotnet\sdk\3.0.100\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,
5): error NETSDK1064: Package Microsoft.CodeAnalysis.Analyzers, version 2.9.3 was not found. It might have
 been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which
might have been due to maximum path length restrictions. [C:\Program Files
(x86)\Jenkins\workspace\test\ProductCoreApi\ProductCoreApi.csproj]

I'm using VS2019. I removed and reinstalled the package and tried all possible measures. Still unable to get an idea of what went wrong. The project is in github. Any idea on what went wrong?

Body:
I encountered a similar problem when trying to build a solution through an MSBuild script.
There's a problematic section in one of the .csproj files:

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    ....
    <Error Condition="!Exists('..\packages\Microsoft.CodeAnalysis.Analyzers.2.9.4"...>
    </Error>
    ...
</Target>

When it was removed, I could continue running the build.
The packages it complains about are all there.


问:
vector of strings and transform with C++20 ranges
What is wrong in the following C++20 ranges basic syntax (Ubuntu 20.04, gcc g++ (Ubuntu 10-20200411-0ubuntu1) 10.0.1 20200411 (experimental) [master revision bb87d5cc77d:75961caccb7:f883c46b4877f637e0fa5025b4d6b5c9040ec566]):

```<code>#include <iostream>
#include <vector>
#include <ranges>

[[nodiscard]]
auto f(const std::vector<std::string>& vec) {
   return vec | std::views::transform([] (const std::string &f){
      return f.size(); });
}

int main() {
    const auto v = f({"c", "dddddddd", "aaaa", "bb"});
    for(auto i : v)
        std::cout << i << ' ';
    std::cout << '\n';
    return 0;
}
</code>```

I'd like to take a vector of strings and transform it to the size of each string.

Trying to iterate with C++11 range for-loop is just crashing.
In gdb, I can see that the std:: ranges view is pointing to invalid memory.

Dealing with non string using same constructs as above works fine.

答:
Seems like a 10.0.1 bug.
taking Pete's example and trying it out on 10.0.1 reproduce the issue. (infinite loop) . Exact same code on https://godbolt.org/z/PqdceV 10.1 produced the desired behavior. I guess I'd need to stick to compiler explorer for now to learn ranges.</p>

Body:
What is wrong in the following C++20 ranges basic syntax (Ubuntu 20.04, gcc g++ (Ubuntu 10-20200411-0ubuntu1) 10.0.1 20200411 (experimental) [master revision bb87d5cc77d:75961caccb7:f883c46b4877f637e0fa5025b4d6b5c9040ec566]):

#include <iostream>
#include <vector>
#include <ranges>

[[nodiscard]]
auto f(const std::vector<std::string>& vec) {
   return vec | std::views::transform([] (const std::string &f){
      return f.size(); });
}

int main() {
    const auto v = f({"c", "dddddddd", "aaaa", "bb"});
    for(auto i : v)
        std::cout << i << ' ';
    std::cout << '\n';
    return 0;
}

I'd like to take a vector of strings and transform it to the size of each string.

Trying to iterate with C++11 range for-loop is just crashing.
In gdb, I can see that the std:: ranges view is pointing to invalid memory.

Dealing with non string using same constructs as above works fine.


问:
Resize in textview when I scroll in customized MotionLayout
I have following project in Github : https://github.com/AliRezaeiii/TMDb-Paging

Here is my person_header layout file :

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="person"
            type="com.sample.android.tmdb.ui.person.PersonWrapper" />

    </data>

    <com.sample.android.tmdb.widget.CollapsibleToolbar
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:minHeight="?attr/actionBarSize"
        app:layoutDescription="@xml/scene_person_header"
        app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
        tools:background="?attr/colorPrimary"
        tools:maxHeight="320dp">

        <ImageView
            android:id="@+id/image_background"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:scaleType="centerCrop"
            app:imageUrl="@{@string/base_backdrop_path(person.backdropPath)}"
            app:layout_constraintVertical_bias="0.38"
            tools:ignore="ContentDescription" />

        <View
            android:id="@+id/icon_background"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@color/window_background"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/guideline" />

        <ImageView
            android:id="@+id/tileable_edge"
            android:layout_width="match_parent"
            android:layout_height="30px"
            android:scaleType="fitXY"
            android:src="@drawable/tileable_edge"
            android:tint="@color/window_background"
            app:layout_constraintBottom_toTopOf="@id/icon_background"
            tools:ignore="PxUsage,contentDescription" />

        <FrameLayout
            android:id="@+id/back_frame"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@android:color/transparent"
            android:paddingStart="@dimen/padding_micro"
            tools:ignore="RtlSymmetry">

            <ImageButton
                android:id="@+id/back"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:background="?android:selectableItemBackgroundBorderless"
                android:src="@drawable/ic_arrow_back_padded"
                android:transitionName="@string/transition_search_back"
                tools:ignore="contentDescription" />

        </FrameLayout>

        <TextView
            android:id="@+id/name"
            android:layout_width="162dp"
            android:layout_height="41dp"
            android:text="@{person.personName}"
            app:autoSizeTextType="uniform"
            tools:text="Ali Rezaei" />

        <RelativeLayout
            android:id="@+id/icon_layout"
            android:layout_width="0dp"
            android:layout_height="0dp">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/icon"
                android:layout_width="120dp"
                android:layout_height="120dp"
                app:civ_border_color="@android:color/white"
                app:civ_border_width="2dp"
                app:profileUrl="@{person.profilePath}"
                tools:src="@drawable/ic_error_outline_black_36dp" />

        </RelativeLayout>

        <android.support.constraint.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.67" />

    </com.sample.android.tmdb.widget.CollapsibleToolbar>

</layout>
</code>```

CollapsibleToolbar is extending MotionLayout :

```<code>class CollapsibleToolbar @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : MotionLayout(context, attrs, defStyleAttr), AppBarLayout.OnOffsetChangedListener {

    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        progress = -verticalOffset / appBarLayout?.totalScrollRange?.toFloat()!!
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        (parent as? AppBarLayout)?.addOnOffsetChangedListener(this)
    }
}
</code>```

And here is scene_person_header xml file :

```<code><MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@+id/start"
        motion:duration="1000"
        motion:interpolator="linear">

        <ConstraintSet android:id="@+id/start">

            <Constraint
                android:id="@id/image_background"
                android:layout_width="0dp"
                android:layout_height="0dp"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toTopOf="parent"
                motion:layout_constraintVertical_bias="0.38" />

            <Constraint
                android:id="@id/icon_background"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/window_background"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toBottomOf="@+id/guideline" />

            <Constraint
                android:id="@id/name"
                android:layout_width="162dp"
                android:layout_height="41dp"
                motion:autoSizeTextType="uniform"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintHorizontal_bias="0.5"
                motion:layout_constraintStart_toStartOf="parent" />

            <Constraint
                android:id="@id/icon_layout"
                android:layout_width="120dp"
                android:layout_height="120dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                motion:layout_constraintBottom_toTopOf="@+id/name"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintHorizontal_bias="0.5"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintVertical_bias="0.24000001"
                motion:layout_constraintVertical_chainStyle="packed" />

            <Constraint
                android:id="@id/back_frame"
                android:layout_width="72dp"
                android:layout_height="?attr/actionBarSize"
                motion:layout_constraintTop_toTopOf="parent" />

        </ConstraintSet>

        <ConstraintSet android:id="@+id/end">
            <Constraint
                android:id="@id/image_background"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:visibility="invisible"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toTopOf="parent"
                motion:layout_constraintVertical_bias="0.38" />

            <Constraint
                android:id="@id/icon_background"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:background="?attr/colorPrimary"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toBottomOf="@+id/guideline" />

            <Constraint
                android:id="@id/name"
                android:layout_width="wrap_content"
                android:layout_height="28dp"
                android:layout_marginBottom="14dp"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintStart_toEndOf="@+id/back_frame" />

            <Constraint
                android:id="@id/icon_layout"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent" />

            <Constraint
                android:id="@id/back_frame"
                android:layout_width="72dp"
                android:layout_height="?attr/actionBarSize"
                motion:layout_constraintBottom_toBottomOf="parent" />

        </ConstraintSet>

    </Transition>

</MotionScene>
</code>```

When I launch PersonActivity, the name of character is shown as bellow image :

As soon as I start to scroll in PersonActivity, name of character resizes and is shown as bellow image :

What should I do to have initial size of name as the initial size of motionLayout start scrolling? Is there any changes I should make here :

```<code><TextView
                android:id="@+id/name"
                android:layout_width="162dp"
                android:layout_height="41dp"
                android:text="@{person.personName}"
                app:autoSizeTextType="uniform"
                tools:text="Ali Rezaei" />
</code>```

答: You can find issue tracking at : https://issuetracker.google.com/issues/155215198</p>

Body:
I have following project in Github : https://github.com/AliRezaeiii/TMDb-Paging

Here is my person_header layout file :

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="person"
            type="com.sample.android.tmdb.ui.person.PersonWrapper" />

    </data>

    <com.sample.android.tmdb.widget.CollapsibleToolbar
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:minHeight="?attr/actionBarSize"
        app:layoutDescription="@xml/scene_person_header"
        app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
        tools:background="?attr/colorPrimary"
        tools:maxHeight="320dp">

        <ImageView
            android:id="@+id/image_background"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:scaleType="centerCrop"
            app:imageUrl="@{@string/base_backdrop_path(person.backdropPath)}"
            app:layout_constraintVertical_bias="0.38"
            tools:ignore="ContentDescription" />

        <View
            android:id="@+id/icon_background"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@color/window_background"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/guideline" />

        <ImageView
            android:id="@+id/tileable_edge"
            android:layout_width="match_parent"
            android:layout_height="30px"
            android:scaleType="fitXY"
            android:src="@drawable/tileable_edge"
            android:tint="@color/window_background"
            app:layout_constraintBottom_toTopOf="@id/icon_background"
            tools:ignore="PxUsage,contentDescription" />

        <FrameLayout
            android:id="@+id/back_frame"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@android:color/transparent"
            android:paddingStart="@dimen/padding_micro"
            tools:ignore="RtlSymmetry">

            <ImageButton
                android:id="@+id/back"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:background="?android:selectableItemBackgroundBorderless"
                android:src="@drawable/ic_arrow_back_padded"
                android:transitionName="@string/transition_search_back"
                tools:ignore="contentDescription" />

        </FrameLayout>

        <TextView
            android:id="@+id/name"
            android:layout_width="162dp"
            android:layout_height="41dp"
            android:text="@{person.personName}"
            app:autoSizeTextType="uniform"
            tools:text="Ali Rezaei" />

        <RelativeLayout
            android:id="@+id/icon_layout"
            android:layout_width="0dp"
            android:layout_height="0dp">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/icon"
                android:layout_width="120dp"
                android:layout_height="120dp"
                app:civ_border_color="@android:color/white"
                app:civ_border_width="2dp"
                app:profileUrl="@{person.profilePath}"
                tools:src="@drawable/ic_error_outline_black_36dp" />

        </RelativeLayout>

        <android.support.constraint.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.67" />

    </com.sample.android.tmdb.widget.CollapsibleToolbar>

</layout>

CollapsibleToolbar is extending MotionLayout :

class CollapsibleToolbar @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : MotionLayout(context, attrs, defStyleAttr), AppBarLayout.OnOffsetChangedListener {

    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        progress = -verticalOffset / appBarLayout?.totalScrollRange?.toFloat()!!
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        (parent as? AppBarLayout)?.addOnOffsetChangedListener(this)
    }
}

And here is scene_person_header xml file :

<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@+id/start"
        motion:duration="1000"
        motion:interpolator="linear">

        <ConstraintSet android:id="@+id/start">

            <Constraint
                android:id="@id/image_background"
                android:layout_width="0dp"
                android:layout_height="0dp"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toTopOf="parent"
                motion:layout_constraintVertical_bias="0.38" />

            <Constraint
                android:id="@id/icon_background"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/window_background"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toBottomOf="@+id/guideline" />

            <Constraint
                android:id="@id/name"
                android:layout_width="162dp"
                android:layout_height="41dp"
                motion:autoSizeTextType="uniform"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintHorizontal_bias="0.5"
                motion:layout_constraintStart_toStartOf="parent" />

            <Constraint
                android:id="@id/icon_layout"
                android:layout_width="120dp"
                android:layout_height="120dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                motion:layout_constraintBottom_toTopOf="@+id/name"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintHorizontal_bias="0.5"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintVertical_bias="0.24000001"
                motion:layout_constraintVertical_chainStyle="packed" />

            <Constraint
                android:id="@id/back_frame"
                android:layout_width="72dp"
                android:layout_height="?attr/actionBarSize"
                motion:layout_constraintTop_toTopOf="parent" />

        </ConstraintSet>

        <ConstraintSet android:id="@+id/end">
            <Constraint
                android:id="@id/image_background"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:visibility="invisible"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toTopOf="parent"
                motion:layout_constraintVertical_bias="0.38" />

            <Constraint
                android:id="@id/icon_background"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:background="?attr/colorPrimary"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent"
                motion:layout_constraintStart_toStartOf="parent"
                motion:layout_constraintTop_toBottomOf="@+id/guideline" />

            <Constraint
                android:id="@id/name"
                android:layout_width="wrap_content"
                android:layout_height="28dp"
                android:layout_marginBottom="14dp"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintStart_toEndOf="@+id/back_frame" />

            <Constraint
                android:id="@id/icon_layout"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                motion:layout_constraintBottom_toBottomOf="parent"
                motion:layout_constraintEnd_toEndOf="parent" />

            <Constraint
                android:id="@id/back_frame"
                android:layout_width="72dp"
                android:layout_height="?attr/actionBarSize"
                motion:layout_constraintBottom_toBottomOf="parent" />

        </ConstraintSet>

    </Transition>

</MotionScene>

When I launch PersonActivity, the name of character is shown as bellow image :

As soon as I start to scroll in PersonActivity, name of character resizes and is shown as bellow image :

What should I do to have initial size of name as the initial size of motionLayout start scrolling? Is there any changes I should make here :

<TextView
                android:id="@+id/name"
                android:layout_width="162dp"
                android:layout_height="41dp"
                android:text="@{person.personName}"
                app:autoSizeTextType="uniform"
                tools:text="Ali Rezaei" />


问:
Why is Android's JSONObject retained in memory?
I am working on an OutOfMemory exception generated when a really large JSONObject is created but never garbage collected by Android's framework. On each subsequent update the memory leak just gets bigger and bigger till I run out of memory. We have a large data structure that changes over time and on each update we send the whole datastructure to the client and refresh it. I know that is not the best way to do it, but changing the whole infrastructure just for Mobile is going to take some time and convincing to do.

As for the here and now, when an Object goes out of scope in Java, it should be marked as available to be garbage collected. I am using the Eclipse MAT tool to do my memory analysis and according to the tool, each String I parse out of the JSONObject has a link back to the original JSONObject. A fix I have is I created a remove function where I iterate through each of the JSONObjects keys and call JSONObject.remove(key) after I am done parsing, that works like a charm and all memory is collected. However, why do I need to do that? I should not have to do that to an out of scope object. Any ideas?

Thanks in advance!

Jared Sheehan

答:
Maybe it's best to convert your JSON response into a POJO as soon as you receive it.
The Jackson JSON parser will do that for you in two lines of code and can also turn it back into your JSON Object if you ever need to do that.

Jackson is very fast (they claim the fastest of all the parsers) so you won't take much of a performance hit.

Check out this tutorial on their website.

from the tutorial, you can take  this simple JSON object:

```<code>{
    "name":
    {
        "first":"Joe",
        "last":"Sixpack"
    },
    "gender":"MALE",
    "verified":false,
    "userImage":"Rm9vYmFyIQ=="
}
</code>```

and parse it into your own object with this code:

```<code>ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
</code>```

Just so you know, I also had issues with memory retention in my latest Android project and eventually gave up on using JSON altogether.

Good luck!

ContentLicense: CC BY-SA 3.0

Body:
Maybe it's best to convert your JSON response into a POJO as soon as you receive it.
The Jackson JSON parser will do that for you in two lines of code and can also turn it back into your JSON Object if you ever need to do that.

Jackson is very fast (they claim the fastest of all the parsers) so you won't take much of a performance hit.

Check out this tutorial on their website.

from the tutorial, you can take  this simple JSON object:

{
    "name":
    {
        "first":"Joe",
        "last":"Sixpack"
    },
    "gender":"MALE",
    "verified":false,
    "userImage":"Rm9vYmFyIQ=="
}

and parse it into your own object with this code:

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);

Just so you know, I also had issues with memory retention in my latest Android project and eventually gave up on using JSON altogether.

Good luck!


问:
Split string on the first white space occurrence
I didn't get an optimized regex that split me a String basing into the first white space occurrence:

```<code>var str="72 tocirah sneab";
</code>```

I need to get:

```<code>[
    "72",
    "tocirah sneab",
]
</code>```

答:
I'm not sure why all other answers are so complicated, when you can do it all in one line, handling the lack of space as well.

As an example, let's get the first and "rest" components of a name:

const [first, rest] = 'John Von Doe'.split(/\s+(.*)/);
console.log({ first, rest });

// As array
const components = 'Surma'.split(/\s+(.*)/);
console.log(components);```

Body:
I didn't get an optimized regex that split me a String basing into the first white space occurrence:

var str="72 tocirah sneab";

I need to get:

[
    "72",
    "tocirah sneab",
]


问:
Flutter build apk and installed got flash blank screen
when I build the flutter app and install on the real android phone I got these errors.

```<code>Launching lib/src/config/flavors/main_stage.dart on DUB AL00 in debug mode...
✓ Built build/app/outputs/apk/debug/app-debug.apk.
E/flutter (32542): [ERROR:flutter/shell/gpu/gpu_surface_gl.cc(70)] Failed to setup Skia Gr context.
Error connecting to the service protocol: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:52745/fiENvL9drJE=/ws
Exited (sigterm)
</code>```

I googled there are saying add --enable-software-rendering , this works with debug mode
but how can I make work when I build an installable APK? If I run as relase mode this argument does not work.

anyone can help? thanks

答: Run > Edit Config > Additional Argument > "--enable-software-rendering"</p>

Body:
when I build the flutter app and install on the real android phone I got these errors.

Launching lib/src/config/flavors/main_stage.dart on DUB AL00 in debug mode...
✓ Built build/app/outputs/apk/debug/app-debug.apk.
E/flutter (32542): [ERROR:flutter/shell/gpu/gpu_surface_gl.cc(70)] Failed to setup Skia Gr context.
Error connecting to the service protocol: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:52745/fiENvL9drJE=/ws
Exited (sigterm)

I googled there are saying add --enable-software-rendering , this works with debug mode
but how can I make work when I build an installable APK? If I run as relase mode this argument does not work.

anyone can help? thanks


问:
Perl Regex: Need help on a way to split string into groups matching a pattern
I need to split this string to an array:

```<code>$string = "9583526578','9583636523','9673522574','9183556528','9983023378";
</code>```

Here's how I want my array to look like after splitting:

```<code>@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]
</code>```

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)

答:
If you can trust they're all integers, extraction is easy.  Just grab all the integers.

```<code>my @numbers = $string =~ /(\d+)/g;
</code>```

Then splitting them into pieces of two...

```<code>push @matrix, [splice @numbers, 0, 2] while @numbers;
</code>```

Not as memory efficient as doing it in place, but simple code (if you grok list processing).

If the only reason you're splitting them into pairs is to process them in pairs, you can destructively iterate through the array...

```<code>while( my @pair = splice @numbers, 0, 2 ) {
    ...
}
</code>```

Or you can iterate in pairs in one of the rare valid uses of a 3-part for loop in Perl.

```<code>for(
    my $idx = 0;
    my @pair = @numbers[$idx, $idx+1];
    $idx += 2;
)
{
    ...
}
</code>```

Finally, you can get fancy and use perl5i.

```<code>use perl5i::2;
@numbers->foreach( func($first, $second) { ... } );
</code>```

You can also use List::MoreUtils natatime.

Body:
I need to split this string to an array:

$string = "9583526578','9583636523','9673522574','9183556528','9983023378";

Here's how I want my array to look like after splitting:

@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)

Body:
If you can trust they're all integers, extraction is easy.  Just grab all the integers.

my @numbers = $string =~ /(\d+)/g;

Then splitting them into pieces of two...

push @matrix, [splice @numbers, 0, 2] while @numbers;

Not as memory efficient as doing it in place, but simple code (if you grok list processing).

If the only reason you're splitting them into pairs is to process them in pairs, you can destructively iterate through the array...

while( my @pair = splice @numbers, 0, 2 ) {
    ...
}

Or you can iterate in pairs in one of the rare valid uses of a 3-part for loop in Perl.

for(
    my $idx = 0;
    my @pair = @numbers[$idx, $idx+1];
    $idx += 2;
)
{
    ...
}

Finally, you can get fancy and use perl5i.

use perl5i::2;
@numbers->foreach( func($first, $second) { ... } );

You can also use List::MoreUtils natatime.


问:
Update specific line on Console
Is it possible for a C# console application to update the the corresponding line from multi-thread?

Something like this

```<code>thread 1: 1 of 100
thread 2: 2 of 2004
thread 3: Initialize
thread 4: Complete
</code>```

Need for updating each line.

Update

I think I am closing to the Answser.

https://learn.microsoft.com/ja-jp/dotnet/api/system.console.setcursorposition?view=netcore-3.1

1.Get A new CursorPosition(ex:LastLine) for each  thread and hold.

2.Use Console.SetCursorPosition(int,int) to Update the corresponding line.

答:
You can use the method Console.SetCursorPosition to set the cursor position and then call Console.Write, that will write starting at the position set.

Something like:

```<code>Console.SetCursorPosition(0, 0); // for line 1
Console.Write($"thread 1: {current1} of {total1}");
Console.SetCursorPosition(0, 1); // for line 2
Console.Write($"thread 2: {current2} of {total2}");
</code>```

Title: Update specific line on Console

Body:
Is it possible for a C# console application to update the the corresponding line from multi-thread?

Something like this

thread 1: 1 of 100
thread 2: 2 of 2004
thread 3: Initialize
thread 4: Complete

Need for updating each line.

Update

I think I am closing to the Answser.

https://learn.microsoft.com/ja-jp/dotnet/api/system.console.setcursorposition?view=netcore-3.1

1.Get A new CursorPosition(ex:LastLine) for each  thread and hold.

2.Use Console.SetCursorPosition(int,int) to Update the corresponding line.

Body:
You can use the method Console.SetCursorPosition to set the cursor position and then call Console.Write, that will write starting at the position set.

Something like:

Console.SetCursorPosition(0, 0); // for line 1
Console.Write($"thread 1: {current1} of {total1}");
Console.SetCursorPosition(0, 1); // for line 2
Console.Write($"thread 2: {current2} of {total2}");


问:
Kubernetes - Postgres - Create Tables
I can create a PostgresSQL deployment in Kubernetes with volumes with no problems. The question I have is how to create the database tables.

I can easily exec in the pod and create the tables but I want it to be automatically createded.

I don't want to build in into the docker image as a want a generic image.

I have thought about a few options such as Kubernetes Batch Job only running once but not sure what the best approach is ?

Thanks.

答:
You have multiple way:

The official postgresql docker image state (the 'Initialization scripts' section):

If you would like to do additional initialization in an image derived from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d

Those scripts are only run if the database is created. eg if you start/restart a pod with a data volume containing an already existing database, those scripts will not be launched.

With kubernetes, you can provide a configmap with the needed file (if file sizes below 1Mb) or provide a volume with your initialization file.

An another option can be the application itself. For instance you may use flywayDB or liquibase embeded in your application (springboot do that transparently).

Title: Kubernetes - Postgres - Create Tables


问:
How does interface helps in hiding details
I was going through an interface in Java from W3c

In Why And When To Use Interfaces?, they have mentioned

1) To achieve security - hide certain details and only show the important details of an object (interface).

but I wasn't able to comprehend how is interface helps in hiding details or security.

In their notes of an interface, they have the following point

Interface methods are by default abstract and public

Interface attributes are by default public, static and final

Based on my understanding of interface, it looks more like interface helps in decreasing the number of error in code because

Interface methods do not have a body - the body is provided by the "implement" class

On implementation of an interface, you must override all of its methods

So we declare all the methods with their accessibility, return type and name and when we implement those methods, if we forgot to create a method which we haven't declared in our interface, it's going to throw an error.

Can someone help me in comprehending the relation of the interface in security?

答:
1) To achieve security - hide certain details and only show the
  important details of an object (interface).

Interface contains only those methods which are mandatory to be implemented by its implementing concrete class (omitting default methods since Java 8)

For example,

```<code>interface StudentOps {
    void insert(Student);
    void delete(Student);
    void update(Student);
}
class JdbcStudentOpsImpl implements StudentOps {
    public void insert(Student s) {
       // code
    }
    public void delete(Student s) {
       // code
    }
    public void update(Student s) {
       // code
    }

    public void validate(Student s) {
       // code
    }
}
</code>```

In the above StudentOps is interface and it contains only 3 methods insert, update, delete. When we create an object without knowing the underlying impl, for example,

```<code>StudentOps studentOps = Factory.createFor("JDBC");
StudentOps studentOps = Factory.createFor("Kafka");
</code>```

We cannot access validate() method, which could be hidden for those who are not aware of the JdbcStudentOpsImpl class.

Considering that there are 2 implementations, one for storing the data into a database via JDBC, another is to push it to Kafka.

The implementations may be provided at runtime and the actual programmer's job is to not worry about the implementation as to where the data will be stored, but to just invoke the  corresponding operations based on runtime parameters like JDBC, Kafka etc.

JdbcStudentOpsImpl, KafkaStudentOpsImpl can be there in different jars (libraries) which should be included in the classpath at runtime, for example.

In such a case, the programmer who calls Factory.createFor() might not know about those classes. So, he does not know what other methods are there in those classes apart from those in the StudentOps. He is just given an interface to access and he has to look after only those methods defined in the interface.

So, according to the example, insert(), update(), delete() are the important details where as validate() is not.

Body:
1) To achieve security - hide certain details and only show the
  important details of an object (interface).

Interface contains only those methods which are mandatory to be implemented by its implementing concrete class (omitting default methods since Java 8)

For example,

interface StudentOps {
    void insert(Student);
    void delete(Student);
    void update(Student);
}
class JdbcStudentOpsImpl implements StudentOps {
    public void insert(Student s) {
       // code
    }
    public void delete(Student s) {
       // code
    }
    public void update(Student s) {
       // code
    }

    public void validate(Student s) {
       // code
    }
}

In the above StudentOps is interface and it contains only 3 methods insert, update, delete. When we create an object without knowing the underlying impl, for example,

StudentOps studentOps = Factory.createFor("JDBC");
StudentOps studentOps = Factory.createFor("Kafka");

We cannot access validate() method, which could be hidden for those who are not aware of the JdbcStudentOpsImpl class.

Considering that there are 2 implementations, one for storing the data into a database via JDBC, another is to push it to Kafka.

The implementations may be provided at runtime and the actual programmer's job is to not worry about the implementation as to where the data will be stored, but to just invoke the  corresponding operations based on runtime parameters like JDBC, Kafka etc.

JdbcStudentOpsImpl, KafkaStudentOpsImpl can be there in different jars (libraries) which should be included in the classpath at runtime, for example.

In such a case, the programmer who calls Factory.createFor() might not know about those classes. So, he does not know what other methods are there in those classes apart from those in the StudentOps. He is just given an interface to access and he has to look after only those methods defined in the interface.

So, according to the example, insert(), update(), delete() are the important details where as validate() is not.


问:
NodeJS Express Mongoose how to make a get query with parameteres
I'm writing a node js method which I want to find vlaues which match the imei.name parameter passed in, and the test field is empty.

This is the method which I tried to use:

```<code>router.get('/gettdata/', (req, res, next) => {

    let aa=req.query.imei;
    console.log(aa);
    Post.findOne( {imei:{"imei.name":req.body},
  test:{$exists:false}
  }

    )
      .then((posts) => {
        res.json(posts);
        console.log(posts);
      })
      .catch(err => console.log(err))
  });
</code>```

it returns an empty field despite it exists when I use only

```<code>Post.findOne( {"imei.name":req.body})
</code>```

it works and when I use only

```<code>Post.findOne(
  test:{$exists:false}
 )
</code>```

it works but the problem is using them two in one time

```<code>{
        "_id" : ObjectId("5eb7f90fb88d8d4d94184333"),
        "imei" : {
                "name" : "bokhhjbr",
                "modele" : "5486"
        },
        "__v" : 0
}
{
        "_id" : ObjectId("5eb7fb9cb88d8d4d94184334"),
        "imei" : {
                "name" : "865566048694354",
                "modele" : "CPH1803"
        },
        "__v" : 0
}
{
        "_id" : ObjectId("5eba73395fd8dd073065efdf"),
        "imei" : {
                "name" : "bok55555555555hjbr",
                "modele" : "5486"
        },
        "createdAt" : ISODate("2020-05-12T09:58:17.203Z"),
        "updatedAt" : ISODate("2020-05-12T09:58:17.203Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5ed0f93c0c93ec1c785358ab"),
        "imei" : {
                "name" : "865566048694354"
        },
        "test" : {
                "tactileState" : "1",
                "pixelState" : "1",
                "greyState" : "1"
        },
        "createdAt" : ISODate("2020-05-29T11:59:56.441Z"),
        "updatedAt" : ISODate("2020-05-29T11:59:56.441Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5ed0f9420c93ec1c785358ac"),
        "imei" : {
                "name" : "865566048694354"
        },
        "test" : {
                "tactileState" : "1",
                "pixelState" : "1",
                "greyState" : "1"
        },
        "createdAt" : ISODate("2020-05-29T12:00:02.040Z"),
        "updatedAt" : ISODate("2020-05-29T12:00:02.040Z"),
        "__v" : 0
}
</code>```

and that's my database shown in cmd.

I need some help - thank you

答:
You are missing the name of the data you passed to the req body. If "imei" is the name of the data you passed to the body, do this;</p>

```<code>Post.findOne({"imei.name":req.body.imei})
</code>```

Body:
I'm writing a node js method which I want to find vlaues which match the imei.name parameter passed in, and the test field is empty.

This is the method which I tried to use:

router.get('/gettdata/', (req, res, next) => {

    let aa=req.query.imei;
    console.log(aa);
    Post.findOne( {imei:{"imei.name":req.body},
  test:{$exists:false}
  }

    )
      .then((posts) => {
        res.json(posts);
        console.log(posts);
      })
      .catch(err => console.log(err))
  });

it returns an empty field despite it exists when I use only

Post.findOne( {"imei.name":req.body})

it works and when I use only

Post.findOne(
  test:{$exists:false}
 )

it works but the problem is using them two in one time

{
        "_id" : ObjectId("5eb7f90fb88d8d4d94184333"),
        "imei" : {
                "name" : "bokhhjbr",
                "modele" : "5486"
        },
        "__v" : 0
}
{
        "_id" : ObjectId("5eb7fb9cb88d8d4d94184334"),
        "imei" : {
                "name" : "865566048694354",
                "modele" : "CPH1803"
        },
        "__v" : 0
}
{
        "_id" : ObjectId("5eba73395fd8dd073065efdf"),
        "imei" : {
                "name" : "bok55555555555hjbr",
                "modele" : "5486"
        },
        "createdAt" : ISODate("2020-05-12T09:58:17.203Z"),
        "updatedAt" : ISODate("2020-05-12T09:58:17.203Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5ed0f93c0c93ec1c785358ab"),
        "imei" : {
                "name" : "865566048694354"
        },
        "test" : {
                "tactileState" : "1",
                "pixelState" : "1",
                "greyState" : "1"
        },
        "createdAt" : ISODate("2020-05-29T11:59:56.441Z"),
        "updatedAt" : ISODate("2020-05-29T11:59:56.441Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5ed0f9420c93ec1c785358ac"),
        "imei" : {
                "name" : "865566048694354"
        },
        "test" : {
                "tactileState" : "1",
                "pixelState" : "1",
                "greyState" : "1"
        },
        "createdAt" : ISODate("2020-05-29T12:00:02.040Z"),
        "updatedAt" : ISODate("2020-05-29T12:00:02.040Z"),
        "__v" : 0
}

and that's my database shown in cmd.

I need some help - thank you

Body:
You are missing the name of the data you passed to the req body. If "imei" is the name of the data you passed to the body, do this;

Post.findOne({"imei.name":req.body.imei})


问:
array filter and if true map data
i have this piece of code which should combine three apicalls together.

API 1: modules (like a container for multiple checkboxes)
data structure is this:

const modules = [
  {
    name: "Modul1",
    id: 1,
  },
  {
    name: "Modul2",
    id: 2,
  },
];
```

<hr>

<p>API 2: the elements which should be inside the modules and related to there
<code>modules[x].id === elements[x].idModule</code></p>

<pre class="lang-js prettyprint-override"><code>const elements = [
  {
    idModule: 1,
    default: false,
    id: 1,
  },
  {
    idModule: 1,
    default: false,
    id: 2,
  },
  {
    idModule: 1,
    default: false,
    id: 3,
  },
  {
    idModule: 2,
    default: false,
    id: 4,
  },
  {
    idModule: 2,
    default: false,
    id: 5,
  },
  {
    idModule: 2,
    default: false,
    id: 6,
  },
  {
    idModule: 2,
    default: false,
    id: 7,
  },
];
</code>```

API 3: the true/false value which should set to the elements related to
elements[x].id === items.items[x].id

const items = {
   "status":true,
   "items":[
      {
         "id":1,
         "value":true
      },
      {
         "id":2,
         "value":true
      },
      {
         "id":3,
         "value":true
      },
      {
         "id":4,
         "value":true
      },
      {
         "id":5,
         "value":true
      },
      {
         "id":6,
         "value":true
      },
      {
         "id":7,
         "value":true
      }
   ]
}
```

<hr>

<p>all three APIs should be combined to one single source of truth.
the result should looks like this:</p>

<pre class="lang-js prettyprint-override"><code>const result = [
  {
    id: 1,
    name: 'Module1',
    elements: [
      {
        idModule: 1,
        default: false,
        id: 1,
        value: true
      },
      {
        idModule: 1,
        default: false,
        id: 2,
        value: true
      },
      {
        idModule: 1,
        default: false,
        id: 3,
        value: true
      }
    ]
  },
  {
    id: 2,
    name: 'Module2',
    elements: [
      {
        idModule: 2,
        default: false,
        id: 4,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 5,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 6,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 7,
        value: true
      }
    ]
  }
];
</code>```

my brain is melting by doing this and i am stuck as f. what i tried for now 2 days is this:

const data = data.modules.map(x => {
  x.modules = data.elements.items.filter(
    d => d.idModule === x.id
  );

  x.modul.map(y => {
    // ---------- some where here the shit its the fan, idk -----------
    y.value = data.items.items.filter(f => {
      f.id === y.id;
    });
    return y;
  });
  return x;
});
```

答:
You can first get the data by mapping the last two API calls, then map the first array with the incoming result:

var modules = [ { name: "Modul1", id: 1, }, { name: "Modul2", id: 2, }];
var elements = [ { idModule: 1, default: false, id: 1, }, { idModule: 1, default: false, id: 2, }, { idModule: 1, default: false, id: 3, }, { idModule: 2, default: false, id: 4, }, { idModule: 2, default: false, id: 5, }, { idModule: 2, default: false, id: 6, }, { idModule: 2, default: false, id: 7, },];
var items = { "status":true, "items":[ { "id":1, "value":true }, { "id":2, "value":true }, { "id":3, "value":true }, { "id":4, "value":true }, { "id":5, "value":true }, { "id":6, "value":true }, { "id":7, "value":true } ]}

var newData = elements.map((val)=>{
  val.value = items.items.find(k=>k.id == val.id).value;
  return val;
});

result = modules.map(val=>{
  val.elements = newData.filter(k=>k.idModule == val.id);
  return val;
});

console.log(result);
    ```

Title: array filter and if true map data

Body:
i have this piece of code which should combine three apicalls together.

API 1: modules (like a container for multiple checkboxes)
data structure is this:

const modules = [
  {
    name: "Modul1",
    id: 1,
  },
  {
    name: "Modul2",
    id: 2,
  },
];

API 2: the elements which should be inside the modules and related to there
modules[x].id === elements[x].idModule

const elements = [
  {
    idModule: 1,
    default: false,
    id: 1,
  },
  {
    idModule: 1,
    default: false,
    id: 2,
  },
  {
    idModule: 1,
    default: false,
    id: 3,
  },
  {
    idModule: 2,
    default: false,
    id: 4,
  },
  {
    idModule: 2,
    default: false,
    id: 5,
  },
  {
    idModule: 2,
    default: false,
    id: 6,
  },
  {
    idModule: 2,
    default: false,
    id: 7,
  },
];

API 3: the true/false value which should set to the elements related to
elements[x].id === items.items[x].id

const items = {
   "status":true,
   "items":[
      {
         "id":1,
         "value":true
      },
      {
         "id":2,
         "value":true
      },
      {
         "id":3,
         "value":true
      },
      {
         "id":4,
         "value":true
      },
      {
         "id":5,
         "value":true
      },
      {
         "id":6,
         "value":true
      },
      {
         "id":7,
         "value":true
      }
   ]
}

all three APIs should be combined to one single source of truth.
the result should looks like this:

const result = [
  {
    id: 1,
    name: 'Module1',
    elements: [
      {
        idModule: 1,
        default: false,
        id: 1,
        value: true
      },
      {
        idModule: 1,
        default: false,
        id: 2,
        value: true
      },
      {
        idModule: 1,
        default: false,
        id: 3,
        value: true
      }
    ]
  },
  {
    id: 2,
    name: 'Module2',
    elements: [
      {
        idModule: 2,
        default: false,
        id: 4,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 5,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 6,
        value: true
      },
      {
        idModule: 2,
        default: false,
        id: 7,
        value: true
      }
    ]
  }
];

my brain is melting by doing this and i am stuck as f. what i tried for now 2 days is this:

const data = data.modules.map(x => {
  x.modules = data.elements.items.filter(
    d => d.idModule === x.id
  );

  x.modul.map(y => {
    // ---------- some where here the shit its the fan, idk -----------
    y.value = data.items.items.filter(f => {
      f.id === y.id;
    });
    return y;
  });
  return x;
});


问:
Visual C++ ListBox as Preference Chooser
So I'm building a tool that allows a user to edit a whole bunch of preferences for various things. There are several groups of settings, too many to use a TabControl without creating arrow sliders to view all of the tabs, so I decided I would try and use a ListBox to list the groups of preferences, and then when they click on them, the settings that they can change show up to the right of the box.

I'm just not sure how to do this. Obviously it would invoke something in the OnSelectionChanged function of the ListBox, but I'm not sure where to go from there. Surely a dialog can have dynamic design, right? Would I mimic the creation of a tabbed-dialog where I create my designs and then bind them to the TabControl, and just do something similar for the ListBox? Again, it's not the ListBox itself that is dynamic. The user will click on "Settings A" from the ListBox, and to the right of the ListBox will be settings 1, 2, and 3 that each have  textboxs/radios/checks.

Any hints on how I can accomplish this? I just think it looks nicer than having a whole bunch of tabs lined up across the top of the box. Thanks in advance to any brilliant minds who can help me out. I'm versed in C++, but I'm very much a beginner at VC++.

答:
You can a vertical splitter with two panes:

one which contains the list

another one which contains the configuration dialogs you would normally use in a tab control

Each time the list selection changes you can load the appropriate dialog in the right pane. You can find a splitter tutorial here: http://www.codeproject.com/KB/wtl/wtl4mfc7.aspx


问:
How to fix "Cannot read property 'responsive_class' of null" in Angular production build
I made a production build of my angular app and when i try to route to another component it logs this error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'responsive_class' of null

```<code>TypeError: Cannot read property 'responsive_class' of null
    at main.872179a97a20c6d35a4f.js:1
    at Array.reduce (<anonymous>)
    at s (main.872179a97a20c6d35a4f.js:1)
    at new t (main.872179a97a20c6d35a4f.js:1)
    at new t (main.872179a97a20c6d35a4f.js:1)
    at new t (main.872179a97a20c6d35a4f.js:1)
    at y (main.872179a97a20c6d35a4f.js:1)
    at main.872179a97a20c6d35a4f.js:1
    at Li (main.872179a97a20c6d35a4f.js:1)
    at Ni (main.872179a97a20c6d35a4f.js:1)
    at D (polyfills.bd7334c8629fc0d28479.js:1)
    at D (polyfills.bd7334c8629fc0d28479.js:1)
    at polyfills.bd7334c8629fc0d28479.js:1
    at e.invokeTask (polyfills.bd7334c8629fc0d28479.js:1)
    at Object.onInvokeTask (main.872179a97a20c6d35a4f.js:1)
    at e.invokeTask (polyfills.bd7334c8629fc0d28479.js:1)
    at t.runTask (polyfills.bd7334c8629fc0d28479.js:1)
    at d (polyfills.bd7334c8629fc0d28479.js:1)
    at t.invokeTask [as invoke] (polyfills.bd7334c8629fc0d28479.js:1)
    at m (polyfills.bd7334c8629fc0d28479.js:1)
</code>```

When it logs this error the screen goes blank but all works fine in development build.

Anyone experienced this?

答:
In production configurations in angular.json,
change buildOptimzation & optimization to false and try deploying.
It might point to the file.</p>

Body:
I made a production build of my angular app and when i try to route to another component it logs this error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'responsive_class' of null

TypeError: Cannot read property 'responsive_class' of null
    at main.872179a97a20c6d35a4f.js:1
    at Array.reduce (<anonymous>)
    at s (main.872179a97a20c6d35a4f.js:1)
    at new t (main.872179a97a20c6d35a4f.js:1)
    at new t (main.872179a97a20c6d35a4f.js:1)
    at new t (main.872179a97a20c6d35a4f.js:1)
    at y (main.872179a97a20c6d35a4f.js:1)
    at main.872179a97a20c6d35a4f.js:1
    at Li (main.872179a97a20c6d35a4f.js:1)
    at Ni (main.872179a97a20c6d35a4f.js:1)
    at D (polyfills.bd7334c8629fc0d28479.js:1)
    at D (polyfills.bd7334c8629fc0d28479.js:1)
    at polyfills.bd7334c8629fc0d28479.js:1
    at e.invokeTask (polyfills.bd7334c8629fc0d28479.js:1)
    at Object.onInvokeTask (main.872179a97a20c6d35a4f.js:1)
    at e.invokeTask (polyfills.bd7334c8629fc0d28479.js:1)
    at t.runTask (polyfills.bd7334c8629fc0d28479.js:1)
    at d (polyfills.bd7334c8629fc0d28479.js:1)
    at t.invokeTask [as invoke] (polyfills.bd7334c8629fc0d28479.js:1)
    at m (polyfills.bd7334c8629fc0d28479.js:1)

When it logs this error the screen goes blank but all works fine in development build.

Anyone experienced this?


问:
Docker Build Failing on Azure Pipeline due to COPY --from=build
Hi guys i'm having trouble getting the COPY --from=build /src /dest in azure build pipeline. Its working on my local though... please see code below

Dockerfile

```<code>#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat

FROM mcr.microsoft.com/dotnet/framework/sdk:4.7.2-windowsservercore-ltsc2019 AS build
WORKDIR /src

COPY . .
COPY SimpleWeb/*.csproj ./SimpleWeb/
COPY SimpleWeb/*.config ./SimpleWeb/
RUN nuget restore

COPY SimpleWeb/. ./SimpleWeb/
WORKDIR /src/SimpleWeb
RUN msbuild /p:Configuration=Release

FROM mcr.microsoft.com/dotnet/framework/aspnet:4.7.2-windowsservercore-ltsc2019 AS runtime
WORKDIR /inetpub/wwwroot
COPY --from=build /src/SimpleWeb/bin/Release/Publish/. .
</code>```

Azure Pipeline.yml

```<code># ASP.NET Core (.NET Framework)
# Build and test ASP.NET Core projects targeting the full .NET Framework.
# Add steps that publish symbols, save build artifacts, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/dotnet-core

trigger:
- master

pool:
  vmImage: 'windows-latest'

steps:
- task: Docker@2
  displayName: Build
  inputs:
    containerRegistry: 'container-registry-dockerhub'
    repository: 'myrepo'
    command: 'build'
    Dockerfile: '**/Dockerfile'
    tags: 'latest'
- task: Docker@2
  displayName: Push
  inputs:
    containerRegistry: 'container-registry-dockerhub'
    repository: 'myrepo'
    command: 'push'
    tags: 'latest'
</code>```

ERROR from Azure CI build

```<code>Step 12/21 : COPY --from=build /src/SimpleWeb/bin/Release/Publish/. .
COPY failed: CreateFile \\?\Volume{a4952e14-500f-4d78-9efe-1a9e638e3459}\src\SimpleWeb\bin\Release\Publish: The system cannot find the path specified.
##[error]The process 'C:\Program Files\Docker\docker.exe' failed with exit code 1
</code>```

------EDITED------
this works though:

COPY --from=build /src/SimpleWeb/. .

i'm not sure why the bin/Release/Publish is not generated on the Azure Pipeline

答:
You can try using dotnet restore instead of nuget restore.

nuget restore will download all NuGet dependencies to your project.
dotnet restore will download all NuGet dependencies as well as references and tools.

Body:
Hi guys i'm having trouble getting the COPY --from=build /src /dest in azure build pipeline. Its working on my local though... please see code below

Dockerfile

#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat

FROM mcr.microsoft.com/dotnet/framework/sdk:4.7.2-windowsservercore-ltsc2019 AS build
WORKDIR /src

COPY . .
COPY SimpleWeb/*.csproj ./SimpleWeb/
COPY SimpleWeb/*.config ./SimpleWeb/
RUN nuget restore

COPY SimpleWeb/. ./SimpleWeb/
WORKDIR /src/SimpleWeb
RUN msbuild /p:Configuration=Release

FROM mcr.microsoft.com/dotnet/framework/aspnet:4.7.2-windowsservercore-ltsc2019 AS runtime
WORKDIR /inetpub/wwwroot
COPY --from=build /src/SimpleWeb/bin/Release/Publish/. .

Azure Pipeline.yml

# ASP.NET Core (.NET Framework)
# Build and test ASP.NET Core projects targeting the full .NET Framework.
# Add steps that publish symbols, save build artifacts, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/dotnet-core

trigger:
- master

pool:
  vmImage: 'windows-latest'

steps:
- task: Docker@2
  displayName: Build
  inputs:
    containerRegistry: 'container-registry-dockerhub'
    repository: 'myrepo'
    command: 'build'
    Dockerfile: '**/Dockerfile'
    tags: 'latest'
- task: Docker@2
  displayName: Push
  inputs:
    containerRegistry: 'container-registry-dockerhub'
    repository: 'myrepo'
    command: 'push'
    tags: 'latest'

ERROR from Azure CI build

Step 12/21 : COPY --from=build /src/SimpleWeb/bin/Release/Publish/. .
COPY failed: CreateFile \\?\Volume{a4952e14-500f-4d78-9efe-1a9e638e3459}\src\SimpleWeb\bin\Release\Publish: The system cannot find the path specified.
##[error]The process 'C:\Program Files\Docker\docker.exe' failed with exit code 1

------EDITED------
this works though:

COPY --from=build /src/SimpleWeb/. .

i'm not sure why the bin/Release/Publish is not generated on the Azure Pipeline


问:
How do I scrape status code from the log file? (in c++)
Each of the string in log file looks like this:

44.225.84.206 - - [12/Mar/2020:07:02:43 +0530] "GET http://example.com/ HTTP/1.1" 200 73 "-" "AWS Security Scanner"

I have to count the no of status code(here 200) in the file.

答:
You can use regular expressions through the std::regex library. "\".+\" (\\d+)" pattern matches any digit after any quoted string and a space. Since your status code is immediately after a quoted string "GET http://example.com/ HTTP/1.1" 200, it will match the first numeric characters till space, so 73 won't be matched. Note that if your log file contains quoted strings anywhere else followed by a space and digits, it will match that too, modify the pattern if needed.

std::regex_search() will match the line and store the result in match. match.str(1) will return the first group; the contents of the first () i.e. 200 as a string. Convert it to an int if needed.

```<code>#include <fstream>
#include <iostream>
#include <regex>
#include <vector>
int main()
{
    std::ifstream log_file("statlog.txt");
    std::regex re("\".+\" (\\d+)");
    std::smatch match;
    std::string line;
    std::vector<std::string> status_code;
    while(std::getline(log_file, line)) {

        if(std::regex_search(line.cbegin(), line.cend(),match, re))
        status_code.push_back(match.str(1));
    }
    for(auto& elem : status_code) std::cout  << elem << '\n';
}
</code>```

This stores all status codes in a vector of strings.

And this is, of course, if you are using C++11 or higher.

Body:
You can use regular expressions through the std::regex library. "\".+\" (\\d+)" pattern matches any digit after any quoted string and a space. Since your status code is immediately after a quoted string "GET http://example.com/ HTTP/1.1" 200, it will match the first numeric characters till space, so 73 won't be matched. Note that if your log file contains quoted strings anywhere else followed by a space and digits, it will match that too, modify the pattern if needed.

std::regex_search() will match the line and store the result in match. match.str(1) will return the first group; the contents of the first () i.e. 200 as a string. Convert it to an int if needed.

#include <fstream>
#include <iostream>
#include <regex>
#include <vector>
int main()
{
    std::ifstream log_file("statlog.txt");
    std::regex re("\".+\" (\\d+)");
    std::smatch match;
    std::string line;
    std::vector<std::string> status_code;
    while(std::getline(log_file, line)) {

        if(std::regex_search(line.cbegin(), line.cend(),match, re))
        status_code.push_back(match.str(1));
    }
    for(auto& elem : status_code) std::cout  << elem << '\n';
}

This stores all status codes in a vector of strings.

And this is, of course, if you are using C++11 or higher.


问:
Uncaught TypeError: Liferay.NotificationsList is not a constructor I am getting in browser while deploying extjs application in liferay
I am using Extjs version 6 and Liferay 6.2.5 when I am deploying application in Liferay I am getting above exception in browser.

答:
(I think Piyush must have resolved it by now, posting it, if anyone else is facing the same issue.)

You need to import liferay-notification js module to use Liferay Notifications.
example:

```<code><aui:script use="liferay-notification">
    new Liferay.Notification({
        closeable: true,
        delay: {
            hide: 3000,
            show: 0,
        },
        duration: 500,
        message: message,
        title: 'Your success Message',
        type: 'success'
        //danger, warning and info also exists
    }).render();
</aui:script>
</code>```

another way is:

```<code><script type="text/javascript">
    AUI().use('liferay-notification', function(A) {
        new Liferay.Notification({
            closeable: true,
            delay: {
                hide: 10000,
                show: 0
            },
            duration: 500,
            message: message,
            render: true,
            title: 'your success message',
            type: 'success'
        }).render('body');
    });
</script>
</code>```

Body:
(I think Piyush must have resolved it by now, posting it, if anyone else is facing the same issue.)

You need to import liferay-notification js module to use Liferay Notifications.
example:

<aui:script use="liferay-notification">
    new Liferay.Notification({
        closeable: true,
        delay: {
            hide: 3000,
            show: 0,
        },
        duration: 500,
        message: message,
        title: 'Your success Message',
        type: 'success'
        //danger, warning and info also exists
    }).render();
</aui:script>

another way is:

<script type="text/javascript">
    AUI().use('liferay-notification', function(A) {
        new Liferay.Notification({
            closeable: true,
            delay: {
                hide: 10000,
                show: 0
            },
            duration: 500,
            message: message,
            render: true,
            title: 'your success message',
            type: 'success'
        }).render('body');
    });
</script>


问:
'[weak self]' in RXSwift closures
Do i need to use [weak self] within RXSwift subscribeNext closures?

I have the code:

```<code>    searchController.searchBar.rx_text.throttle(0.2, scheduler: MainScheduler.instance).subscribeNext { searchText in
        self.viewModel.searchForLocation(searchText)
    }.addDisposableTo(DisposelBag.sharedDisposelBag.disposeBag)
</code>```

Do i need to modify it so that there is a [weak self] capture list at the beginning of the closure? Like this:

```<code>    searchController.searchBar.rx_text.throttle(0.2, scheduler: MainScheduler.instance).subscribeNext { [weak self] searchText in
        self?.viewModel.searchForLocation(searchText)
    }.addDisposableTo(DisposelBag.sharedDisposelBag.disposeBag)
</code>```

答:
[unowned self] means self cannot be nil when block gets called.if block gets called and self is nil,then app crash.

[weak self] means self can be nil when block gets called.As a matter of that,you have to handle optional self inside the block.

SO,My quick answer is
1.when you are referring a view model in a view controller block,always use [unowned self] because you can ensure view model always exists in its associated view controller.

2.in other cases,always be alerted when you use self in a block.choose unowned vs weak based on if self can be nil or not.

Title: '[weak self]' in RXSwift closures

Body:
Do i need to use [weak self] within RXSwift subscribeNext closures?

I have the code:

    searchController.searchBar.rx_text.throttle(0.2, scheduler: MainScheduler.instance).subscribeNext { searchText in
        self.viewModel.searchForLocation(searchText)
    }.addDisposableTo(DisposelBag.sharedDisposelBag.disposeBag)

Do i need to modify it so that there is a [weak self] capture list at the beginning of the closure? Like this:

    searchController.searchBar.rx_text.throttle(0.2, scheduler: MainScheduler.instance).subscribeNext { [weak self] searchText in
        self?.viewModel.searchForLocation(searchText)
    }.addDisposableTo(DisposelBag.sharedDisposelBag.disposeBag)


问:
#include errors detected in vscode
I am using Visual Studio Code in my C++ project. I installed Microsoft C/C++ Extension for VS Code. I got the following error:

#include errors detected. Please update your includePath. IntelliSense features for this translation unit (/path/to/project/file.cpp) will be provided by the Tag Parser.

答:
Left mouse click on the bulb of error line

Click Edit Include path

Then this window popup

Just set Compiler path

Title: #include errors detected in vscode