问:
How to create Semaphores in c?
Im trying to recreate a "Blackbox" library. In my CS class when we are supposed to use Semaphores (in our on paper final) we are given a "sem.h" file. there are 3 functions one for creating a new Semaphore with an inital number of tokens, one for taking a token out of a semaphore and one for placing a token into a semaphore. at 0 tokes any thread using the blocking funktion has to wait for a token.

for better understanding ive been trying to recreate this sem.h and sem.c based on some exams asking for an implementation of single funktions. since this is all intended to be done on paper, it donst compile but I feel im close

sem.h

```<code>typedef struct SEM SEM;
struct SEM *semCreate(int);
void P(struct SEM*); //tokens--
void V(struct SEM*); //tokens++
</code>```

sem.c

```<code>#include "sem.h"
#include <pthread.h>
#include <errno.h>
typedef struct SEM{
    volatile int val; //number of tokens
    pthread_mutex_t m;
    pthread_cond_t c;
}SEM;

/*create new semaphore with #initVal tokens */
SEM *semCreate(int initVal){
    static SEM *sem ={
        .val=initVal
    };
    errno = 0;
    if((errno = pthread_mutex_init(&sem->m,NULL))!=0){
        return NULL;
    }
    if((errno = pthread_cond_init(&sem->c,NULL))!=0){
        return NULL;
    }
    return sem;
}
//take a token from the semaphore
void P(SEM *sem){
    if((errno = pthread_mutex_lock(&sem->m))!=0){
        return;
    }
    while(sem->val <=0){
        if((errno=pthread_cond_wait(&sem->c,&sem->m))!=0){
            pthread_mutex_unlock(&sem->m);
            return;
        }
        sem->val--;
        if(errno = pthread_mutex_unlock(&sem->m)!=0)return;
    }
}
//put a token into the semaphore
void V(SEM *sem){
    if((errno = pthread_mutex_lock(&sem->m))!=0){
        return;
    }

    sem-> val++;

    if((errno = pthread_cond_broadcast(&sem->c))!=0)return;
    if((errno=pthread_mutex_unlock(&sem->m)!=0)) return;
}

</code>```

Incase it isnt clear what this is for:
The functions should limit how many threads can access a segment of code at the same time
example

```<code>//global
static SEM *sem = semCreate(1);
/.../
//critical segment in threadfunction
P(sem);
doReadAndWriteGlobalList();
V(sem);
</code>```

as soon as the 1st thread passes P() any subsequent calls of P wont be able to pass it until V was called on the same sem

on compiling I get the following error:

```<code>sem.c: In function ‘semCreate’:
sem.c:14:3: error: field name not in record or union initializer
   .val=initVal
   ^
sem.c:14:3: note: (near initialization for ‘sem’)
sem.c:14:8: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
   .val=initVal
        ^~~~~~~
sem.c:14:8: note: (near initialization for ‘sem’)
sem.c:14:8: error: initializer element is not constant
sem.c:14:8: note: (near initialization for ‘sem’)
cc1: all warnings being treated as errors
</code>```

答:
You don't want a static var. You want to create a new object (memory allocation) every time semCreate is called. As such,

```<code>static SEM *sem ={
    .val=initVal
};
</code>```

should be

```<code>SEM *sem = malloc(sizeof(SEM));
sem->val = initVal;
</code>```

Don't forget to free the semaphore after you're done with it. That includes on error!

```<code>SEM *semCreate(int initVal){
    SEM *sem = malloc(sizeof(SEM));
    if (!sem)
        goto Error1;

    sem->val = initVal;

    errno = pthread_mutex_init(&sem->m, NULL);
    if (!errno)
       goto Error2;

    errno = pthread_cond_init(&sem->c, NULL);
    if (!errno)
       goto Error3;

    return sem;

Error3:
    pthread_mutex_destroy(&sem->m);
Error2:
    free(buf);
Error1:
    return NULL;
}
</code>```

Aside from that, your code has multiple problems. In short, P is completely wrong.

P can call pthread_cond_signal with an unlocked mutex.

P can return with the mutex still locked.

P decrements the value when it's non-positive when it's suppose to decrement it when it's positive.

And there's the issue that both P and V perform pointless and even harmful error handling. Skipping unlocking the mutex if the broadcast fails? Yeah, let's not do that.

Let's start from scratch with a basic solution, one with no regards for safety or efficiency.

```<code>void V(SEM *sem) {
   ++sem->val;
}

void P(SEM *sem) {
   // Wait for the semaphore to have a positive value.
   while (sem->val < 1) {
      // This is where another thread could change sem->val.
   }

   --sem->val;
}
</code>```

Now, let's make it thread-safe through mutual exclusion.

```<code>void V(SEM *sem) {
   pthread_mutex_lock(&sem->m);
   ++sem->val;
   pthread_mutex_unlock(&sem->m);
}

void P(SEM *sem) {
   pthread_mutex_lock(&sem->m);

   // Wait for the semaphore to have a positive value.
   while (sem->val < 1) {
      pthread_mutex_unlock(&sem->m);
      // This is where another thread could change sem->val.
      pthread_mutex_lock(&sem->m);
   }

   --sem->val;
   pthread_mutex_unlock(&sem->m);
}
</code>```

But that's a busy wait. Let's use a condition var to sleep until the semaphore changes. (Remember that cond_wait unlocks the provided mutex on entry and relocks it before returning.)

```<code>void V(SEM *sem) {
   pthread_mutex_lock(&sem->m);

   ++sem->val;

   // Wake up a thread that's waiting, if any.
   if (sem->val > 0)
      pthread_cond_signal(&sem->c);

   pthread_mutex_unlock(&sem->m);
}

void P(SEM *sem) {
   pthread_mutex_lock(&sem->m);

   // Wait for the semaphore to have a positive value.
   while (sem->val < 1)
      pthread_cond_wait(&sem->c, &sem->m);

   --sem->val;

   // Wake up a thread that's waiting, if any.
   if (sem->val > 0)
      pthread_cond_signal(&sem->c);

   pthread_mutex_unlock(&sem->m);
}
</code>```

Tada!

Notes:

There's no point in calling pthread_cond_broadcast since only one thread can be modify the semaphore at a time. By having both V and P call pthread_cond_signal when appropriate, we avoid waking up threads for nothing.

We can leave out checking if pthread_mutex_lock, pthread_mutex_unlock and pthread_cond_signal fail in working code as these only fail as the result of a coding error.

Title: How to create Semaphores in c?

Body:
Im trying to recreate a "Blackbox" library. In my CS class when we are supposed to use Semaphores (in our on paper final) we are given a "sem.h" file. there are 3 functions one for creating a new Semaphore with an inital number of tokens, one for taking a token out of a semaphore and one for placing a token into a semaphore. at 0 tokes any thread using the blocking funktion has to wait for a token.

for better understanding ive been trying to recreate this sem.h and sem.c based on some exams asking for an implementation of single funktions. since this is all intended to be done on paper, it donst compile but I feel im close

sem.h

typedef struct SEM SEM;
struct SEM *semCreate(int);
void P(struct SEM*); //tokens--
void V(struct SEM*); //tokens++

sem.c

#include "sem.h"
#include <pthread.h>
#include <errno.h>
typedef struct SEM{
    volatile int val; //number of tokens
    pthread_mutex_t m;
    pthread_cond_t c;
}SEM;

/*create new semaphore with #initVal tokens */
SEM *semCreate(int initVal){
    static SEM *sem ={
        .val=initVal
    };
    errno = 0;
    if((errno = pthread_mutex_init(&sem->m,NULL))!=0){
        return NULL;
    }
    if((errno = pthread_cond_init(&sem->c,NULL))!=0){
        return NULL;
    }
    return sem;
}
//take a token from the semaphore
void P(SEM *sem){
    if((errno = pthread_mutex_lock(&sem->m))!=0){
        return;
    }
    while(sem->val <=0){
        if((errno=pthread_cond_wait(&sem->c,&sem->m))!=0){
            pthread_mutex_unlock(&sem->m);
            return;
        }
        sem->val--;
        if(errno = pthread_mutex_unlock(&sem->m)!=0)return;
    }
}
//put a token into the semaphore
void V(SEM *sem){
    if((errno = pthread_mutex_lock(&sem->m))!=0){
        return;
    }

    sem-> val++;

    if((errno = pthread_cond_broadcast(&sem->c))!=0)return;
    if((errno=pthread_mutex_unlock(&sem->m)!=0)) return;
}

Incase it isnt clear what this is for:
The functions should limit how many threads can access a segment of code at the same time
example

//global
static SEM *sem = semCreate(1);
/.../
//critical segment in threadfunction
P(sem);
doReadAndWriteGlobalList();
V(sem);

as soon as the 1st thread passes P() any subsequent calls of P wont be able to pass it until V was called on the same sem

on compiling I get the following error:

sem.c: In function ‘semCreate’:
sem.c:14:3: error: field name not in record or union initializer
   .val=initVal
   ^
sem.c:14:3: note: (near initialization for ‘sem’)
sem.c:14:8: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
   .val=initVal
        ^~~~~~~
sem.c:14:8: note: (near initialization for ‘sem’)
sem.c:14:8: error: initializer element is not constant
sem.c:14:8: note: (near initialization for ‘sem’)
cc1: all warnings being treated as errors

Body:
You don't want a static var. You want to create a new object (memory allocation) every time semCreate is called. As such,

static SEM *sem ={
    .val=initVal
};

should be

SEM *sem = malloc(sizeof(SEM));
sem->val = initVal;

Don't forget to free the semaphore after you're done with it. That includes on error!

SEM *semCreate(int initVal){
    SEM *sem = malloc(sizeof(SEM));
    if (!sem)
        goto Error1;

    sem->val = initVal;

    errno = pthread_mutex_init(&sem->m, NULL);
    if (!errno)
       goto Error2;

    errno = pthread_cond_init(&sem->c, NULL);
    if (!errno)
       goto Error3;

    return sem;

Error3:
    pthread_mutex_destroy(&sem->m);
Error2:
    free(buf);
Error1:
    return NULL;
}

Aside from that, your code has multiple problems. In short, P is completely wrong.

P can call pthread_cond_signal with an unlocked mutex.

P can return with the mutex still locked.

P decrements the value when it's non-positive when it's suppose to decrement it when it's positive.

And there's the issue that both P and V perform pointless and even harmful error handling. Skipping unlocking the mutex if the broadcast fails? Yeah, let's not do that.

Let's start from scratch with a basic solution, one with no regards for safety or efficiency.

void V(SEM *sem) {
   ++sem->val;
}

void P(SEM *sem) {
   // Wait for the semaphore to have a positive value.
   while (sem->val < 1) {
      // This is where another thread could change sem->val.
   }

   --sem->val;
}

Now, let's make it thread-safe through mutual exclusion.

void V(SEM *sem) {
   pthread_mutex_lock(&sem->m);
   ++sem->val;
   pthread_mutex_unlock(&sem->m);
}

void P(SEM *sem) {
   pthread_mutex_lock(&sem->m);

   // Wait for the semaphore to have a positive value.
   while (sem->val < 1) {
      pthread_mutex_unlock(&sem->m);
      // This is where another thread could change sem->val.
      pthread_mutex_lock(&sem->m);
   }

   --sem->val;
   pthread_mutex_unlock(&sem->m);
}

But that's a busy wait. Let's use a condition var to sleep until the semaphore changes. (Remember that cond_wait unlocks the provided mutex on entry and relocks it before returning.)

void V(SEM *sem) {
   pthread_mutex_lock(&sem->m);

   ++sem->val;

   // Wake up a thread that's waiting, if any.
   if (sem->val > 0)
      pthread_cond_signal(&sem->c);

   pthread_mutex_unlock(&sem->m);
}

void P(SEM *sem) {
   pthread_mutex_lock(&sem->m);

   // Wait for the semaphore to have a positive value.
   while (sem->val < 1)
      pthread_cond_wait(&sem->c, &sem->m);

   --sem->val;

   // Wake up a thread that's waiting, if any.
   if (sem->val > 0)
      pthread_cond_signal(&sem->c);

   pthread_mutex_unlock(&sem->m);
}

Tada!

Notes:

There's no point in calling pthread_cond_broadcast since only one thread can be modify the semaphore at a time. By having both V and P call pthread_cond_signal when appropriate, we avoid waking up threads for nothing.

We can leave out checking if pthread_mutex_lock, pthread_mutex_unlock and pthread_cond_signal fail in working code as these only fail as the result of a coding error.


来源: stackexchange

问:
Assign results of promise.all() in typescript
I'm trying to assign the results of Promise.all() in typescript but somehow Promise.all() changes the return type to number | <actual type>, also when I try to do it inside then()...
Is there a way to do this?

答:
I figured the type change isn't from Promise.all() itself, but from the catch block which returns the result of array.push().

Changing the error handling to:

.catch(err => {
    errors.push(err);
    return {};
});
```

seems to solve this.

ContentLicense: CC BY-SA 4.0

Body:
I figured the type change isn't from Promise.all() itself, but from the catch block which returns the result of array.push().

Changing the error handling to:

.catch(err => {
    errors.push(err);
    return {};
});

seems to solve this.


问:
Spring JPA REST sort by nested property
I have entity Market and Event. Market entity has a column:

```<code>@ManyToOne(fetch = FetchType.EAGER)
private Event event;
</code>```

Next I have a repository:

```<code>public interface MarketRepository extends PagingAndSortingRepository<Market, Long> {
}
</code>```

and a projection:

```<code>@Projection(name="expanded", types={Market.class})
public interface ExpandedMarket {
    public String getName();
    public Event getEvent();
}
</code>```

using REST query /api/markets?projection=expanded&sort=name,asc I get successfully the list of markets with nested event properties ordered by market's name:

```<code>{
    "_embedded" : {
        "markets" : [ {
            "name" : "Match Odds",
            "event" : {
                "id" : 1,
                "name" : "Watford vs Crystal Palace"
            },
            ...
        }, {
            "name" : "Match Odds",
            "event" : {
                "id" : 2,
                "name" : "Arsenal vs West Brom",
            },
            ...
        },
        ...
    }
}
</code>```

But what I need is to get list of markets ordered by event's name, I tried the query /api/markets?projection=expanded&sort=event.name,asc but it didn't work. What should I do to make it work?

答:
This page has an idea that works. The idea is to use a controller on top of the repository, and apply the projection separately.

Here's a piece of code that works (SpringBoot 2.2.4)

```<code>import ro.vdinulescu.AssignmentsOverviewProjection;
import ro.vdinulescu.repository.AssignmentRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RepositoryRestController
public class AssignmentController {
    @Autowired
    private AssignmentRepository assignmentRepository;

    @Autowired
    private ProjectionFactory projectionFactory;

    @Autowired
    private PagedResourcesAssembler<AssignmentsOverviewProjection> resourceAssembler;

    @GetMapping("/assignments")
    public PagedModel<EntityModel<AssignmentsOverviewProjection>> listAssignments(@RequestParam(required = false) String search,
                                                                                @RequestParam(required = false) String sort,
                                                                                Pageable pageable) {
        // Spring creates the Pageable object correctly for simple properties,
        // but for nested properties we need to fix it manually
        pageable = fixPageableSort(pageable, sort, Set.of("client.firstName", "client.age"));

        Page<Assignment> assignments = assignmentRepository.filter(search, pageable);
        Page<AssignmentsOverviewProjection> projectedAssignments = assignments.map(assignment -> projectionFactory.createProjection(
                AssignmentsOverviewProjection.class,
                assignment));

        return resourceAssembler.toModel(projectedAssignments);
    }

    private Pageable fixPageableSort(Pageable pageable, String sortStr, Set<String> allowedProperties) {
        if (!pageable.getSort().equals(Sort.unsorted())) {
            return pageable;
        }

        Sort sort = parseSortString(sortStr, allowedProperties);
        if (sort == null) {
            return pageable;
        }

        return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);
    }

    private Sort parseSortString(String sortStr, Set<String> allowedProperties) {
        if (StringUtils.isBlank(sortStr)) {
            return null;
        }

        String[] split = sortStr.split(",");
        if (split.length == 1) {
            if (!allowedProperties.contains(split[0])) {
                return null;
            }
            return Sort.by(split[0]);
        } else if (split.length == 2) {
            if (!allowedProperties.contains(split[0])) {
                return null;
            }
            return Sort.by(Sort.Direction.fromString(split[1]), split[0]);
        } else {
            return null;
        }
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Spring JPA REST sort by nested property

Body:
I have entity Market and Event. Market entity has a column:

@ManyToOne(fetch = FetchType.EAGER)
private Event event;

Next I have a repository:

public interface MarketRepository extends PagingAndSortingRepository<Market, Long> {
}

and a projection:

@Projection(name="expanded", types={Market.class})
public interface ExpandedMarket {
    public String getName();
    public Event getEvent();
}

using REST query /api/markets?projection=expanded&sort=name,asc I get successfully the list of markets with nested event properties ordered by market's name:

{
    "_embedded" : {
        "markets" : [ {
            "name" : "Match Odds",
            "event" : {
                "id" : 1,
                "name" : "Watford vs Crystal Palace"
            },
            ...
        }, {
            "name" : "Match Odds",
            "event" : {
                "id" : 2,
                "name" : "Arsenal vs West Brom",
            },
            ...
        },
        ...
    }
}

But what I need is to get list of markets ordered by event's name, I tried the query /api/markets?projection=expanded&sort=event.name,asc but it didn't work. What should I do to make it work?

Body:
This page has an idea that works. The idea is to use a controller on top of the repository, and apply the projection separately.

Here's a piece of code that works (SpringBoot 2.2.4)

import ro.vdinulescu.AssignmentsOverviewProjection;
import ro.vdinulescu.repository.AssignmentRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RepositoryRestController
public class AssignmentController {
    @Autowired
    private AssignmentRepository assignmentRepository;

    @Autowired
    private ProjectionFactory projectionFactory;

    @Autowired
    private PagedResourcesAssembler<AssignmentsOverviewProjection> resourceAssembler;

    @GetMapping("/assignments")
    public PagedModel<EntityModel<AssignmentsOverviewProjection>> listAssignments(@RequestParam(required = false) String search,
                                                                                @RequestParam(required = false) String sort,
                                                                                Pageable pageable) {
        // Spring creates the Pageable object correctly for simple properties,
        // but for nested properties we need to fix it manually
        pageable = fixPageableSort(pageable, sort, Set.of("client.firstName", "client.age"));

        Page<Assignment> assignments = assignmentRepository.filter(search, pageable);
        Page<AssignmentsOverviewProjection> projectedAssignments = assignments.map(assignment -> projectionFactory.createProjection(
                AssignmentsOverviewProjection.class,
                assignment));

        return resourceAssembler.toModel(projectedAssignments);
    }

    private Pageable fixPageableSort(Pageable pageable, String sortStr, Set<String> allowedProperties) {
        if (!pageable.getSort().equals(Sort.unsorted())) {
            return pageable;
        }

        Sort sort = parseSortString(sortStr, allowedProperties);
        if (sort == null) {
            return pageable;
        }

        return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);
    }

    private Sort parseSortString(String sortStr, Set<String> allowedProperties) {
        if (StringUtils.isBlank(sortStr)) {
            return null;
        }

        String[] split = sortStr.split(",");
        if (split.length == 1) {
            if (!allowedProperties.contains(split[0])) {
                return null;
            }
            return Sort.by(split[0]);
        } else if (split.length == 2) {
            if (!allowedProperties.contains(split[0])) {
                return null;
            }
            return Sort.by(Sort.Direction.fromString(split[1]), split[0]);
        } else {
            return null;
        }
    }

}


问:
Dissecting Number Ranges
I'm trying to figure out the most efficient way to generate a WHERE query. I asked another question earlier, which was similar, but I will get right to the point on this one.

Given a collection of number ranges, ie 1-1000, 1500-1600 it is quite simple to create a mysql where condition to select records which are between these values.

ie, you would just do:

WHERE (lft BETWEEN 1 and 1000) OR (lft BETWEEN 1500-1600). However, what if you wanted to incorporate a NOT BETWEEN as well.

For example, if you define several rules, like...

ALLOW BETWEEN 1 - 1000

ALLOW BETWEEN 1500 - 1600

ALLOW BETWEEN 1250 - 1300

DENY BETWEEN 25 - 50

How can I merge these rules in order to efficiently generate a WHERE condition.
I would like the WHERE to dissect the ALLOW BETWEEN 1 - 1000 in order to create a gap in it. So that it would become 1-24 and 51-1000. Because the DENY rule is defined after the first rule, it "overwrites" the previous rules.

As another example,
Say that you have

ALLOW BETWEEN 5 - 15

DENY BETWEEN 10 - 50

ALLOW BETWEEN 45 - 60

Then I would like to generate a WHERE condition which would allow me to do:

WHERE (lft BETWEEN 5 and 9) OR (lft BETWEEN 45 and 60).

Notes (Edits)

Also, the maximum range that would ever allowed is 1 - 5600000. (Which would be 'Earth') ie. Allow everything on Earth.

The number ranges are actually the LEFT values in a NESTED SET MODEL. These aren't unique keys.
You can read why I want to do this in this question I asked earlier.
https://stackoverflow.com/questions/6020553/generating-a-mysql-between-where-condition-based-on-an-access-ruleset

Possible important note on my number ranges I maybe shouldn't have used the sample example which I did, but one important note about the nature of the number ranges is that, the ranges should actually always entirely consume or be consumed by a previous rule. For example, I used the example above, 10-50 allow, and deny 45-60. This wouldn't actually ever happen in my data set. It would actually be, allow 10-50, then the DENY would have to either be entirely consumed by that range, ie, 34-38. OR, entirely consume the previous rule. 9-51. This is because the ranges actually represent lft and rgt values in a nested set model and you cannot have overlaps like I presented.

I didn't think to mention that when asking the question, but after seeing the working sample code below, I can see that this note is actually important.

(Edited example mysql to include OR instead of AND as per comment below)

答:
I would process the instructions one at a time creating a list of numbers that should be included.  Then finally translating that list into a set of ranges for the where clause.  Here is some pseudo code:</p>

```<code>$numbers = array();
foreach (conditions as $condition) {
    if ($condition is include) {
        for ($i = $condition.start; $i <= $condition.end; $i++) {
            $numbers[$i] = true;
        }
    } else {
        for ($i = $condition.start; $i <= $condition.end; $i++) {
            unset($numbers[$i]);
        }
    }
}
ksort($numbers);
</code>```

Title: Dissecting Number Ranges

Body:
I would process the instructions one at a time creating a list of numbers that should be included.  Then finally translating that list into a set of ranges for the where clause.  Here is some pseudo code:

$numbers = array();
foreach (conditions as $condition) {
    if ($condition is include) {
        for ($i = $condition.start; $i <= $condition.end; $i++) {
            $numbers[$i] = true;
        }
    } else {
        for ($i = $condition.start; $i <= $condition.end; $i++) {
            unset($numbers[$i]);
        }
    }
}
ksort($numbers);


问:
MongoDB / mongoose order by nested object value where other value is equal to
I have this mongoose Schema:

const PostsSchema = new Schema(
  {
    type: { type: String, default: "house", index: true },
    title: { type: String, required: true },
    descriptiopn: String,
    image: String,
    userId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
      index: true
    },
    details: [{ name: String, label: String, value: Schema.Types.Mixed }]
  },
  { collection: "posts", timestamps: true }
);
```

<p>I'm trying to order the documents by <code>details.value</code> where <code>details.name="something</code>"</p>

<p>For example if one of the details object looks like this:</p>

```{"name":"size", "label":"Size", "value": 50}
```

I want to order by it's value where name="size"

Is there a way to do it or perhaps should I structure the schema differently?

Thanks for the help :)

答:
You can use mongodb aggregation framework.

First we need to $unwind details,  then to be able to first sort by details.name: "size" we are adding a sortPriority field with $addFields, then we are sorting by this sortPriority field and details.value. After sorting we are using $group and $replaceRoot aggregations to shape our collections to back to their original structure.

You can use the following aggregate:

db.collection.aggregate([
  {
    $unwind: "$details"
  },
  {
    $addFields: {
      "details.sortPriority": {
        $eq: [
          "$details.name",
          "size"
        ]
      }
    }
  },
  {
    $sort: {
      "details.sortPriority": -1,
      "details.value": -1
    }
  },
  {
    $project: {
      "details.sortPriority": 0
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "details": {
        "$push": "$details"
      },
      "allFields": {
        "$first": "$$ROOT"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$allFields",
          {
            "details": "$details"
          }
        ]
      }
    }
  }
])
```

<p>Playground</p>

<p>Sample input:</p>

```[
  {
    _id: ObjectId("5a934e000102030405000000"),
    type: "house",
    title: "title 1",
    userId: "user 1",
    details: [
      {
        "name": "size",
        "label": "Size",
        "value": 50
      },
      {
        "name": "size",
        "label": "Size",
        "value": 70
      },
      {
        "name": "color",
        "label": "Color",
        "value": 60
      }
    ]
  },
  {
    _id: ObjectId("5a934e000102030405000001"),
    type: "house",
    title: "title 2",
    userId: "user 2",
    details: [
      {
        "name": "size",
        "label": "Size",
        "value": 10
      },
      {
        "name": "color",
        "label": "Color",
        "value": 20
      },
      {
        "name": "size",
        "label": "color",
        "value": 30
      }
    ]
  }
]
```

<p>Output:</p>

```[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "details": [
      {
        "label": "Size",
        "name": "size",
        "value": 70
      },
      {
        "label": "Size",
        "name": "size",
        "value": 50
      },
      {
        "label": "Color",
        "name": "color",
        "value": 60
      }
    ],
    "title": "title 1",
    "type": "house",
    "userId": "user 1"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "details": [
      {
        "label": "color",
        "name": "size",
        "value": 30
      },
      {
        "label": "Size",
        "name": "size",
        "value": 10
      },
      {
        "label": "Color",
        "name": "color",
        "value": 20
      }
    ],
    "title": "title 2",
    "type": "house",
    "userId": "user 2"
  }
]
```

<p>In mongoose you can use the aggregation using <code>ModelName.aggregate([...])</code></p>

<p>For example if your model ise <code>Post</code>:</p>

<pre class="lang-js prettyprint-override"><code>await Post.aggregate([...]);
</code>```

Body:
I have this mongoose Schema:

const PostsSchema = new Schema(
  {
    type: { type: String, default: "house", index: true },
    title: { type: String, required: true },
    descriptiopn: String,
    image: String,
    userId: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
      index: true
    },
    details: [{ name: String, label: String, value: Schema.Types.Mixed }]
  },
  { collection: "posts", timestamps: true }
);

I'm trying to order the documents by details.value where details.name="something"

For example if one of the details object looks like this:

{"name":"size", "label":"Size", "value": 50}

I want to order by it's value where name="size"

Is there a way to do it or perhaps should I structure the schema differently?

Thanks for the help :)

Body:
You can use mongodb aggregation framework.

First we need to $unwind details,  then to be able to first sort by details.name: "size" we are adding a sortPriority field with $addFields, then we are sorting by this sortPriority field and details.value. After sorting we are using $group and $replaceRoot aggregations to shape our collections to back to their original structure.

You can use the following aggregate:

db.collection.aggregate([
  {
    $unwind: "$details"
  },
  {
    $addFields: {
      "details.sortPriority": {
        $eq: [
          "$details.name",
          "size"
        ]
      }
    }
  },
  {
    $sort: {
      "details.sortPriority": -1,
      "details.value": -1
    }
  },
  {
    $project: {
      "details.sortPriority": 0
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "details": {
        "$push": "$details"
      },
      "allFields": {
        "$first": "$$ROOT"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$allFields",
          {
            "details": "$details"
          }
        ]
      }
    }
  }
])

Playground

Sample input:

[
  {
    _id: ObjectId("5a934e000102030405000000"),
    type: "house",
    title: "title 1",
    userId: "user 1",
    details: [
      {
        "name": "size",
        "label": "Size",
        "value": 50
      },
      {
        "name": "size",
        "label": "Size",
        "value": 70
      },
      {
        "name": "color",
        "label": "Color",
        "value": 60
      }
    ]
  },
  {
    _id: ObjectId("5a934e000102030405000001"),
    type: "house",
    title: "title 2",
    userId: "user 2",
    details: [
      {
        "name": "size",
        "label": "Size",
        "value": 10
      },
      {
        "name": "color",
        "label": "Color",
        "value": 20
      },
      {
        "name": "size",
        "label": "color",
        "value": 30
      }
    ]
  }
]

Output:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "details": [
      {
        "label": "Size",
        "name": "size",
        "value": 70
      },
      {
        "label": "Size",
        "name": "size",
        "value": 50
      },
      {
        "label": "Color",
        "name": "color",
        "value": 60
      }
    ],
    "title": "title 1",
    "type": "house",
    "userId": "user 1"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "details": [
      {
        "label": "color",
        "name": "size",
        "value": 30
      },
      {
        "label": "Size",
        "name": "size",
        "value": 10
      },
      {
        "label": "Color",
        "name": "color",
        "value": 20
      }
    ],
    "title": "title 2",
    "type": "house",
    "userId": "user 2"
  }
]

In mongoose you can use the aggregation using ModelName.aggregate([...])

For example if your model ise Post:

await Post.aggregate([...]);


问:
Create DockerFile from repository
I dont know if it's possible to create a DockerFile from an existing private repository. I created a container and installed an configured the server (i dont remember all the commands), so now I want it to be syncronized with my GitHub account so whenever I push in the branch it updates the changes in the image as well.

For the automatic builds it says that I need a DockerFile but I never created one. Is there an option to automatically create a dockerfile from an exisitng image/container. Using the docker history command doesnt help much because I made the server configurations using docker exec.

Is it possible?

Thanks in advance.

答:
You need to start over.  Docker doesn't remember the commands you ran inside the container either, so it has no way to reconstruct the Dockerfile.  In any case, running docker build will always start from a clean environment, so it's helpful to build your Dockerfile without a bunch of manual installations.

For most languages you can probably easily find a sample Dockerfile by just looking for one.  Most of these are a pretty generic form: start FROM an appropriate base image, install OS dependencies, install library dependencies, COPY the application in, build it, and set runtime metadata like CMD.  You might be able to use one unmodified for popular platforms, since it's a little unusual to mention specific files other than the one that lists your dependencies (Node's package.json, Python's requirements.txt, ...).

You can also build up a Dockerfile by hand fairly easily.  Your secret weapon here is Docker layer caching: if you re-run docker build and nothing has changed up to and including the current line, Docker will skip over it and use the result from the last build.  You can fairly easily docker system prune to get rid of the extra images that got creating during the building process.  So a more incremental process can look like:

Start FROM an appropriate base image

If you want to run some command, add a RUN line and re-run docker build; do not docker exec or try to modify things in place

If that went wrong in an obvious way, modify the RUN line and re-run docker build

If it goes wrong in a non-obvious way, add "debugging printf" lines RUN ls -lrt; or docker build prints out 12-digit hex image IDs as it goes along, so docker run --rm -it 0123456789ab /bin/sh to get a shell to poke around the result of a given step

When you're done, commit the resulting Dockerfile to source control

This is probably very similar to the process you did already, except instead of docker execing a series of commands, you're writing them down in the Dockerfile and building images.

Title: Create DockerFile from repository


问:
Matrix which is 1 when row and column are both odd or both even
I want to create a matrix which which has:

The value 1 if the row is odd and the column is odd

The value 1 if the row is even and the column is even

The value 0 Otherwise.

I want to get the same results as the code below, but in a one line (command window) expression:

```<code> N=8;
 A = zeros(N);

 for row = 1:1:length(A)
     for column = 1:1:length(A)
        if(mod(row,2) == 1 && mod(column,2) == 1)

             A(row,column*(mod(column,2) == 1)) = 1;

         elseif(mod(row,2)== 0 && mod(column,2) == 0 )

             A(row,column*(mod(column,2) == 0)) = 1;

        end
     end
  end
 disp(A)
</code>```

This is the expected result:

```<code> 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
</code>```

答:
Can you take three lines?

```<code>N=8;
A = zeros(N);
A(1:2:end, 1:2:end) = 1;
A(2:2:end, 2:2:end) = 1;
</code>```

One line solution (when N is even):

```<code>A = repmat([1, 0; 0 1], [N/2, N/2]);
</code>```

Body:
I want to create a matrix which which has:

The value 1 if the row is odd and the column is odd

The value 1 if the row is even and the column is even

The value 0 Otherwise.

I want to get the same results as the code below, but in a one line (command window) expression:

 N=8;
 A = zeros(N);

 for row = 1:1:length(A)
     for column = 1:1:length(A)
        if(mod(row,2) == 1 && mod(column,2) == 1)

             A(row,column*(mod(column,2) == 1)) = 1;

         elseif(mod(row,2)== 0 && mod(column,2) == 0 )

             A(row,column*(mod(column,2) == 0)) = 1;

        end
     end
  end
 disp(A)

This is the expected result:

 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1
 1     0     1     0     1     0     1     0
 0     1     0     1     0     1     0     1

Body:
Can you take three lines?

N=8;
A = zeros(N);
A(1:2:end, 1:2:end) = 1;
A(2:2:end, 2:2:end) = 1;

One line solution (when N is even):

A = repmat([1, 0; 0 1], [N/2, N/2]);


问:
return type of function inferred incorrectly if the return statement is outside a switch statement
given

```<code>const ACTION_1 = "ACTION_1";
type ACTION_1 = "ACTION_1";

const ACTION_2 = "ACTION_2";
type ACTION_2 = "ACTION_2";

type ActionTypes =
  | ACTION_1
  | ACTION_2

export type Reducer<S = any> = (
  state: S | undefined,
  action: ActionTypes
) => S
</code>```

when I have this Reducer:

```<code>const reducer: Reducer<boolean> = (
  state = false,
  action
) => {
  switch (action) {
    case ACTION_1:
       return true;
    case ACTION_2:
       return false;
    default:
  }
  return state;
}
</code>```

in strict mode it complains that this function has a return type of IState | undefined but when I swap the return state; at the end for a default: return state in the switch statement it is fine. Or even just an empty default: and leaving the return statement at the bottom will, placate the compiler.

With the return type it even recognises in vscode that the return statement is unreachable. I understand it has to take it into account because run time it doesn't know if the switch statement was actually exhaustive.

But even if I have the default, it does know the return is definitely unreachable and still it complains about the fact this function could return IState | undefined.

And even that is wrong because there's a default value for the state parameter. So it is never undefined.

Is this a bug? Or a known limitation?

Playground Link

答: This was fixed in typescript version 3.8.</p>

Body:
given

const ACTION_1 = "ACTION_1";
type ACTION_1 = "ACTION_1";

const ACTION_2 = "ACTION_2";
type ACTION_2 = "ACTION_2";

type ActionTypes =
  | ACTION_1
  | ACTION_2

export type Reducer<S = any> = (
  state: S | undefined,
  action: ActionTypes
) => S

when I have this Reducer:

const reducer: Reducer<boolean> = (
  state = false,
  action
) => {
  switch (action) {
    case ACTION_1:
       return true;
    case ACTION_2:
       return false;
    default:
  }
  return state;
}

in strict mode it complains that this function has a return type of IState | undefined but when I swap the return state; at the end for a default: return state in the switch statement it is fine. Or even just an empty default: and leaving the return statement at the bottom will, placate the compiler.

With the return type it even recognises in vscode that the return statement is unreachable. I understand it has to take it into account because run time it doesn't know if the switch statement was actually exhaustive.

But even if I have the default, it does know the return is definitely unreachable and still it complains about the fact this function could return IState | undefined.

And even that is wrong because there's a default value for the state parameter. So it is never undefined.

Is this a bug? Or a known limitation?

Playground Link


问:
How to use MouseMotion ints in another method
So basically I'm playing around with Graphics and bunch fun things which I want to know before making a game I want to know different ways of how I can use different loops to do some fun things but I cannot figure out how I can use the INT I make in the method of mouseMoved and then use it in the Graphics Method. The code might show a better example of what I'm trying to explain.

```<code>package com.martin;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.*;

public class Grids extends JFrame implements MouseMotionListener {

    JPanel p = new JPanel();

    public int width = 1200;
    public int height = 800;

    public Grids() {
        addMouseMotionListener(this);
        windowLoader();
    }

    public static void main(String[] args){
        new Grids();
    }
    public void windowLoader() {
        setPreferredSize(new Dimension(width, height));
        setMaximumSize(new Dimension(width, height));
        setMinimumSize(new Dimension(width, height));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
//        setBackground(Color.BLACK);

        p.setSize(width, height);
        p.setOpaque(false);
//        p.setBackground(Color.BLACK);
        add(p);

        pack();
        setVisible(true);
    }

    public void mouseMoved(MouseEvent e) {
        double mouseX = e.getX();
        double mouseY = e.getY();

    }
    public void mouseDragged(MouseEvent e) {
    }

    public void paint(Graphics g) {
        Random rand = new Random();

        int cols, rows;
        int size = 8;
        Color color;

        for (rows = 0; rows < width; rows++) {
            for (cols = 0; cols < height; cols++) {
                color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));

//                g.setColor(color);
//                g.fillRect(rows * size, cols * size, size, size);

//                g.drawRect(rows * size, cols * size, size, size);

//                g.drawLine(rows * size, cols * size, size, size);

//                g.drawRoundRect(rows * size, cols * size, size, size, 10, 10);

//                g.fillRoundRect(rows * size, cols * size, size, size, 10, 10);
            }
        }
//        int x = 0;
//        int y = 0;
//        int spacing = rand.nextInt(20) + 1;
//
//        while (spacing > -1) {
//            spacing = spacing + rand.nextInt(20);
//        }
//
//        while (x < width) {
//            g.drawLine(x, 0, x, height);
//            x = x + spacing;
//        }
//        while (y < height) {
//            g.drawLine(0, y, width, y);
//            y = y + spacing;
//        }

//        Point mouseL = MouseInfo.getPointerInfo().getLocation();

//        double mouseX = mouseL.getX();
//        double mouseY = mouseL.getY();
        int x = 0, y = 0;

//Can't access the int from the mouseMoved I get red underline for error (variable cannot be found)

        while (x < width) {
            if (mouseX < 1) {
                x = x + 10;
            } else {
                x = x + (int)mouseX;
            }
            while (y < height) {
                if (mouseY < 1) {
                    y = y + 10;
                } else {
                    y = y + (int)mouseY;
                }
                g.fillRoundRect(x, y, 10, 10, 10, 10);
            }
        }

        repaint();
    }
}
</code>```

This is the whole code and I tried using the MouseInfo to get the pointer location but it gets the location of the JFrame component and I want to get the mouse location on the JFrame itself and not off the component.

答:
I believe the following mre demonstrates the functionality you want.

Use drawTrail to turn trail drawing on or off:

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Grids extends JPanel implements MouseMotionListener {

    public final static int WIDTH = 1200, HEIGHT = 800, POINT_SIZE = 10;
    private double mouseX, mouseY;
    private List<Point> points ; //stores all trail points
    private boolean drawTrail = true; //change to false to draw only one point at the mouse location

    public Grids() {
        addMouseMotionListener(this);
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.WHITE);
        if(drawTrail) {
            points = new ArrayList<>(); //add mouse point to collection
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {

        //set a min distance between points
        if( Math.abs(mouseX - e.getX()) >= POINT_SIZE || Math.abs(mouseY - e.getY()) >= POINT_SIZE ) {
            if(drawTrail) {
                points.add(new Point(e.getX(),e.getY()));
            }
            mouseX = e.getX();
            mouseY = e.getY();
            repaint();
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Random rand = new Random();

        if(drawTrail){
            //draw all collected points
            for (Point p : points){
                Color color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
                g.setColor(color);
                g.fillOval(p.x, p.y, POINT_SIZE, POINT_SIZE);
            }
        }else{
            //if you only want the point at the
            Color color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
            g.setColor(color);
            g.fillOval((int)mouseX, (int)mouseY, POINT_SIZE, POINT_SIZE);
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {/*todo*/}

    public static void main(String[] args0) {
        JFrame frame = new JFrame();
        frame.add(new Grids());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }
}
</code>```

Body:
So basically I'm playing around with Graphics and bunch fun things which I want to know before making a game I want to know different ways of how I can use different loops to do some fun things but I cannot figure out how I can use the INT I make in the method of mouseMoved and then use it in the Graphics Method. The code might show a better example of what I'm trying to explain.

package com.martin;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.*;

public class Grids extends JFrame implements MouseMotionListener {

    JPanel p = new JPanel();

    public int width = 1200;
    public int height = 800;

    public Grids() {
        addMouseMotionListener(this);
        windowLoader();
    }

    public static void main(String[] args){
        new Grids();
    }
    public void windowLoader() {
        setPreferredSize(new Dimension(width, height));
        setMaximumSize(new Dimension(width, height));
        setMinimumSize(new Dimension(width, height));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
//        setBackground(Color.BLACK);

        p.setSize(width, height);
        p.setOpaque(false);
//        p.setBackground(Color.BLACK);
        add(p);

        pack();
        setVisible(true);
    }

    public void mouseMoved(MouseEvent e) {
        double mouseX = e.getX();
        double mouseY = e.getY();

    }
    public void mouseDragged(MouseEvent e) {
    }

    public void paint(Graphics g) {
        Random rand = new Random();

        int cols, rows;
        int size = 8;
        Color color;

        for (rows = 0; rows < width; rows++) {
            for (cols = 0; cols < height; cols++) {
                color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));

//                g.setColor(color);
//                g.fillRect(rows * size, cols * size, size, size);

//                g.drawRect(rows * size, cols * size, size, size);

//                g.drawLine(rows * size, cols * size, size, size);

//                g.drawRoundRect(rows * size, cols * size, size, size, 10, 10);

//                g.fillRoundRect(rows * size, cols * size, size, size, 10, 10);
            }
        }
//        int x = 0;
//        int y = 0;
//        int spacing = rand.nextInt(20) + 1;
//
//        while (spacing > -1) {
//            spacing = spacing + rand.nextInt(20);
//        }
//
//        while (x < width) {
//            g.drawLine(x, 0, x, height);
//            x = x + spacing;
//        }
//        while (y < height) {
//            g.drawLine(0, y, width, y);
//            y = y + spacing;
//        }

//        Point mouseL = MouseInfo.getPointerInfo().getLocation();

//        double mouseX = mouseL.getX();
//        double mouseY = mouseL.getY();
        int x = 0, y = 0;

//Can't access the int from the mouseMoved I get red underline for error (variable cannot be found)

        while (x < width) {
            if (mouseX < 1) {
                x = x + 10;
            } else {
                x = x + (int)mouseX;
            }
            while (y < height) {
                if (mouseY < 1) {
                    y = y + 10;
                } else {
                    y = y + (int)mouseY;
                }
                g.fillRoundRect(x, y, 10, 10, 10, 10);
            }
        }

        repaint();
    }
}

This is the whole code and I tried using the MouseInfo to get the pointer location but it gets the location of the JFrame component and I want to get the mouse location on the JFrame itself and not off the component.

Body:
I believe the following mre demonstrates the functionality you want.

Use drawTrail to turn trail drawing on or off:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Grids extends JPanel implements MouseMotionListener {

    public final static int WIDTH = 1200, HEIGHT = 800, POINT_SIZE = 10;
    private double mouseX, mouseY;
    private List<Point> points ; //stores all trail points
    private boolean drawTrail = true; //change to false to draw only one point at the mouse location

    public Grids() {
        addMouseMotionListener(this);
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.WHITE);
        if(drawTrail) {
            points = new ArrayList<>(); //add mouse point to collection
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {

        //set a min distance between points
        if( Math.abs(mouseX - e.getX()) >= POINT_SIZE || Math.abs(mouseY - e.getY()) >= POINT_SIZE ) {
            if(drawTrail) {
                points.add(new Point(e.getX(),e.getY()));
            }
            mouseX = e.getX();
            mouseY = e.getY();
            repaint();
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Random rand = new Random();

        if(drawTrail){
            //draw all collected points
            for (Point p : points){
                Color color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
                g.setColor(color);
                g.fillOval(p.x, p.y, POINT_SIZE, POINT_SIZE);
            }
        }else{
            //if you only want the point at the
            Color color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
            g.setColor(color);
            g.fillOval((int)mouseX, (int)mouseY, POINT_SIZE, POINT_SIZE);
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {/*todo*/}

    public static void main(String[] args0) {
        JFrame frame = new JFrame();
        frame.add(new Grids());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }
}


问:
How to move focus from "skip to main content" to an iframe and access iframe content in JAWS?
Scenario:

In my application, content in Iframe is loading from server side and entire markup comes from the backend. There is navigation menu buttons in the main html page and Skip to main content link. Role for the iframe body is given as "application"(also tried with document). When Skip to main content is removed, the JAWS read the iframe content as expected, but as soon as "Skip to main content" section is enabled, JAWS reads just the first line inside iframe. What aria role or property I should add, such that when focus is moved from "skip to main content" to iframe, JAWS should start reading the entire content inside iframe?

Sample code used to move focus inside iframe:

```<code>window.skipNav = function(event) {
switch(event.type)
{
case "keydown":
if (event && event.keyCode == 13) {
setTimeout(setFocusIframe, 100);
}
break;
case "click":
setTimeout(setFocusIframe, 100);
break;
default:
break;

}

}

function setFocusIframe() {
this.iframe[0].contentWindow.document.body.focus()
// var f = jQuery("iframe:first")
// if(f.length > 0) {
// //f[0].contentWindow.document.body.focus();
// f[0].contentWindow.focus();
// console.log("skipNav-------------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
// }
}
</code>```

答:
Try to check if document.activeElement returns the element you are trying to focus on.

Sometimes jQuery .focus() fucntion dont do what you expect.

Body:
Scenario:

In my application, content in Iframe is loading from server side and entire markup comes from the backend. There is navigation menu buttons in the main html page and Skip to main content link. Role for the iframe body is given as "application"(also tried with document). When Skip to main content is removed, the JAWS read the iframe content as expected, but as soon as "Skip to main content" section is enabled, JAWS reads just the first line inside iframe. What aria role or property I should add, such that when focus is moved from "skip to main content" to iframe, JAWS should start reading the entire content inside iframe?

Sample code used to move focus inside iframe:

window.skipNav = function(event) {
switch(event.type)
{
case "keydown":
if (event && event.keyCode == 13) {
setTimeout(setFocusIframe, 100);
}
break;
case "click":
setTimeout(setFocusIframe, 100);
break;
default:
break;

}

}

function setFocusIframe() {
this.iframe[0].contentWindow.document.body.focus()
// var f = jQuery("iframe:first")
// if(f.length > 0) {
// //f[0].contentWindow.document.body.focus();
// f[0].contentWindow.focus();
// console.log("skipNav-------------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
// }
}


问:
How can I merge 2 dictionaries into one array?
My JSON data look like this image below. Now I wanna merge the value of Shop Type and Promotion into one to use as collection view data. How can I do that?

I just filter the response data from the server like this:

```<code>        var dataBanDau: [SDFilterModel] = []
        var quickData: [SDFilterModel] = []

        let filters: [SDFilterModel] = data

        self.filterEntries = filters

        //let nsarray = NSArray(array: self.filterEntries! , copyItems: true)
//            self.filterEntriesStoreConstant = nsarray as! Array

        self.dataBanDau = filters

        for i in 0..<self.dataBanDau.count {
            if self.dataBanDau[i].search_key.count == 0 {
                self.quickData.append(self.dataBanDau[i])
            }
        }

        self.quickData = self.quickData.filter {
            $0.type != "range"
        }

        DispatchQueue.main.async {
            //Note: Reload TableView
            self.quickFilterCollection.reloadData()
            completed(true)
        }
    }
</code>```

the class SDFilterModel:

```<code>class SDFilterModel: DSBaseModel {
    var name = String()
    var type = String()
    var is_expanded = Int()
    var search_key = String()
    var filterEntries : [SDFilterModel]?

    override func copy(with zone: NSZone? = nil) -> Any {
        // This is the reason why `init(_ model: GameModel)`
        // must be required, because `GameModel` is not `final`.
        let copy = SDFilterModel(dict: self.dictionary)

        if let arrAttribute = NSArray(array: self.value , copyItems: true) as? [AttributeValueModel] {
            copy.value = arrAttribute
        }

        return copy
    }

    override init(dict: Dictionary<String, Any>) {
        super.init(dict: dict);
        value = self.valueParse()

        name = dict.getString(forKey: "name")
        type = dict.getString(forKey: "type")
        search_key = dict.getString(forKey: "search_key")
        is_expanded = dict.getInt(forKey: "is_expanded")!
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var value: [AttributeValueModel] = [];

    func valueParse()-> [AttributeValueModel] {
        guard let childs  = (self.dictionary["value"]) as? [Dictionary<String, AnyObject>]
            else { return [] }

        var output: [AttributeValueModel] = [];

        for  aDict in childs {
            let item = AttributeValueModel(dict:aDict);

//            if type == .Range  && item.option_id == "0" {
//                item.setRangeOptionID(aValue: item.option_name!)
//            }
//
            output.append(item);
        }

        return output;
    }
</code>```

答:
Create the models like this

```<code>struct Option {
    let name: String
    let searchKey: String
    let id: String
}

struct Model {
    let type: String
    let name: String
    let isExpanded: Bool
    let value: [Option]
}
</code>```

You should get the options array values and join all the arrays

```<code>let models:[Model] = //...
let collectionViewArray = models.map { $0.value }.reduce([Option](), +)
</code>```

Using for loop

```<code>var collectionViewArray = [Option]()
for model  in models {
    collectionViewArray.append(contentsOf: model.value)
}
</code>```

Body:
My JSON data look like this image below. Now I wanna merge the value of Shop Type and Promotion into one to use as collection view data. How can I do that?

I just filter the response data from the server like this:

        var dataBanDau: [SDFilterModel] = []
        var quickData: [SDFilterModel] = []

        let filters: [SDFilterModel] = data

        self.filterEntries = filters

        //let nsarray = NSArray(array: self.filterEntries! , copyItems: true)
//            self.filterEntriesStoreConstant = nsarray as! Array

        self.dataBanDau = filters

        for i in 0..<self.dataBanDau.count {
            if self.dataBanDau[i].search_key.count == 0 {
                self.quickData.append(self.dataBanDau[i])
            }
        }

        self.quickData = self.quickData.filter {
            $0.type != "range"
        }

        DispatchQueue.main.async {
            //Note: Reload TableView
            self.quickFilterCollection.reloadData()
            completed(true)
        }
    }

the class SDFilterModel:

class SDFilterModel: DSBaseModel {
    var name = String()
    var type = String()
    var is_expanded = Int()
    var search_key = String()
    var filterEntries : [SDFilterModel]?

    override func copy(with zone: NSZone? = nil) -> Any {
        // This is the reason why `init(_ model: GameModel)`
        // must be required, because `GameModel` is not `final`.
        let copy = SDFilterModel(dict: self.dictionary)

        if let arrAttribute = NSArray(array: self.value , copyItems: true) as? [AttributeValueModel] {
            copy.value = arrAttribute
        }

        return copy
    }

    override init(dict: Dictionary<String, Any>) {
        super.init(dict: dict);
        value = self.valueParse()

        name = dict.getString(forKey: "name")
        type = dict.getString(forKey: "type")
        search_key = dict.getString(forKey: "search_key")
        is_expanded = dict.getInt(forKey: "is_expanded")!
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var value: [AttributeValueModel] = [];

    func valueParse()-> [AttributeValueModel] {
        guard let childs  = (self.dictionary["value"]) as? [Dictionary<String, AnyObject>]
            else { return [] }

        var output: [AttributeValueModel] = [];

        for  aDict in childs {
            let item = AttributeValueModel(dict:aDict);

//            if type == .Range  && item.option_id == "0" {
//                item.setRangeOptionID(aValue: item.option_name!)
//            }
//
            output.append(item);
        }

        return output;
    }

Body:
Create the models like this

struct Option {
    let name: String
    let searchKey: String
    let id: String
}

struct Model {
    let type: String
    let name: String
    let isExpanded: Bool
    let value: [Option]
}

You should get the options array values and join all the arrays

let models:[Model] = //...
let collectionViewArray = models.map { $0.value }.reduce([Option](), +)

Using for loop

var collectionViewArray = [Option]()
for model  in models {
    collectionViewArray.append(contentsOf: model.value)
}


问:
{Flex: 1} not working with relative positioning
I want the second View to be relatively positioned at -50 below the first View, but the second View does not extend completely at the bottom.

```<code>import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1, backgroundColor: 'blue', top: 0}} />
    </View>
  );
};
</code>```

```<code>import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1, backgroundColor: 'blue', top: -50}} />
    </View>
  );
};
</code>```

You can see at the bottom there are 50 pixels that are white.

答:
Try below snippets

<View style={{ flex: 1, position: "relative" }}>
          <View
            style={{
              height: 100,
              backgroundColor: "red",
              position: "absolute",
              top: 0,
              zIndex: 1,
              width: "100%"
            }}
          >
            <Text>OverlayStorybook</Text>
          </View>
          <View
            style={{
              flex: 1,
              border: "1px solid green",
              marginTop: 50,
              zIndex: 2
            }}
          />
        </View>```

Body:
I want the second View to be relatively positioned at -50 below the first View, but the second View does not extend completely at the bottom.

import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1, backgroundColor: 'blue', top: 0}} />
    </View>
  );
};

import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1, backgroundColor: 'blue', top: -50}} />
    </View>
  );
};

You can see at the bottom there are 50 pixels that are white.


问:
I want default argument promotion's example
At C standard 6.5.2.2. paragraph 6

If the expression that denotes the called function has a type that does not include a prototype, the
  integer promotions are performed on each argument, and arguments that have type float are
  promoted to double. These are called the default argument promotions.

"the expression that denotes the called function has a type that does not include a prototype" What can this be described as code?

```<code>char a = 1;
printf("%d", a); /*"the expression that denotes the called function" is printf, and `a`
doesn't have prototype(char). but a can't be replaced as `char a` originally.  ...? */
</code>```

This is my thought that can be applicable to above standard. Is this right?

答:
For historical reasons, functions in C can be declared the old way, without a prototype, as:

```<code>type function()
</code>```

or the new way, with a prototype, as:

```<code>type function(type parameter)
type function(type parameter, type parameter)
type function(type parameter, type parameter, type parameter)
… and so on
</code>```

Thus, a function declaration in which the types of the parameters are given is said to have a prototype. This affects preparation of the arguments when calling a function. With a prototype, the arguments are converted to the declared types of the parameters. Without a prototype, the arguments are converted to default types, using rules called the default argument promotions. (Also, if a function is just being declared, not defined, the names of the parameters can be omitted, leaving a prototype that just lists types, as in type function(type, type, type).)

Because of the old grammar, to declare a function with a prototype that says it has no parameters, you need to explicitly say void: type function(void). (This is different in C++, which does not have to support the old grammar. In C++, type function() is a prototype with no parameters.)

Additionally, a prototype can specify that there are variable arguments by putting ,... after one or more regular parameters:

```<code>type function(type parameter,...)
</code>```

In this case, the first arguments are converted to the parameter types, but the arguments that correspond to the ... are converted using the default argument promotions. printf is declared this way.

The default argument promotions are:

Integers narrower (technically, of lesser rank) than int are promoted to int if it can represent all the values of the source type or unsigned int otherwise.

float arguments are converted to double.

There is also some finickiness about bit-fields in the default argument promotions, which I cannot say has ever arisen in code for me.

History

In the old C grammar, a function would be defined with:

```<code>type function(name0, name1, name2)
type name0;
type name1;
type name2;
</code>```

and it would be declared without a prototype, as with type function(). This means the caller did not know the actual types of the parameters. But you could not just pass a char value for a char argument or a short value for a short argument, because C, in trying to be flexible so it could work on many types of computers, had rules about char and short values being promoted to int in expressions. Additionally, character constants like 'X' have type int, not char, so, if somebody called a function with foo('X'), the compiler would not know if foo really wanted just a char rather than an int. So the default argument promotions were made to match the integer promotions.

Later versions of C fixed this by providing a way to declare the argument types in declarations visible to the caller, so the arguments always match the parameters (and the compiler has more information it can use to provide error messages). But the old grammar still has to be supported so that old code can be compiled.

More

The phrase in the C standard, “the expression that denotes the called function,” is used because you can call functions through pointers, not just their names. For example, we can write:

```<code>    int (*FunctionPointer)() = (int (*)()) printf;
</code>```

and then call printf using FunctionPointer("Hello, world.\n");. Then “the expression that denotes the called function” is FunctionPointer, and it does not have a prototype even though printf does. (There is no good reason to do this with the printf function, but some esoteric code may do some unsavory things.)

You can initially declare a function without a prototype:

```<code>int foo();
</code>```

and later add a prototype:

```<code>int foo(float x, char *y);
</code>```

The compiler will merge the declarations, and the resulting foo will have a prototype.

Body:
At C standard 6.5.2.2. paragraph 6

If the expression that denotes the called function has a type that does not include a prototype, the
  integer promotions are performed on each argument, and arguments that have type float are
  promoted to double. These are called the default argument promotions.

"the expression that denotes the called function has a type that does not include a prototype" What can this be described as code?

char a = 1;
printf("%d", a); /*"the expression that denotes the called function" is printf, and `a`
doesn't have prototype(char). but a can't be replaced as `char a` originally.  ...? */

This is my thought that can be applicable to above standard. Is this right?

Body:
For historical reasons, functions in C can be declared the old way, without a prototype, as:

type function()

or the new way, with a prototype, as:

type function(type parameter)
type function(type parameter, type parameter)
type function(type parameter, type parameter, type parameter)
… and so on

Thus, a function declaration in which the types of the parameters are given is said to have a prototype. This affects preparation of the arguments when calling a function. With a prototype, the arguments are converted to the declared types of the parameters. Without a prototype, the arguments are converted to default types, using rules called the default argument promotions. (Also, if a function is just being declared, not defined, the names of the parameters can be omitted, leaving a prototype that just lists types, as in type function(type, type, type).)

Because of the old grammar, to declare a function with a prototype that says it has no parameters, you need to explicitly say void: type function(void). (This is different in C++, which does not have to support the old grammar. In C++, type function() is a prototype with no parameters.)

Additionally, a prototype can specify that there are variable arguments by putting ,... after one or more regular parameters:

type function(type parameter,...)

In this case, the first arguments are converted to the parameter types, but the arguments that correspond to the ... are converted using the default argument promotions. printf is declared this way.

The default argument promotions are:

Integers narrower (technically, of lesser rank) than int are promoted to int if it can represent all the values of the source type or unsigned int otherwise.

float arguments are converted to double.

There is also some finickiness about bit-fields in the default argument promotions, which I cannot say has ever arisen in code for me.

History

In the old C grammar, a function would be defined with:

type function(name0, name1, name2)
type name0;
type name1;
type name2;

and it would be declared without a prototype, as with type function(). This means the caller did not know the actual types of the parameters. But you could not just pass a char value for a char argument or a short value for a short argument, because C, in trying to be flexible so it could work on many types of computers, had rules about char and short values being promoted to int in expressions. Additionally, character constants like 'X' have type int, not char, so, if somebody called a function with foo('X'), the compiler would not know if foo really wanted just a char rather than an int. So the default argument promotions were made to match the integer promotions.

Later versions of C fixed this by providing a way to declare the argument types in declarations visible to the caller, so the arguments always match the parameters (and the compiler has more information it can use to provide error messages). But the old grammar still has to be supported so that old code can be compiled.

More

The phrase in the C standard, “the expression that denotes the called function,” is used because you can call functions through pointers, not just their names. For example, we can write:

    int (*FunctionPointer)() = (int (*)()) printf;

and then call printf using FunctionPointer("Hello, world.\n");. Then “the expression that denotes the called function” is FunctionPointer, and it does not have a prototype even though printf does. (There is no good reason to do this with the printf function, but some esoteric code may do some unsavory things.)

You can initially declare a function without a prototype:

int foo();

and later add a prototype:

int foo(float x, char *y);

The compiler will merge the declarations, and the resulting foo will have a prototype.


问:
how to fill missing values in a vector with the mean of value before and after the missing one
Currently I am trying to impute values in a vector in R. The conditions
of the imputation are.

Find all NA values

Then check if they have an existing value before and after them

Also check if the value which follows the NA is larger than
the value before the NA

If the conditions are met, calculate a mean taking the values before
and after.

Replace the NA value with the imputed one

```<code># example one
input_one = c(1,NA,3,4,NA,6,NA,NA)

# example two
input_two = c(NA,NA,3,4,5,6,NA,NA)

# example three
input_three = c(NA,NA,3,4,NA,6,NA,NA)

</code>```

I started out to write code to detect the values which can
be imputed. But I got stuck with the following.

```<code># incomplete function to detect the values
sapply(split(!is.na(input[c(rbind(which(is.na(c(input)))-1, which(is.na(c(input)))+1))]),
             rep(1:(length(!is.na(input[c(which(is.na(c(input)))-1, which(is.na(c(input)))+1)]))/2), each = 2)), all)
</code>```

This however only detects the NAs which might be
imputable and it only works with example one. It is incomplete and
unfortunately super hard to read and understand.

Any help with this would be highly appreciated.

答:
We can use dplyrs lag and lead functions for that:

```<code>input_three = c(NA,NA,3,4,NA,6,NA,NA)

library(dplyr)
ifelse(is.na(input_three) & lead(input_three) > lag(input_three),
       (lag(input_three)  + lead(input_three))/ 2,
       input_three)
</code>```

Retrurns:

```<code>[1] NA NA  3  4  5  6 NA NA
</code>```

Edit

Explanation:

We use ifelse which is the vectorized version of if. I.e. everything within ifelse will be applied to each element of the vectors.
First we test if the elements are NA and if the following element is > than the previous. To get the previous and following element we can use dplyr lead and lag functions:

lag offsets a vector to the right (default is 1 step):

```<code>lag(1:5)
</code>```

Returns:

```<code>[1] NA  1  2  3  4
</code>```

lead offsets a vector to the left:

```<code>lead(1:5)
</code>```

Returns:

```<code>[1]  2  3  4  5 NA
</code>```

Now to the 'test' clause of ifelse:

```<code>is.na(input_three) & lead(input_three) > lag(input_three)
</code>```

Which returns:

```<code>[1]    NA    NA FALSE FALSE  TRUE FALSE    NA    NA
</code>```

Then if the ifelse clause evaluates to TRUE we want to return the sum of the previous and following element divided by 2, othrwise return the original element

Body:
Currently I am trying to impute values in a vector in R. The conditions
of the imputation are.

Find all NA values

Then check if they have an existing value before and after them

Also check if the value which follows the NA is larger than
the value before the NA

If the conditions are met, calculate a mean taking the values before
and after.

Replace the NA value with the imputed one

# example one
input_one = c(1,NA,3,4,NA,6,NA,NA)

# example two
input_two = c(NA,NA,3,4,5,6,NA,NA)

# example three
input_three = c(NA,NA,3,4,NA,6,NA,NA)

I started out to write code to detect the values which can
be imputed. But I got stuck with the following.

# incomplete function to detect the values
sapply(split(!is.na(input[c(rbind(which(is.na(c(input)))-1, which(is.na(c(input)))+1))]),
             rep(1:(length(!is.na(input[c(which(is.na(c(input)))-1, which(is.na(c(input)))+1)]))/2), each = 2)), all)

This however only detects the NAs which might be
imputable and it only works with example one. It is incomplete and
unfortunately super hard to read and understand.

Any help with this would be highly appreciated.

Body:
We can use dplyrs lag and lead functions for that:

input_three = c(NA,NA,3,4,NA,6,NA,NA)

library(dplyr)
ifelse(is.na(input_three) & lead(input_three) > lag(input_three),
       (lag(input_three)  + lead(input_three))/ 2,
       input_three)

Retrurns:

[1] NA NA  3  4  5  6 NA NA

Edit

Explanation:

We use ifelse which is the vectorized version of if. I.e. everything within ifelse will be applied to each element of the vectors.
First we test if the elements are NA and if the following element is > than the previous. To get the previous and following element we can use dplyr lead and lag functions:

lag offsets a vector to the right (default is 1 step):

lag(1:5)

Returns:

[1] NA  1  2  3  4

lead offsets a vector to the left:

lead(1:5)

Returns:

[1]  2  3  4  5 NA

Now to the 'test' clause of ifelse:

is.na(input_three) & lead(input_three) > lag(input_three)

Which returns:

[1]    NA    NA FALSE FALSE  TRUE FALSE    NA    NA

Then if the ifelse clause evaluates to TRUE we want to return the sum of the previous and following element divided by 2, othrwise return the original element


问:
Xcode, Pods ProjectName.debug.xcconfig unable to open file. Wrong directory
When I build project, I see build error: ProjectName.debug.xcconfig unable to open file. I couldn't understand my problem for a long time, but today I take attention, what directory is wrong: full error: projectName/Pods/Pods...ProjectName.debug.xcconfig unable to open file Where Pods part duplicated, so correct directory must be as projectName/Pods...ProjectName.debug.xcconfig How to fix it?

答: Remove the duplicates from the Pods folder ƒrom xcode project here:


问:
Substracting every nth element of a matrix from every ith element from another matrix
I have two matrices

```<code>A = [a,b,c,d,e,f,g,h,i,j,k,l]
B = [w,x,y,z]
</code>```

I want to substract like [a,e,i] from w and [b,,f,j] from x like that.
All these letters are floats. The results will be in an array.

Could you assist how to substract every n-th element ofa matrix from every i-th element from another matrix?

答:
You can first reshape your array to a 4×3 matrix, then subtract it, and then reshape it back. For example:

```<code>(A.reshape(-1, 4) - B).flatten()
</code>```

For example:

```<code>>>> A
array([8, 7, 1, 4, 6, 2, 5, 4, 6, 8, 8, 1])
>>> B
array([7, 4, 2, 1])
>>> (A.reshape(-1,4) - B).flatten()
array([ 1,  3, -1,  3, -1, -2,  3,  3, -1,  4,  6,  0])
</code>```

Body:
I have two matrices

A = [a,b,c,d,e,f,g,h,i,j,k,l]
B = [w,x,y,z]

I want to substract like [a,e,i] from w and [b,,f,j] from x like that.
All these letters are floats. The results will be in an array.

Could you assist how to substract every n-th element ofa matrix from every i-th element from another matrix?

Body:
You can first reshape your array to a 4×3 matrix, then subtract it, and then reshape it back. For example:

(A.reshape(-1, 4) - B).flatten()

For example:

>>> A
array([8, 7, 1, 4, 6, 2, 5, 4, 6, 8, 8, 1])
>>> B
array([7, 4, 2, 1])
>>> (A.reshape(-1,4) - B).flatten()
array([ 1,  3, -1,  3, -1, -2,  3,  3, -1,  4,  6,  0])


问:
Arrange values within a specific group
I'm trying to arrange values in decreasing order within a exact group in a nested dataframe. My input data looks like this. I've got two grouping variables (group1 and group2) and three values (i.e. id, value2, value3).

```<code>library(tidyverse)
set.seed(1234)

df <- tibble(group1 = c(rep(LETTERS[1:3], 4)),
             group2 = c(rep(0, 6), rep(2, 6)),
             value2 = rnorm(12, 20, sd = 10),
             value3 = rnorm(12, 20, sd = 50)) %>%
  group_by(group1) %>%
  mutate(id = c(1:4)) %>%
  ungroup()
</code>```

I decided to group them by group1 and group2 and then nest():

```<code>df_nested <- df %>%
  group_by(group1, group2) %>%
  nest()

# A tibble: 6 x 3
# Groups:   group1, group2 [6]
  group1 group2 data
  <chr>   <dbl> <list>
1 A           0 <tibble [2 x 3]>
2 B           0 <tibble [2 x 3]>
3 C           0 <tibble [2 x 3]>
4 A           2 <tibble [2 x 3]>
5 B           2 <tibble [2 x 3]>
6 C           2 <tibble [2 x 3]>
</code>```

Perfect. Now I need to sort only those data which group2 is equal to 2 by id. However I'm receiving a following error:

```<code>df_nested %>%
  mutate(data = map2_df(.x = data, .y = group2,
                     ~ifelse(.y == 2, arrange(-.x$id),
                             .x)))
</code>```

Error: Argument 1 must have names

答:
You could do :

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

df_nested$data <- map2(df_nested$data, df_nested$group2,~if(.y == 2)
                       arrange(.x, -.x$id) else .x)
</code>```

So data where group2 is not equal to 2 is not sorted

```<code>df_nested$data[[1]]
# A tibble: 2 x 3
#  value2 value3    id
#   <dbl>  <dbl> <int>
#1  13.1  -89.0      1
#2   9.76  -3.29     2
</code>```

and where group2 is 2 is sorted.

```<code>df_nested$data[[4]]
# A tibble: 2 x 3
#value2 value3    id
# <dbl>  <dbl> <int>
#1   15.0  -28.4   4
#2   31.0  -22.8   3
</code>```

If you want to combine them do :

```<code>map2_df(df_nested$data, df_nested$group2,~if(.y == 2) arrange(.x, -.x$id) else .x)
</code>```

Title: Arrange values within a specific group

Body:
I'm trying to arrange values in decreasing order within a exact group in a nested dataframe. My input data looks like this. I've got two grouping variables (group1 and group2) and three values (i.e. id, value2, value3).

library(tidyverse)
set.seed(1234)

df <- tibble(group1 = c(rep(LETTERS[1:3], 4)),
             group2 = c(rep(0, 6), rep(2, 6)),
             value2 = rnorm(12, 20, sd = 10),
             value3 = rnorm(12, 20, sd = 50)) %>%
  group_by(group1) %>%
  mutate(id = c(1:4)) %>%
  ungroup()

I decided to group them by group1 and group2 and then nest():

df_nested <- df %>%
  group_by(group1, group2) %>%
  nest()

# A tibble: 6 x 3
# Groups:   group1, group2 [6]
  group1 group2 data
  <chr>   <dbl> <list>
1 A           0 <tibble [2 x 3]>
2 B           0 <tibble [2 x 3]>
3 C           0 <tibble [2 x 3]>
4 A           2 <tibble [2 x 3]>
5 B           2 <tibble [2 x 3]>
6 C           2 <tibble [2 x 3]>

Perfect. Now I need to sort only those data which group2 is equal to 2 by id. However I'm receiving a following error:

df_nested %>%
  mutate(data = map2_df(.x = data, .y = group2,
                     ~ifelse(.y == 2, arrange(-.x$id),
                             .x)))

Error: Argument 1 must have names

Body:
You could do :

library(dplyr)
library(purrr)

df_nested$data <- map2(df_nested$data, df_nested$group2,~if(.y == 2)
                       arrange(.x, -.x$id) else .x)

So data where group2 is not equal to 2 is not sorted

df_nested$data[[1]]
# A tibble: 2 x 3
#  value2 value3    id
#   <dbl>  <dbl> <int>
#1  13.1  -89.0      1
#2   9.76  -3.29     2

and where group2 is 2 is sorted.

df_nested$data[[4]]
# A tibble: 2 x 3
#value2 value3    id
# <dbl>  <dbl> <int>
#1   15.0  -28.4   4
#2   31.0  -22.8   3

If you want to combine them do :

map2_df(df_nested$data, df_nested$group2,~if(.y == 2) arrange(.x, -.x$id) else .x)


问:
How can I recursively print a File Array?
I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.

```<code>import java.io.*;

public class RecursiveDir {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[]args) throws IOException {
    System.out.print("Please enter a directory name: ");
    File f = new File(br.readLine());

    FileFilter filter = new FileFilter() {

        public boolean accept(File f) {
            if(f.isDirectory()) {
                return true;
            }
            return false;
        }

    };

    File[] list = f.listFiles(filter);
    System.out.println(returnDir(list,list.length));
}

public static File returnDir(File[] file,int counter) {
    File f = file[counter];
    if(counter == 0) {
        return file[0];
    }else {
        return f = returnDir(file,counter--);
    }
}
}
</code>```

EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.

答:
You are going out of the array bound because you need to pass list.length - 1 to the method.

Even if you did that, though, you would have an infinite recursion, because counter-- will use the value of counter, and then decrement it. So that means you are calling returnDir with the current value of counter. Use either --counter, or counter - 1.

Body:
I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.

import java.io.*;

public class RecursiveDir {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[]args) throws IOException {
    System.out.print("Please enter a directory name: ");
    File f = new File(br.readLine());

    FileFilter filter = new FileFilter() {

        public boolean accept(File f) {
            if(f.isDirectory()) {
                return true;
            }
            return false;
        }

    };

    File[] list = f.listFiles(filter);
    System.out.println(returnDir(list,list.length));
}

public static File returnDir(File[] file,int counter) {
    File f = file[counter];
    if(counter == 0) {
        return file[0];
    }else {
        return f = returnDir(file,counter--);
    }
}
}

EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.


问:
Compare values in two lists and return the similar or nearest value from a third list
I will like to find similar values of j in v and return x. when the value in j is not equal to v, I will like the code the detect the 2 value in v that j values between. so if j falls between v1 and v2, I will like the code to return max(x1,x2)- ( ((j-v1)/(v2-v1))*(max(x1,x2)-min(x1,x2)))

```<code>v= [100,200,300,400,500,600,700,800,900,1000,1100]
x= [67,56,89,21,90,54,38,93,46,17,75]
j= [200,300,400,460,500,600,700,800,870,900,950]

for i in range(len(v)-1):
    if v[i] > j and V[i+1] < j:
        p = max(x[i],x[i+1])- ( ((j-v[i])/(v[i+1]-v[i]))*(max(x[i],x[i+1])-min(x[i],x[i+1])))
    elif v[i] ==j:
        b= x[i]
print(p,b)

"""
n = [x[i] for i, v_ele in enumerate(v) if v_ele in j]
p=  [x[i] for i, v_ele in enumerate(v) if v_ele > j and v_ele
print(n)
"""
</code>```

I will like my answers to return

```<code>[56,89,21,48.6,90,54,38,93,60.1,46,31.5]
</code>```

答:
We can do this using the following two helper functions. Note that I think there may be a slight error for the fourth element in your expected output in the question - I get that value as 62.4 while you have 48.6.

Code:

```<code>def get_v_indx(j_ele, v):
    if j_ele in v:
        return v.index(j_ele)
    else:
        for i, ele in enumerate(v):
            if ele > j_ele:
                return i-1+(j_ele-v[i-1])/(ele-v[i-1])

def get_x_ele(i, x):
    try:
        return x[i]
    except TypeError:
        return x[int(i)] + (x[int(i)+1]-x[int(i)])*(i-int(i))
</code>```

Usage:

```<code>>>> [get_x_ele(get_v_indx(j_ele, v), x) for j_ele in j]
[56, 89, 21, 62.4, 90, 54, 38, 93, 60.1, 46, 31.5]
</code>```

Body:
I will like to find similar values of j in v and return x. when the value in j is not equal to v, I will like the code the detect the 2 value in v that j values between. so if j falls between v1 and v2, I will like the code to return max(x1,x2)- ( ((j-v1)/(v2-v1))*(max(x1,x2)-min(x1,x2)))

v= [100,200,300,400,500,600,700,800,900,1000,1100]
x= [67,56,89,21,90,54,38,93,46,17,75]
j= [200,300,400,460,500,600,700,800,870,900,950]

for i in range(len(v)-1):
    if v[i] > j and V[i+1] < j:
        p = max(x[i],x[i+1])- ( ((j-v[i])/(v[i+1]-v[i]))*(max(x[i],x[i+1])-min(x[i],x[i+1])))
    elif v[i] ==j:
        b= x[i]
print(p,b)

"""
n = [x[i] for i, v_ele in enumerate(v) if v_ele in j]
p=  [x[i] for i, v_ele in enumerate(v) if v_ele > j and v_ele
print(n)
"""

I will like my answers to return

[56,89,21,48.6,90,54,38,93,60.1,46,31.5]

Body:
We can do this using the following two helper functions. Note that I think there may be a slight error for the fourth element in your expected output in the question - I get that value as 62.4 while you have 48.6.

Code:

def get_v_indx(j_ele, v):
    if j_ele in v:
        return v.index(j_ele)
    else:
        for i, ele in enumerate(v):
            if ele > j_ele:
                return i-1+(j_ele-v[i-1])/(ele-v[i-1])

def get_x_ele(i, x):
    try:
        return x[i]
    except TypeError:
        return x[int(i)] + (x[int(i)+1]-x[int(i)])*(i-int(i))

Usage:

>>> [get_x_ele(get_v_indx(j_ele, v), x) for j_ele in j]
[56, 89, 21, 62.4, 90, 54, 38, 93, 60.1, 46, 31.5]


答:
that is because you change tc while iterating through it.
you can achieve your goal with a simple list comprehension:

tc = [item for item in tc if not item.startswith('00:00:00.')]
```

Title: Python startswith() not removing all matches

Body:
Not sure if I am doing anything silly here but I am trying to remove all items in a list which starts with 00:00:00. but not all items are matched.

tc = ['00:00:00.360', '00:00:00.920', '00:00:00.060', '00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:00.140', '00:00:00.280', '00:00:01.200', '00:00:00.400', '00:00:01.220', '00:00:00.380']
for item in tc:
    if item.startswith(str('00:00:00.')):
        tc.remove(item)
print (tc)

Result:

['00:00:00.920', '00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:00.280', '00:00:01.200', '00:00:01.220']

Expected Result:

['00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:01.200', '00:00:01.220']

Any idea what could be the issue here?